🌊 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(ruflo-console): 0.12.0 review fixes — confirm before any slash launch, no double hand-over, guidance bound to its goal, PII read from hasPII, auto-run reset on restart
ruvbe130834691d
diff --git a/plugins/ruflo-console/hooks/mission-control.ts b/plugins/ruflo-console/hooks/mission-control.tsindex f1e0442ad1..e4f3d8eb4f 100644--- a/plugins/ruflo-console/hooks/mission-control.ts+++ b/plugins/ruflo-console/hooks/mission-control.ts@@ -18,6 +18,9 @@ import type { Runner } from './runner'import { CLI_PREFIXES, type State } from './state'import type { Derived, LedgerEvent, LedgerTask, McState, McTab, MissionActions, MissionRecord } from './mission-types'+import { cancelSpec, createSpec, dispatchSpec, isInflight, resultOf, setPaused } from './mission-specs'++export { cancelSpec, createSpec, dispatchSpec, resultOf, setPaused }export type { Derived, LedgerEvent, LedgerTask, McState, McTab, MissionActions, MissionRecord } from './mission-types'const states = new WeakMap<State, McState>()@@ -45,6 +48,7 @@ export function setGoal(state: State, goal: string): void {const mc = mcOf(state)mc.goal = plain(goal, 500).trim()+ mc.screen = nullif (!mc.isProfilePicked) mc.profile = profileOf(mc.goal)mc.planned = mc.goal === '' ? null : planOf(mc.profile, mc.rigor)}@@ -130,7 +134,10 @@ export async function loadLedger(state: State, host: Host): Promise<void> {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 isShaped = Array.isArray(m?.tasks) && m.tasks.every(task => typeof task?.id === 'string' && Array.isArray(task.dependsOn)) && Array.isArray(m.events)++ // Auto-run never survives a restart: a new session starts by asking.+ if (typeof m?.id === 'string' && /^msn_[a-f0-9]{24}$/.test(m.id) && isShaped) mc.missions.set(m.id, { ...m, auto: false })}const active = (saved as { active?: unknown }).active@@ -139,170 +146,6 @@ export async function loadLedger(state: State, host: Host): Promise<void> {}/** `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@@ -324,21 +167,36 @@ export function missionActions(state: State, host: Host, runner: Runner): Missioconst objective = activeMission(state)?.objective ?? mc.goalif (objective.trim() === '') return say(label, false, 'type a goal first: it works on the goal')+ if (blocksGuidance(mc.screen)) return say(`${label} blocked`, false, `AIDefence: ${mc.screen?.detail ?? ''}. Change the goal.`)const args = plain(objective, MAX_TEXT)- if (state.turnActive) {- void host.fillPrompt(`/${slash} ${args}`).then(- isFilled => say(isFilled ? 'prepared in the prompt box' : 'no prompt box here', isFilled, `press Enter to run /${slash} in the main conversation`),- () => say(label, false, 'the prompt box refused it'),- )-- return- }-- void host.runSlash(slash, args).then(- () => say(`${label}: /${slash} is running`, true, 'in the main conversation: the pane follows the task store'),- () => say(label, false, `/${slash} did not run`),+ // It starts a model turn: asked first, with the exact command.+ runner.ask(+ {+ label: `run /${slash} on the goal in the main Claude UI`,+ scope: 'controls',+ args: [],+ shows: `/${slash} ${plain(args, 100)}`,+ expect: 'the command in the main conversation',+ note: 'Starts a Claude Code turn (billed as any turn is); mid-turn it is only prepared in the prompt box.',+ run: async () => {+ if (state.turnActive) {+ void host.fillPrompt(`/${slash} ${args}`).then(+ isFilled => say(isFilled ? 'prepared in the prompt box' : 'no prompt box here', isFilled, `press Enter to run /${slash} in the main conversation`),+ () => say(label, false, 'the prompt box refused it'),+ )++ return+ }++ void host.runSlash(slash, args).then(+ () => say(`${label}: /${slash} is running`, true, 'in the main conversation: the pane follows the task store'),+ () => say(label, false, `/${slash} did not run`),+ )+ },+ },+ 'type a goal first',)}@@ -478,8 +336,7 @@ export function advance(state: State, host: Host): void {const task = nextTask(mission, state.snapshot?.tasks ?? [])- if (task === null || task.dispatchedAtMs !== undefined) return+ if (task === null || isInflight(task)) 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.tsindex ff897ba333..99e11e63ba 100644--- a/plugins/ruflo-console/hooks/mission-guidance.ts+++ b/plugins/ruflo-console/hooks/mission-guidance.ts@@ -10,6 +10,7 @@ import { termText } from './harness'import type { Host } from './host'import { type Plan, lifecycleOf } from './goap'import type { McState } from './mission-control'+import { blocksGuidance } from './mission-options'import { planText } from './mission-text'import type { Runner } from './runner'import { settingsOf } from './settings'@@ -164,6 +165,7 @@ export function guidanceSpec(state: State, host: Host, mc: McState): ActionSpecif (mc.planned === null) return nullconst argv = guidanceArgv(state)+ const goal = mc.goalreturn {label: `ask claude -p for detailed guidance on this mission: ${termText(mc.goal.replace(/\s+/g, ' '), 44)}`,@@ -171,12 +173,17 @@ export function guidanceSpec(state: State, host: Host, mc: McState): ActionSpecargs: 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),+ // The goal or its screen may have changed while the ask was open: only the goal that was asked about goes out.+ run: async () => {+ if (mc.goal === goal && !blocksGuidance(mc.screen)) 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 {+ // A turn for the previous goal is stopped, not left to run on (and be paid for) with no way to stop it.+ mc.guidance?.stop?.()mc.guidance = nullconst ai = settingsOf(state).aidiff --git a/plugins/ruflo-console/hooks/mission-options.ts b/plugins/ruflo-console/hooks/mission-options.tsindex 13ca3de009..273e7f5602 100644--- a/plugins/ruflo-console/hooks/mission-options.ts+++ b/plugins/ruflo-console/hooks/mission-options.ts@@ -10,6 +10,7 @@ import { plain } from './data/parse'import type { Host } from './host'import { CLI_PREFIXES, type State } from './state'import { GOALS_PLUGIN } from './mission-skills'+import { jsonAfter } from './data/cli'import { mcpReader } from './secure'export type Screen = { status: 'safe' | 'unsafe' | 'pii' | 'unavailable'; detail: string }@@ -43,7 +44,7 @@ const title = (slash: string): string => {export function capabilitiesOf(state: State): CapabilityGroup[] {const groups = new Map<string, Capability[]>()- for (const slash of state.commandNames) {+ for (const slash of new Set(state.commandNames)) {const at = slash.indexOf(':')if (at < 0 || !/^ruflo[a-z0-9-]*:[A-Za-z0-9._-]+$/.test(slash)) continue@@ -76,6 +77,23 @@ async function verdict(state: State, host: Host, tool: string, text: string): Pr}}+/** `aidefence_has_pii` answers `{hasPII}` (or piiFound / piiDetected): read as PII FOUND or SAFE, whatever else it says. */+async function piiVerdict(state: State, host: Host, text: string): Promise<string | null> {+ try {+ const out = await host.run(argv(state, 'aidefence_has_pii', text), 60_000)+ const result = jsonAfter(out.stdout)+ const record = typeof result === 'object' && result !== null && !Array.isArray(result) ? (result as Record<string, unknown>) : null+ const content = Array.isArray(record?.content) ? (record.content[0] as { text?: unknown } | undefined) : undefined+ const inner = typeof content?.text === 'string' ? jsonAfter(content.text) : record+ const row = typeof inner === 'object' && inner !== null && !Array.isArray(inner) ? (inner as Record<string, unknown>) : null+ const found = row?.hasPII ?? row?.piiFound ?? row?.piiDetected++ return typeof found === 'boolean' ? (found ? 'PII FOUND' : 'SAFE') : null+ } catch {+ return null+ }+}+/*** Screens text the person typed for a mission with AIDefence. Empty text is safe. A tool that answers nothing readable is* `unavailable` (the screen warns; it never blocks on a missing detector), and the text is never shown in the result.@@ -85,11 +103,12 @@ export async function screenText(state: State, host: Host, raw: string): Promiseif (text === '') return { status: 'safe', detail: 'nothing to screen' }- const [safe, pii] = await Promise.all([verdict(state, host, 'aidefence_is_safe', text), verdict(state, host, 'aidefence_has_pii', text)])+ const [safe, pii] = await Promise.all([verdict(state, host, 'aidefence_is_safe', text), piiVerdict(state, host, text)])- if (safe === null && pii === null) return { status: 'unavailable', detail: 'AIDefence did not answer (is @claude-flow/aidefence installed?): the text was not screened' }if (safe?.startsWith('UNSAFE') === true) return { status: 'unsafe', detail: plain(safe, 160) }if (pii?.startsWith('PII FOUND') === true || safe?.startsWith('PII FOUND') === true) return { status: 'pii', detail: 'personal or secret data detected' }+ // Both detectors must answer: half an answer is not a screen.+ if (safe === null || pii === null) return { status: 'unavailable', detail: 'AIDefence did not fully answer (is @claude-flow/aidefence installed?): the text was not fully screened' }return { status: 'safe', detail: 'no threats or PII found' }}diff --git a/plugins/ruflo-console/hooks/mission-palette.ts b/plugins/ruflo-console/hooks/mission-palette.tsindex 5066f5daf5..b5b3022a00 100644--- a/plugins/ruflo-console/hooks/mission-palette.ts+++ b/plugins/ruflo-console/hooks/mission-palette.ts@@ -1,5 +1,6 @@/** 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 { blocksCreate } from './mission-options'import { activeMission, cancelSpec, createSpec, dispatchSpec, mcOf, missionWired, nextTask, setGoal } from './mission-control'import type { PaletteEntry } from './palette'import type { State } from './state'@@ -15,7 +16,7 @@ export function missionPalette(state: State): PaletteEntry[] {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-create', group: 'missions', label: 'create the mission and its tasks from the planned goal (asks first)', run: spec(() => (wired === undefined || blocksCreate(mcOf(state).screen) ? null : createSpec(state, wired.host, () => undefined))) },{id: 'mission-next',group: 'missions',@@ -31,7 +32,7 @@ export function missionPalette(state: State): PaletteEntry[] {{ 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-guide', group: 'missions', label: 'mission-guide <instruction>: a visible instruction to Claude (screened, asks first)', run: text('mission-guide', value => local('guide Claude', () => wired?.actions.guide(value))) },{ 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-specs.ts b/plugins/ruflo-console/hooks/mission-specs.tsnew file mode 100644index 0000000000..547a61263e--- /dev/null+++ b/plugins/ruflo-console/hooks/mission-specs.ts@@ -0,0 +1,223 @@+/** The confirm-gated writes of Mission Control: create the mission and its tasks, hand a task to Claude, cancel. */+import type { ActionSpec } from './actions'+import { plain, type TaskRecord } from './data/parse'+import { stageOf, toMissionPlan, type Profile } from './goap'+import type { Host } from './host'+import { activeMission, instructionOf, mcOf, nextTask, record, rufloTaskOf, saveLedger } from './mission-control'+import type { LedgerTask, MissionRecord } from './mission-types'+import { CLI_PREFIXES, type State } from './state'++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 goal = mc.goal+ const body = toMissionPlan(planned)+ const stamp = Date.now().toString(36)++ return {+ label: `create the mission and its ${body.tasks.length} tasks: ${plain(goal, 60)}`,+ scope: 'goal',+ args: [],+ argv: argvOf(state, 'mission_create', { requestId: `console-create-${stamp}`, objective: 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 () => {+ // The goal changed while this ask was open: the plan on screen is not the plan that was asked for.+ if (mc.goal !== goal) return void (mc.last = { label: 'not created', ok: false, detail: 'the goal changed since you asked; ask again' })++ try {+ await createChain()+ } catch (error) {+ mc.last = { label: 'creating the mission failed', ok: false, detail: plain(error instanceof Error ? error.message : String(error), 160) }+ host.invalidate()+ }+ },+ }++ async function createChain(): Promise<void> {+ {+ 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: 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 missing = tasks.filter(task => task.rufloTaskId === undefined).length++ if (missing > 0) {+ for (const task of tasks) if (task.rufloTaskId !== undefined) await host.run(argvOf(state, 'task_cancel', { taskId: task.rufloTaskId, reason: 'mission creation failed in the console' }), 60_000).catch(() => undefined)++ return fail(`${missing} of ${tasks.length} tasks could not be created`, `mission ${id} exists without tasks; the tasks that were made were cancelled. Ask again.`)+ }++ const record0: MissionRecord = {+ id,+ objective: 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. */+/** Tasks handed over in the last seconds: the task store has not refreshed yet, so they still read ready. */+const inflight = new WeakSet<LedgerTask>()++export const isInflight = (task: LedgerTask): boolean => inflight.has(task)++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 () => {+ // The ask stays open for a while: the mission may have moved (paused, cancelled, auto-run took it, a double press).+ if (mission.paused || mission.cancelled || inflight.has(task) || nextTask(mission, state.snapshot?.tasks ?? [])?.id !== task.id) {+ mcOf(state).last = { label: `task ${task.id} not handed over`, ok: false, detail: 'the mission changed since you asked (paused, cancelled, or that task already went)' }+ host.invalidate()++ return+ }++ inflight.add(task)+ host.after(15_000, () => inflight.delete(task))+ 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)++ try {+ await send(text)+ } catch (error) {+ // The prompt did not go: put the task back so the mission does not stall on a task nobody is doing.+ await host.run(argvOf(state, 'task_update', { taskId: task.rufloTaskId, status: 'pending', progress: 0 }), 60_000).catch(() => undefined)+ task.dispatchedAtMs = undefined+ inflight.delete(task)+ mcOf(state).last = { label: `task ${task.id} was not sent`, ok: false, detail: plain(error instanceof Error ? error.message : String(error), 140) }+ host.invalidate()++ return+ }++ 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()+ },+ }+}diff --git a/plugins/ruflo-console/hooks/views/mission-launch.ts b/plugins/ruflo-console/hooks/views/mission-launch.tsindex 425a2d7817..1660f9a6d7 100644--- a/plugins/ruflo-console/hooks/views/mission-launch.ts+++ b/plugins/ruflo-console/hooks/views/mission-launch.ts@@ -40,7 +40,7 @@ export function launchSteps(ctx: Ctx): Step[] {label: 'Claude guidance',state: guidanceOff ? 'skip' : blocksGuidance(screen) ? 'blocked' : guidance?.status === 'done' ? 'done' : guidance?.status === 'running' ? 'running' : 'todo',detail: guidanceOff ? 'off in Settings' : guidance === null ? 'claude -p advises by stage and suggests ruflo capabilities (asks first)' : guidance.status === 'running' ? 'writing…' : guidance.note,- ...(planned && !guidanceOff && !blocksGuidance(screen) && guidance?.status !== 'running' ? { action: { key: 'mc-todo-guidance', label: guidance === null ? ' ✦ ask Claude ' : ' ↻ again ', run: () => m.askGuidance() } } : {}),+ ...(planned && !guidanceOff && !blocksGuidance(screen) && (screen !== null || !mc.isScreenOn) && guidance?.status !== 'running' ? { action: { key: 'mc-todo-guidance', label: guidance === null ? ' ✦ ask Claude ' : ' ↻ again ', run: () => m.askGuidance() } } : {}),})steps.push({diff --git a/plugins/ruflo-console/tests/fixtures/mission-cli.ts b/plugins/ruflo-console/tests/fixtures/mission-cli.tsindex bcd77afc17..209c9a078e 100644--- a/plugins/ruflo-console/tests/fixtures/mission-cli.ts+++ b/plugins/ruflo-console/tests/fixtures/mission-cli.ts@@ -15,7 +15,7 @@ export function missionCli(argv: readonly string[]): Answer {const tool = argv[at + 1]if (tool === 'aidefence_is_safe') return out({ safe: !/ignore (all )?previous instructions/i.test(String(argv[argv.indexOf('-p') + 1])), threats: [] })- if (tool === 'aidefence_has_pii') return out({ piiFound: false })+ if (tool === 'aidefence_has_pii') return out({ hasPII: false })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 })diff --git a/plugins/ruflo-console/tests/mission-control.spec.ts b/plugins/ruflo-console/tests/mission-control.spec.tsindex 62ca4c9ced..3323b15114 100644--- a/plugins/ruflo-console/tests/mission-control.spec.ts+++ b/plugins/ruflo-console/tests/mission-control.spec.ts@@ -29,6 +29,7 @@ function hostOf(calls: Calls, answer: (tool: string, params: Record<string, unknstoreGet: async (key: string) => calls.stored.get(key),storeSet: async (key: string, value: unknown) => void calls.stored.set(key, value),invalidate: () => undefined,+ after: () => ({ cancel: () => 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}`),@@ -273,7 +274,11 @@ describe('mission control: handing work to the primary session', () => {})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([])+ const { state, calls, actions, asked } = setup([])+ const confirm = async () => {+ await asked.at(-1)?.spec?.run?.()+ await new Promise(resolve => setTimeout(resolve, 0))+ }setGoal(state, 'add a dark mode toggle')actions.skill('goal-plan')@@ -281,11 +286,13 @@ describe('mission control: handing work to the primary session', () => {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([])+ expect(asked.at(-1)?.spec?.label).toContain('run /ruflo-goals:goal-plan on the goal')+ await confirm()expect(calls.slashes).toEqual(['ruflo-goals:goal-plan add a dark mode toggle'])state.turnActive = trueactions.skill('goal-plan')- await new Promise(resolve => setTimeout(resolve, 0))+ await confirm()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'])})diff --git a/plugins/ruflo-console/tests/mission-review.spec.ts b/plugins/ruflo-console/tests/mission-review.spec.tsnew file mode 100644index 0000000000..43b4546a9b--- /dev/null+++ b/plugins/ruflo-console/tests/mission-review.spec.ts@@ -0,0 +1,177 @@+/**+ * Regressions from the 0.12.0 adversarial review: a model turn never starts without a confirm, a stale ask never sends a goal+ * it was not asked about, a task is never handed over twice or left stuck, a half answer is not a screen, and auto-run does not+ * survive a restart.+ */+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 { guidanceSpec } from '../hooks/mission-guidance'+import { dispatchSpec, loadLedger, mcOf, missionActions, setGoal, type MissionRecord } from '../hooks/mission-control'+import { blocksGuidance, capabilitiesOf, screenText } from '../hooks/mission-options'+import type { Runner } from '../hooks/runner'+import { newState, type State } from '../hooks/state'++const ID = 'msn_0123456789abcdef01234567'+const out = (data: unknown) => `[INFO] Executing tool\nResult:\n${JSON.stringify(data, null, 2)}`+const tick = () => new Promise(resolve => setTimeout(resolve, 5))+const task = (id: string, status: string): TaskRecord => ({ id, type: 'feature', description: '', status, assignedTo: [], tags: [] })++function mission(): MissionRecord {+ return {+ id: ID, objective: 'x', profile: 'feature', rigor: 'standard', acceptance: [], events: [], paused: false, cancelled: false, auto: true, createdAtMs: 1,+ tasks: [{ id: 't1', title: 'Specify', phase: 'S', agent: 'specification', requirement: 'spec', dependsOn: [], rufloTaskId: 'r1' }],+ }+}++type Answer = (tool: string) => unknown++function host(answer: Answer = () => ({ ok: true }), fails: { send?: boolean } = {}) {+ const runs: string[] = []+ const prompts: string[] = []+ const h = {+ run: async (argv: readonly string[]) => {+ const tool = argv[argv.indexOf('-t') + 1] as string++ runs.push(tool)++ return { exitCode: 0, stdout: out(answer(tool)), stderr: '' }+ },+ storeGet: async () => undefined,+ storeSet: async () => undefined,+ invalidate: () => undefined,+ after: () => ({ cancel: () => undefined }),+ submitPrompt: async (text: string) => {+ if (fails.send === true) throw new Error('the box is busy')++ prompts.push(text)+ },+ fillPrompt: async () => true,+ runSlash: async () => undefined,+ } as unknown as Host++ return { h, runs, prompts }+}++const stateWith = (tasks: TaskRecord[]): State => {+ const state = newState({})++ state.snapshot = { tasks } as never++ return state+}++describe('review regressions', () => {+ it('a slash launch asks first, and is refused outright for a goal AIDefence flagged', async () => {+ const state = stateWith([])+ const { h } = host()+ const asked: (ActionSpec | null)[] = []+ const slashes: string[] = []++ ;(h as unknown as { runSlash: (c: string) => Promise<void> }).runSlash = async c => void slashes.push(c)+ state.commandNames = ['ruflo-ruos:deploy']+ setGoal(state, 'ship it')++ const actions = missionActions(state, h, { ask: (spec: ActionSpec | null) => void asked.push(spec) } as unknown as Runner)++ actions.capability('ruflo-ruos:deploy')+ expect(slashes).toEqual([])+ expect(asked[0]?.label).toContain('run /ruflo-ruos:deploy on the goal')+ mcOf(state).screen = { status: 'unsafe', detail: 'UNSAFE · 1 threat' }+ actions.capability('ruflo-ruos:deploy')+ expect(asked).toHaveLength(1)+ expect(mcOf(state).last?.label).toContain('blocked')+ })++ it('a guidance ask only goes out for the goal it was made for, and not once the goal is flagged', async () => {+ const state = stateWith([])+ const { h, runs } = host()++ setGoal(state, 'first goal')++ const spec = guidanceSpec(state, h, mcOf(state)) as ActionSpec++ setGoal(state, 'a different goal')+ await spec.run?.()+ await tick()+ expect(runs).toEqual([])+ expect(mcOf(state).guidance).toBeNull()+ })++ it('a task is handed over once: a second confirm, a paused or cancelled mission, and a stale ask do nothing', async () => {+ const state = stateWith([task('r1', 'pending')])+ const { h, runs, prompts } = host()+ const m = mission()+ const t = m.tasks[0]!+ const send = (text: string) => h.submitPrompt(text)++ await dispatchSpec(state, h, m, t, send).run?.()+ await dispatchSpec(state, h, m, t, send).run?.()+ expect(prompts).toHaveLength(1)+ expect(runs.filter(tool => tool === 'task_update')).toHaveLength(1)++ const m2 = mission()++ m2.paused = true+ await dispatchSpec(state, h, m2, m2.tasks[0]!, send).run?.()+ expect(prompts).toHaveLength(1)+ })++ it('a prompt that could not be sent puts the task back, so the mission does not stall on it', async () => {+ const state = stateWith([task('r1', 'pending')])+ const { h, runs } = host(() => ({ ok: true }), { send: true })+ const m = mission()+ const t = m.tasks[0]!++ await dispatchSpec(state, h, m, t, text => h.submitPrompt(text)).run?.()+ expect(runs.filter(tool => tool === 'task_update')).toHaveLength(2)+ expect(t.dispatchedAtMs).toBeUndefined()+ expect(mcOf(state).last?.ok).toBe(false)+ // and it can be handed over again at once+ await dispatchSpec(state, h, m, t, async () => undefined).run?.()+ expect(runs.filter(tool => tool === 'task_update')).toHaveLength(3)+ })++ it('half a screen is not a screen: one detector silent is unavailable, an unsafe answer wins, and PII is read from hasPII', async () => {+ const state = stateWith([])+ const answer = (safe: unknown, pii: unknown): Answer => tool => (tool === 'aidefence_is_safe' ? safe : pii)+ const run = (safe: unknown, pii: unknown) => screenText(state, host(answer(safe, pii)).h, 'add a toggle')++ expect((await run({ safe: true, threats: [] }, { hasPII: false })).status).toBe('safe')+ expect((await run({ safe: true, threats: [] }, { nothing: true })).status).toBe('unavailable')+ expect((await run({ nothing: true }, { hasPII: false })).status).toBe('unavailable')+ expect((await run({ safe: false, threats: [{ type: 'injection', severity: 'high' }] }, { nothing: true })).status).toBe('unsafe')+ expect((await run({ safe: true, threats: [] }, { hasPII: true })).status).toBe('pii')+ expect(blocksGuidance({ status: 'unavailable', detail: '' })).toBe(false)+ })++ it('a new goal forgets the old goal’s verdict', () => {+ const state = stateWith([])++ setGoal(state, 'first')+ mcOf(state).screen = { status: 'safe', detail: 'ok' }+ setGoal(state, 'second')+ expect(mcOf(state).screen).toBeNull()+ })++ it('auto-run does not survive a restart, and a ledger with a malformed task is dropped, not crashed on', async () => {+ const state = newState({})+ const good = { ...mission(), auto: true }+ const bad = { ...mission(), id: 'msn_aaaaaaaaaaaaaaaaaaaaaaaa', tasks: [null] }+ const { h } = host()++ ;(h as unknown as { storeGet: () => Promise<unknown> }).storeGet = async () => ({ active: ID, missions: [good, bad] })+ await loadLedger(state, h)+ expect(mcOf(state).missions.get(ID)?.auto).toBe(false)+ expect(mcOf(state).missions.has('msn_aaaaaaaaaaaaaaaaaaaaaaaa')).toBe(false)+ })++ it('commands listed twice are offered once', () => {+ const state = stateWith([])++ state.commandNames = ['ruflo-sparc:sparc', 'ruflo-sparc:sparc', 'ruflo-ruos:deploy']+ expect(capabilitiesOf(state).flatMap(group => group.items.map(item => item.slash)).sort()).toEqual(['ruflo-ruos:deploy', 'ruflo-sparc:sparc'])+ })+})