Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

fix(ruflo-console): control plane measured in an interactive session (ADR-471)

ruva6f35488dfed
diff --git a/plugins/ruflo-console/hooks/data/wf-control.ts b/plugins/ruflo-console/hooks/data/wf-control.ts
index 5feb865e17..4648e33a6a 100644
--- a/plugins/ruflo-console/hooks/data/wf-control.ts
+++ b/plugins/ruflo-console/hooks/data/wf-control.ts
@@ -1,13 +1,15 @@
/**
- * Stop, Message and Redirect for a running workflow run or agent (ADR-465). Pure: the run, the agent and the bridge in, `ActionSpec`s out.
- * Each spec goes through the page's confirm card, which shows the EXACT engine call; the call itself is `$.tool.call` (through the host's
- * `toolCall`), so the engine's permission check and dialog decide it, never this file. What the spike proved, and no more:
+ * Stop, Message and Redirect for a running workflow run or agent (ADR-465, measured in ADR-471). Pure: the run, the agent and the bridge in,
+ * `ActionSpec`s out. Each spec goes through the page's confirm card, which shows the EXACT engine call; the call itself is `$.tool.call`
+ * (through the host's `toolCall`), so the engine's permission check and dialog decide it, never this file. What an interactive session
+ * answered (Claude Code 2.1.289, 2026-10-06, evidence in ADR-471):
*
- * TaskStop verified on a real background agent (task_id = the agent's id): "Successfully stopped task", then status "killed".
- * For a workflow run's id, or the id of an agent inside a workflow run, no one has tried it: the engine's own answer is shown.
- * SendMessage verified only to QUEUE a message for a named or id-addressed background agent in this session
- * ("Message queued for delivery ... at its next tool round"). Delivery and being acted on are not verified.
- * Redirect the stop above (same proof), then the resume text prepared in the prompt box (never sent): two halves, said as two.
+ * TaskStop the WORKFLOW'S TASK id (the `taskId` of the Workflow tool's result, read from the session transcript) stops the whole run and
+ * its agents. The `wf_` run id and the id of an agent inside the run are answered "No task found": no single workflow agent can
+ * be stopped through the engine. (An Agent-tool agent is a different case, see ADR-471; this page never lists those.)
+ * SendMessage to a RUNNING workflow agent's id: delivered into that agent's own transcript within milliseconds and acted on. To a finished
+ * one: "could not be resumed". By its label: "not reachable".
+ * Redirect the run stop above, then the resume text prepared in the prompt box (never sent): two halves, said as two.
*
* A refusal (`deny`) is shown and nothing else is tried: no other route is used to do what the engine would not. A failed or unreachable
* call keeps the person's choice: the same words as a prepared prompt are one button away. Everything drawn is masked first.
@@ -23,8 +25,8 @@ import type { WfAgent, WfRun } from './workflows'
export type Bridge = Pick<Host, 'toolCall' | 'toolCheck'>
export type ControlKind = 'stop-agent' | 'stop-run' | 'message' | 'redirect' | 'text'
-/** How much of the path is known: what the spike showed, or what nobody has tried. */
-export type Proof = 'verified' | 'queued-only' | 'unverified' | 'prefill'
+/** What was measured: it worked, the engine refuses it, or nothing is called (the text is only prepared). */
+export type Proof = 'verified' | 'does-not-work' | 'prefill'
export type ControlAction = {
id: ControlKind
@@ -39,9 +41,14 @@ export type ControlAction = {
why: string
}
+/** Where a run's task id stands: found in the session transcript, or why not (still being read, no transcript, not in it). */
+export type TaskRef = { id: string } | { why: string }
+
export type ControlInput = {
run: WfRun
agent: WfAgent | null
+ /** The Workflow tool's task id for the run (TaskStop takes this, not the `wf_` run id): read from the session transcript by the view. */
+ task: TaskRef
/** The sentence typed for Message and Redirect. */
text: string
bridge: Bridge & Pick<Host, 'fillPrompt'>
@@ -59,6 +66,37 @@ export const controlLine = (isOn: boolean): string => (isOn ? 'Stop, message and
/** An id the engine hands out is letters, digits, dash and underscore; anything else is not passed to a tool. */
export const ENGINE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{5,63}$/
+/** Which build and day the capability words below were measured on (ADR-471). */
+export const MEASURED = { version: '2.1.289', date: '2026-10-06' } as const
+const AT = `Claude Code ${MEASURED.version}, ${MEASURED.date}`
+
+const RUN_ID = /^wf_[A-Za-z0-9-]{1,40}$/
+
+/** The text a task-id search looks for in the session transcript: the Workflow tool's launch result carries its `taskId` and `runId` together. */
+export const taskPattern = (runId: string): string => `"taskId":"[A-Za-z0-9]{6,40}","taskType":"local_workflow"[^}]{0,600}"runId":"${runId}"`
+
+/**
+ * The Workflow task id of a run in the text of its session transcript (or of a search's matching lines); null when it is not there. A RESUMED
+ * run keeps its run id and gets a new task id (measured: `resumeFromRunId` answered the same runId with a different taskId), so the LAST launch wins.
+ */
+export function taskIdOf(text: string, runId: string): string | null {
+ if (!RUN_ID.test(runId)) return null
+
+ const hits = [...text.matchAll(new RegExp(taskPattern(runId), 'g'))]
+ const last = hits.at(-1)
+
+ return last === undefined ? null : (/"taskId":"([A-Za-z0-9]{6,40})"/.exec(last[0])?.[1] ?? null)
+}
+
+/** The session transcript that launched a run: the run's directory (`<session>/subagents/workflows/<run>`) without its tail, plus `.jsonl`. Null when the path is not a run path. */
+export function transcriptOf(run: Pick<WfRun, 'dir'>, isRunPath: (path: string) => boolean): string | null {
+ if (run.dir === undefined || !isRunPath(run.dir)) return null
+
+ const session = run.dir.replace(/\/subagents\/workflows\/[^/]+\/?$/, '')
+
+ return session === run.dir ? null : `${session}.jsonl`
+}
+
const CAP = 240
const stopCall = (id: string): string => `TaskStop ${JSON.stringify({ task_id: id })}`
const messageCall = (to: string, message: string): string => `SendMessage ${JSON.stringify({ to, message })}`
@@ -93,7 +131,7 @@ export function classifyReply(reply: ToolReply | undefined): Outcome {
return { ok: true, kind: 'done', text: said === '' ? 'the engine answered ok with no text' : said }
}
-const clean = (value: string): string => cleanText(plain(value, 400)).slice(0, CAP)
+const clean = (value: string): string => cleanText(plain(value.replace(/<\/?tool_use_error>/g, ''), 400)).slice(0, CAP)
/** Calls one tool and classifies the answer; a rejection (no such tool, aborted) is an error outcome, never thrown. */
export async function callTool(bridge: Bridge, input: { tool: string } & Record<string, unknown>): Promise<Outcome> {
@@ -168,9 +206,11 @@ function stopSpec(input: ControlInput, id: string, label: string, proofNote: str
}
}
+const STOP_AGENT_ANSWER = (id: string): string => `TaskStop {"task_id":"${id}"} is answered "No task found with ID: ${id}"`
+
/**
- * What the control tab offers for the cursor. Message and Redirect need the typed sentence; every action says what it sends, how far its
- * path is proven and what to do where it is not. A ruflo swarm agent is not a Claude task: its stop and notes are the page's own.
+ * What the control tab offers for the cursor. Message and Redirect need the typed sentence; every action says what it sends and what the
+ * engine answered when it was tried (ADR-471). A ruflo swarm agent is not a Claude task: its stop and notes are the page's own.
*/
export function controlActions(input: ControlInput): ControlAction[] {
const { run, agent, bridge } = input
@@ -183,33 +223,35 @@ export function controlActions(input: ControlInput): ControlAction[] {
return out
}
- const runId = ENGINE_ID.test(run.id) ? run.id : null
+ const taskId = 'id' in input.task && ENGINE_ID.test(input.task.id) ? input.task.id : null
+ const taskWhy = 'why' in input.task ? input.task.why : 'the run\'s task id is not one the engine can be given'
const agentId = agent !== null && ENGINE_ID.test(agent.id) ? agent.id : null
const wired = bridge.toolCall !== undefined
const typed = guardText(input.text, 300)
const resume = typed.ok ? resumeText(run, agent, typed.text, input.isRunPath) : null
+ const stopWhy = !wired ? 'this host does not bind tool calls: stop it in Claude Code\'s Workflows panel' : taskWhy
add({
id: 'stop-agent',
label: agent === null ? 'stop the agent' : `stop agent ${clean(agent.label).slice(0, 30)}`,
- proof: 'verified',
- proofText: 'TaskStop worked on a real background agent (task_id = its id; its status became killed). An agent inside a workflow run has not been tried: the engine says.',
- spec: !wired ? null : agentId === null ? null : stopSpec(input, agentId, `stop agent ${clean(agent?.label ?? agentId).slice(0, 40)}`, 'Proven on a background Agent-tool agent; for an agent of a workflow run the engine\'s answer is the proof.'),
- why: !wired ? 'this host does not bind tool calls: prepare the text instead' : agent === null ? 'pick an agent first (the cursor)' : 'that agent\'s id is not one the engine can be given',
+ proof: 'does-not-work',
+ proofText: `does not work: the engine stops a whole workflow run, not one agent of it. ${STOP_AGENT_ANSWER(agentId ?? '<agent id>')} (${AT}). Use "stop the whole run".`,
+ spec: null,
+ why: `the engine cannot stop one workflow agent: ${STOP_AGENT_ANSWER(agentId ?? '<agent id>')}; stop the whole run instead`,
})
add({
id: 'stop-run',
label: `stop the whole run ${clean(run.name).slice(0, 30)}`,
- proof: 'unverified',
- proofText: 'TaskStop with a workflow run\'s id was not tried in the spike. The call is real and permission-checked; the engine\'s answer, and the run read again, say whether it took.',
- spec: !wired || runId === null ? null : stopSpec(input, runId, `stop workflow run ${clean(run.name).slice(0, 40)}`, 'Not proven for a workflow run id: the engine may answer that no such task exists.'),
- why: !wired ? 'this host does not bind tool calls: stop it in Claude Code\'s Workflows panel' : 'that run\'s id is not one the engine can be given',
+ proof: 'verified',
+ proofText: `verified: TaskStop with the run's TASK id stopped the run and both of its agents mid-tool-call (${AT}). The wf_ run id is answered "No task found", so the task id is read from the session transcript.`,
+ spec: !wired || taskId === null ? null : stopSpec(input, taskId, `stop workflow run ${clean(run.name).slice(0, 40)}`, 'The id is the Workflow tool\'s task id for this run, read from the session transcript. A run started by another session is answered "No task found".'),
+ why: stopWhy,
})
if (!typed.ok) {
- add({ id: 'message', label: 'message the agent', proof: 'queued-only', proofText: 'SendMessage queued a message for a running named agent in this session; whether it was delivered and acted on was not verified.', spec: null, why: typed.why })
- add({ id: 'redirect', label: 'redirect: stop, then resume with guidance', proof: 'unverified', proofText: 'Half one is the stop (see above); half two is text prepared in your prompt box.', spec: null, why: typed.why })
+ add({ id: 'message', label: 'message the agent', proof: 'verified', proofText: MESSAGE_TEXT, spec: null, why: typed.why })
+ add({ id: 'redirect', label: 'redirect: stop, then resume with guidance', proof: 'verified', proofText: REDIRECT_TEXT, spec: null, why: typed.why })
return out
}
@@ -222,9 +264,9 @@ export function controlActions(input: ControlInput): ControlAction[] {
label: `message agent ${clean(agent?.label ?? to).slice(0, 40)}`,
args: [],
shows: messageCall(to, typed.text),
- expect: 'the engine answers that the message was queued',
+ expect: 'the engine answers that the message was sent to the agent',
declared: 'write',
- note: 'Calls the engine\'s SendMessage through the session\'s permission check. The spike showed it QUEUES a message at the agent\'s next tool round; it did not show the agent reads or acts on it. An agent that is not a running, reachable one is answered "not reachable" and nothing is sent.',
+ note: `Calls the engine's SendMessage through the session's permission check. Measured (${AT}): to a RUNNING workflow agent's id it lands in that agent's own transcript within milliseconds; the answer says "Resuming agent", and the agent may also show as a background agent. A finished or stopped agent is answered "could not be resumed: No transcript found"; its label is answered "not reachable". Whatever the agent then does (a tool needing approval) raises its own dialog.`,
run: async () => {
const verdict = await permissionOf(bridge, 'SendMessage', { to, message: typed.text })
@@ -232,22 +274,22 @@ export function controlActions(input: ControlInput): ControlAction[] {
const outcome = await callTool(bridge, { tool: 'SendMessage', to, message: typed.text, summary: typed.text.slice(0, 40) })
- input.report('message agent', outcome.ok, outcome.ok ? `${outcome.text} (queued is not delivered: the agent may never act on it)` : `${outcome.text}${outcome.kind === 'denied' ? ': nothing was sent and no other route is tried' : ' (use "prepare as text" to ask the main session to relay it)'}`)
+ input.report('message agent', outcome.ok, outcome.ok ? `${outcome.text} (the engine's words; it is delivered while the agent runs, and a finished agent is answered "could not be resumed")` : `${outcome.text}${outcome.kind === 'denied' ? ': nothing was sent and no other route is tried' : ' (use "prepare as text" to ask the main session to relay it)'}`)
},
}
- add({ id: 'message', label: agent === null ? 'message the agent' : `message ${clean(agent.label).slice(0, 30)}`, proof: 'queued-only', proofText: 'Queued for delivery at the agent\'s next tool round (verified on a named background agent); delivery and effect are not.', spec: messageSpec, why: !wired ? 'this host does not bind tool calls: prepare the text instead' : agent === null ? 'pick an agent first (the cursor)' : 'that agent\'s id is not one the engine can be given' })
+ add({ id: 'message', label: agent === null ? 'message the agent' : `message ${clean(agent.label).slice(0, 30)}`, proof: 'verified', proofText: MESSAGE_TEXT, spec: messageSpec, why: !wired ? 'this host does not bind tool calls: prepare the text instead' : agent === null ? 'pick an agent first (the cursor)' : 'that agent\'s id is not one the engine can be given' })
const redirectSpec: ActionSpec | null =
- !wired || runId === null || resume === null
+ !wired || taskId === null || resume === null
? null
- : stopSpec(input, runId, `redirect run ${clean(run.name).slice(0, 36)}: stop, then prepare the resume`, 'Half one of two: the stop. Half two prepares the resume text in your prompt box, only when the stop worked.', async () => {
+ : stopSpec(input, taskId, `redirect run ${clean(run.name).slice(0, 36)}: stop, then prepare the resume`, 'Half one of two: the stop. Half two prepares the resume text in your prompt box, only when the stop worked.', async () => {
const isFilled = await Promise.resolve(bridge.fillPrompt(resume)).catch(() => false)
return isFilled ? 'The resume text with your guidance is in the prompt box: press Enter there to resume.' : 'There is no prompt box to put the resume text in.'
})
- add({ id: 'redirect', label: 'redirect: stop, then resume with guidance', proof: 'unverified', proofText: 'Half one is the stop (TaskStop, proof as the run stop); half two is text prepared in your prompt box and never sent for you.', spec: redirectSpec === null ? null : { ...redirectSpec, shows: `${stopCall(runId ?? '')}, then into the prompt box: ${resume?.slice(0, 120) ?? ''}` }, why: !wired ? 'this host does not bind tool calls: prepare the text instead' : 'this run has no id the engine can be given' })
+ add({ id: 'redirect', label: 'redirect: stop, then resume with guidance', proof: 'verified', proofText: REDIRECT_TEXT, spec: redirectSpec === null ? null : { ...redirectSpec, shows: `${stopCall(taskId ?? '')}, then into the prompt box: ${resume?.slice(0, 120) ?? ''}` }, why: stopWhy })
const prompt = relayText(run, agent, typed.text)
@@ -255,3 +297,6 @@ export function controlActions(input: ControlInput): ControlAction[] {
return out
}
+
+const MESSAGE_TEXT = `verified: a message to a RUNNING workflow agent's id arrived in that agent's own transcript within ~30 ms and it began to act on it (${AT}). A finished agent: "could not be resumed". Its label: "not reachable".`
+const REDIRECT_TEXT = `verified: the stop (as "stop the whole run", ${AT}); the resume is only text prepared in your prompt box, never sent for you.`
diff --git a/plugins/ruflo-console/hooks/data/wf-convo.ts b/plugins/ruflo-console/hooks/data/wf-convo.ts
index 5241a073d3..16a0d33d6f 100644
--- a/plugins/ruflo-console/hooks/data/wf-convo.ts
+++ b/plugins/ruflo-console/hooks/data/wf-convo.ts
@@ -19,6 +19,8 @@ export type Msg = {
state: SendState | 'you' | 'received'
tokensIn?: number
tokensOut?: number
+ /** One figure with no in/out split (the codex CLI reports "tokens used" only). */
+ tokensTotal?: number
costUsd?: number
model?: string
}
@@ -83,14 +85,14 @@ export function addMessage(convo: Convo, target: string, entry: Omit<Msg, 'id'>)
/** Records what you sent and what came of it (the answer, the queue note or the reason it did not go). */
export function recordSend(convo: Convo, target: Target, body: string, result: SendResult, nowMs: number): void {
addMessage(convo, target.id, { atMs: nowMs, who: 'you', text: body, state: 'you' })
- addMessage(convo, target.id, { atMs: nowMs, who: 'target', text: result.text, state: result.state, ...(result.tokensIn !== undefined && { tokensIn: result.tokensIn }), ...(result.tokensOut !== undefined && { tokensOut: result.tokensOut }), ...(result.costUsd !== undefined && { costUsd: result.costUsd }), ...(result.model !== undefined && { model: result.model }) })
+ addMessage(convo, target.id, { atMs: nowMs, who: 'target', text: result.text, state: result.state, ...(result.tokensIn !== undefined && { tokensIn: result.tokensIn }), ...(result.tokensOut !== undefined && { tokensOut: result.tokensOut }), ...(result.tokensTotal !== undefined && { tokensTotal: result.tokensTotal }), ...(result.costUsd !== undefined && { costUsd: result.costUsd }), ...(result.model !== undefined && { model: result.model }) })
}
-export type Stats = { sent: number; answered: number; failed: number; tokensIn: number; tokensOut: number; usd: number | null; pricedAnswers: number }
+export type Stats = { sent: number; answered: number; failed: number; tokensIn: number; tokensOut: number; tokensTotal: number; usd: number | null; pricedAnswers: number }
/** Per-thread totals. USD sums only the answers whose provider reported one: `usd` is null when none did (n/a, not $0). */
export function statsOf(thread: Thread): Stats {
- const stats: Stats = { sent: 0, answered: 0, failed: 0, tokensIn: 0, tokensOut: 0, usd: null, pricedAnswers: 0 }
+ const stats: Stats = { sent: 0, answered: 0, failed: 0, tokensIn: 0, tokensOut: 0, tokensTotal: 0, usd: null, pricedAnswers: 0 }
for (const msg of thread.msgs) {
if (msg.who === 'you') stats.sent++
@@ -99,6 +101,7 @@ export function statsOf(thread: Thread): Stats {
stats.tokensIn += msg.tokensIn ?? 0
stats.tokensOut += msg.tokensOut ?? 0
+ stats.tokensTotal += msg.tokensTotal ?? 0
if (msg.costUsd !== undefined) {
stats.usd = (stats.usd ?? 0) + msg.costUsd
@@ -123,7 +126,7 @@ export function compareOf(convo: Convo, targets: readonly Target[]): CompareCell
label: target.label,
text: answer?.text ?? (askedAt < 0 ? 'not asked' : 'no answer yet'),
state: answer?.state ?? 'none',
- tokens: answer === undefined || (answer.tokensIn === undefined && answer.tokensOut === undefined) ? 'tokens n/a' : `${answer.tokensIn ?? '?'} in · ${answer.tokensOut ?? '?'} out`,
+ tokens: answer?.tokensTotal !== undefined && answer.tokensIn === undefined && answer.tokensOut === undefined ? `${answer.tokensTotal} total (no in/out split reported)` : answer === undefined || (answer.tokensIn === undefined && answer.tokensOut === undefined) ? 'tokens n/a' : `${answer.tokensIn ?? '?'} in · ${answer.tokensOut ?? '?'} out`,
usd: answer?.costUsd === undefined ? 'cost n/a' : `$${answer.costUsd.toFixed(4)} (billed, as the provider reported it)`,
}
})
@@ -151,7 +154,7 @@ export const transcriptName = (target: string, nowMs: number): string => `convo-
/** The thread as markdown, masked again here whatever the thread holds, and cut at the cap (the cut says how much was left out). */
export function transcriptMarkdown(thread: Thread, target: Target, nowMs: number): { text: string; isCut: boolean } {
const head = [`# Conversation with ${tidy(target.label, 80)}`, '', `Saved ${new Date(nowMs).toISOString()} by the ruflo console. Transport: ${target.transport}. ${target.leavesText}.`, thread.dropped > 0 ? `The ${thread.dropped} oldest messages were dropped by the ${MAX_MSGS}-message cap.` : '', '']
- const body = thread.msgs.map(msg => `**${msg.who === 'you' ? 'you' : tidy(target.label, 60)}** (${new Date(msg.atMs).toISOString()}, ${msg.state}${msg.tokensIn !== undefined || msg.tokensOut !== undefined ? `, ${msg.tokensIn ?? '?'} in / ${msg.tokensOut ?? '?'} out tokens` : ''}${msg.costUsd === undefined ? '' : `, $${msg.costUsd.toFixed(4)} billed`}):\n\n${tidy(msg.text, MAX_TEXT)}\n`)
+ const body = thread.msgs.map(msg => `**${msg.who === 'you' ? 'you' : tidy(target.label, 60)}** (${new Date(msg.atMs).toISOString()}, ${msg.state}${msg.tokensIn !== undefined || msg.tokensOut !== undefined ? `, ${msg.tokensIn ?? '?'} in / ${msg.tokensOut ?? '?'} out tokens` : msg.tokensTotal !== undefined ? `, ${msg.tokensTotal} tokens total` : ''}${msg.costUsd === undefined ? '' : `, $${msg.costUsd.toFixed(4)} billed`}):\n\n${tidy(msg.text, MAX_TEXT)}\n`)
const all = [...head, ...body].join('\n')
return all.length <= TRANSCRIPT_MAX ? { text: all, isCut: false } : { text: `${all.slice(0, TRANSCRIPT_MAX)}\n\n(cut at ${TRANSCRIPT_MAX} characters; ${all.length - TRANSCRIPT_MAX} more were not saved)\n`, isCut: true }
diff --git a/plugins/ruflo-console/hooks/data/wf-send.ts b/plugins/ruflo-console/hooks/data/wf-send.ts
index 26d397cc16..2a1b0edf4d 100644
--- a/plugins/ruflo-console/hooks/data/wf-send.ts
+++ b/plugins/ruflo-console/hooks/data/wf-send.ts
@@ -27,14 +27,15 @@ export type SendDeps = Pick<Host, 'toolCall' | 'toolCheck' | 'run' | 'httpSend'
export type SendState = 'reply' | 'queued' | 'sent' | 'error' | 'refused'
-export type SendResult = { ok: boolean; state: SendState; text: string; tokensIn?: number; tokensOut?: number; costUsd?: number; model?: string }
+/** `tokensTotal` is for a provider that reports one figure without a split (the codex CLI's "tokens used"). */
+export type SendResult = { ok: boolean; state: SendState; text: string; tokensIn?: number; tokensOut?: number; tokensTotal?: number; costUsd?: number; model?: string }
export type Payload = { shows: string; note: string }
const REPLY_CAP = 4000
const WAIT = { peer: 600_000, codex: 300_000, cli: 60_000, http: 120_000 }
-const err = (state: SendState, text: string): SendResult => ({ ok: false, state, text: tidy(text, 300) })
+const err = (state: SendState, text: string): SendResult => ({ ok: false, state, text: tidy(text, 300).trim() })
/** Text from outside: escapes and control characters out, credentials masked, capped. */
export const tidy = (value: string, max = REPLY_CAP): string => cleanText(value).slice(0, max)
@@ -71,7 +72,7 @@ export function payloadOf(target: Target, raw: string, deps: Pick<SendDeps, 'con
case 'prompt':
return done(`to Claude in this session, as a visible prompt: "${body}"`, 'Starts a turn of this session (billed as any turn is). Its answer is the next turn in the transcript.')
case 'send-message':
- return done(`SendMessage ${JSON.stringify({ to: target.ref, message: body })}`, 'The engine queues it for the agent\'s next tool round; delivery and effect are not verified.')
+ return done(`SendMessage ${JSON.stringify({ to: target.ref, message: body })}`, 'The engine puts it in the agent\'s inbox and delivers it when the agent\'s current turn ends (measured 161 and 165 s into a running agent\'s loop, Claude Code 2.1.289); the agent then acted on it within 2 s, and any tool it runs raises its own permission dialog.')
case 'hive': {
if (deps.hive === null) return { ok: false, why: 'there is no hive-mind to write to' }
@@ -151,7 +152,7 @@ export async function sendTo(deps: SendDeps, target: Target, raw: string): Promi
const outcome = await callTool(deps, { tool: 'SendMessage', to: target.ref, message: body, summary: body.slice(0, 40) })
- return outcome.ok ? { ok: true, state: 'queued', text: `${outcome.text} (queued is not delivered)` } : err(outcome.kind === 'denied' ? 'refused' : 'error', outcome.text)
+ return outcome.ok ? { ok: true, state: 'queued', text: `${outcome.text} (queued: it reaches the agent when its current turn ends)` } : err(outcome.kind === 'denied' ? 'refused' : 'error', outcome.text)
}
case 'hive': {
if (target.ref === 'propose') {
@@ -178,13 +179,13 @@ export async function sendTo(deps: SendDeps, target: Target, raw: string): Promi
case 'peer': {
const result = await deps.run(['bash', deps.helper, 'dispatch', target.ref, body, ...(deps.trustedPeers.has(target.ref) ? [] : ['--confirm'])], WAIT.peer).catch((error: unknown) => ({ exitCode: -1, stdout: '', stderr: error instanceof Error ? error.message : 'refused' }))
- return result.exitCode === 0 && result.stdout.trim() !== '' ? { ok: true, state: 'reply', text: tidy(result.stdout) } : err('error', result.stderr.trim() !== '' ? result.stderr : `the peer answered nothing (exit ${result.exitCode})`)
+ return result.exitCode === 0 && result.stdout.trim() !== '' ? { ok: true, state: 'reply', text: tidy(result.stdout).trim() } : err('error', result.stderr.trim() !== '' ? result.stderr : `the peer answered nothing (exit ${result.exitCode})`)
}
case 'codex': {
const result = await deps.run(['codex', 'exec', '-s', 'read-only', '--skip-git-repo-check', '--ephemeral', '-C', deps.cwd, '-'], WAIT.codex, body).catch((error: unknown) => ({ exitCode: -1, stdout: '', stderr: error instanceof Error ? error.message : 'refused' }))
const used = /tokens used\s*[:\n]\s*([\d,]+)/i.exec(result.stderr + result.stdout)?.[1]
- return result.exitCode === 0 && result.stdout.trim() !== '' ? { ok: true, state: 'reply', text: tidy(result.stdout), ...(used !== undefined && { tokensOut: Number(used.replace(/,/g, '')) }) } : err('error', result.stderr.trim() !== '' ? result.stderr : `codex answered nothing (exit ${result.exitCode})`)
+ return result.exitCode === 0 && result.stdout.trim() !== '' ? { ok: true, state: 'reply', text: tidy(result.stdout).trim(), ...(used !== undefined && { tokensTotal: Number(used.replace(/,/g, '')) }) } : err('error', result.stderr.trim() !== '' ? result.stderr : `codex answered nothing (exit ${result.exitCode})`)
}
case 'http': {
const endpoint = endpointOf(target, deps.config)
diff --git a/plugins/ruflo-console/hooks/data/wf-targets.ts b/plugins/ruflo-console/hooks/data/wf-targets.ts
index 977868717f..73718c22bf 100644
--- a/plugins/ruflo-console/hooks/data/wf-targets.ts
+++ b/plugins/ruflo-console/hooks/data/wf-targets.ts
@@ -148,7 +148,7 @@ export function targetsOf(input: TargetInput): Target[] {
for (const agent of input.agents.slice(0, 20)) {
const id = mention(agent.name)
- if (id !== '' && !out.some(held => held.id === id)) out.push({ id, label: `agent ${agent.name}`, transport: 'send-message', leaves: 'machine', leavesText: 'nothing: queued inside this session', cost: 'session-turn', costText: 'the agent\'s own next turn', arrival: 'none', arrivalText: 'queued for its next tool round; its answer is not routed back here', ref: agent.id })
+ if (id !== '' && !out.some(held => held.id === id)) out.push({ id, label: `agent ${agent.name}`, transport: 'send-message', leaves: 'machine', leavesText: 'nothing: queued inside this session', cost: 'session-turn', costText: 'the agent\'s own next turn', arrival: 'none', arrivalText: 'in its inbox at once, read when its current turn ends (minutes into a long turn); its answer is not routed back here', ref: agent.id })
}
if (input.hasHive) out.push({ id: 'hive', label: 'ruflo hive-mind', transport: 'hive', leaves: 'machine', leavesText: 'nothing: written to the hive\'s shared memory', cost: 'free', costText: 'no model call', arrival: 'none', arrivalText: 'appended to the hive memory; a worker sees it only if its own turn reads it (a proposal needs votes)', ref: 'hive' })
diff --git a/plugins/ruflo-console/hooks/data/wf-triage.ts b/plugins/ruflo-console/hooks/data/wf-triage.ts
index 9f6ce6eb06..bb7357e6a7 100644
--- a/plugins/ruflo-console/hooks/data/wf-triage.ts
+++ b/plugins/ruflo-console/hooks/data/wf-triage.ts
@@ -125,7 +125,7 @@ export function rerunText(run: WfRun, failed: readonly TriageItem[], hasJournal:
const list = (items: readonly TriageItem[]): string => `${items.slice(0, 10).map(name).join('; ')}${items.length > 10 ? `; +${items.length - 10} more` : ''}`
return [
- ...(run.running > 0 ? ['Stop the run first (the Control tab\'s Stop asks first and calls TaskStop; unverified for a workflow run\'s own id: Claude Code\'s Workflows panel always works), then:'] : []),
+ ...(run.running > 0 ? ['Stop the run first (the Control tab\'s Stop asks first and calls TaskStop with the run\'s task id: verified to stop the whole run on Claude Code 2.1.289; it cannot stop a single agent; Claude Code\'s Workflows panel also works), then:'] : []),
`Workflow({ scriptPath: "<the script that started this run>", resumeFromRunId: "${run.id}" })`,
...(again.length > 0 ? [`runs again, no result recorded: ${list(again)}`] : []),
...(cached.length > 0 ? [`stays cached, its error is its recorded result: ${list(cached)}. Change that agent() call or its input to run it again`] : []),
diff --git a/plugins/ruflo-console/hooks/views/wf-control.ts b/plugins/ruflo-console/hooks/views/wf-control.ts
index 6691b6dd2f..a93e83b8a6 100644
--- a/plugins/ruflo-console/hooks/views/wf-control.ts
+++ b/plugins/ruflo-console/hooks/views/wf-control.ts
@@ -8,10 +8,11 @@
import type { RenderElement } from 'claude-code'
import { cleanText } from '../data/wf-clean'
-import { controlActions, type ControlAction, type ControlInput } from '../data/wf-control'
+import { controlActions, taskIdOf, taskPattern, transcriptOf, type ControlAction, type ControlInput, type TaskRef } from '../data/wf-control'
import { tidy } from '../data/wf-send'
import type { Host } from '../host'
import type { State } from '../state'
+import type { WfRun } from '../data/workflows'
import { isRunPath } from '../wf-actions'
import { button, col, kv, text, THEME, type Ctx } from './common'
import { registerSlot, type SlotEnv } from './wf-slots'
@@ -26,6 +27,7 @@ export const wireWfControl = (state: State, host: Host): void => void hosts.set(
export function resetControl(state: State): void {
hosts.delete(state)
drafts.delete(state)
+ tasks.delete(state)
}
const draftOf = (state: State): { text: string } => {
@@ -39,7 +41,66 @@ const draftOf = (state: State): { text: string } => {
return held
}
-const COLOR: Record<ControlAction['proof'], string | undefined> = { verified: THEME.ok, 'queued-only': THEME.warn, unverified: THEME.warn, prefill: undefined }
+const COLOR: Record<ControlAction['proof'], string | undefined> = { verified: THEME.ok, 'does-not-work': THEME.bad, prefill: undefined }
+
+/** The task ids found (or why not), by run: TaskStop takes the Workflow tool's task id, which only the session transcript holds while a run is live (ADR-471). */
+const tasks = new WeakMap<State, Map<string, { ref: TaskRef; atMs: number; isPending: boolean }>>()
+/** The id is read again after this long: a reason because the launch line may not have been written yet, an id because a RESUME gives the same run a new task id. */
+const RETRY_MS = 5_000
+const SMALL = 2_000_000
+
+/** Reads the run's task id once per run: the transcript in full when it is small, else a search of it; every failure is a reason, never a guess. */
+async function findTask(state: State, host: Host, run: Pick<WfRun, 'id' | 'dir'>): Promise<TaskRef> {
+ const path = transcriptOf(run, candidate => isRunPath(candidate, state.configDir))
+
+ if (path === null) return { why: 'the run\'s session transcript is not at a path the console may read' }
+
+ try {
+ const size = (await host.fs.stat(path).catch(() => undefined))?.size
+
+ if (size === undefined) return { why: 'the session transcript that launched this run is not there (a run started by another session cannot be stopped from here)' }
+
+ const found = size <= SMALL ? taskIdOf(await host.fs.read(path), run.id) : await searchTask(host, path, run.id)
+
+ return found === null ? { why: 'this run\'s task id is not in the session transcript (it was launched by another session): stop it in Claude Code\'s Workflows panel' } : { id: found }
+ } catch {
+ return { why: 'the session transcript could not be read' }
+ }
+}
+
+/** A transcript too large to read whole: grep prints only the launch result's task and run ids (argv, no shell; the path is a checked run path). */
+async function searchTask(host: Host, path: string, runId: string): Promise<string | null> {
+ const result = await host.run(['grep', '-o', '-E', taskPattern(runId), path], 10_000)
+
+ return result.exitCode === 0 ? taskIdOf(result.stdout, runId) : null
+}
+
+function taskOf(state: State, host: Host | undefined, run: WfRun): TaskRef {
+ let held = tasks.get(state)
+
+ if (held === undefined) {
+ held = new Map()
+ tasks.set(state, held)
+ }
+
+ const known = held.get(run.id)
+ const now = Date.now()
+
+ if (known !== undefined && (known.isPending || now - known.atMs < RETRY_MS)) return known.ref
+
+ if (host === undefined) return { why: 'no host to read the session transcript' }
+
+ // A stale answer stays on screen while it is read again (so a button never flickers to "reading"); a first read has nothing to show yet.
+ const pending: TaskRef = known?.ref ?? { why: 'reading the session transcript for this run\'s task id: draw again in a moment' }
+
+ held.set(run.id, { ref: pending, atMs: now, isPending: true })
+ void findTask(state, host, run).then(found => {
+ held?.set(run.id, { ref: found, atMs: Date.now(), isPending: false })
+ host.invalidate()
+ })
+
+ return pending
+}
/** The inputs the data module needs, from the page's cursor; null where there is no run or no host to act through. */
export function inputOf(env: Pick<SlotEnv, 'ctx' | 'run' | 'agent'>, text: string): ControlInput | null {
@@ -52,6 +113,7 @@ export function inputOf(env: Pick<SlotEnv, 'ctx' | 'run' | 'agent'>, text: strin
return {
run: env.run,
agent: env.agent,
+ task: env.run.kind === 'workflow' ? taskOf(state, host, env.run) : { why: 'a ruflo swarm has no workflow task' },
text,
bridge: { toolCall: host.toolCall, toolCheck: host.toolCheck, fillPrompt: host.fillPrompt },
report: (label, ok, detail) => {
@@ -77,8 +139,9 @@ function controlTab(env: SlotEnv): RenderElement[] {
for (const action of actions) {
rows.push(button(ctx, `wf-control-${action.id}`, action.label, () => ctx.act.workflows.ask(action.spec, action.why)))
- rows.push(text(ctx, ` call: ${action.spec === null ? `none (${action.why})` : action.call}`, { dimColor: true }))
- rows.push(text(ctx, ` proof: ${action.proof} · ${action.proofText}`, { ...(COLOR[action.proof] === undefined ? { dimColor: true } : { color: COLOR[action.proof] as string }) }))
+ // Wrapped, not cut: the measured words end with the version and the day they were measured on.
+ rows.push(ctx.kit.Text({ wrap: 'wrap', dimColor: true, children: ` call: ${action.spec === null ? `none (${action.why})` : action.call}` }))
+ rows.push(ctx.kit.Text({ wrap: 'wrap', ...(COLOR[action.proof] === undefined ? { dimColor: true } : { color: COLOR[action.proof] as string }), children: ` proof: ${action.proof} · ${action.proofText}` }))
}
rows.push(text(ctx, 'A refusal by the engine is shown and nothing else is tried in its place. Stopping is not undone by resuming.', { dimColor: true }))
@@ -86,7 +149,7 @@ function controlTab(env: SlotEnv): RenderElement[] {
return [col(ctx, rows, 'wf-control')]
}
-/** The stop action of the extras row: the picked agent if one is picked, else the run. Null (with the reason on the confirm row) where it cannot be made. */
+/** The stop action of the extras row: always the whole run (the engine cannot stop one workflow agent, ADR-471). Null (with the reason on the confirm row) where it cannot be made. */
export function stopSlotSpec(env: SlotEnv): ReturnType<typeof controlActions>[number]['spec'] {
const input = inputOf(env, '')
@@ -94,13 +157,13 @@ export function stopSlotSpec(env: SlotEnv): ReturnType<typeof controlActions>[nu
const actions = controlActions(input)
- return (env.agent === null ? actions.find(action => action.id === 'stop-run') : actions.find(action => action.id === 'stop-agent'))?.spec ?? null
+ return actions.find(action => action.id === 'stop-run')?.spec ?? null
}
/** Registers this module's slots; a repeat is refused harmlessly (the registry keeps the first). */
export function registerControlSlots(): void {
registerSlot({ kind: 'tab', id: 'control', label: 'control', when: env => env.run !== null && env.run.kind === 'workflow', render: controlTab })
- registerSlot({ kind: 'action', id: 'ctl-stop', label: 'stop', why: 'nothing to stop: a ruflo swarm run (use x), an id the engine would not accept, or a build with no tool bridge', spec: stopSlotSpec })
+ registerSlot({ kind: 'action', id: 'ctl-stop', label: 'stop', why: 'nothing to stop: a ruflo swarm run (use x), a run whose task id is not in this session\'s transcript, or a build with no tool bridge', spec: stopSlotSpec })
}
registerControlSlots()
diff --git a/plugins/ruflo-console/hooks/views/wf-convo.ts b/plugins/ruflo-console/hooks/views/wf-convo.ts
index 6e34453825..495773dec7 100644
--- a/plugins/ruflo-console/hooks/views/wf-convo.ts
+++ b/plugins/ruflo-console/hooks/views/wf-convo.ts
@@ -63,7 +63,7 @@ function threadRows(ctx: Ctx, target: Target, convoOf: ReturnType<typeof liveOf>
if (thread === undefined || thread.msgs.length === 0) return [text(ctx, `No messages with @${target.id} yet.`, { dimColor: true })]
const stats = statsOf(thread)
- const rows: RenderElement[] = [text(ctx, `${stats.sent} sent · ${stats.answered} answered · ${stats.failed} failed · tokens ${stats.tokensIn === 0 && stats.tokensOut === 0 ? 'n/a' : `${stats.tokensIn} in / ${stats.tokensOut} out`} · cost ${stats.usd === null ? 'n/a (no billed figure reported)' : `$${stats.usd.toFixed(4)} billed`}${thread.dropped > 0 ? ` · ${thread.dropped} oldest dropped at the ${MAX_MSGS}-message cap` : ''}`, { dimColor: true })]
+ const rows: RenderElement[] = [text(ctx, `${stats.sent} sent · ${stats.answered} answered · ${stats.failed} failed · tokens ${stats.tokensIn === 0 && stats.tokensOut === 0 ? (stats.tokensTotal === 0 ? 'n/a' : `${stats.tokensTotal} total`) : `${stats.tokensIn} in / ${stats.tokensOut} out${stats.tokensTotal === 0 ? '' : ` + ${stats.tokensTotal} total`}`} · cost ${stats.usd === null ? 'n/a (no billed figure reported)' : `$${stats.usd.toFixed(4)} billed`}${thread.dropped > 0 ? ` · ${thread.dropped} oldest dropped at the ${MAX_MSGS}-message cap` : ''}`, { dimColor: true })]
for (const msg of thread.msgs.slice(-SHOWN)) {
const color = msg.who === 'you' ? THEME.info : STATE_COLOR[msg.state]
diff --git a/plugins/ruflo-console/tests/fixtures/control-real.ts b/plugins/ruflo-console/tests/fixtures/control-real.ts
new file mode 100644
index 0000000000..bb9c718932
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/control-real.ts
@@ -0,0 +1,65 @@
+/**
+ * What a real interactive Claude Code answered, copied from the ADR-471 measurement run (Claude Code 2.1.289, 2026-10-06, isolated config, haiku,
+ * a file-driven probe mod calling `$.tool.call`). Ids are the run's own; the only key in this folder is a made-up test string. Nothing here was edited
+ * except to drop fields no test reads.
+ */
+export const VERSION = '2.1.289'
+
+type Reply = { result?: unknown; text?: string; isError?: boolean; deny?: string }
+
+/** The Workflow tool's launch result, as the session transcript holds it (`toolUseResult`), inside the line a task-id search reads. */
+export const LAUNCH_LINE = '{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"Workflow started in the background."}]},"toolUseResult":{"status":"async_launched","taskId":"wyp2n5acy","taskType":"local_workflow","workflowName":"ctl-wf","runId":"wf_186c6243-718","summary":"two haiku agents, node timer steps","transcriptDir":"/c/projects/-tmp-ctl-test/0ba58c85/subagents/workflows/wf_186c6243-718","scriptPath":"/tmp/ctl-test/ctl-wf.js"},"sessionId":"0ba58c85-964c-447e-af40-914e6aeb706b"}'
+
+export const WF = { runId: 'wf_186c6243-718', taskId: 'wyp2n5acy', agentA: 'af9570828161afcaf', agentB: 'a77af355be2b4d9a0' }
+
+export const REAL: Record<string, Reply> = {
+ // TaskStop
+ stopWorkflowTask: { result: { message: 'Successfully stopped task: wyp2n5acy (two haiku agents, node timer steps)', task_id: 'wyp2n5acy', task_type: 'local_workflow', command: 'two haiku agents, node timer steps' }, text: '{"message":"Successfully stopped task: wyp2n5acy (two haiku agents, node timer steps)","task_id":"wyp2n5acy","task_type":"local_workflow","command":"two haiku agents, node timer steps"}' },
+ stopWorkflowRunId: { result: 'Error: No task found with ID: wf_186c6243-718', text: '<tool_use_error>No task found with ID: wf_186c6243-718</tool_use_error>', isError: true },
+ stopWorkflowAgent: { result: 'Error: No task found with ID: a77af355be2b4d9a0', text: '<tool_use_error>No task found with ID: a77af355be2b4d9a0</tool_use_error>', isError: true },
+ stopUnnamedBackgroundAgent: { result: { message: 'Successfully stopped task: a5d7590f2256bbb08 (Run 10 Node setTimeout calls and report done)', task_id: 'a5d7590f2256bbb08', task_type: 'local_agent', command: 'Run 10 Node setTimeout calls and report done' }, text: '{"message":"Successfully stopped task: a5d7590f2256bbb08 (Run 10 Node setTimeout calls and report done)","task_id":"a5d7590f2256bbb08","task_type":"local_agent","command":"Run 10 Node setTimeout calls and report done"}' },
+ stopNamedAgentById: { result: "Error: No task found with ID: asleeper-5b260a36f5ca5237. Running teammates: sleeper@session-0ba58c85", text: "<tool_use_error>No task found with ID: asleeper-5b260a36f5ca5237. Running teammates: sleeper@session-0ba58c85</tool_use_error>", isError: true },
+ stopNamedAgentByTeammateId: { result: { message: "Successfully stopped task: tx8xpvkja (run bash 'sleep 240' once, then reply done)", task_id: 'tx8xpvkja', task_type: 'in_process_teammate', command: "run bash 'sleep 240' once, then reply done" }, text: '{"message":"Successfully stopped task: tx8xpvkja (run bash \'sleep 240\' once, then reply done)","task_id":"tx8xpvkja","task_type":"in_process_teammate","command":"run bash \'sleep 240\' once, then reply done"}' },
+ stopTaskOfAnotherSession: { text: '<tool_use_error>No task found with ID: wyp2n5acy</tool_use_error>', isError: true },
+ // SendMessage
+ messageRunningWorkflowAgent: { result: { success: true, message: 'Resuming agent af95708', resumedAgentId: 'af9570828161afcaf', pin: { id: 'af9570828161afcaf', name: 'af9570828161afcaf', ref: 'db25dd' } }, text: '{"success":true,"message":"Resuming agent af95708","resumedAgentId":"af9570828161afcaf","pin":{"id":"af9570828161afcaf","name":"af9570828161afcaf","ref":"db25dd"}}' },
+ messageWorkflowAgentByLabel: { text: '{"success":false,"message":"No agent named \'wa\' is reachable.\\nUse ListAgents to see everyone you can message."}' },
+ messageFinishedWorkflowAgent: { text: '{"success":false,"message":"Agent \\"a77af355be2b4d9a0\\" could not be resumed: No transcript found for agent ID: a77af355be2b4d9a0. If you read this id in a message from another Claude Code process (e.g. the lead\'s subagent, seen from a teammate pane), it never ran in this session — reply through \\"team-lead\\" or the session that sent it instead of the raw id."}' },
+ messageNamedTeammateByName: { result: { success: true, message: "Message sent to sleeper's inbox", msg_id: '89717ea8-11c5-4558-ba40-f7130f6a6652', routing: { sender: 'team-lead', target: '@sleeper', targetColor: 'blue', summary: 'console test', content: 'Console test: at your next tool round, use Bash t…' } } },
+ messageRunningTeammateById: { text: '{"success":true,"message":"Teammate \\"asleeper-31d8fd41a7f1dcb1\\" is already running; queued your message for its next turn.","msg_id":"7fdaa767-6f24-4cd6-bcea-4fe403bafd7e"}' },
+ messagePeerSession: { text: '{"success":true,"message":"“ping” → ctl-peer-bb (another Claude session on this machine; in that session\'s inbox, not yet read by its Claude — a [Cross-session delivery notice] follows if that session holds it (usually a different permission mode) or refuses it)","msg_id":"4cdd61b0-3e65-4ce4-9305-5ddf5001d13f"}' },
+ // permission
+ writeRefusedInDialog: { deny: "The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed." },
+ bashAcceptedInDialog: { result: { stdout: '', stderr: '', interrupted: false, isImage: false, noOutputExpected: true }, text: '(Bash completed with no output)' },
+}
+
+/** `$.tool.check` answers, default (manual) permission mode. */
+export const CHECKS = {
+ bashEcho: { decision: 'allow' },
+ taskStop: { decision: 'allow' },
+ sendMessage: { decision: 'allow' },
+ write: { decision: 'ask', reason: "Claude requested permissions to write to /tmp/ctl-test/w.txt, but you haven't granted it yet." },
+ bashTouch: { decision: 'ask', reason: "touch in '/tmp/ctl-test/t1' needs approval. The path is inside the working directories for this session ('/tmp/ctl-test'), and Claude Code asks before a shell command creates, changes or removes files there." },
+} as const
+
+/** `$.tool.call({tool:'Workflow'})` from a mod: refused by the host. */
+export const WORKFLOW_FROM_MOD = 'ctl-probe: tool.call: runs the Workflow tool, whose agents run outside the at-once bound on spawns: $.agent.spawn is the door (host check)'
+
+/** `codex exec -s read-only --skip-git-repo-check --ephemeral -C <cwd> -` with the prompt "Reply with exactly the word: pong" on stdin (codex-cli 0.160.0). */
+export const CODEX = {
+ stdout: 'pong\n',
+ stderr: 'OpenAI Codex v0.160.0\n--------\nworkdir: /tmp/ctl-test\nmodel: gpt-6-astra\nprovider: openai\napproval: never\nsandbox: read-only\nreasoning effort: high\nreasoning summaries: none\nsession id: 01a11359-564d-7791-86e8-6b52a425d1fd\n--------\nuser\nReply with exactly the word: pong\n\ncodex\npong\nhook: Stop\nhook: Stop Completed\ntokens used\n5,271\n',
+}
+
+/** `bash ~/.claude/helpers/federation.sh dispatch ...` refusals, both before any ssh (exit 1, stdout empty). */
+export const FEDERATION = {
+ noSuchPeer: { argv: ['bash', 'federation.sh', 'dispatch', 'ctl-no-such-peer', 'hello'], exitCode: 1, stdout: '', stderr: 'federation: no such peer: ctl-no-such-peer\n' },
+ untrusted: { argv: ['bash', 'federation.sh', 'dispatch', "Reuven's Mac mini", 'hello'], exitCode: 1, stdout: '', stderr: "federation: peer 'Reuven's Mac mini' is not trusted — pass --confirm to override (one-shot)\n" },
+}
+
+/** What the stub OpenAI-compatible server (127.0.0.1) received and answered when `$.http.fetch` posted to it from an interactive session. */
+export const HTTP_STUB = {
+ seen: { method: 'POST', url: '/v1/chat/completions', auth: 'present', contentType: 'application/json', body: '{"model":"m","messages":[{"role":"user","content":"hi"}]}' },
+ answer: { ok: true, status: 200, text: '{"id":"x","model":"stub-model","choices":[{"message":{"role":"assistant","content":"stub says hi; echo auth=Bearer sk-test-KEY123456"}}],"usage":{"prompt_tokens":7,"completion_tokens":5,"cost":0.00012}}' },
+ metadataHostFromEngine: 'ctl-probe: $.http.fetch(http://169.254.169.254/latest/) aborted: no complete answer within 30000ms',
+}
diff --git a/plugins/ruflo-console/tests/wf-control-views.spec.ts b/plugins/ruflo-console/tests/wf-control-views.spec.ts
index 878d427f6a..13aeaafb55 100644
--- a/plugins/ruflo-console/tests/wf-control-views.spec.ts
+++ b/plugins/ruflo-console/tests/wf-control-views.spec.ts
@@ -17,6 +17,7 @@ import { resetControl, stopSlotSpec, wireWfControl } from '../hooks/views/wf-con
import { workflowsPage } from '../hooks/views/wf-page'
import { slotsFor, type SlotEnv } from '../hooks/views/wf-slots'
import { workflowsActions } from '../hooks/wf-actions'
+import { LAUNCH_LINE, REAL } from './fixtures/control-real'
import { liveOf, refreshFacts, resetConvo, saveTranscript, sendSpec, stopWatch, watchSpec } from '../hooks/wf-convo-live'
import { targetsFor } from '../hooks/wf-convo-live'
@@ -42,16 +43,24 @@ const wfRun = (over: Partial<WfRun> = {}): WfRun => ({ id: 'wf_abc12345', name:
type Fake = { host: Host; tools: Record<string, unknown>[]; runs: { argv: readonly string[]; stdin?: string }[]; http: { url: string; headers: Record<string, string>; body: string }[]; prompts: string[]; every: { ms: number; fn: () => void; cancelled: boolean }[]; invalidated: () => number; bbs: { text: string }[] }
-function fake(over: { tool?: boolean; peers?: string; stat?: boolean } = {}): Fake {
+/** The session transcript the run was launched from, as the real Workflow launch line wrote it (with this file's run id). */
+const TRANSCRIPT = '/home/u/.claude/projects/-p/sess.jsonl'
+const LAUNCH = LAUNCH_LINE.replace('wf_186c6243-718', 'wf_abc12345')
+const settle = async (): Promise<void> => void (await new Promise(resolve => setTimeout(resolve, 5)))
+
+let launchLines = (): string => LAUNCH
+
+function fake(over: { tool?: boolean; peers?: string; stat?: boolean; transcript?: 'ok' | 'missing' | 'other' | 'huge' } = {}): Fake {
const out: Fake = { host: undefined as never, tools: [], runs: [], http: [], prompts: [], every: [], invalidated: () => 0, bbs: [] }
let invalidated = 0
const host = {
home: async () => '/home/u',
- fs: { read: async (path: string) => (path.endsWith('peers.json') ? (over.peers ?? '{"peers":[{"host":"zenbook","trusted":true}]}') : Promise.reject(new Error('ENOENT'))), stat: async () => (over.stat === true ? { size: 1 } : Promise.reject(new Error('ENOENT'))), list: async () => [] },
+ fs: { read: async (path: string) => (path.endsWith('peers.json') ? (over.peers ?? '{"peers":[{"host":"zenbook","trusted":true}]}') : path === TRANSCRIPT && (over.transcript ?? 'ok') !== 'missing' ? (over.transcript === 'other' ? LAUNCH.replace('wf_abc12345', 'wf_zzz') : launchLines()) : Promise.reject(new Error('ENOENT'))), stat: async (path: string) => (path === TRANSCRIPT && over.transcript !== 'missing' ? { size: over.transcript === 'huge' ? 9_000_000 : 500 } : over.stat === true ? { size: 1 } : Promise.reject(new Error('ENOENT'))), list: async () => [] },
run: async (argv: readonly string[], _ms: number, stdin?: string) => {
out.runs.push({ argv, ...(stdin !== undefined && { stdin }) })
if (argv[0] === 'which') return { exitCode: 0, stdout: '/usr/bin/codex', stderr: '' }
+ if (argv[0] === 'grep') return { exitCode: 0, stdout: LAUNCH.match(/"taskId":"wyp2n5acy".*?"runId":"wf_abc12345"/)?.[0] ?? '', stderr: '' }
if (argv[0] === 'printenv') return { exitCode: 0, stdout: 'key-value-1234567\n', stderr: '' }
if (argv.includes('federation_bbs_watch')) return { exitCode: 0, stdout: `Result:\n${JSON.stringify({ envelopes: [{ envelopeId: 'e1', payload: { text: 'peer: use sharding' }, timestamp: '2026-10-05T00:00:00Z' }] })}`, stderr: '' }
@@ -72,7 +81,7 @@ function fake(over: { tool?: boolean; peers?: string; stat?: boolean } = {}): Fa
return { ok: true, status: 200, text: JSON.stringify({ model: 'm', choices: [{ message: { content: `answer from ${url.includes('a.example') ? 'A' : 'B'}` } }], usage: { prompt_tokens: 3, completion_tokens: 4 } }) }
},
- ...(over.tool === false ? {} : { toolCall: async (input: Record<string, unknown>) => { out.tools.push(input); return { text: '{"message":"Successfully stopped task: acf991387298086c7 (sleeper)"}' } }, toolCheck: async () => ({ decision: 'allow' as const }) }),
+ ...(over.tool === false ? {} : { toolCall: async (input: Record<string, unknown>) => { out.tools.push(input); return REAL.stopWorkflowTask as never }, toolCheck: async () => ({ decision: 'allow' as const }) }),
} as unknown as Host
out.host = host
@@ -83,6 +92,9 @@ function fake(over: { tool?: boolean; peers?: string; stat?: boolean } = {}): Fa
const world = (): { state: State; ctx: Ctx; asked: { spec: ActionSpec | null; why: string }[] } => {
const state = newState({})
+
+ state.configDir = '/home/u/.claude'
+
const asked: { spec: ActionSpec | null; why: string }[] = []
const act = { workflows: { ask: (spec: ActionSpec | null, why = '') => void asked.push({ spec, why }), setUi: () => undefined } } as unknown as Actions
@@ -113,34 +125,104 @@ describe('registration beside the other features', () => {
describe('the control tab', () => {
beforeEach(() => resetFolds())
- it('draws the exact call and the proof of each action, and the stop button asks with a card that shows the call', async () => {
+ it('draws the exact call and the measured proof of each action, and the stop button asks with a card that shows the call', async () => {
const { ctx, asked } = world()
const f = fake()
wireWfControl(ctx.state, f.host)
+ expect(words(tab('control').render(envOf(ctx)))).toMatch(/reading the session transcript/)
+ await settle()
const tree = tab('control').render(envOf(ctx))
const text = words(tree)
- expect(text).toContain(`call: TaskStop {"task_id":"${AGENT}"}`)
- expect(text).toMatch(/proof: verified · TaskStop worked on a real background agent/)
- expect(text).toMatch(/proof: unverified · TaskStop with a workflow run's id was not tried/)
- expect(text).toMatch(/proof: queued-only/)
+ expect(text).toContain('call: TaskStop {"task_id":"wyp2n5acy"}')
+ expect(text).toMatch(/proof: verified · verified: TaskStop with the run's TASK id stopped the run/)
+ expect(text).toMatch(/proof: does-not-work · does not work: the engine stops a whole workflow run, not one agent/)
+ expect(text).toMatch(/call: none \(the engine cannot stop one workflow agent: TaskStop \{"task_id":"acf991387298086c7"\} is answered "No task found with ID/)
expect(text).toContain('bound: each call goes through the engine')
- press(tree, 'wf-control-stop-agent')
- expect(asked[0]?.spec?.shows).toBe(`TaskStop {"task_id":"${AGENT}"}`)
+ expect(text).not.toMatch(/unverified|queued-only/)
+ press(tree, 'wf-control-stop-run')
+ expect(asked[0]?.spec?.shows).toBe('TaskStop {"task_id":"wyp2n5acy"}')
expect(f.tools).toHaveLength(0)
await asked[0]?.spec?.run?.()
- expect(f.tools).toEqual([{ tool: 'TaskStop', task_id: AGENT }])
+ expect(f.tools).toEqual([{ tool: 'TaskStop', task_id: 'wyp2n5acy' }])
expect(ctx.state.outcome).toMatchObject({ ok: true, detail: expect.stringContaining('Successfully stopped task') })
resetControl(ctx.state)
})
- it('typing the message makes Message and Redirect real, with the exact SendMessage on the card', () => {
+ it('the stop button of one agent has no spec and says why: the engine would answer "No task found"', async () => {
+ const { ctx, asked } = world()
+
+ wireWfControl(ctx.state, fake().host)
+ tab('control').render(envOf(ctx))
+ await settle()
+ press(tab('control').render(envOf(ctx)), 'wf-control-stop-agent')
+ expect(asked[0]?.spec).toBeNull()
+ expect(asked[0]?.why).toMatch(/cannot stop one workflow agent/)
+ })
+
+ it('a resumed run keeps its run id and gets a new task id: the id is read again after a few seconds, and the card then shows the new one', async () => {
+ const { ctx } = world()
+ const real = Date.now
+
+ launchLines = () => LAUNCH
+ wireWfControl(ctx.state, fake().host)
+ tab('control').render(envOf(ctx))
+ await settle()
+ expect(words(tab('control').render(envOf(ctx)))).toContain('call: TaskStop {"task_id":"wyp2n5acy"}')
+
+ launchLines = () => `${LAUNCH}\n${LAUNCH.replace('wyp2n5acy', 'wekh7caqa')}`
+ Date.now = () => real() + 6_000
+
+ try {
+ expect(words(tab('control').render(envOf(ctx)))).toContain('wyp2n5acy')
+ await settle()
+ expect(words(tab('control').render(envOf(ctx)))).toContain('call: TaskStop {"task_id":"wekh7caqa"}')
+ } finally {
+ Date.now = real
+ launchLines = () => LAUNCH
+ }
+ })
+
+ it('a run launched by another session (its task id is not in this transcript) cannot be stopped from here, and says so', async () => {
+ for (const transcript of ['missing', 'other'] as const) {
+ const { ctx, asked } = world()
+ const f = fake({ transcript })
+
+ wireWfControl(ctx.state, f.host)
+ tab('control').render(envOf(ctx))
+ await settle()
+ press(tab('control').render(envOf(ctx)), 'wf-control-stop-run')
+ expect(asked[0]?.spec).toBeNull()
+ expect(asked[0]?.why).toMatch(/Workflows panel|not there/)
+ expect(f.tools).toHaveLength(0)
+ }
+ })
+
+ it('a transcript too large to read is searched with grep (fixed argv, a checked path), and only the ids come back', async () => {
+ const { ctx, asked } = world()
+ const f = fake({ transcript: 'huge' })
+
+ wireWfControl(ctx.state, f.host)
+ tab('control').render(envOf(ctx))
+ await settle()
+ press(tab('control').render(envOf(ctx)), 'wf-control-stop-run')
+
+ const grep = f.runs.find(entry => entry.argv[0] === 'grep')
+
+ expect(grep?.argv.slice(0, 3)).toEqual(['grep', '-o', '-E'])
+ expect(grep?.argv[3]).toContain('"runId":"wf_abc12345"')
+ expect(grep?.argv[4]).toBe(TRANSCRIPT)
+ expect(asked[0]?.spec?.shows).toBe('TaskStop {"task_id":"wyp2n5acy"}')
+ })
+
+ it('typing the message makes Message and Redirect real, with the exact SendMessage on the card', async () => {
const { ctx, asked } = world()
wireWfControl(ctx.state, fake().host)
type(tab('control').render(envOf(ctx)), 'wf-control-text', 'use the cache')
+ await settle()
const tree = tab('control').render(envOf(ctx))
@@ -158,7 +240,7 @@ describe('the control tab', () => {
const tree = tab('control').render(envOf(ctx))
expect(words(tree)).toMatch(/not bound in this build/)
- press(tree, 'wf-control-stop-agent')
+ press(tree, 'wf-control-stop-run')
expect(asked[0]?.spec).toBeNull()
expect(asked[0]?.why).toMatch(/does not bind tool calls/)
})
@@ -170,15 +252,17 @@ describe('the control tab', () => {
expect(stopSlotSpec(envOf(ctx))).toBeNull()
})
- it('the stop button of the extras row stops the picked agent, or the run when none is picked', () => {
+ it('the stop button of the extras row always stops the whole run (the engine cannot stop one agent), picked agent or not', async () => {
const { ctx } = world()
wireWfControl(ctx.state, fake().host)
- expect(stopSlotSpec(envOf(ctx))?.shows).toContain(AGENT)
- expect(stopSlotSpec({ ...envOf(ctx), agent: null })?.shows).toContain('wf_abc12345')
+ stopSlotSpec(envOf(ctx))
+ await settle()
+ expect(stopSlotSpec(envOf(ctx))?.shows).toBe('TaskStop {"task_id":"wyp2n5acy"}')
+ expect(stopSlotSpec({ ...envOf(ctx), agent: null })?.shows).toBe('TaskStop {"task_id":"wyp2n5acy"}')
})
- it('draws on the real page: the control tab and the stop button, beside the Conversation rule', () => {
+ it('draws on the real page: the control tab and the stop button, beside the Conversation rule', async () => {
const { state } = world()
const f = fake()
@@ -189,6 +273,10 @@ describe('the control tab', () => {
state.wf.tab = 'control'
const act = { workflows: workflowsActions(state, f.host, { ask: () => undefined } as never) } as unknown as Actions
+
+ workflowsPage({ kit, state, nowMs: 1_000, columns: 120, pictures: new Map(), act })
+ await settle()
+
const tree = workflowsPage({ kit, state, nowMs: 1_000, columns: 120, pictures: new Map(), act })
const text = words(tree)
diff --git a/plugins/ruflo-console/tests/wf-control.spec.ts b/plugins/ruflo-console/tests/wf-control.spec.ts
index 6a212be806..b4e4c4dd5c 100644
--- a/plugins/ruflo-console/tests/wf-control.spec.ts
+++ b/plugins/ruflo-console/tests/wf-control.spec.ts
@@ -1,23 +1,25 @@
/**
- * Stop, Message and Redirect (ADR-465): the exact engine call on the card, the engine's permission respected, the spike's real answers
- * classified, and every failure said as itself. Fake bridges only. Run with
+ * Stop, Message and Redirect (ADR-465, measured in ADR-471): the exact engine call on the card, the engine's permission respected, the REAL
+ * answers of an interactive Claude Code (tests/fixtures/control-real.ts) classified, and every failure said as itself. Fake bridges only. Run with
* npx vitest run plugins/ruflo-console/tests/wf-control.spec.ts --testTimeout=30000
*/
import { describe, expect, it } from 'vitest'
import type { ToolReply } from '../hooks/host'
-import { callTool, classifyReply, controlActions, ENGINE_ID, permissionOf, relayText, resumeText, type Bridge, type ControlAction, type ControlInput } from '../hooks/data/wf-control'
+import { callTool, classifyReply, controlActions, ENGINE_ID, permissionOf, relayText, resumeText, taskIdOf, transcriptOf, type Bridge, type ControlAction, type ControlInput, type TaskRef } from '../hooks/data/wf-control'
+import { LAUNCH_LINE, REAL, WF } from './fixtures/control-real'
import type { WfAgent, WfRun } from '../hooks/data/workflows'
const AGENT = 'acf991387298086c7'
const RUN = 'wf_abc12345'
+const TASK = 'wyp2n5acy'
const agent = (over: Partial<WfAgent> = {}): WfAgent => ({ id: AGENT, label: 'sleeper', phase: 'Build', state: 'running', hasWorktree: false, ...over })
const run = (over: Partial<WfRun> = {}): WfRun => ({ id: RUN, name: 'my flow', kind: 'workflow', state: 'running', phases: [{ title: 'Build', agents: [agent()], done: 0, total: 1, running: 1, failed: 0 }], running: 1, done: 0, failed: 0, idle: 0, total: 1, totalTokens: null, isTokensPartial: false, hasRecord: false, dir: '/home/u/.claude/projects/-p/sess/subagents/workflows/wf_abc12345', ...over })
type Calls = { tool: Record<string, unknown>[]; check: { tool: string; input: unknown }[]; fill: string[]; said: { label: string; ok: boolean; detail: string }[] }
-function harness(over: { reply?: ToolReply | ((input: Record<string, unknown>) => ToolReply); verdict?: 'allow' | 'ask' | 'deny'; reject?: string; noTool?: boolean; fill?: boolean; text?: string; agent?: WfAgent | null; run?: WfRun } = {}): { input: ControlInput; calls: Calls } {
+function harness(over: { reply?: ToolReply | ((input: Record<string, unknown>) => ToolReply); verdict?: 'allow' | 'ask' | 'deny'; task?: TaskRef; reject?: string; noTool?: boolean; fill?: boolean; text?: string; agent?: WfAgent | null; run?: WfRun } = {}): { input: ControlInput; calls: Calls } {
const calls: Calls = { tool: [], check: [], fill: [], said: [] }
const reply = over.reply ?? { text: JSON.stringify({ message: 'Successfully stopped task: acf991387298086c7 (sleeper)', task_type: 'local_agent' }) }
const bridge: Bridge & { fillPrompt: (text: string) => Promise<boolean> } = {
@@ -26,17 +28,37 @@ function harness(over: { reply?: ToolReply | ((input: Record<string, unknown>) =
fillPrompt: async text => { calls.fill.push(text); return over.fill ?? true },
}
- return { calls, input: { run: over.run ?? run(), agent: over.agent === undefined ? agent() : over.agent, text: over.text ?? '', bridge, report: (label, ok, detail) => calls.said.push({ label, ok, detail }), isRunPath: path => path.startsWith('/home/u/.claude/projects/') && !path.includes('..') } }
+ return { calls, input: { task: over.task ?? { id: TASK }, run: over.run ?? run(), agent: over.agent === undefined ? agent() : over.agent, text: over.text ?? '', bridge, report: (label, ok, detail) => calls.said.push({ label, ok, detail }), isRunPath: path => path.startsWith('/home/u/.claude/projects/') && !path.includes('..') } }
}
const by = (actions: ControlAction[], id: string): ControlAction => actions.find(action => action.id === id) as ControlAction
-describe('classifyReply: the engine\'s words, as the spike saw them', () => {
- it('reads the real TaskStop success, the real TaskStop miss and the real SendMessage answers', () => {
- expect(classifyReply({ text: '{"message":"Successfully stopped task: acf991387298086c7 (sleeper)","task_type":"local_agent"}' })).toMatchObject({ ok: true, kind: 'done', text: expect.stringContaining('Successfully stopped task') })
- expect(classifyReply({ text: 'Error: No task found with ID: nonexistent', isError: true })).toMatchObject({ ok: false, kind: 'error', text: expect.stringContaining('No task found') })
- expect(classifyReply({ result: { success: true, message: 'Message queued for delivery to sleeper at its next tool round.' } })).toMatchObject({ ok: true, text: expect.stringContaining('queued') })
- expect(classifyReply({ text: '{"success":false,"message":"No agent named \'nobody\' is reachable.\\nUse ListAgents to see everyone you can message."}' })).toMatchObject({ ok: false, kind: 'error', text: expect.stringContaining('nobody') })
+describe('classifyReply: the engine\'s own words, as an interactive session answered them (ADR-471)', () => {
+ it('reads every real TaskStop answer: the workflow task stops; the run id, an agent of the run and another session\'s task are "No task found", with no tag wrapper', () => {
+ expect(classifyReply(REAL.stopWorkflowTask as never)).toMatchObject({ ok: true, kind: 'done', text: expect.stringContaining('Successfully stopped task: wyp2n5acy') })
+ expect(classifyReply(REAL.stopUnnamedBackgroundAgent as never)).toMatchObject({ ok: true, kind: 'done' })
+ expect(classifyReply(REAL.stopNamedAgentByTeammateId as never)).toMatchObject({ ok: true, kind: 'done' })
+
+ for (const miss of [REAL.stopWorkflowRunId, REAL.stopWorkflowAgent, REAL.stopNamedAgentById, REAL.stopTaskOfAnotherSession]) {
+ const outcome = classifyReply(miss as never)
+
+ expect(outcome).toMatchObject({ ok: false, kind: 'error', text: expect.stringContaining('No task found with ID') })
+ expect(outcome.text).not.toContain('<tool_use_error>')
+ }
+ })
+
+ it('reads every real SendMessage answer: delivered, inbox, queued for the next turn, a refusal by label, a finished agent, a peer session', () => {
+ expect(classifyReply(REAL.messageRunningWorkflowAgent as never)).toMatchObject({ ok: true, text: 'Resuming agent af95708' })
+ expect(classifyReply(REAL.messageNamedTeammateByName as never)).toMatchObject({ ok: true, text: "Message sent to sleeper's inbox" })
+ expect(classifyReply(REAL.messageRunningTeammateById as never)).toMatchObject({ ok: true, text: expect.stringContaining('queued your message for its next turn') })
+ expect(classifyReply(REAL.messagePeerSession as never)).toMatchObject({ ok: true, text: expect.stringContaining('in that session') })
+ expect(classifyReply(REAL.messageWorkflowAgentByLabel as never)).toMatchObject({ ok: false, kind: 'error', text: expect.stringContaining("No agent named 'wa' is reachable") })
+ expect(classifyReply(REAL.messageFinishedWorkflowAgent as never)).toMatchObject({ ok: false, kind: 'error', text: expect.stringContaining('could not be resumed: No transcript found') })
+ })
+
+ it('the real dialog answers: a refused Write is a deny (nothing written), an accepted Bash is its output', () => {
+ expect(classifyReply(REAL.writeRefusedInDialog as never)).toMatchObject({ ok: false, kind: 'denied', text: expect.stringContaining('the engine refused it') })
+ expect(classifyReply(REAL.bashAcceptedInDialog as never)).toMatchObject({ ok: true, kind: 'done' })
})
it('a deny is a refusal, not an error; a missing bridge says so; nothing is invented for an empty answer', () => {
@@ -65,86 +87,131 @@ describe('classifyReply: the engine\'s words, as the spike saw them', () => {
})
})
-describe('Stop', () => {
- it('shows the exact call, runs it through the host after the permission check, and reports the engine\'s own words', async () => {
- const { input, calls } = harness()
- const stop = by(controlActions(input), 'stop-agent')
+describe('Stop: the whole run by its TASK id; one workflow agent cannot be stopped', () => {
+ it('shows the exact call with the task id, runs it through the host after the permission check, and reports the engine\'s own words', async () => {
+ const { input, calls } = harness({ reply: REAL.stopWorkflowTask as never })
+ const stop = by(controlActions(input), 'stop-run')
expect(stop.proof).toBe('verified')
- expect(stop.call).toBe(`TaskStop {"task_id":"${AGENT}"}`)
+ expect(stop.proofText).toMatch(/^verified: TaskStop with the run's TASK id stopped the run and both of its agents.*Claude Code 2\.1\.289, 2026-10-06/)
+ expect(stop.call).toBe(`TaskStop {"task_id":"${TASK}"}`)
expect(stop.spec?.declared).toBe('write')
expect(calls.tool).toHaveLength(0)
await stop.spec?.run?.()
- expect(calls.check).toEqual([{ tool: 'TaskStop', input: { task_id: AGENT } }])
- expect(calls.tool).toEqual([{ tool: 'TaskStop', task_id: AGENT }])
- expect(calls.said).toEqual([expect.objectContaining({ ok: true, detail: expect.stringContaining('Successfully stopped task') })])
+ expect(calls.check).toEqual([{ tool: 'TaskStop', input: { task_id: TASK } }])
+ expect(calls.tool).toEqual([{ tool: 'TaskStop', task_id: TASK }])
+ expect(calls.said).toEqual([expect.objectContaining({ ok: true, detail: expect.stringContaining('Successfully stopped task: wyp2n5acy') })])
expect(calls.said[0]?.detail).toContain('re-read the run')
})
- it('the run stop is labelled unverified (the spike never stopped a workflow run) and calls TaskStop with the run id', async () => {
- const { input, calls } = harness()
- const stop = by(controlActions(input), 'stop-run')
+ it('never passes the wf_ run id or an agent id to TaskStop (the engine answers "No task found" for both: measured)', async () => {
+ const { input, calls } = harness({ reply: REAL.stopWorkflowTask as never })
- expect(stop.proof).toBe('unverified')
- expect(stop.proofText).toMatch(/not tried/)
- await stop.spec?.run?.()
- expect(calls.tool).toEqual([{ tool: 'TaskStop', task_id: RUN }])
+ for (const action of controlActions(input)) await action.spec?.run?.()
+
+ expect(calls.tool.filter(call => call.tool === 'TaskStop').every(call => call.task_id === TASK)).toBe(true)
+ expect(JSON.stringify(calls.tool)).not.toContain(RUN)
+ expect(JSON.stringify(calls.tool)).not.toContain(AGENT)
+ })
+
+ it('stopping one agent does not work: no spec, and the engine\'s real refusal is on the row', () => {
+ const stop = by(controlActions(harness().input), 'stop-agent')
+
+ expect(stop.proof).toBe('does-not-work')
+ expect(stop.spec).toBeNull()
+ expect(stop.proofText).toMatch(/does not work.*No task found with ID: acf991387298086c7.*2\.1\.289/)
+ expect(stop.why).toMatch(/cannot stop one workflow agent/)
+ expect(REAL.stopWorkflowAgent?.text).toContain('No task found with ID')
})
it('an engine "deny" from the permission check stops it before any call: no other route is tried', async () => {
const { input, calls } = harness({ verdict: 'deny' })
- await by(controlActions(input), 'stop-agent').spec?.run?.()
+ await by(controlActions(input), 'stop-run').spec?.run?.()
expect(calls.tool).toHaveLength(0)
expect(calls.said[0]).toMatchObject({ ok: false, detail: expect.stringMatching(/permission check: deny.*no other route is tried/) })
})
- it('a deny answered by the call itself is shown the same way, and an unknown task is shown as an error', async () => {
+ it('a deny answered by the call itself is shown the same way; a task the engine does not know is shown as its error', async () => {
const denied = harness({ reply: { deny: 'Claude requested permissions to stop which is blocked' } })
- await by(controlActions(denied.input), 'stop-agent').spec?.run?.()
+ await by(controlActions(denied.input), 'stop-run').spec?.run?.()
expect(denied.calls.said[0]).toMatchObject({ ok: false, detail: expect.stringMatching(/engine refused it.*no other route/) })
- const missing = harness({ reply: { text: 'Error: No task found with ID: x', isError: true } })
+ const missing = harness({ reply: REAL.stopTaskOfAnotherSession as never })
- await by(controlActions(missing.input), 'stop-agent').spec?.run?.()
- expect(missing.calls.said[0]).toMatchObject({ ok: false, detail: expect.stringContaining('No task found') })
+ await by(controlActions(missing.input), 'stop-run').spec?.run?.()
+ expect(missing.calls.said[0]).toMatchObject({ ok: false, detail: expect.stringContaining('No task found with ID: wyp2n5acy') })
})
- it('a host with no tool bridge has no stop spec and says why; an id the engine would not accept is not passed on', () => {
- const none = controlActions(harness({ noTool: true }).input)
+ it('with no task id there is no stop spec and the reason says why (reading it, not in the transcript); no tool bridge says so too', () => {
+ const none = controlActions(harness({ task: { why: 'this run\'s task id is not in the session transcript' } }).input)
- expect(by(none, 'stop-agent').spec).toBeNull()
- expect(by(none, 'stop-agent').why).toMatch(/does not bind tool calls/)
- expect(by(controlActions(harness({ agent: agent({ id: 'a b;rm' }) }).input), 'stop-agent').spec).toBeNull()
+ expect(by(none, 'stop-run').spec).toBeNull()
+ expect(by(none, 'stop-run').why).toMatch(/not in the session transcript/)
+ expect(by(none, 'redirect').spec).toBeNull()
+ expect(by(controlActions(harness({ noTool: true }).input), 'stop-run').why).toMatch(/does not bind tool calls/)
+ expect(by(controlActions(harness({ task: { id: 'a b;rm' } }).input), 'stop-run').spec).toBeNull()
expect(ENGINE_ID.test('a1')).toBe(false)
- expect(by(controlActions(harness({ agent: null }).input), 'stop-agent').why).toMatch(/pick an agent/)
+ })
+})
+
+describe('the run\'s task id comes from the session transcript', () => {
+ it('reads the real Workflow launch result: the task id beside the run id', () => {
+ expect(taskIdOf(`{"x":1}\n${LAUNCH_LINE}\n{"y":2}`, WF.runId)).toBe(WF.taskId)
+ expect(taskIdOf(LAUNCH_LINE, 'wf_other-run')).toBeNull()
+ expect(taskIdOf('', WF.runId)).toBeNull()
+ })
+
+ it('a RESUMED run has two launches under one run id: the last task id is the live one (measured: same runId, new taskId)', () => {
+ const resumed = LAUNCH_LINE.replace('wyp2n5acy', 'wekh7caqa')
+
+ expect(taskIdOf(`${LAUNCH_LINE}\n{"other":1}\n${resumed}`, WF.runId)).toBe('wekh7caqa')
+ expect(taskIdOf(`${resumed}\n${LAUNCH_LINE}`, WF.runId)).toBe(WF.taskId)
+ })
+
+ it('refuses a run id that is not a run id (it is put in a pattern), and a task id that is not letters and digits', () => {
+ expect(taskIdOf(LAUNCH_LINE, 'wf_.*')).toBeNull()
+ expect(taskIdOf(LAUNCH_LINE, 'x"|"')).toBeNull()
+ expect(taskIdOf(LAUNCH_LINE.replace('wyp2n5acy', 'a b;rm -rf'), WF.runId)).toBeNull()
+ })
+
+ it('finds the launching transcript from the run directory, and only inside the projects folder', () => {
+ const ok = (path: string): boolean => path.startsWith('/home/u/.claude/projects/')
+
+ expect(transcriptOf({ dir: '/home/u/.claude/projects/-p/sess-1/subagents/workflows/wf_abc12345' }, ok)).toBe('/home/u/.claude/projects/-p/sess-1.jsonl')
+ expect(transcriptOf({ dir: '/etc/subagents/workflows/wf_abc12345' }, ok)).toBeNull()
+ expect(transcriptOf({ dir: '/home/u/.claude/projects/-p/elsewhere' }, ok)).toBeNull()
+ expect(transcriptOf({}, ok)).toBeNull()
})
})
describe('Message', () => {
- it('needs the typed sentence, then shows the exact SendMessage, labelled queued-only', async () => {
+ it('needs the typed sentence, then shows the exact SendMessage, labelled verified with what was measured', async () => {
expect(by(controlActions(harness().input), 'message').spec).toBeNull()
expect(by(controlActions(harness().input), 'message').why).toMatch(/type the guidance/)
- const { input, calls } = harness({ text: 'use the cache', reply: { result: { success: true, message: 'Message queued for delivery to sleeper at its next tool round.' } } })
+ const { input, calls } = harness({ text: 'use the cache', reply: REAL.messageRunningWorkflowAgent as never })
const message = by(controlActions(input), 'message')
- expect(message.proof).toBe('queued-only')
+ expect(message.proof).toBe('verified')
+ expect(message.proofText).toMatch(/^verified: a message to a RUNNING workflow agent's id arrived in that agent's own transcript.*2\.1\.289.*could not be resumed.*not reachable/)
expect(message.call).toBe(`SendMessage {"to":"${AGENT}","message":"use the cache"}`)
await message.spec?.run?.()
expect(calls.tool).toEqual([{ tool: 'SendMessage', to: AGENT, message: 'use the cache', summary: 'use the cache' }])
- expect(calls.said[0]).toMatchObject({ ok: true, detail: expect.stringMatching(/queued.*queued is not delivered/) })
+ expect(calls.said[0]).toMatchObject({ ok: true, detail: expect.stringMatching(/Resuming agent af95708.*could not be resumed/) })
})
- it('an unreachable agent is an error that offers the prompt-box text, not a success', async () => {
- const { input, calls } = harness({ text: 'hello', reply: { text: '{"success":false,"message":"No agent named x is reachable."}' } })
+ it('a finished agent and an agent named by its label are errors that offer the prompt-box text, not successes', async () => {
+ for (const real of [REAL.messageFinishedWorkflowAgent, REAL.messageWorkflowAgentByLabel]) {
+ const { input, calls } = harness({ text: 'hello', reply: real as never })
- await by(controlActions(input), 'message').spec?.run?.()
- expect(calls.said[0]).toMatchObject({ ok: false, detail: expect.stringContaining('prepare as text') })
+ await by(controlActions(input), 'message').spec?.run?.()
+ expect(calls.said[0]).toMatchObject({ ok: false, detail: expect.stringContaining('prepare as text') })
+ }
})
it('a text with a credential in it, or a leading dash, is not sent at all', () => {
@@ -170,10 +237,11 @@ describe('Redirect: two halves, said as two', () => {
const { input, calls } = harness({ text: 'prefer the cache' })
const redirect = by(controlActions(input), 'redirect')
- expect(redirect.call).toContain(`TaskStop {"task_id":"${RUN}"}, then into the prompt box`)
+ expect(redirect.call).toContain(`TaskStop {"task_id":"${TASK}"}, then into the prompt box`)
+ expect(redirect.proofText).toMatch(/^verified: the stop.*the resume is only text prepared in your prompt box/)
expect(redirect.spec?.note).toMatch(/only when the stop worked/)
await redirect.spec?.run?.()
- expect(calls.tool).toEqual([{ tool: 'TaskStop', task_id: RUN }])
+ expect(calls.tool).toEqual([{ tool: 'TaskStop', task_id: TASK }])
expect(calls.fill).toHaveLength(1)
expect(calls.fill[0]).toContain(`resumeFromRunId: "${RUN}"`)
expect(calls.fill[0]).toContain('prefer the cache')
@@ -182,7 +250,7 @@ describe('Redirect: two halves, said as two', () => {
})
it('when the stop fails the resume text is NOT prepared (a resume against a live run would fight it)', async () => {
- const { input, calls } = harness({ text: 'x y', reply: { text: 'Error: No task found', isError: true } })
+ const { input, calls } = harness({ text: 'x y', reply: REAL.stopWorkflowRunId as never })
await by(controlActions(input), 'redirect').spec?.run?.()
expect(calls.fill).toHaveLength(0)
diff --git a/plugins/ruflo-console/tests/wf-convo.spec.ts b/plugins/ruflo-console/tests/wf-convo.spec.ts
index 16a67a7d2b..e1e45bca9b 100644
--- a/plugins/ruflo-console/tests/wf-convo.spec.ts
+++ b/plugins/ruflo-console/tests/wf-convo.spec.ts
@@ -5,6 +5,7 @@
import { describe, expect, it } from 'vitest'
import type { HiveInfo } from '../hooks/data/parse'
+import { CODEX, FEDERATION, REAL } from './fixtures/control-real'
import { addMessage, applyFetch, compareOf, fanOutOf, fromBbs, fromChannel, lastAnswer, MAX_MSGS, MAX_THREADS, newConvo, pollParams, POLL_MAX, recordSend, relayBody, statsOf, threadOf, transcriptMarkdown, transcriptName, TRANSCRIPT_MAX } from '../hooks/data/wf-convo'
import { chatBody, parseChat, payloadOf, sendTo, taskNote, type SendDeps } from '../hooks/data/wf-send'
import { convoOptionsOf, endpointsOf, isBaseUrl, MAX_FANOUT, OPENROUTER, parseConfig, parseMentions, peersOf, targetsOf, type Target } from '../hooks/data/wf-targets'
@@ -33,7 +34,7 @@ function deps(over: Partial<SendDeps> & { env?: string | null; httpReply?: { ok:
},
httpSend: async (url, init) => { rec.http.push({ url, init }); return over.httpReply ?? { ok: true, status: 200, text: JSON.stringify({ model: 'm', choices: [{ message: { content: 'an answer' } }], usage: { prompt_tokens: 12, completion_tokens: 5 } }) } },
submitPrompt: async text => { rec.prompts.push(text) },
- toolCall: async input => { rec.tool.push(input); return { text: '{"success":true,"message":"Message queued for delivery to sleeper at its next tool round."}' } },
+ toolCall: async input => { rec.tool.push(input); return REAL.messageNamedTeammateByName as never },
toolCheck: async () => ({ decision: over.verdict ?? 'allow' }),
...over,
}
@@ -167,7 +168,8 @@ describe('the exact payload on the card equals what is sent', () => {
const queued = await sendTo(d, t(d, 'sleeper'), 'hello')
expect(rec.tool).toEqual([{ tool: 'SendMessage', to: 'acf991387298086c7', message: 'hello', summary: 'hello' }])
- expect(queued).toMatchObject({ ok: true, state: 'queued', text: expect.stringContaining('queued is not delivered') })
+ expect(queued).toMatchObject({ ok: true, state: 'queued', text: expect.stringContaining("Message sent to sleeper's inbox") })
+ expect(queued.text).toContain('it reaches the agent when its current turn ends')
await sendTo(d, t(d, 'bbs-ops'), 'hello')
await sendTo(d, t(d, 'peer-zenbook'), 'hello')
@@ -185,6 +187,44 @@ describe('the exact payload on the card equals what is sent', () => {
expect(rec.run[1]?.timeoutMs).toBe(600_000)
})
+ it('Codex: the real codex 0.160.0 answer is the final message on stdout, and its one \'tokens used\' figure is a TOTAL, not an output count', async () => {
+ const { d } = deps({ runReply: () => ({ exitCode: 0, stdout: CODEX.stdout, stderr: CODEX.stderr }) })
+ const answered = await sendTo(d, t(d, 'codex'), 'Reply with exactly the word: pong')
+
+ expect(answered).toMatchObject({ ok: true, state: 'reply', text: 'pong', tokensTotal: 5271 })
+ expect(answered.tokensOut).toBeUndefined()
+ expect(answered.tokensIn).toBeUndefined()
+ expect(payloadOf(t(d, 'codex'), 'x', d)).toMatchObject({ ok: true, payload: { shows: expect.stringContaining('codex exec -s read-only --skip-git-repo-check --ephemeral -C /work/proj -') } })
+
+ const convo = newConvo()
+
+ recordSend(convo, t(d, 'codex'), 'q', answered, 1)
+ expect(statsOf(convo.threads.get('codex') as never)).toMatchObject({ tokensTotal: 5271, tokensIn: 0, tokensOut: 0 })
+ expect(compareOf(convo, [t(d, 'codex')], 'q')[0]?.tokens).toBe('5271 total (no in/out split reported)')
+ })
+
+ it('Codex with no stdout, or a non-zero exit, is an error and nothing is invented', async () => {
+ const { d } = deps({ runReply: () => ({ exitCode: 1, stdout: '', stderr: 'codex: not logged in' }) })
+
+ expect(await sendTo(d, t(d, 'codex'), 'x')).toMatchObject({ ok: false, state: 'error', text: expect.stringContaining('not logged in') })
+ })
+
+ it('the federation helper: the argv the console builds is what federation.sh parses (host, then the prompt, then --confirm for an untrusted peer), and its real refusals come back as errors', async () => {
+ const trusted = deps({ runReply: () => ({ exitCode: FEDERATION.noSuchPeer.exitCode, stdout: FEDERATION.noSuchPeer.stdout, stderr: FEDERATION.noSuchPeer.stderr }) })
+ const gone = await sendTo(trusted.d, t(trusted.d, 'peer-zenbook'), 'hello')
+
+ expect(trusted.rec.run[0]?.argv).toEqual(['bash', '/home/u/.claude/helpers/federation.sh', 'dispatch', 'zenbook', 'hello'])
+ expect(gone).toMatchObject({ ok: false, state: 'error', text: FEDERATION.noSuchPeer.stderr.trim() })
+
+ const untrusted = deps({ runReply: () => ({ exitCode: FEDERATION.untrusted.exitCode, stdout: '', stderr: FEDERATION.untrusted.stderr }) })
+
+ expect(await sendTo(untrusted.d, t(untrusted.d, 'peer-ruv-mac-mini'), 'hello')).toMatchObject({ ok: false, state: 'error' })
+ expect(untrusted.rec.run[0]?.argv).toEqual(['bash', '/home/u/.claude/helpers/federation.sh', 'dispatch', 'ruv-mac-mini', 'hello', '--confirm'])
+ // The helper takes any non-flag word as the prompt: a body that starts with a dash would be eaten as an option, so it is refused before any argv exists.
+ expect(payloadOf(t(untrusted.d, 'peer-zenbook'), '--allow-destructive', untrusted.d)).toMatchObject({ ok: false })
+ expect(payloadOf(t(untrusted.d, 'peer-zenbook'), '--confirm', untrusted.d)).toMatchObject({ ok: false })
+ })
+
it('the engine\'s permission "deny" for SendMessage stops the send before the call', async () => {
const { d, rec } = deps({ verdict: 'deny' })
diff --git a/plugins/ruflo-console/tests/wf-send-stub.spec.ts b/plugins/ruflo-console/tests/wf-send-stub.spec.ts
new file mode 100644
index 0000000000..a96b408e7a
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-send-stub.spec.ts
@@ -0,0 +1,105 @@
+/**
+ * The OpenAI-compatible send against a REAL local HTTP server (ADR-471): the exact bytes the confirm card showed are the bytes the server received,
+ * the key comes from the named environment variable (a test-only string, never printed), and a provider that echoes it has it masked. The
+ * transport functions are real (node fetch, a real `printenv`); only the engine is absent. Run with
+ * npx vitest run plugins/ruflo-console/tests/wf-send-stub.spec.ts
+ */
+import { execFile } from 'node:child_process'
+import { createServer, type Server } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+
+import { chatBody, payloadOf, sendTo, type SendDeps } from '../hooks/data/wf-send'
+import { isBaseUrl, parseConfig, targetsOf, type Target } from '../hooks/data/wf-targets'
+
+const KEY = 'stubkey-9d41-test-only'
+const seen: { method?: string; url?: string; authorization?: string; contentType?: string; body: string }[] = []
+let server: Server
+let base = ''
+
+beforeAll(async () => {
+ server = createServer((req, res) => {
+ let body = ''
+
+ req.on('data', chunk => (body += chunk))
+ req.on('end', () => {
+ seen.push({ ...(req.method !== undefined && { method: req.method }), ...(req.url !== undefined && { url: req.url }), ...(req.headers.authorization !== undefined && { authorization: req.headers.authorization }), ...(typeof req.headers['content-type'] === 'string' && { contentType: req.headers['content-type'] }), body })
+ res.setHeader('content-type', 'application/json')
+ res.end(JSON.stringify({ model: 'stub-model', choices: [{ message: { content: `stub says hi; echo ${req.headers.authorization ?? 'no-auth'}` } }], usage: { prompt_tokens: 7, completion_tokens: 5, cost: 0.00012 } }))
+ })
+ })
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`
+ process.env.STUB_MODEL_KEY = KEY
+})
+
+afterAll(() => {
+ delete process.env.STUB_MODEL_KEY
+ server.close()
+})
+
+const run: SendDeps['run'] = (argv, timeoutMs, stdin) =>
+ new Promise(resolve => {
+ const child = execFile(argv[0] as string, argv.slice(1), { timeout: timeoutMs }, (error, stdout, stderr) => resolve({ exitCode: error === null ? 0 : typeof error.code === 'number' ? error.code : 1, stdout, stderr, isStdoutTruncated: false, isStderrTruncated: false }))
+
+ if (stdin !== undefined) child.stdin?.end(stdin)
+ })
+
+const depsOf = (config: string): SendDeps => ({
+ cli: [], helper: '', trustedPeers: new Set(), cwd: '/tmp', hive: null, config: parseConfig(config), run,
+ httpSend: async (url, init) => {
+ const response = await fetch(url, { method: init.method, headers: init.headers, body: init.body })
+
+ return { ok: response.ok, status: response.status, text: await response.text() }
+ },
+ submitPrompt: async () => undefined,
+})
+const targetOf = (d: SendDeps, id: string): Target => targetsOf({ agents: [], peers: [], config: d.config, hasHive: false, hasCodex: false }).find(target => target.id === id) as Target
+
+describe('the stub endpoint receives exactly what the card showed', () => {
+ it('the request body is the one on the card, the key rides one header, and the echoed key is masked in the answer', async () => {
+ const d = depsOf(`endpoint:stub=${base}|STUB_MODEL_KEY|stub-model`)
+ const target = targetOf(d, 'stub')
+ const card = payloadOf(target, 'compare raft and paxos', d)
+
+ expect(card.ok).toBe(true)
+
+ const answered = await sendTo(d, target, 'compare raft and paxos')
+
+ expect(seen).toHaveLength(1)
+ expect(seen[0]).toMatchObject({ method: 'POST', url: '/v1/chat/completions', contentType: 'application/json', authorization: `Bearer ${KEY}` })
+ expect(seen[0]?.body).toBe(chatBody({ name: 'stub', baseUrl: base, keyEnv: 'STUB_MODEL_KEY', model: 'stub-model' }, 'compare raft and paxos'))
+ expect(card.ok && card.payload.shows).toContain(seen[0]?.body)
+ expect(card.ok && card.payload.shows).toContain('Authorization: Bearer ‹from $STUB_MODEL_KEY›')
+ expect(card.ok && card.payload.shows).not.toContain(KEY)
+ expect(answered).toMatchObject({ ok: true, state: 'reply', tokensIn: 7, tokensOut: 5, costUsd: 0.00012, model: 'stub-model' })
+ expect(answered.text).toContain('stub says hi; echo ‹masked›')
+ expect(answered.text).not.toContain(KEY)
+ })
+
+ it('with the key variable unset nothing reaches the server', async () => {
+ const before = seen.length
+ const d = depsOf(`endpoint:stub2=${base}|STUB_UNSET_KEY_VAR|stub-model`)
+
+ expect(await sendTo(d, targetOf(d, 'stub2'), 'hi')).toMatchObject({ ok: false, state: 'refused' })
+ expect(seen).toHaveLength(before)
+ })
+
+ it('with NONE as the key name no Authorization header is sent', async () => {
+ const d = depsOf(`endpoint:open=${base}|NONE|stub-model`)
+
+ await sendTo(d, targetOf(d, 'open'), 'hi')
+ expect(seen.at(-1)?.authorization).toBeUndefined()
+ })
+})
+
+describe('the SSRF rules still hold (the engine itself does not refuse a link-local address: it waits 30 s, ADR-471)', () => {
+ it.each(['http://169.254.169.254/latest', 'https://169.254.169.254/v1', 'http://0.0.0.0:8080/v1', 'http://[::ffff:169.254.169.254]/v1', 'https://metadata.google.internal/v1', 'http://instance-data/v1', 'http://224.0.0.1/v1', 'http://evil.example.com/v1', 'https://user:[email protected]/v1', 'https://x.example.com/v1?key=1', 'file:///etc/passwd', 'ftp://x.example.com/v1'])('refuses %s', url => {
+ expect(isBaseUrl(url)).toBe(false)
+ expect(parseConfig(`endpoint:x=${url}|KEY|m`).endpoints).toEqual([])
+ })
+
+ it('allows this machine, a tailnet address and https hosts', () => {
+ for (const url of ['http://127.0.0.1:18765/v1', 'http://localhost:11434/v1', 'http://100.104.125.72:11434/v1', 'https://openrouter.ai/api/v1']) expect(isBaseUrl(url)).toBe(true)
+ })
+})
diff --git a/plugins/ruflo-console/tests/wf-triage.spec.ts b/plugins/ruflo-console/tests/wf-triage.spec.ts
index d7b3f4b907..47876a8737 100644
--- a/plugins/ruflo-console/tests/wf-triage.spec.ts
+++ b/plugins/ruflo-console/tests/wf-triage.spec.ts
@@ -107,11 +107,12 @@ describe('rerunText', () => {
expect(text.join('\n')).toMatch(/stays cached.*build:b \(Build\)/)
})
- it('tells the person to stop a running run first (the Control tab asks and calls TaskStop; unverified for the run own id), and says when the journal was not read', () => {
+ it('tells the person to stop a running run first (the Control tab asks and calls TaskStop with the run task id: verified on 2.1.289), and says when the journal was not read', () => {
const run = { ...finished(), running: 1 }
const text = rerunText(run, failedOf(triageRun(run, null)), false) ?? []
- expect(text[0]).toMatch(/Stop the run first \(the Control tab's Stop asks first and calls TaskStop; unverified/)
+ expect(text[0]).toMatch(/Stop the run first \(the Control tab's Stop asks first and calls TaskStop with the run's task id: verified to stop the whole run on Claude Code 2\.1\.289; it cannot stop a single agent/)
+ expect(text[0]).not.toMatch(/unverified/)
expect(text.join('\n')).toMatch(/journal was not read/)
})
diff --git a/v3/docs/adr/ADR-471-control-plane-measured-capabilities.md b/v3/docs/adr/ADR-471-control-plane-measured-capabilities.md
new file mode 100644
index 0000000000..775e21d8d3
--- /dev/null
+++ b/v3/docs/adr/ADR-471-control-plane-measured-capabilities.md
@@ -0,0 +1,131 @@
+# ADR 471: The control plane, measured
+
+Status: Accepted
+
+Date: 2026-10-06
+
+Amends: ADR-465 §2.1 (the Stop labels and the id Stop is called with), §2.2 (Codex tokens, the `@agent` arrival text) and §4 (its "Unverified" list), ADR-464's amendment sentences that carried the same labels.
+
+Builds on: ADR-465 (the control plane and the multi-model bridge), ADR-453 (confirm-gated verbs)
+
+## 1. Context
+
+ADR-465 shipped Stop, Message, Redirect and the Conversation with a proof label on each action, and listed what no one had tried: TaskStop with a
+workflow run's id and with the id of an agent inside a run, SendMessage to a workflow-engine agent, delivery (not "queued") of a message, a
+permission dialog during `$.tool.call`, the Codex output shape, a federation argv, and a call to an OpenAI-compatible endpoint. This ADR is the
+measurement of every one of those in a real interactive session, and the change of the code and the words to what was measured.
+
+Method: Claude Code **2.1.289**, 2026-10-06, `claude --model haiku` in a tmux pane with an isolated `CLAUDE_CONFIG_DIR` (the login copied 0600 and
+shredded), working directory a throwaway git repo, default permission mode ("manual"). A throwaway probe mod (a file-driven poller calling
+`$.tool.call`, `$.tool.check`, `$.agent.list`, `$.http.fetch` and writing each answer with its timestamps) stood in for the console where the
+console was not the thing under test; the console itself (this plugin, loaded with `--plugin-dir`) was driven by mouse and keys for the Stop
+confirm card. Real answers are the fixtures in `plugins/ruflo-console/tests/fixtures/control-real.ts`. Model spend about $0.6 (measured from the
+session transcripts, haiku list prices); the Codex run is the person's own subscription.
+
+## 2. The capability matrix
+
+"Works" means observed to take effect, not only an answer of `success`.
+
+| # | Call (as the console makes it) | Answer | Verdict |
+|---|---|---|---|
+| 1 | `TaskStop {task_id: <Workflow task id>}` (`wyp2n5acy`, from the Workflow tool's launch result) | `Successfully stopped task: wyp2n5acy (...)`, `task_type: local_workflow`; both agents were interrupted mid-tool-call within the same second (their transcripts end `[Request interrupted by user for tool use]`), no `node` child left | **works: stops the whole run** |
+| 2 | `TaskStop {task_id: "wf_186c6243-718"}` (the run id) | `No task found with ID: wf_186c6243-718` (`isError`) | **does not work** |
+| 3 | `TaskStop {task_id: <id of an agent inside the run>}` | `No task found with ID: a77af355be2b4d9a0` (`isError`) | **does not work: one workflow agent cannot be stopped** |
+| 4 | the same task id from another session | `No task found with ID: wyp2n5acy` | does not work: a run another session launched cannot be stopped from here |
+| 5 | `TaskStop` of an Agent-tool background agent, unnamed, by `id` | `Successfully stopped task: a5d7590f2256bbb08`, `task_type: local_agent`, `agent.list` status `killed` | works (ADR-465's spike case) |
+| 6 | the same, **named** (`Agent({name:'sleeper'})`), by the `id` `agent.list` shows (`asleeper-...`) | `No task found with ID: asleeper-... Running teammates: sleeper@session-0ba58c85` | does not work: ADR-465's "verified" was for unnamed agents |
+| 7 | the same, by the `teammateId` (`sleeper@session-0ba58c85`) | `Successfully stopped task: ... task_type: in_process_teammate`; gone from `agent.list` | works (running or idle) |
+| 8 | `SendMessage {to: <id of a RUNNING workflow agent>}` | `{success:true, message:"Resuming agent af95708", resumedAgentId, pin}`. In that agent's own transcript 28 ms later: "The coordinator sent a message while you were working: ... Address this before completing your current task."; 1.6 s after, the agent began to act on it (a `ToolSearch` for SendMessage to reply). The agent then also shows in `agent.list` as a standalone background agent | **works: delivered mid-task** |
+| 9 | the same, the run stopped or the agent finished | `{success:false, message:"Agent ... could not be resumed: No transcript found for agent ID: ..."}` | refused by the engine (error) |
+| 10 | `SendMessage {to: "wa"}` (the agent's workflow label) | `{success:false, message:"No agent named 'wa' is reachable. Use ListAgents ..."}` | does not work by label |
+| 11 | `SendMessage {to: "sleeper"}` (a named Agent-tool agent, running a long turn) | `Message sent to sleeper's inbox`. Not in the agent's context until its **turn ended**: sent 22:15:48, injected 22:18:29.49 (161 s), then 22:27:54 to 22:30:39.97 (165 s) in a second trial; the agent ran its Bash 1.5 s after injection. By `id` the engine says `Teammate "..." is already running; queued your message for its next turn.` | **works, delivered at the next turn, not the next tool round** |
+| 12 | what the agent then does needs approval | a Bash `echo > file` of the agent raised its own dialog in that agent's view ("Bash command from the sleeper agent"); the file was written only after "Yes" | the agent's own permissions apply |
+| 13 | `SendMessage {to: <peer session>}` (a second interactive session started in another folder) | `in that session's inbox, not yet read by its Claude`; enqueued in the peer's transcript 17 ms after the call; the idle peer started a turn by itself and answered ("Got it — ping received") | **works: delivered and acted on** |
+| 14 | `ListAgents` from a mod | lists this session's teammates and the peer sessions of the **same config dir** (an isolated config sees only its own) | works |
+| 15 | `$.agent.list()` during a workflow run | `[]`: workflow agents are not in it | so run and agent ids come from disk |
+| 16 | `$.tool.call({tool:'Workflow', ...})` from a mod | thrown: "runs the Workflow tool, whose agents run outside the at-once bound on spawns: `$.agent.spawn` is the door (host check)" | refused: a mod cannot launch a workflow; only the model's turn can |
+| 17 | `$.tool.check` (default mode) | Bash `echo` allow; `TaskStop` allow; `SendMessage` allow; `Write` and a Bash `touch` **ask** with the engine's reason | verdict available without a dialog |
+| 18 | `$.tool.call` of a tool the check says **ask** | a real dialog opens in the interactive session, titled "from the ctl-probe plugin" (Create file / Bash command); the call waits (15.6 s and 3.5 s in the two trials). "No" resolves `{deny: "The user doesn't want to proceed with this tool use..."}` and nothing is written; "Yes" runs it and resolves the tool's output | **never bypassed**: the engine's dialog decides |
+| 19 | `TaskStop` / `SendMessage` through `$.tool.call` in default mode | no dialog (their check is allow) | the confirm card is the only gate for these two |
+| 20 | `codex exec -s read-only --skip-git-repo-check --ephemeral -C <cwd> -`, prompt on stdin (codex-cli 0.160.0, logged in) | stdout is the final message only (`pong\n`); stderr is a banner then `tokens used\n5,271`; exit 0 | works; the figure is a **total** (no in/out split) |
+| 21 | federation helper, `dispatch <host> "<prompt>" [--confirm]` | the helper has no dry run. Refusals measured, both before any ssh, exit 1, empty stdout: `federation: no such peer: X`; `federation: peer 'X' is not trusted — pass --confirm to override (one-shot)`. No real peer was dispatched to | argv builder confirmed against the helper's own parser; a dispatch itself **not run** (see §5) |
+| 22 | OpenAI-compatible POST to a stub on 127.0.0.1 through `$.http.fetch` from an interactive session | 200; the stub saw `POST /v1/chat/completions`, `content-type: application/json`, the `Authorization` header and the body byte for byte | works |
+| 23 | `$.http.fetch("http://169.254.169.254/...")` | **not refused**: it waited and aborted at 30 s ("no complete answer within 30000ms") | the engine has no link-local rule: the console's own `isBaseUrl` is the only SSRF gate |
+| 24 | `Workflow({scriptPath, resumeFromRunId})` after a stop | started again under the **same** `runId`, with a **new** `taskId` | the resume text is valid; the live task id changes |
+
+## 3. Decision
+
+### 3.1 Stop a run by its task id; remove Stop-one-agent
+
+The Workflow tool's **task id** is what TaskStop takes (rows 1 to 3). While a run is live it exists in one place on disk: the launching
+session's transcript (`<session>.jsonl`, the line whose `toolUseResult` has `status:"async_launched"`, `taskType:"local_workflow"`, `taskId` and
+`runId`); the run record `workflows/<run>.json` carries it only after the run ends. `data/wf-control.ts` gains `taskIdOf` (pure; the **last**
+launch of a run id wins, row 24), `transcriptOf` (the transcript path from the run directory, inside the projects folder only) and
+`taskPattern`. `views/wf-control.ts` reads it (the file itself up to 2 MB, else `grep -o -E <pattern> <path>` with fixed argv, no shell; a read that
+fails is a reason shown on the row, never a guess) and re-reads it every 5 s, because a resume changes it.
+
+- `stop-run` is `TaskStop {task_id: <task id>}`, label `verified`.
+- `stop-agent` has no spec and shows the engine's refusal (row 3) with the date and version. The extras-row Stop button always stops the run.
+- Redirect's stop half uses the task id; its resume half is text in the prompt box and never sent (the resume itself was run once, row 24, and its
+ text is right: `resumeFromRunId` with the run id).
+- A run launched by another session is answered "No task found" (row 4): the row says so and points at Claude Code's Workflows panel.
+
+### 3.2 Message
+
+`SendMessage {to: <agent id>}` is `verified` for a running workflow agent (rows 8 to 10) and the words say what the engine answers for a finished
+agent and for a label. The Conversation's `@<agent>` target (Agent-tool agents, `to` = the id `agent.list` shows) now states the measured arrival:
+in the inbox at once, **read when the agent's turn ends** (rows 11 and 12), and a tool the agent then runs raises its own dialog.
+
+Note for a later feature, not built: stopping an Agent-tool agent needs its `teammateId` when it is named (row 6 and 7); `ENGINE_ID` rejects `@`.
+The Workflows page lists only workflow runs, so it never issues that call.
+
+### 3.3 Labels
+
+`Proof` is `verified | does-not-work | prefill`; every proof sentence begins with `verified:` or `does not work:` and carries Claude Code 2.1.289,
+2026-10-06. "unverified" and "queued-only" are gone from the code and the UI, including `data/wf-triage.ts`'s re-run text, which now says Stop
+asks first, calls TaskStop with the run's task id, and cannot stop one agent. The proof and call lines on the tab are wrapped, not cut, so the date
+is never clipped.
+
+### 3.4 Replies and tokens
+
+`classifyReply` strips the engine's `<tool_use_error>` wrapper (the real miss has the tag in `text` and a string in `result`). Codex's one "tokens
+used" figure is stored as `tokensTotal` and shown as "N total (no in/out split reported)", not as output tokens; Codex and peer answers and error
+text are trimmed of the trailing newline.
+
+### 3.5 What was already right
+
+The permission handling stands (rows 17 to 19): the console asks `$.tool.check`, stops on `deny`, calls `$.tool.call`, and shows the engine's answer;
+a refused dialog is a refusal and no other route is tried. The SSRF rules stand and are now known to be the only ones (row 23). The federation argv
+`bash federation.sh dispatch <host> <body> [--confirm]` matches the helper's parser, which takes any non-flag word as the prompt, so the console's
+refusal of a body that begins with a dash is what stops a body being read as a flag.
+
+## 4. Evidence and tests
+
+- `tests/fixtures/control-real.ts`: the real answers of rows 1 to 20 and 22 to 23 (ids kept, no secret; the key in the stub test is a made-up string).
+- `tests/wf-control.spec.ts`: every real TaskStop and SendMessage answer classified; the task id from the real launch line, last launch wins,
+ hostile run ids refused; Stop never passes the run id or an agent id; Stop-agent has no spec and carries the refusal; the redirect uses the task id.
+- `tests/wf-control-views.spec.ts`: the id is read from the transcript (small file, huge file by grep with its exact argv, another session's run,
+ a missing file); the card shows `TaskStop {"task_id":"wyp2n5acy"}`; no "unverified" anywhere in the tab.
+- `tests/wf-send-stub.spec.ts`: a real HTTP server on 127.0.0.1, a real `printenv`, node `fetch`: the bytes received equal the bytes on the card
+ (`chatBody`), the key rides one header and an echoed key is masked in the answer, an unset variable sends nothing, `NONE` sends no header; twelve
+ hostile base URLs are refused.
+- `tests/wf-convo.spec.ts`: the real Codex stdout and stderr, the helper's two real refusals, the dash-first body refused.
+- Live, in the interactive session: the console's Stop button, its confirm card (`runs: TaskStop {"task_id":"wyoffjclz"}`) and the outcome row
+ "stop workflow run wf_740b4be5-aa0: Successfully stopped task: wyoffjclz"; both agents interrupted. After a resume the card showed the new task
+ id (`wekh7caqa`) without a restart.
+- Mutations of the code under test, each killed by a test, are listed in the commit message.
+
+## 5. Still unverified, and why
+
+- A real federation peer dispatch: it runs `claude -p` on another machine with that machine's permissions and spends its login; the task forbade
+ dispatching to a real peer. Only the argv and the helper's refusals are measured. (A peer host such as `Reuven's Mac mini` also fails the console's
+ host pattern, so it is not offered; unchanged.)
+- A run launched by another session being stopped from this one: the engine answers "No task found" (row 4), not tried in the other direction.
+- OpenRouter itself (a real key and the real service), `usage.cost`, and a metered gateway: only a stub was called, so no money was spent.
+- Stop-one-agent for Agent-tool agents from the console: the engine allows it (rows 5 to 7) but the Workflows page does not list those agents, so no
+ button exists to test.
+- The `--permission-mode` variants (acceptEdits, bypass, auto): only the default mode was driven; `$.tool.check` is the console's guard for the rest.
+
+## 6. Rollback
+
+Revert this ADR's commit: the code returns to ADR-465's labels and ids (and to a Stop that the engine answers "No task found").