🌊 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(console): mission create retries only real lock timeouts, undoes and reads back on abort, reports run outcomes in lastResult
Dragan Spiridonovb9086fc471ef
diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.tsindex 3a741dde93..9e81cda6e4 100644--- a/plugins/ruflo-console/hooks/actions.ts+++ b/plugins/ruflo-console/hooks/actions.ts@@ -20,8 +20,11 @@ export type ActionSpec = {verifyLocal?: (host: Pick<Host, 'fs' | 'home'>) => Promise<boolean>/** Reads only: runs at once, without the confirm step, and shows what the CLI printed. */isReadOnly?: boolean- /** Not a ruflo CLI call: what runs instead once confirmed (a terminal harness), reporting for itself. */- run?: () => Promise<void>+ /**+ * Not a ruflo CLI call: what runs instead once confirmed (a terminal harness), reporting for itself. A run that answers a RunReport also has+ * the runner keep it as the console's outcome, so what console_state shows Claude (and `/ruflo yes` prints) is how the run ended.+ */+ run?: () => Promise<void | RunReport>/** 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>`. */@@ -52,6 +55,9 @@ export type ActionSpec = {findings?: Findings}+/** How a run that reports for itself ended, in the shape of the console's outcome. */+export type RunReport = { label: string; ok: boolean; detail: string; lines?: string[] }+export const exec = (tool: string, params: Record<string, string>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as constconst SAFE_WORD = /^[A-Za-z0-9_.-]{1,40}$/diff --git a/plugins/ruflo-console/hooks/adr.ts b/plugins/ruflo-console/hooks/adr.tsindex 0fea6d84d5..8741da84a2 100644--- a/plugins/ruflo-console/hooks/adr.ts+++ b/plugins/ruflo-console/hooks/adr.ts@@ -5,7 +5,7 @@* root: a folder or file that is a link is never read or written through, a new file never overwrites, and a status change is refused* if the file moved since the diff was shown. The pure parts are in data/adr.ts, data/adr-write.ts and data/adr-scope.ts.*/-import type { ActionSpec } from './actions'+import type { ActionSpec, RunReport } from './actions'import { replaceFile } from './activity-io'import { indexOf, lint, MAX_FILE, MAX_FILES, parseAdr, type AdrDoc, type AdrStatus, type Finding, type Registry, STATUSES } from './data/adr'import { checkScope, digestBlock, reportLines, suggest, type ScopeReport, type Suggestion } from './data/adr-scope'@@ -174,6 +174,20 @@ export const say = (state: State, host: Pick<Host, 'invalidate'>, label: string,host.invalidate()}+/**+ * The page's last result as a run's report, so the runner keeps it as the outcome Claude reads too. The detail is the line that says what+ * happened: the first of a success, the last of a failure (whatever was written before it stays in the lines).+ */+export function reported(state: State): RunReport | undefined {+ const last = adrOf(state).last++ if (last === null) return undefined++ const at = last.ok ? 0 : Math.max(0, last.lines.length - 1)++ return { label: last.label, ok: last.ok, detail: last.lines[at] ?? '', lines: last.lines.filter((_, index) => index !== at) }+}+/** One event on the Events page and one toast (source console, level info): the ADR said what happened, once. */export function announce(state: State, host: Pick<Host, 'toast'>, text: string): void {const line = plain(text, 118)@@ -237,6 +251,8 @@ export function initSpec(state: State, host: Pick<Host, 'fs' | 'run' | 'invalidaawait loadAdrs(state, host)say(state, host, 'initialise ADRs', problem === null, problem === null ? [`created ${dir}/${first.file}`, 'your project now has an ADR folder; propose the next record from this page'] : [problem])if (problem === null) announce(state, host, `ADRs initialised: ${dir}/${first.file}`)++ return reported(state)},}}@@ -272,6 +288,8 @@ export function proposeSpec(state: State, host: Pick<Host, 'fs' | 'run' | 'invalif (problem === null) adrOf(state).selected = namesay(state, host, `propose ADR ${number}`, problem === null, problem === null ? [`created ${dir}/${name}`, 'edit its Context and Decision, then accept it from this page'] : [problem])if (problem === null) announce(state, host, `ADR ${number} proposed: ${title}`)++ return reported(state)},}}@@ -340,21 +358,22 @@ export async function statusSpec(state: State, host: Pick<Host, 'fs' | 'run' | 'note: `Changes only the lines shown, in ${plan.changes.length} file${plan.changes.length === 1 ? '' : 's'} of your project. A file that changed since this diff was made is left alone.`,run: async () => {const done: string[] = []+ const failed = (lines: string[]): RunReport | undefined => (say(state, host, `change ADR ${doc.number ?? doc.file}`, false, lines), reported(state))for (const change of plan.changes) {const path = abs(state, dir, change.file)const safe = await checkNoLinks(host.fs, path, { cwd: root(state) }, { allowExisting: true })- if (!safe.ok) return say(state, host, `change ADR ${doc.number ?? doc.file}`, false, [...done, safe.why])+ if (!safe.ok) return failed([...done, safe.why])const now = await host.fs.read(path).catch(() => null)- if (now !== change.before) return say(state, host, `change ADR ${doc.number ?? doc.file}`, false, [...done, `${change.file} changed since the diff was shown: nothing was written to it. Ask again.`])+ if (now !== change.before) return failed([...done, `${change.file} changed since the diff was shown: nothing was written to it. Ask again.`])const result = await host.run(replaceFileArgv(path, true, await writeFlavorReady()), 10_000, change.after).catch(() => null)const back = await host.fs.read(path).catch(() => null)- if (result === null || result.exitCode !== 0 || back !== change.after) return say(state, host, `change ADR ${doc.number ?? doc.file}`, false, [...done, `${change.file} could not be written as shown`])+ if (result === null || result.exitCode !== 0 || back !== change.after) return failed([...done, `${change.file} could not be written as shown`])done.push(`wrote ${change.file}`)}@@ -362,6 +381,8 @@ export async function statusSpec(state: State, host: Pick<Host, 'fs' | 'run' | 'await loadAdrs(state, host)say(state, host, `change ADR ${doc.number ?? doc.file}`, true, done)announce(state, host, `ADR ${doc.number ?? doc.file} ${to === 'superseded' && by !== null ? `superseded by ADR ${by.number}` : to}`)++ return reported(state)},}}diff --git a/plugins/ruflo-console/hooks/data/mcp-run.ts b/plugins/ruflo-console/hooks/data/mcp-run.tsnew file mode 100644index 0000000000..54e6bdac0e--- /dev/null+++ b/plugins/ruflo-console/hooks/data/mcp-run.ts@@ -0,0 +1,81 @@+/**+ * One run of `ruflo mcp exec -t <tool> -p <json>`, read as Mission Control's create chain needs it. Pure: no `$`.+ *+ * What the CLI prints (captured from ruflo 3.56.1, commands/mcp.ts and mcp-client.ts):+ * stderr `[INFO] Executing tool: <tool>`, and on a failure `[ERROR] Tool execution failed: Failed to execute MCP tool '<tool>': <cause>`+ * stdout ` Parameters: {…the input…}`, then on success `[OK] Tool executed in …`, a line `Result:` and the answer as JSON+ * A failure prints no `Result:` line, so the Parameters object is the only JSON on stdout: it is never read as the answer.+ */+import { closeOf } from './json-span'+import { errorLine, failureReason } from './failure'+import { plain, recordOf } from './parse'++/** The cause the policy runtime throws when it could not take `.claude-flow/policy/state.lock` in time (#3164, #3892). */+export const LOCK_TIMEOUT = 'policy-state-lock-timeout'++const ANSI = /\x1b\[[0-9;]*m/g+const RESULT_LINE = /^Result:[ \t]*$/m++/** The text after the CLI's own `Result:` line (a line of its own, so a parameter that holds "Result:" is not it), or null when there is none. */+export function afterResult(stdout: string): string | null {+ const text = stdout.replace(ANSI, '')+ const marker = RESULT_LINE.exec(text)++ return marker === null ? null : text.slice(marker.index + marker[0].length)+}++/** The JSON object the tool answered (after `Result:`), strings and their brackets skipped, or null when it answered none. */+export function resultOf(stdout: string): Record<string, unknown> | null {+ const tail = afterResult(stdout)+ const start = tail === null ? -1 : tail.search(/[{[]/)++ if (tail === null || start < 0) return null++ const end = closeOf(tail, start)++ if (end < 0) return null++ try {+ return recordOf(JSON.parse(tail.slice(start, end + 1)))+ } catch {+ return null+ }+}++/** One run read: the tool's answer (null when none), whether it is the success the step needs, whether trying again may help, and why not. */+export type Attempt = { result: Record<string, unknown> | null; ok: boolean; transient: boolean; reason: string }++/** The CLI's cause, its two wrappers dropped ("Tool execution failed: Failed to execute MCP tool 'x': <cause>"). */+const causeOf = (line: string): string => line.replace(/^Tool execution failed:\s*/i, '').replace(/^Failed to execute MCP tool '[^']*':\s*/i, '').trim()++/** What one try came to: the process's output, a rejection from the host (it could not start, or was refused), or the caller's own time limit. */+export type RunRead = { exitCode: number; stdout: string; stderr: string } | { error: unknown } | { timedOutMs: number }++/**+ * Reads one run of `mcp exec`. `isDone` judges the tool's parsed answer by its own keys (never a substring of the output, which quotes the+ * person's text). Transient, and only then, when:+ * - the CLI's cause is exactly `policy-state-lock-timeout` (thrown before the tool runs, so nothing was written),+ * - the caller's own time limit ended the wait (`timedOutMs`, a structured signal, never a message), or+ * - the process exited non-zero with stdout and stderr both empty.+ * Any answer, any other error line (a refusal that mentions a timeout, `command not found`), and any rejection of the host (a command that+ * could not start, an approval that was refused or timed out) are definite.+ */+export function readAttempt(run: RunRead, isDone: (result: Record<string, unknown>) => boolean): Attempt {+ if ('timedOutMs' in run) return { result: null, ok: false, transient: true, reason: `no answer in ${Math.round(run.timedOutMs / 1000)} s; the CLI process may still finish (check \`ruflo task list\`)` }+ if ('error' in run) return { result: null, ok: false, transient: false, reason: `the CLI could not be run: ${plain(run.error instanceof Error ? run.error.message : String(run.error), 140) || 'no reason given'}` }++ const result = resultOf(run.stdout)++ if (result !== null) {+ const ok = run.exitCode === 0 && isDone(result)+ const tail = afterResult(run.stdout) ?? ''++ return { result, ok, transient: false, reason: ok ? '' : plain(failureReason({ stdout: tail }) || String(result.message ?? '') || 'the tool answered without the expected result', 160) }+ }++ const cause = plain(causeOf(errorLine(run.stderr) ?? errorLine(run.stdout) ?? ''), 160)+ const silent = run.exitCode !== 0 && run.stdout.trim() === '' && run.stderr.trim() === ''+ const said = cause || plain(run.stderr.split('\n').map(line => line.trim()).filter(line => line !== '').pop() ?? '', 160)++ return { result: null, ok: false, transient: cause === LOCK_TIMEOUT || silent, reason: said === '' ? `no answer (exit ${run.exitCode})` : said }+}diff --git a/plugins/ruflo-console/hooks/mission-create.ts b/plugins/ruflo-console/hooks/mission-create.tsnew file mode 100644index 0000000000..4aeaf6be67--- /dev/null+++ b/plugins/ruflo-console/hooks/mission-create.ts@@ -0,0 +1,329 @@+/**+ * Mission Control's create chain: `mission_create`, `mission_plan`, then one `task_create` per plan node, behind one confirm.+ *+ * On a busy project every `mcp exec` waits on the policy state lock and some fail with `policy-state-lock-timeout` (#3164, #3892). A step that+ * failed that way (or got no answer in time, or printed nothing at all) is tried again after RETRY_WAITS_MS; any other failure is final.+ * `task_create` has no request id, so after each wait, just before trying again, the task store is read: one task that is exactly this step's+ * (its description and both tags, open) is a late success and is used; more than one stops the chain (it never guesses); a store that cannot+ * be read stops a retry whose first try may have written; and after the last failed try the store is read once more (the last try's write+ * may have landed with its answer lost). Provenance is the mission id: the step's description and tag carry the id this create was just+ * given, so no older task can match; the time window (SKEW_MS) only keeps out a stale store and is wide for clock skew.+ *+ * Time is strict: no call, wait or read starts after its deadline, each is cut to the time left, and a call the host never answers is let go+ * at that time (the CLI process may still finish: the report says so). When the create cannot finish, every open task tagged with this+ * mission in the store (not only those whose create was acknowledged) is cancelled with the same retries, the mission record is asked to+ * cancel, and the store and the mission observation are READ BACK: the result says what they show, not what was asked.+ */+import type { ActionSpec, RunReport } from './actions'+import { taskStatusOf } from './data/automate'+import { PROJECT, under } from './data/files'+import { readAttempt, type Attempt, type RunRead } from './data/mcp-run'+import { parseMissions } from './data/missions'+import { parseTasks, plain, recordOf, type TaskRecord } from './data/parse'+import { stageOf, toMissionPlan, type Profile } from './goap'+import { checkLimit, MISSION_OBJECTIVE_MAX } from './full-text'+import type { Host } from './host'+import { mcOf, record, saveLedger } from './mission-control'+import type { LedgerTask, MissionRecord } from './mission-types'+import { CLI_PREFIXES, type State } from './state'++export const argvOf = (state: State, tool: string, params: unknown): string[] => [...CLI_PREFIXES[state.options.cli], 'mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)]++export const taskType = (profile: Profile) => (profile === 'bugfix' ? 'bugfix' : profile === 'refactor' ? 'refactor' : profile === 'research' ? 'research' : 'feature')++/**+ * Why the mission cannot be created from this goal, or null: the ruflo mission record takes an objective of at most MISSION_OBJECTIVE_MAX+ * characters (mission_create's input schema), and the goal is never cut to fit (ADR-481). Checked before the ask, with the exact count.+ */+export function createWhy(state: State): string | null {+ const goal = mcOf(state).goal+ const fit = checkLimit(goal, MISSION_OBJECTIVE_MAX, 'the goal', 'the ruflo mission record takes at most that many; planning, guidance and the skills use the whole goal', 'No mission was created; ✎ edit the goal to fit.')++ return fit.ok ? null : fit.message+}++/** The waits before a step that failed for a transient reason is tried again: up to three more tries, 1, 2 and 4 s apart. */+export const RETRY_WAITS_MS: readonly number[] = [1_000, 2_000, 4_000]+/** No create step starts after this long; what was made is then undone. */+export const CREATE_DEADLINE_MS = 180_000+/** Undoing (cancels, the mission cancel, the read-back) gets this long on top; past it, no step is retried. */+export const CLEANUP_BUDGET_MS = 120_000+/** One read of the task store or the mission observation may take this long. */+export const READ_MS = 5_000+/** One CLI call may take this long (less when the deadline is nearer). */+export const CALL_MS = 60_000+/** A store task this much older than the create can still be its late success: the mission id binds it; this only allows for clock skew. */+export const SKEW_MS = 5 * 60_000+/** The host's own process limit is set this much past the caller's, so the caller's (structured) time limit is the one that ends a wait. */+const HOST_GRACE_MS = 2_000++/** The creates running now, per console, with when each started: a second create is refused while one runs. */+const creating = new WeakMap<State, number>()++export const isCreating = (state: State): boolean => creating.has(state)++const nonce = (): string => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`++const pause = (host: Host, ms: number): Promise<void> =>+ new Promise(resolve => {+ try {+ host.after(ms, () => resolve())+ } catch {+ resolve()+ }+ })++/** `work`, or `late` once `ms` have passed without it settling (a timer of this module, so a host that never answers is let go). */+function within<T>(work: Promise<T>, ms: number, late: T): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined++ return Promise.race([work, new Promise<T>(resolve => (timer = setTimeout(() => resolve(late), Math.max(0, ms))))]).finally(() => clearTimeout(timer))+}++/** A file of the project, or null when it cannot be read within `ms` (at most READ_MS; nothing is read when no time is left). */+async function readWithin(state: State, host: Host, path: string, ms: number = READ_MS): Promise<string | null> {+ if (ms <= 0) return null++ try {+ return await within(Promise.resolve().then(() => host.fs.read(under(state.cwd, path))), Math.min(READ_MS, ms), null)+ } catch {+ return null+ }+}++const readStore = async (state: State, host: Host, ms?: number): Promise<TaskRecord[] | null> => {+ const text = await readWithin(state, host, PROJECT.tasks, ms)++ return text === null ? null : parseTasks(text)+}++type Step = { id: string; description: string; tags: string[] }++/** The tasks in the store that are exactly this step's: its description and both tags (the mission id binds them), still open, made since `sinceMs`. */+export function stepTasks(tasks: readonly TaskRecord[], missionId: string, step: Step, sinceMs: number): TaskRecord[] {+ const description = plain(step.description, 200)++ return tasks.filter(task => {+ const status = taskStatusOf(task.status)++ return (status === 'pending' || status === 'in_progress') && task.description === description && (task.tags ?? []).includes(`mission:${missionId}`) && (task.tags ?? []).includes(`task:${step.id}`) && (task.createdAtMs ?? 0) >= sinceMs+ })+}++type Outcome = Attempt & { tries: number }++/** 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 === '' || createWhy(state) !== null) return null++ const planned = mc.planned+ const goal = mc.goal+ const body = toMissionPlan(planned)+ const stamp = nonce()++ 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 () => {+ const since = creating.get(state)++ // One create at a time: a second would race the first for the same store and the same lock.+ if (since !== undefined) mc.last = { label: 'not created', ok: false, detail: `a mission is already being created (started ${Math.round((Date.now() - since) / 1000)} s ago); wait for its result` }+ // The goal changed while this ask was open: the plan on screen is not the plan that was asked for.+ else if (mc.goal !== goal) mc.last = { label: 'not created', ok: false, detail: 'the goal changed since you asked; ask again' }+ else {+ creating.set(state, Date.now())+ try {+ await createChain()+ } catch (error) {+ mc.last = { label: 'creating the mission failed', ok: false, detail: plain(error instanceof Error ? error.message : String(error), 160) }+ } finally {+ creating.delete(state)+ host.invalidate()+ }+ }++ host.invalidate()++ // How it ended is the console's outcome too, so Claude reads it from console_state however long the chain took.+ return mc.last === null ? undefined : ({ label: mc.last.label, ok: mc.last.ok, detail: mc.last.detail, ...(mc.last.lines !== undefined && { lines: mc.last.lines }) } satisfies RunReport)+ },+ }++ async function createChain(): Promise<void> {+ const startedMs = Date.now()+ // The mission id in the description and the tag is what binds a store task to this create; the window only allows for clock skew.+ const sinceMs = startedMs - SKEW_MS+ const deadline = startedMs + CREATE_DEADLINE_MS+ const cleanupEnd = deadline + CLEANUP_BUDGET_MS+ const fail = (label: string, detail: string, lines?: string[]) => void (mc.last = { label, ok: false, detail: plain(detail, 200), ...(lines !== undefined && { lines }) })++ const left = (until: number) => until - Date.now()+ const outOfTime: Attempt = { result: null, ok: false, transient: false, reason: 'out of time: not started' }++ /** One try of a tool: never started at or after `until`, and let go at the time left (the host's own limit is a little later). */+ const once = async (tool: string, params: unknown, isDone: (result: Record<string, unknown>) => boolean, until: number): Promise<Attempt> => {+ const ms = Math.min(CALL_MS, left(until))++ if (ms <= 0) return outOfTime++ const run = await within<RunRead>(host.run(argvOf(state, tool, params), ms + HOST_GRACE_MS).catch((error: unknown) => ({ error })), ms, { timedOutMs: ms })++ return readAttempt(run, isDone)+ }++ /**+ * Tries a step, and again after each wait while it fails for a transient reason and there is time before `until`. `beforeRetry` runs+ * after the wait, just before the next try: it may answer the step itself (a late success found), stop it (an answer of `ok: false`),+ * or let it be tried again (null).+ */+ const attempt = async (tool: string, params: unknown, isDone: (result: Record<string, unknown>) => boolean, until: number, beforeRetry?: () => Promise<Attempt | null>): Promise<Outcome> => {+ let last = await once(tool, params, isDone, until)+ let tries = 1++ for (const wait of RETRY_WAITS_MS) {+ // A wait that would end at or past the deadline is not started: there would be no time left for the try after it.+ if (last.ok || !last.transient || wait >= left(until)) break++ await pause(host, wait)++ const instead = await beforeRetry?.()++ if (instead != null) return { ...instead, reason: instead.ok ? '' : `${instead.reason} (after: ${last.reason})`, tries }+ if (left(until) <= 0) break++ last = await once(tool, params, isDone, until)+ tries += 1+ }++ // The last try failed for a transient reason: its write may have landed with the answer lost. One more look, if there is time for it.+ if (!last.ok && last.transient && left(until) > 0) {+ const found = await beforeRetry?.()++ // Only a late success counts here; anything else keeps the last try's own reason (cleanup cancels every task of the mission anyway).+ if (found?.ok === true) return { ...found, reason: '', tries }+ }++ return { ...last, tries }+ }++ const answered = (result: Record<string, unknown>) => result.ok === true+ const created = await attempt('mission_create', { requestId: `console-create-${stamp}`, objective: goal }, result => answered(result) && typeof recordOf(result.data)?.missionId === 'string', deadline)+ const data = recordOf(created.result?.data) ?? {}++ if (!created.ok || typeof data.missionId !== 'string') return fail('mission_create failed', `${created.reason || 'no answer'} (${tries(created)})`)++ const id = data.missionId+ const createdRevision = typeof data.revision === 'number' ? data.revision : 1+ // mission_create and mission_plan carry a request id, so a retry after a late success is answered from the record, never applied twice.+ const placed = await attempt('mission_plan', { requestId: `console-plan-${stamp}`, missionId: id, expectedRevision: createdRevision, plan: body }, answered, deadline)++ if (!placed.ok) return undo(id, createdRevision, [], `the plan was not recorded: ${placed.reason || 'no answer'} (${tries(placed)})`, 'mission not created: mission_plan failed')++ const planData = recordOf(placed.result?.data) ?? {}+ const planRevision = typeof planData.revision === 'number' ? planData.revision : createdRevision + 1+ const tasks: LedgerTask[] = []++ for (const node of planned.steps) {+ if (Date.now() >= deadline) return undo(id, planRevision, tasks, `the create ran past its ${CREATE_DEADLINE_MS / 60_000} min limit before task ${node.id}`, `mission not created: out of time at task ${node.id}`)++ const title = body.tasks.find(candidate => candidate.id === node.id)?.title ?? node.action.title+ const step: Step = { id: node.id, description: `[${id}/${node.id}] ${title}`.slice(0, 200), tags: [`mission:${id}`, `task:${node.id}`, `phase:${node.action.phase}`] }+ const made = await attempt('task_create', { type: taskType(planned.profile), description: step.description, priority: 'normal', tags: step.tags }, result => typeof result.taskId === 'string' && result.success !== false && result.error === undefined, deadline, async () => {+ const store = await readStore(state, host, left(deadline))++ if (store === null) return { result: null, ok: false, transient: false, reason: 'the task store could not be read to check for a late success, so the step was not tried again' }++ const found = stepTasks(store, id, step, sinceMs)++ if (found.length > 1) return { result: null, ok: false, transient: false, reason: `${found.length} tasks in the store match task ${node.id} (${found.map(task => task.id).join(', ')}); not guessing which one is ours` }++ return found.length === 1 ? { result: { taskId: found[0]?.id }, ok: true, transient: false, reason: '' } : null+ })+ const rufloTaskId = made.ok && typeof made.result?.taskId === 'string' ? made.result.taskId : undefined++ if (rufloTaskId === undefined) return undo(id, planRevision, tasks, `task ${node.id}: ${made.reason || 'no answer'} (${tries(made)})`, `mission not created: task ${node.id} could not be made`)++ tasks.push({ id: node.id, title: node.action.title, phase: node.action.phase, stage: stageOf(node.action), agent: node.action.agent, requirement: node.action.requirement, dependsOn: node.dependsOn, rufloTaskId })+ }++ const record0: MissionRecord = {+ id,+ objective: goal,+ profile: planned.profile,+ rigor: planned.rigor,+ planDigest: typeof planData.planDigest === 'string' ? planData.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.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()++ /**+ * The create cannot finish. Every open task of this mission is cancelled: those whose create was acknowledged, and any other the store+ * holds with this mission's tag (a create whose answer was lost). Then the mission record is asked to cancel (once more at the revision a+ * conflict names), and the task store and the mission observation are read back: the result says what they show. Nothing starts after+ * the cleanup deadline; what was left for lack of time is named.+ */+ async function undo(missionId: string, revision: number, made: LedgerTask[], why: string, label: string): Promise<void> {+ const tag = `mission:${missionId}`+ const before = await readStore(state, host, left(cleanupEnd))+ const acknowledged = made.map(task => task.rufloTaskId as string)+ const tagged = (before ?? []).filter(task => (task.tags ?? []).includes(tag)).map(task => task.id)+ const ids = [...new Set([...acknowledged, ...tagged])]+ const closed = new Set((before ?? []).filter(task => ['cancelled', 'completed'].includes(taskStatusOf(task.status))).map(task => task.id))+ const skipped: string[] = []++ for (const taskId of ids) {+ if (closed.has(taskId)) continue+ if (left(cleanupEnd) <= 0) skipped.push(taskId)+ else await attempt('task_cancel', { taskId, reason: 'mission creation failed in the console' }, result => result.success === true, cleanupEnd)+ }++ const cancel = (expectedRevision: number, suffix: string) => attempt('mission_request_action', { requestId: `console-abort-${stamp}${suffix}`, missionId, expectedRevision, action: 'cancel', reason: plain(`creation failed in the console: ${why}`, 400) }, answered, cleanupEnd)+ let asked = await cancel(revision, '')+ const current = asked.result?.code === 'revision-conflict' && typeof asked.result.currentRevision === 'number' ? asked.result.currentRevision : null++ if (!asked.ok && current !== null && current !== revision && left(cleanupEnd) > 0) asked = await cancel(current, '-r')++ const after = await readStore(state, host, left(cleanupEnd))+ const seen = after === null ? null : [...new Set([...ids, ...after.filter(task => (task.tags ?? []).includes(tag)).map(task => task.id)])].map(taskId => ({ taskId, status: taskStatusOf(after.find(task => task.id === taskId)?.status) || 'missing' }))+ const open = seen?.filter(entry => entry.status !== 'cancelled' && entry.status !== 'completed') ?? []+ const observed = parseMissions(await readWithin(state, host, PROJECT.missions, left(cleanupEnd)))?.missions.find(mission => mission.id === missionId)?.state+ const total = seen?.length ?? 0+ const storeLine =+ seen === null+ ? `the task store could not be read back: ${ids.length === 0 ? 'no task of this mission is known' : `the cancels of ${ids.join(', ')} are unconfirmed`}`+ : total === 0+ ? 'the store holds no task of this mission'+ : `the store shows ${total - open.length} of the ${total} tasks of this mission cancelled${open.length > 0 ? `; ${open.length} not cancelled: ${open.map(entry => `${entry.taskId} (${entry.status})`).join(', ')}` : ''}`+ const recordLine = `mission ${missionId}: ${asked.ok ? 'cancel accepted' : `cancel not accepted: ${asked.reason || 'no answer'}`}; the observation shows ${observed ?? 'nothing readable'}`+ const timeLine = skipped.length > 0 ? [`out of cleanup time: not asked to cancel ${skipped.join(', ')}`] : []+ const summary = seen === null ? 'Store not readable' : total === 0 ? 'No task in the store' : `Store: ${total - open.length} of ${total} cancelled${open.length > 0 ? `, ${open.length} not` : ''}`++ fail(label, `${why}. ${summary}; mission ${observed ?? 'state unknown'}. Ask again.`, [why, storeLine, recordLine, ...timeLine])+ }+ }+}++const tries = (outcome: Outcome): string => `${outcome.tries} ${outcome.tries === 1 ? 'try' : 'tries'}`diff --git a/plugins/ruflo-console/hooks/mission-specs.ts b/plugins/ruflo-console/hooks/mission-specs.tsindex 62ea13a1f4..5cd0ad2cd6 100644--- a/plugins/ruflo-console/hooks/mission-specs.ts+++ b/plugins/ruflo-console/hooks/mission-specs.ts@@ -1,152 +1,19 @@/** 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 { resultOf } from './data/mcp-run'import { taskStatusOf } from './data/automate'-import { stageOf, toMissionPlan, type Profile } from './goap'-import { checkLimit, MISSION_OBJECTIVE_MAX } from './full-text'import type { Host } from './host'import { adrBlockFor } from './adr-mission'import { EVENT_RESUMED, stoppedByAdvisor } from './mission-advisor'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'+import { argvOf } from './mission-create'+import 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')--/**- * Why the mission cannot be created from this goal, or null: the ruflo mission record takes an objective of at most MISSION_OBJECTIVE_MAX- * characters (mission_create's input schema), and the goal is never cut to fit (ADR-481). Checked before the ask, with the exact count.- */-export function createWhy(state: State): string | null {- const goal = mcOf(state).goal- const fit = checkLimit(goal, MISSION_OBJECTIVE_MAX, 'the goal', 'the ruflo mission record takes at most that many; planning, guidance and the skills use the whole goal', 'No mission was created; ✎ edit the goal to fit.')-- return fit.ok ? null : fit.message-}--/** 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 === '' || createWhy(state) !== null) 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()- }- }-}+/** The JSON object the tool answered after its own `Result:` line, or null (a failure prints none: the Parameters line is never read as one). */+export { resultOf } from './data/mcp-run'+export { createSpec, createWhy, RETRY_WAITS_MS } from './mission-create'/** 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. */diff --git a/plugins/ruflo-console/hooks/mission-text.ts b/plugins/ruflo-console/hooks/mission-text.tsindex 884adb65ff..f543c0aa17 100644--- a/plugins/ruflo-console/hooks/mission-text.ts+++ b/plugins/ruflo-console/hooks/mission-text.ts@@ -82,5 +82,5 @@ export function missionAnswer(state: State, paletteId: string | null): string |if (paletteId === 'mission-goal') return mc.planned === null ? 'type a goal after the id: /ruflo plan <goal>' : planText(mc.planned, mc.goal, settingsOf(state).ai)if (paletteId === 'mission-status') return statusText(state)- return mc.last === null ? null : `${mc.last.ok ? '✓' : '✗'} ${mc.last.label}${mc.last.detail === '' ? '' : ` — ${mc.last.detail}`}`+ return mc.last === null ? null : [`${mc.last.ok ? '✓' : '✗'} ${mc.last.label}${mc.last.detail === '' ? '' : ` — ${mc.last.detail}`}`, ...(mc.last.lines ?? []).map(line => ` ${line}`)].join('\n')}diff --git a/plugins/ruflo-console/hooks/mission-types.ts b/plugins/ruflo-console/hooks/mission-types.tsindex 458d68ca82..b12bef3c09 100644--- a/plugins/ruflo-console/hooks/mission-types.ts+++ b/plugins/ruflo-console/hooks/mission-types.ts@@ -45,7 +45,8 @@ export type McState = {/** AIDefence's verdict on the goal (null: not screened yet or the screen is off), and whether the screen is on. */screen: Screen | nullisScreenOn: boolean- last: { label: string; ok: boolean; detail: string; atMs?: number; next?: string } | null+ /** `lines` add what one line cannot hold (which tasks are still pending after a failed create). */+ last: { label: string; ok: boolean; detail: string; atMs?: number; next?: string; lines?: string[] } | null}export type MissionActions = {diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.tsindex c7a4582bd0..43720c0372 100644--- a/plugins/ruflo-console/hooks/runner.ts+++ b/plugins/ruflo-console/hooks/runner.ts@@ -58,9 +58,19 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runnerasync function execute(spec: ActionSpec): Promise<void> {// A harness run reports into the terminal and may take minutes: it does not hold the other buttons.if (spec.run !== undefined) {+ // The outcome slot as this run starts. Every writer replaces the object (never edits it), so "still this object" means no other+ // action reported meanwhile: exact, where comparing millisecond stamps let a same-millisecond result be overwritten.+ const outcomeAtStart = state.outcomeconst running = spec.run()- background = running.then(() => undefined, () => undefined)+ // A run that answers how it ended becomes the outcome when it ends, however long after the confirm that is: the page shows it on its+ // own panel, and this is the one place console_state and `/ruflo yes` read (a long mission create used to leave an older result there).+ // One outcome per action: when another action reported meanwhile, its outcome stays, and this one goes to the Events feed instead.+ background = running.then(report => {+ if (report === undefined || report === null) return+ if (state.outcome === outcomeAtStart) say(report.label, report.ok, report.detail, report.lines)+ else record(state.events, [{ atMs: Date.now(), kind: 'tools', text: `${report.ok ? '✓' : '✗'} ${plain(report.label, 80)}: ${plain(report.detail, 160)} (finished after a newer result)` }])+ }, () => undefined)// A read that runs its own command (a skills search) is waited on, so `/ruflo run` answers with what it found.if (spec.isReadOnly === true) await runningdiff --git a/plugins/ruflo-console/hooks/views/mission-control.ts b/plugins/ruflo-console/hooks/views/mission-control.tsindex a1c4d82621..38f618bf10 100644--- a/plugins/ruflo-console/hooks/views/mission-control.ts+++ b/plugins/ruflo-console/hooks/views/mission-control.ts@@ -236,7 +236,7 @@ export function missionControlView(ctx: Ctx): RenderElement {if (mission !== null) rows.push(...controlRows(ctx, mission))- if (mc.last !== null) rows.push(...fullRows(ctx, ` ${mc.last.ok ? '✓' : '✗'} `, `${mc.last.label}${mc.last.detail === '' ? '' : ` — ${mc.last.detail}`}`, { key: 'mc-last', color: mc.last.ok ? THEME.ok : THEME.bad, maxLines: 12, hint: 'your text is still in its field' }))+ if (mc.last !== null) rows.push(...fullRows(ctx, ` ${mc.last.ok ? '✓' : '✗'} `, `${mc.last.label}${mc.last.detail === '' ? '' : ` — ${mc.last.detail}`}`, { key: 'mc-last', color: mc.last.ok ? THEME.ok : THEME.bad, maxLines: 12, hint: 'your text is still in its field' }), ...(mc.last.lines ?? []).slice(0, 8).map(line => text(ctx, ` ${line}`, { dimColor: true })))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'))diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.codenew file mode 100644index 0000000000..573541ac97--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.code@@ -0,0 +1 @@+0diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.errnew file mode 100644index 0000000000..896eff45e4--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.err@@ -0,0 +1 @@+[INFO] Executing tool: mission_request_actiondiff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.outnew file mode 100644index 0000000000..82dce41532--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.out@@ -0,0 +1,15 @@+ Parameters: {"requestId":"cap-6","missionId":"msn_694db5dfd982c67fd44f4dfc","expectedRevision":2,"action":"cancel","reason":"capture"}++[OK] Tool executed in 38.50ms++Result:+{+ "ok": true,+ "data": {+ "missionId": "msn_694db5dfd982c67fd44f4dfc",+ "revision": 4,+ "state": "cancelled",+ "deduplicated": false,+ "sequence": 4+ }+}diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.codenew file mode 100644index 0000000000..573541ac97--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.code@@ -0,0 +1 @@+0diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.errnew file mode 100644index 0000000000..896eff45e4--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.err@@ -0,0 +1 @@+[INFO] Executing tool: mission_request_actiondiff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.outnew file mode 100644index 0000000000..22d05aab5d--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.out@@ -0,0 +1,11 @@+ Parameters: {"requestId":"cap-3","missionId":"msn_694db5dfd982c67fd44f4dfc","expectedRevision":2,"action":"cancel","reason":"capture"}++[OK] Tool executed in 9.70ms++Result:+{+ "ok": false,+ "code": "revision-conflict",+ "message": "revision-conflict: expected 2, current 1; refresh and retry",+ "currentRevision": 1+}diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.codenew file mode 100644index 0000000000..573541ac97--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.code@@ -0,0 +1 @@+0diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.errnew file mode 100644index 0000000000..cf9fbd0d7a--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.err@@ -0,0 +1 @@+[INFO] Executing tool: mission_creatediff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.outnew file mode 100644index 0000000000..98b95d76e1--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.out@@ -0,0 +1,14 @@+ Parameters: {"requestId":"cap-1","objective":"capture a transcript"}++[OK] Tool executed in 31.17ms++Result:+{+ "ok": true,+ "data": {+ "missionId": "msn_694db5dfd982c67fd44f4dfc",+ "revision": 1,+ "state": "draft",+ "deduplicated": false+ }+}diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.codenew file mode 100644index 0000000000..573541ac97--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.code@@ -0,0 +1 @@+0diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.errnew file mode 100644index 0000000000..54d710b2c0--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.err@@ -0,0 +1 @@+[INFO] Executing tool: mission_plandiff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.outnew file mode 100644index 0000000000..459cd05213--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.out@@ -0,0 +1,16 @@+ Parameters: {"requestId":"cap-5","missionId":"msn_694db5dfd982c67fd44f4dfc","expectedRevision":1,"plan":{"tasks":[{"id":"t1","title":"a","dependsOn":[],"executor":{"mode":"session-bound","requirement":"x"}}],"acceptance":[{"id":"a1","check":"x","producer":"t1"}],"budget":{"currency":"USD","ceilingMinor":100}}}++[OK] Tool executed in 33.63ms++Result:+{+ "ok": true,+ "data": {+ "missionId": "msn_694db5dfd982c67fd44f4dfc",+ "revision": 2,+ "state": "planned",+ "deduplicated": false,+ "sequence": 2,+ "planDigest": "sha256:f8bdcf5db12ba3e80b2729509fb8bf7b54e5c57fc567566f6709537de9b3e8a9"+ }+}diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.codenew file mode 100644index 0000000000..573541ac97--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.code@@ -0,0 +1 @@+0diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.errnew file mode 100644index 0000000000..54d710b2c0--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.err@@ -0,0 +1 @@+[INFO] Executing tool: mission_plandiff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.outnew file mode 100644index 0000000000..4b14dbc1b5--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.out@@ -0,0 +1,10 @@+ Parameters: {"requestId":"cap-2","missionId":"msn_694db5dfd982c67fd44f4dfc","expectedRevision":1,"plan":{"tasks":[{"id":"t1","title":"a","dependsOn":[],"executor":{"mode":"session-bound"}}],"acceptance":[{"id":"a1","check":"x"}],"budget":{"currency":"USD","ceilingMinor":100}}}++[OK] Tool executed in 10.48ms++Result:+{+ "ok": false,+ "code": "invalid-input",+ "message": "invalid-input: plan.tasks.0.executor.requirement: Required; plan.acceptance.0.producer: Required"+}diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.codenew file mode 100644index 0000000000..573541ac97--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.code@@ -0,0 +1 @@+0diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.errnew file mode 100644index 0000000000..c777688a6f--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.err@@ -0,0 +1 @@+[INFO] Executing tool: task_canceldiff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.outnew file mode 100644index 0000000000..8617cb9667--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.out@@ -0,0 +1,10 @@+ Parameters: {"taskId":"task-0-none","reason":"capture"}++[OK] Tool executed in 8.48ms++Result:+{+ "success": false,+ "taskId": "task-0-none",+ "error": "Task not found"+}diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.codenew file mode 100644index 0000000000..573541ac97--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.code@@ -0,0 +1 @@+0diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.errnew file mode 100644index 0000000000..c777688a6f--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.err@@ -0,0 +1 @@+[INFO] Executing tool: task_canceldiff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.outnew file mode 100644index 0000000000..fd632c0019--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.out@@ -0,0 +1,11 @@+ Parameters: {"taskId":"task-1791563600018-yl0nu9","reason":"capture"}++[OK] Tool executed in 7.44ms++Result:+{+ "success": true,+ "taskId": "task-1791563600018-yl0nu9",+ "status": "cancelled",+ "cancelledAt": "2026-10-09T16:34:02.808Z"+}diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.codenew file mode 100644index 0000000000..d00491fd7e--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.code@@ -0,0 +1 @@+1diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.errnew file mode 100644index 0000000000..537c8fa8c4--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.err@@ -0,0 +1,2 @@+[INFO] Executing tool: task_create+[ERROR] Tool execution failed: Failed to execute MCP tool 'task_create': policy-state-lock-timeoutdiff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.outnew file mode 100644index 0000000000..03627118d5--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.out@@ -0,0 +1 @@+ Parameters: {"type":"test","description":"x [ok}]"}diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.codenew file mode 100644index 0000000000..573541ac97--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.code@@ -0,0 +1 @@+0diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.errnew file mode 100644index 0000000000..7053616997--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.err@@ -0,0 +1 @@+[INFO] Executing tool: task_creatediff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.outnew file mode 100644index 0000000000..650ed4758b--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.out@@ -0,0 +1,15 @@+ Parameters: {"type":"test","description":"x"}++[OK] Tool executed in 6.83ms++Result:+{+ "taskId": "task-1791563600018-yl0nu9",+ "type": "test",+ "description": "x",+ "priority": "normal",+ "status": "pending",+ "createdAt": "2026-10-09T16:33:20.018Z",+ "assignedTo": [],+ "tags": []+}diff --git a/plugins/ruflo-console/tests/fixtures/mission-cli-real.ts b/plugins/ruflo-console/tests/fixtures/mission-cli-real.tsnew file mode 100644index 0000000000..23b2cf5460--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/mission-cli-real.ts@@ -0,0 +1,133 @@+/**+ * The fake `ruflo mcp exec` for the mission-create specs. Its output is REAL: tests/fixtures/mcp-exec holds transcripts captured from ruflo+ * 3.56.1 in a scratch project (the lock timeout induced by holding .claude-flow/policy/state.lock), and every answer here is one of them+ * with its Parameters line and its Result swapped for the call's: `Parameters:` on stdout before any `Result:`, `[INFO]`/`[ERROR]` on stderr.+ */+import { readFileSync } from 'node:fs'+import { join } from 'node:path'++import type { ActionSpec } from '../../hooks/actions'+import { PROJECT } from '../../hooks/data/files'+import type { Host } from '../../hooks/host'+import { READ_MS } from '../../hooks/mission-create'+import { createSpec, mcOf, setGoal } from '../../hooks/mission-control'+import { newState, type State } from '../../hooks/state'++export type Run = { exitCode: number; stdout: string; stderr: string }++const FIXTURES = join(__dirname, 'mcp-exec')+/** A transcript exactly as the CLI printed it. */+export const real = (name: string): Run => ({ stdout: readFileSync(join(FIXTURES, `${name}.out`), 'utf8'), stderr: readFileSync(join(FIXTURES, `${name}.err`), 'utf8'), exitCode: Number(readFileSync(join(FIXTURES, `${name}.code`), 'utf8').trim()) })++/** The real success transcript of `tool`, its Parameters line and its Result swapped for this call's (the layout byte for byte). */+export function answer(params: unknown, result: unknown, tool: string, base = real('t-ok')): Run {+ return {+ exitCode: 0,+ stdout: base.stdout.replace(/^( {2}Parameters: ).*$/m, `$1${JSON.stringify(params)}`).replace(/(\nResult:\n)[\s\S]*$/, `$1${JSON.stringify(result, null, 2)}\n`),+ stderr: base.stderr.replace(/task_create/g, tool),+ }+}++/** The real lock-timeout transcript for this call. */+export function locked(params: unknown, tool: string): Run {+ const base = real('t-lock')++ return { exitCode: base.exitCode, stdout: base.stdout.replace(/^( {2}Parameters: ).*$/m, `$1${JSON.stringify(params)}`), stderr: base.stderr.replace(/task_create/g, tool) }+}++export const ID = 'msn_0123456789abcdef01234567'+/** A try whose answer was lost: the process exited non-zero and printed nothing (transient). */+export const LOST: Run = { exitCode: 1, stdout: '', stderr: '' }+export const isOk = (result: Record<string, unknown>) => typeof result.taskId === 'string'++export type Store = Record<string, { taskId: string; type: string; description: string; status: string; tags: string[]; assignedTo: string[]; createdAt: string }>+export type World = { runs: { tool: string; params: Record<string, unknown> }[]; waits: number[]; store: Store; mission: string; onWait?: () => void; unreadable?: boolean }+export type Special = (tool: string, params: Record<string, unknown>, nth: number, world: World) => Run | Error | Promise<Run | undefined> | undefined++/** A CLI that answers in the real transcripts' layout; task_create writes the store the console reads back, the mission cancel the observation. */+export function hostOf(world: World, special: Special = () => undefined): Host {+ let made = 0+ const seen = new Map<string, number>()+ const make = (params: Record<string, unknown>, taskId = `task-${++made}`) => {+ world.store[taskId] = { taskId, type: String(params.type), description: String(params.description), status: 'pending', tags: params.tags as string[], assignedTo: [], createdAt: new Date().toISOString() }++ return taskId+ }++ return {+ run: async (argv: readonly string[]) => {+ const tool = argv[argv.indexOf('-t') + 1] as string+ const params = JSON.parse(argv[argv.indexOf('-p') + 1] as string) as Record<string, unknown>+ const key = tool === 'task_create' ? `${tool}:${String((params.tags as string[])[1])}` : tool === 'task_cancel' ? `${tool}:${String(params.taskId)}` : tool+ const nth = (seen.get(key) ?? 0) + 1++ seen.set(key, nth)+ world.runs.push({ tool, params })++ const out = await special(tool, params, nth, world)++ if (out instanceof Error) throw out+ if (out !== undefined) return out+ if (tool === 'mission_create') return answer(params, { ok: true, data: { missionId: ID, revision: 1, state: 'draft', deduplicated: false } }, tool, real('m-create'))+ if (tool === 'mission_plan') return answer(params, { ok: true, data: { missionId: ID, revision: 2, state: 'planned', deduplicated: false, sequence: 2, planDigest: 'sha256:abc' } }, tool, real('m-plan-ok'))+ if (tool === 'task_create') {+ const taskId = make(params)++ return answer(params, { ...world.store[taskId], priority: 'normal' }, tool)+ }+ if (tool === 'task_cancel') {+ const task = world.store[String(params.taskId)]++ if (task === undefined) return answer(params, { success: false, taskId: params.taskId, error: 'Task not found' }, tool, real('t-cancel-missing'))+ task.status = 'cancelled'++ return answer(params, { success: true, taskId: params.taskId, status: 'cancelled', cancelledAt: new Date().toISOString() }, tool, real('t-cancel'))+ }+ if (tool === 'mission_request_action') {+ world.mission = 'cancelled'++ return answer(params, { ok: true, data: { missionId: ID, revision: 4, state: 'cancelled', deduplicated: false, sequence: 4 } }, tool, real('m-cancel-ok'))+ }++ return answer(params, { ok: true }, tool)+ },+ fs: {+ read: async (path: string) => {+ if (world.unreadable === true) throw new Error('EACCES')+ if (path.endsWith(PROJECT.tasks)) return JSON.stringify({ tasks: world.store, version: '3.0.0' })+ if (path.endsWith(PROJECT.missions)) return JSON.stringify({ schemaVersion: 1, contract: 'ruflo.mission-observation/1', source: 'ruflo-cli/missions', observedAt: new Date().toISOString(), truncated: false, missions: [{ missionId: ID, objective: 'x', state: world.mission, revision: 4, executionMode: 'session-bound' }] })++ throw new Error('ENOENT')+ },+ stat: async () => undefined,+ list: async () => [],+ },+ // The backoff waits go through the host's clock: recorded, and they return at once (after the test's hook). Read time limits never fire.+ after: (ms: number, fn: () => void) => {+ if (ms === READ_MS) return { cancel: () => undefined }+ world.waits.push(ms)+ world.onWait?.()+ fn()++ return { cancel: () => undefined }+ },+ storeGet: async () => undefined,+ storeSet: async () => undefined,+ invalidate: () => undefined,+ } as unknown as Host+}++export const fresh = (): World => ({ runs: [], waits: [], store: {}, mission: 'planned' })++export function planned(): { state: State; steps: string[] } {+ const state = newState({})++ state.snapshot = { tasks: [], agents: [], claims: [], swarm: null, plugins: { missingFromClone: [] }, alerts: [] } as never+ setGoal(state, 'add a dark mode toggle to settings')++ return { state, steps: (mcOf(state).planned?.steps ?? []).map(step => step.id) }+}++export const creates = (world: World, step?: string) => world.runs.filter(run => run.tool === 'task_create' && (step === undefined || (run.params.tags as string[]).includes(`task:${step}`)))+export const isStep = (params: Record<string, unknown>, step: string | undefined) => (params.tags as string[] | undefined)?.includes(`task:${step}`) === true+export const run = async (state: State, host: Host) => (createSpec(state, host, () => undefined) as ActionSpec).run?.()diff --git a/plugins/ruflo-console/tests/mission-create-retry.spec.ts b/plugins/ruflo-console/tests/mission-create-retry.spec.tsnew file mode 100644index 0000000000..a3d050e041--- /dev/null+++ b/plugins/ruflo-console/tests/mission-create-retry.spec.ts@@ -0,0 +1,277 @@+/**+ * Creating a mission on a busy project: every `mcp exec` takes the policy state lock, and on a large policy state some calls time out on it+ * (#3164, #3892). The CLI output here is REAL: tests/fixtures/mcp-exec holds `ruflo mcp exec` transcripts captured from ruflo 3.56.1 in a+ * scratch project (the lock timeout induced by holding .claude-flow/policy/state.lock), and the fake CLI (tests/fixtures/mission-cli-real.ts) answers in exactly that+ * shape: `Parameters:` on stdout before any `Result:`, `[INFO]`/`[ERROR]` on stderr.+ * npx vitest run plugins/ruflo-console/tests/mission-create-retry.spec.ts+ */+import { afterEach, describe, expect, it, vi } from 'vitest'++import type { ActionSpec } from '../hooks/actions'+import { readAttempt, resultOf } from '../hooks/data/mcp-run'+import { CREATE_DEADLINE_MS, RETRY_WAITS_MS } from '../hooks/mission-create'+import { activeMission, createSpec, mcOf } from '../hooks/mission-control'+import { answer, creates, fresh, hostOf, ID, isOk, isStep, locked, LOST, planned, real, run } from './fixtures/mission-cli-real'++afterEach(() => vi.useRealTimers())++describe('reading one real mcp exec run', () => {+ it('a real lock timeout: the Parameters object before it is not read as an answer, and it is transient', () => {+ const run = real('t-lock')++ expect(run.stdout).toContain('Parameters: {')+ expect(run.stdout).not.toContain('Result:')+ expect(resultOf(run.stdout)).toBeNull()+ expect(readAttempt(run, isOk)).toEqual({ result: null, ok: false, transient: true, reason: 'policy-state-lock-timeout' })++ // The live case: a description with no bracket in it, so the Parameters object is valid JSON (it must still not be the answer).+ const live = locked({ type: 'feature', description: `[${ID}/t5] Implement`, priority: 'normal', tags: [`mission:${ID}`, 'task:t5'] }, 'task_create')++ expect(resultOf(live.stdout)).toBeNull()+ expect(readAttempt(live, isOk).transient).toBe(true)+ })++ it('a real success is read after its own Result line; a description holding } and "Result:" does not confuse it', () => {+ expect(readAttempt(real('t-ok'), isOk)).toMatchObject({ ok: true, transient: false, result: { taskId: 'task-1791563600018-yl0nu9' } })++ const tricky = { type: 'test', description: 'x [ok}] Result: {"taskId":"fake"}' }+ const run = answer(tricky, { taskId: 'task-9', description: tricky.description, tags: [] }, 'task_create')++ expect(readAttempt(run, isOk)).toMatchObject({ ok: true, result: { taskId: 'task-9', description: tricky.description } })+ })++ it('definite answers are never transient: a refusal in the answer, a policy denial that mentions a timeout, a command that cannot start', () => {+ expect(readAttempt(real('t-cancel-missing'), result => result.success === true)).toMatchObject({ ok: false, transient: false, reason: 'Task not found' })+ expect(readAttempt(real('m-plan'), result => result.ok === true)).toMatchObject({ ok: false, transient: false })+ expect(readAttempt(real('m-plan'), result => result.ok === true).reason).toContain('invalid-input')++ // The denial format of mcp-client.ts (`policy-<outcome>:<reason>; receipt=<id>`) in the real failure layout; a denial was not induced live.+ const denial = { ...real('t-lock'), stderr: real('t-lock').stderr.replace('policy-state-lock-timeout', 'policy-denied:task.create is limited; retry after the rate timeout window; receipt=r1') }++ expect(readAttempt(denial, isOk)).toMatchObject({ ok: false, transient: false })+ expect(readAttempt(denial, isOk).reason).toContain('policy-denied')+ expect(readAttempt({ error: new Error('spawn ruflo ENOENT') }, isOk)).toMatchObject({ transient: false })+ // A rejection of the host is never transient, whatever its words; only the caller's own (structured) time limit is.+ expect(readAttempt({ error: new Error('still running after 60000 ms') }, isOk)).toMatchObject({ transient: false })+ expect(readAttempt({ error: new Error('permission denied: timed out waiting for approval') }, isOk)).toMatchObject({ transient: false })+ expect(readAttempt({ timedOutMs: 60_000 }, isOk)).toMatchObject({ transient: true })+ expect(readAttempt({ timedOutMs: 60_000 }, isOk).reason).toContain('may still finish')+ // Truly empty output with a failing exit is transient; any output (a shell's "command not found", housekeeping only) is not.+ expect(readAttempt({ exitCode: 1, stdout: '', stderr: '' }, isOk)).toMatchObject({ transient: true, reason: 'no answer (exit 1)' })+ expect(readAttempt({ exitCode: 127, stdout: '', stderr: 'zsh: command not found: ruflo\n' }, isOk)).toMatchObject({ transient: false, reason: 'zsh: command not found: ruflo' })+ expect(readAttempt({ exitCode: 1, stdout: ' Parameters: {"a":1}\n', stderr: '[INFO] Executing tool: task_create\n' }, isOk)).toMatchObject({ transient: false })+ })+})+++describe('mission create on a busy project', () => {+ it('a real lock timeout on one step is tried again after the first wait: the mission is created with all 15 tasks', async () => {+ const { state, steps } = planned()+ const world = fresh()+ const host = hostOf(world, (tool, params, nth) => (tool === 'task_create' && isStep(params, steps[4]) && nth === 1 ? locked(params, tool) : undefined))++ expect(steps).toHaveLength(15)+ await run(state, host)++ expect(mcOf(state).last).toMatchObject({ ok: true, label: `mission ${ID} planned` })+ expect(activeMission(state)?.tasks).toHaveLength(15)+ expect(creates(world, steps[4])).toHaveLength(2)+ expect(world.waits).toEqual([RETRY_WAITS_MS[0]])+ expect(Object.keys(world.store)).toHaveLength(15)+ expect(world.runs.some(entry => entry.tool === 'task_cancel' || entry.tool === 'mission_request_action')).toBe(false)+ })++ it('a create that timed out but wrote during the backoff is found after the wait and not made twice', async () => {+ const { state, steps } = planned()+ const world = fresh()+ let late: Record<string, unknown> | null = null+ const host = hostOf(world, (tool, params, nth) => {+ if (tool !== 'task_create' || !isStep(params, steps[2]) || nth !== 1) return undefined+ late = params++ return LOST+ })++ // The slow CLI finishes its write while the console waits.+ world.onWait = () => {+ if (late !== null && world.store['task-late'] === undefined) world.store['task-late'] = { taskId: 'task-late', type: 'feature', description: String(late.description), status: 'pending', tags: late.tags as string[], assignedTo: [], createdAt: new Date().toISOString() }+ }+ await run(state, host)++ expect(mcOf(state).last?.ok).toBe(true)+ expect(creates(world, steps[2])).toHaveLength(1)+ expect(activeMission(state)?.tasks.find(task => task.id === steps[2])?.rufloTaskId).toBe('task-late')+ expect(Object.keys(world.store)).toHaveLength(15)+ })++ it('two tasks in the store that both match the step stop the create: it reports them and does not guess', async () => {+ const { state, steps } = planned()+ const world = fresh()+ const host = hostOf(world, (tool, params, nth, w) => {+ if (tool !== 'task_create' || !isStep(params, steps[1]) || nth !== 1) return undefined+ for (const taskId of ['task-a', 'task-b']) w.store[taskId] = { taskId, type: 'feature', description: String(params.description), status: 'pending', tags: params.tags as string[], assignedTo: [], createdAt: new Date().toISOString() }++ return LOST+ })++ await run(state, host)++ expect(creates(world, steps[1])).toHaveLength(1)+ expect(mcOf(state).last?.ok).toBe(false)+ expect(mcOf(state).last?.lines?.[0]).toContain('2 tasks in the store match')+ expect(mcOf(state).last?.lines?.[0]).toContain('task-a, task-b')+ expect(activeMission(state)).toBeNull()+ })++ it('a store that cannot be read stops a retry whose first try may have written', async () => {+ const { state, steps } = planned()+ const world = fresh()+ const host = hostOf(world, (tool, params, nth, w) => {+ if (tool !== 'task_create' || !isStep(params, steps[0]) || nth !== 1) return undefined+ w.unreadable = true++ return LOST+ })++ await run(state, host)++ expect(creates(world)).toHaveLength(1)+ expect(mcOf(state).last?.lines?.[0]).toContain('the task store could not be read')+ })++ it('a denial that mentions a timeout is not tried again', async () => {+ const { state, steps } = planned()+ const world = fresh()+ const host = hostOf(world, (tool, params) => (tool === 'task_create' && isStep(params, steps[1]) ? { ...locked(params, tool), stderr: locked(params, tool).stderr.replace('policy-state-lock-timeout', 'policy-denied:retry after the rate timeout window; receipt=r1') } : undefined))++ await run(state, host)++ expect(creates(world, steps[1])).toHaveLength(1)+ expect(world.waits).toEqual([])+ expect(mcOf(state).last?.detail).toContain('policy-denied')+ })++ it('a step that keeps timing out on the lock aborts: cancels retried, the store and the mission READ BACK, the pending id named', async () => {+ const { state, steps } = planned()+ const world = fresh()+ const host = hostOf(world, (tool, params, nth) => {+ if (tool === 'task_create' && isStep(params, steps[5])) return locked(params, tool)+ if (tool === 'task_cancel' && params.taskId === 'task-2' && nth === 1) return locked(params, tool)+ if (tool === 'task_cancel' && params.taskId === 'task-4') return locked(params, tool)++ return undefined+ })++ await run(state, host)++ const last = mcOf(state).last+ const asked = world.runs.filter(entry => entry.tool === 'mission_request_action')++ expect(creates(world, steps[5])).toHaveLength(1 + RETRY_WAITS_MS.length)+ expect(creates(world)).toHaveLength(5 + 1 + RETRY_WAITS_MS.length)+ expect(world.runs.filter(entry => entry.tool === 'task_cancel' && entry.params.taskId === 'task-2')).toHaveLength(2)+ expect(world.runs.filter(entry => entry.tool === 'task_cancel' && entry.params.taskId === 'task-4')).toHaveLength(1 + RETRY_WAITS_MS.length)+ expect(asked).toHaveLength(1)+ expect(asked[0]?.params).toMatchObject({ missionId: ID, action: 'cancel', expectedRevision: 2 })+ expect(last?.ok).toBe(false)+ expect(last?.label).toBe(`mission not created: task ${steps[5]} could not be made`)+ expect(last?.lines?.[0]).toBe(`task ${steps[5]}: policy-state-lock-timeout (${1 + RETRY_WAITS_MS.length} tries)`)+ expect(last?.lines?.[1]).toBe('the store shows 4 of the 5 tasks of this mission cancelled; 1 not cancelled: task-4 (pending)')+ expect(last?.lines?.[2]).toBe(`mission ${ID}: cancel accepted; the observation shows cancelled`)+ expect(last?.detail).toContain('Store: 4 of 5 cancelled, 1 not')+ expect(world.store['task-4']?.status).toBe('pending')+ })++ it('an acknowledged cancel that did not land is reported as the store shows it, not as acknowledged', async () => {+ const { state, steps } = planned()+ const world = fresh()+ const host = hostOf(world, (tool, params) => {+ if (tool === 'task_create' && isStep(params, steps[2])) return answer(params, { success: false, error: 'invalid type' }, tool)+ // The CLI answers success for task-1, but the store never changed (ack lost / write lost).+ if (tool === 'task_cancel' && params.taskId === 'task-1') return answer(params, { success: true, taskId: 'task-1', status: 'cancelled' }, tool, real('t-cancel'))++ return undefined+ })++ await run(state, host)++ expect(mcOf(state).last?.lines?.[1]).toBe('the store shows 1 of the 2 tasks of this mission cancelled; 1 not cancelled: task-1 (pending)')+ })++ it('a refused plan cancels the mission that was already created, at the created revision', async () => {+ const { state } = planned()+ const world = fresh()+ const refused = real('m-plan')+ const host = hostOf(world, tool => (tool === 'mission_plan' ? refused : undefined))++ await run(state, host)++ const asked = world.runs.filter(entry => entry.tool === 'mission_request_action')++ expect(creates(world)).toHaveLength(0)+ expect(asked).toHaveLength(1)+ expect(asked[0]?.params).toMatchObject({ missionId: ID, action: 'cancel', expectedRevision: 1 })+ expect(mcOf(state).last?.label).toBe('mission not created: mission_plan failed')+ expect(mcOf(state).last?.lines?.[0]).toContain('invalid-input')+ expect(mcOf(state).last?.lines?.[2]).toBe(`mission ${ID}: cancel accepted; the observation shows cancelled`)+ })++ it('a revision conflict on the mission cancel is asked once more at the revision it names', async () => {+ const { state } = planned()+ const world = fresh()+ const conflict = real('m-cancel')+ const host = hostOf(world, (tool, params, nth) => (tool === 'mission_plan' ? real('m-plan') : tool === 'mission_request_action' && nth === 1 ? { ...conflict, stdout: conflict.stdout.replace('"currentRevision": 1', '"currentRevision": 3') } : undefined))++ await run(state, host)++ const asked = world.runs.filter(entry => entry.tool === 'mission_request_action')++ expect(asked.map(entry => entry.params.expectedRevision)).toEqual([1, 3])+ expect(new Set(asked.map(entry => entry.params.requestId)).size).toBe(2)+ })++ it('a second create while one runs is refused; request ids are unique per create', async () => {+ const { state } = planned()+ const world = fresh()+ let release: () => void = () => undefined+ const gate = new Promise<void>(resolve => (release = resolve))+ const host = hostOf(world, async (tool, params, nth) => {+ if (tool === 'mission_create' && nth === 1) await gate++ return undefined+ })+ const first = createSpec(state, host, () => undefined) as ActionSpec+ const second = createSpec(state, host, () => undefined) as ActionSpec+ const running = first.run?.()++ await Promise.resolve()++ const refused = await second.run?.()++ expect(refused).toMatchObject({ ok: false, label: 'not created' })+ expect(refused?.detail).toContain('already being created')+ release()+ await running+ expect(mcOf(state).last?.ok).toBe(true)+ expect(world.runs.filter(entry => entry.tool === 'mission_create')).toHaveLength(1)+ expect(first.argv?.join(' ')).not.toBe(second.argv?.join(' '))+ })++ it('the create stops at its deadline and undoes what it made', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })++ const { state } = planned()+ const world = fresh()+ // Each task_create takes 40 s of the clock.+ const host = hostOf(world, tool => void (tool === 'task_create' && vi.setSystemTime(Date.now() + 40_000)))++ await run(state, host)++ const made = Math.ceil(CREATE_DEADLINE_MS / 40_000)++ expect(creates(world)).toHaveLength(made)+ expect(mcOf(state).last?.label).toContain('out of time')+ expect(mcOf(state).last?.lines?.[1]).toBe(`the store shows ${made} of the ${made} tasks of this mission cancelled`)+ })+})+diff --git a/plugins/ruflo-console/tests/mission-create-time.spec.ts b/plugins/ruflo-console/tests/mission-create-time.spec.tsnew file mode 100644index 0000000000..cbf7032ba7--- /dev/null+++ b/plugins/ruflo-console/tests/mission-create-time.spec.ts@@ -0,0 +1,248 @@+/**+ * Mission create under lost answers and strict time, what counts as transient, and how the outcome of a long run (and of an ADR page write)+ * reaches console_state's lastResult. The CLI output is the real transcripts' (tests/fixtures/mission-cli-real.ts).+ * npx vitest run plugins/ruflo-console/tests/mission-create-time.spec.ts+ */+import { existsSync, readFileSync } from 'node:fs'+import { join } from 'node:path'++import { afterEach, describe, expect, it, vi } from 'vitest'++import type { ActionSpec } from '../hooks/actions'+import { adrOf, proposeSpec } from '../hooks/adr'+import type { Host } from '../hooks/host'+import { CALL_MS, CLEANUP_BUDGET_MS, CREATE_DEADLINE_MS, isCreating, RETRY_WAITS_MS } from '../hooks/mission-create'+import { activeMission, createSpec, mcOf } from '../hooks/mission-control'+import { callTool } from '../hooks/model-tools'+import { createRunner } from '../hooks/runner'+import type { State } from '../hooks/state'+import { cleanAfter, loaded, TODAY } from './adr-helpers'+import { setup } from './fixtures/control-setup'+import { creates, fresh, hostOf, ID, isStep, locked, LOST, planned, run } from './fixtures/mission-cli-real'+import { useNativeWriteFlavor } from './fixtures/write-flavor'++cleanAfter()+afterEach(() => vi.useRealTimers())++describe('lost answers, strict time, and what counts as transient', () => {+ it('the last try writes and its answer is lost: a final store read finds it, so the mission is created without a duplicate', async () => {+ const { state, steps } = planned()+ const world = fresh()+ const host = hostOf(world, (tool, params, nth, w) => {+ if (tool !== 'task_create' || !isStep(params, steps[3])) return undefined+ if (nth <= RETRY_WAITS_MS.length) return locked(params, tool)+ // The last try writes the task, then its answer is lost.+ w.store['task-lost'] = { taskId: 'task-lost', type: 'feature', description: String(params.description), status: 'pending', tags: params.tags as string[], assignedTo: [], createdAt: new Date().toISOString() }++ return LOST+ })++ await run(state, host)++ expect(creates(world, steps[3])).toHaveLength(1 + RETRY_WAITS_MS.length)+ expect(mcOf(state).last?.ok).toBe(true)+ expect(activeMission(state)?.tasks.find(task => task.id === steps[3])?.rufloTaskId).toBe('task-lost')+ expect(Object.keys(world.store)).toHaveLength(15)+ })++ it('cleanup cancels every open task of the mission in the store, not only the acknowledged ones', async () => {+ const { state, steps } = planned()+ const world = fresh()+ const host = hostOf(world, (tool, params, nth, w) => {+ if (tool !== 'task_create' || !isStep(params, steps[1]) || nth !== 1) return undefined+ for (const taskId of ['task-a', 'task-b']) w.store[taskId] = { taskId, type: 'feature', description: String(params.description), status: 'pending', tags: params.tags as string[], assignedTo: [], createdAt: new Date().toISOString() }++ return LOST+ })++ await run(state, host)++ const cancelled = world.runs.filter(entry => entry.tool === 'task_cancel').map(entry => entry.params.taskId)++ expect(cancelled).toEqual(expect.arrayContaining(['task-1', 'task-a', 'task-b']))+ expect(mcOf(state).last?.lines?.[1]).toBe('the store shows 3 of the 3 tasks of this mission cancelled')+ expect(Object.values(world.store).every(task => task.status === 'cancelled')).toBe(true)+ })++ it('a store task stamped before the console started (clock skew) is still this step\'s late success: no duplicate', async () => {+ const { state, steps } = planned()+ const world = fresh()+ const skewed = new Date(Date.now() - 2_000).toISOString()+ const host = hostOf(world, (tool, params, nth, w) => {+ if (tool !== 'task_create' || !isStep(params, steps[0]) || nth !== 1) return undefined+ w.store['task-skew'] = { taskId: 'task-skew', type: 'feature', description: String(params.description), status: 'pending', tags: params.tags as string[], assignedTo: [], createdAt: skewed }++ return LOST+ })++ await run(state, host)++ expect(creates(world, steps[0])).toHaveLength(1)+ expect(activeMission(state)?.tasks[0]?.rufloTaskId).toBe('task-skew')+ expect(Object.keys(world.store)).toHaveLength(15)+ })++ it('a CLI that is not there is not retried', async () => {+ const { state } = planned()+ const world = fresh()+ const host = hostOf(world, () => ({ exitCode: 127, stdout: '', stderr: 'zsh: command not found: ruflo\n' }))++ await run(state, host)++ expect(world.runs).toHaveLength(1)+ expect(world.waits).toEqual([])+ expect(mcOf(state).last?.detail).toContain('command not found')+ })++ it('a host rejection that mentions a timeout (an approval that timed out) is not retried', async () => {+ const { state } = planned()+ const world = fresh()+ const host = hostOf(world, () => new Error('permission denied: timed out waiting for approval'))++ await run(state, host)++ expect(world.runs).toHaveLength(1)+ expect(world.waits).toEqual([])+ })++ it('no call starts after its deadline: cleanup stops at its own and names what it left', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })++ const { state } = planned()+ const world = fresh()+ const t0 = Date.now()+ const starts: { tool: string; atMs: number }[] = []+ // Each task_create takes 40 s of the clock, each task_cancel 50 s.+ const host = hostOf(world, tool => {+ starts.push({ tool, atMs: Date.now() - t0 })+ if (tool === 'task_create') vi.setSystemTime(Date.now() + 40_000)+ if (tool === 'task_cancel') vi.setSystemTime(Date.now() + 50_000)++ return undefined+ })++ await run(state, host)++ const cleanupEnd = CREATE_DEADLINE_MS + CLEANUP_BUDGET_MS++ expect(starts.filter(entry => entry.tool === 'task_create').every(entry => entry.atMs < CREATE_DEADLINE_MS)).toBe(true)+ expect(starts.every(entry => entry.atMs < cleanupEnd)).toBe(true)+ expect(starts.filter(entry => entry.tool === 'task_cancel')).toHaveLength(2)+ expect(starts.some(entry => entry.tool === 'mission_request_action')).toBe(false)+ expect(mcOf(state).last?.lines?.join('\n')).toContain('out of cleanup time: not asked to cancel task-3, task-4, task-5')+ })++ it('a call the host never answers is let go at the time left: the create ends, the guard is released, the report says it may still finish', async () => {+ vi.useFakeTimers()++ const { state, steps } = planned()+ const world = fresh()+ const host = hostOf(world, (tool, params) => (tool === 'task_create' && isStep(params, steps[0]) ? new Promise<undefined>(() => undefined) : undefined))+ let settled = false+ const running = run(state, host).then(() => (settled = true))++ for (let i = 0; i < 40 && !settled; i++) await vi.advanceTimersByTimeAsync(CALL_MS)+ await running++ expect(settled).toBe(true)+ expect(isCreating(state)).toBe(false)+ expect(mcOf(state).last?.ok).toBe(false)+ expect(mcOf(state).last?.lines?.[0]).toContain('the CLI process may still finish')+ expect(world.runs.filter(entry => entry.tool === 'mission_request_action')).toHaveLength(1)+ })+})++/** Asks for `spec` through the real runner, says yes, waits for its own run, then reads lastResult as console_state hands it to Claude. */+async function lastResultAfter(state: State, host: Host, spec: ActionSpec, meanwhile?: () => void): Promise<{ label: string; ok: boolean; detail: string; lines: string[] } | null> {+ const runner = createRunner(state, host, { freshRead: async () => undefined, setView: () => undefined, drill: () => undefined, command: () => undefined })+ const { deps } = setup('read')++ // An older, unrelated result sits in the slot, as it did live.+ state.outcome = { label: 'an older read', ok: true, verified: 'n/a', detail: 'unrelated', atMs: Date.now() - 1_000 }+ runner.ask(spec, '')+ await runner.confirm()+ meanwhile?.()+ await runner.finished()+ // The stub snapshot is not a full one: the screen text console_state also builds reads the disk as not read yet.+ state.snapshot = null++ const text = await callTool('console_state', {}, { ...deps, state })++ if (!text.startsWith('{')) throw new Error(text)++ return (JSON.parse(text) as { lastResult: { label: string; ok: boolean; detail: string; lines: string[] } | null }).lastResult+}++describe('the outcome of a long or page action reaches lastResult', () => {+ it('mission create: an abort, with the CLI reason and the read-back', async () => {+ const { state, steps } = planned()+ const world = fresh()+ const host = hostOf(world, (tool, params) => (tool === 'task_create' && isStep(params, steps[3]) ? locked(params, tool) : undefined))+ const result = await lastResultAfter(state, host, createSpec(state, host, () => undefined) as ActionSpec)++ expect(result?.ok).toBe(false)+ expect(result?.label).toBe(`mission not created: task ${steps[3]} could not be made`)+ expect(result?.lines.join('\n')).toContain('policy-state-lock-timeout')+ expect(result?.lines.join('\n')).toContain('the store shows 3 of the 3 tasks of this mission cancelled')+ })++ it('mission create: a success', async () => {+ const { state } = planned()+ const host = hostOf(fresh())+ const result = await lastResultAfter(state, host, createSpec(state, host, () => undefined) as ActionSpec)++ expect(result).toMatchObject({ ok: true, label: `mission ${ID} planned` })+ })++ it('another action that reports in the same millisecond the run started is not overwritten by the run\'s late result', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })++ const { state } = planned()+ const host = hostOf(fresh())+ const result = await lastResultAfter(state, host, createSpec(state, host, () => undefined) as ActionSpec, () => {+ state.outcome = { label: 'another action', ok: true, verified: 'n/a', detail: 'same millisecond', atMs: Date.now() }+ })++ expect(result?.label).toBe('another action')+ })++ it('a late completion does not overwrite a newer outcome of another action; it goes to the Events feed', async () => {+ const { state } = planned()+ const host = hostOf(fresh())+ const result = await lastResultAfter(state, host, createSpec(state, host, () => undefined) as ActionSpec, () => {+ state.outcome = { label: 'another action', ok: true, verified: 'n/a', detail: 'newer', atMs: Date.now() + 5 }+ })++ expect(result?.label).toBe('another action')+ expect(state.events.some(event => event.text.includes(`mission ${ID} planned`) && event.text.includes('finished after a newer result'))).toBe(true)+ })++})++describe('the outcome of an ADR page write reaches lastResult', () => {+ // A real disk: the write argv is the one this machine's tools take, found the way the console finds it at session start.+ useNativeWriteFlavor()++ it('adr-propose on a real disk: ✓, and the file exists', async () => {+ const { root, state, world } = await loaded('nygard')+ const spec = proposeSpec(state, world.host as never, 'Cache reads', TODAY) as ActionSpec+ const target = /create (\S+)/.exec(spec.shows ?? '')?.[1] as string+ const result = await lastResultAfter(state, world.host as never, spec)++ expect(result).toMatchObject({ ok: true, label: 'propose ADR 4', detail: `created ${target}` })+ expect(existsSync(join(root, target))).toBe(true)+ expect(readFileSync(join(root, target), 'utf8')).toContain('Cache reads')+ })++ it('adr-propose: the write fails', async () => {+ const { state, world } = await loaded('nygard')+ // The write command fails, as it did live: the page said so, and console_run said "Ran: propose ADR 4".+ const host = { ...world.host, run: async () => ({ exitCode: 1, stdout: '', stderr: 'install: illegal option -- D' }) }+ const spec = proposeSpec(state, host as never, 'Cache reads', TODAY) as ActionSpec+ const result = await lastResultAfter(state, host as never, spec)++ expect(adrOf(state).last?.ok).toBe(false)+ expect(result).toMatchObject({ ok: false, label: 'propose ADR 4' })+ expect(result?.detail).toContain('the write failed (exit 1: install: illegal option -- D)')+ })+})