Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

feat(console): workflow links, run events, mission-as-workflow and guidance (ADR-460)

ruvd3767df09a15
diff --git a/plugins/ruflo-console/hooks/data/wf-events.ts b/plugins/ruflo-console/hooks/data/wf-events.ts
new file mode 100644
index 0000000000..778dc9b988
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/wf-events.ts
@@ -0,0 +1,82 @@
+/**
+ * What a workflow read changed that a person would want announced beyond what the page already says (ADR-460). The page's own
+ * pass (wf-live.ts runNotices) announces a run that finished or failed; this adds what it does not: an agent that failed, an agent or
+ * run that has gone quiet (the read's own `stale` / `stalled` judgement, STALE_MS without a transcript line), and, for an agent a
+ * mission tagged (data/wf-links.ts), a finished one. Every function is pure and sees only two reads, so the first read announces
+ * nothing. The ruflo swarm is folded into the page's run list after the read, so it never reaches here: only workflow runs do.
+ *
+ * Each change is returned twice, as a band notice draft and as a mission event, so the merge owner can record the second into the
+ * mission ledger (`applyMissionEvents`) from the one place that holds the ledger. Text comes from labels, so it is washed first.
+ */
+import type { MissionRecord } from '../mission-types'
+import type { NoticeDraft } from '../notices'
+import { cleanText } from './wf-clean'
+import { readLabelTag } from './wf-links'
+import { STALE_MS, type WfRun } from './workflows'
+
+export type MissionEventKind = 'agent-failed' | 'agent-stuck' | 'agent-done'
+export type MissionEvent = { missionId: string; taskId: string; kind: MissionEventKind; note: string; key: string }
+export type RunChanges = { notices: NoticeDraft[]; mission: MissionEvent[] }
+
+const tail = (id: string): string => id.replace(/[^A-Za-z0-9]/g, '').slice(-8)
+const minutes = Math.round(STALE_MS / 60_000)
+
+/** What changed between two reads of the workflow runs; `prev` null (no read before) announces nothing. */
+export function eventsBetween(prev: readonly WfRun[] | null, next: readonly WfRun[]): RunChanges {
+ const out: RunChanges = { notices: [], mission: [] }
+
+ if (prev === null) return out
+
+ const before = new Map(prev.flatMap(run => [[`${run.id}`, run.state] as const, ...run.phases.flatMap(phase => phase.agents.map(agent => [`${run.id}/${agent.id}`, agent.state] as const))]))
+
+ for (const run of next) {
+ const name = cleanText(run.name)
+
+ if (run.state === 'stalled' && before.has(run.id) && before.get(run.id) !== 'stalled') out.notices.push({ level: 'warn', text: `workflow ${name} looks stuck: nothing written for ${minutes} min`, key: `r-${tail(run.id)}-stuck`, go: 'workflows' })
+
+ for (const phase of run.phases) {
+ for (const agent of phase.agents) {
+ const was = before.get(`${run.id}/${agent.id}`)
+
+ if (was === agent.state) continue
+
+ const label = cleanText(agent.label)
+ const tag = readLabelTag(agent.label)
+ const mission = tag !== null && !('malformed' in tag) ? tag : null
+ const where = mission === null ? `${label} in ${name}` : `${cleanText(mission.rest) || label} (mission ${cleanText(mission.missionId)}, task ${cleanText(mission.taskId)})`
+ const kind: MissionEventKind | null = agent.state === 'failed' ? 'agent-failed' : agent.state === 'stale' ? 'agent-stuck' : agent.state === 'done' && mission !== null ? 'agent-done' : null
+
+ if (kind === null) continue
+
+ const key = `a-${tail(run.id)}${tail(agent.id)}-${kind.slice(6, 7)}`
+ const words = kind === 'agent-failed' ? `failed: ${where}` : kind === 'agent-stuck' ? `looks stuck (${minutes} min quiet): ${where}` : `finished: ${where}`
+
+ out.notices.push({ level: kind === 'agent-failed' ? 'bad' : kind === 'agent-stuck' ? 'warn' : 'ok', text: `agent ${words}`, key, go: 'workflows' })
+ if (mission !== null) out.mission.push({ missionId: mission.missionId, taskId: mission.taskId, kind, note: `workflow agent ${words}`.slice(0, 160), key })
+ }
+ }
+ }
+
+ return out
+}
+
+/**
+ * Appends each event to its mission's record, once (an event's key is its `evidenceRef`), for a mission and task the ledger holds.
+ * Mutates the records it is handed and returns how many were added; the caller saves the ledger when it is above zero.
+ */
+export function applyMissionEvents(missions: ReadonlyMap<string, MissionRecord>, events: readonly MissionEvent[], nowMs: number): number {
+ let added = 0
+
+ for (const event of events) {
+ const mission = missions.get(event.missionId)
+
+ if (mission === undefined || !mission.tasks.some(task => task.id === event.taskId)) continue
+ if (mission.events.some(held => held.type === 'workflow' && held.evidenceRef === event.key)) continue
+
+ mission.events.push({ seq: Math.max(0, ...mission.events.map(held => held.seq)) + 1, atMs: nowMs, type: 'workflow', taskId: event.taskId, status: event.kind, evidenceRef: event.key, note: cleanText(event.note) })
+ if (mission.events.length > 500) mission.events.splice(0, mission.events.length - 500)
+ added += 1
+ }
+
+ return added
+}
diff --git a/plugins/ruflo-console/hooks/data/wf-guide.ts b/plugins/ruflo-console/hooks/data/wf-guide.ts
new file mode 100644
index 0000000000..880f86616e
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/wf-guide.ts
@@ -0,0 +1,182 @@
+/**
+ * The ruflo side of the Workflows page: how a swarm nests, and what a person can say to it (ADR-460). Pure: the snapshot's records in,
+ * rows and `ActionSpec`s out. Nothing runs here; each spec goes through the runner's confirm card as a fixed argv (an `mcp exec` call
+ * with one JSON argument, or a `ruflo` subcommand), and each action says in words what is sent and whether anything acts on it.
+ *
+ * What is true of ruflo today, read from its source and not assumed: a broadcast is appended to the hive's shared memory (the last 100)
+ * and no worker is interrupted; a task or claim edit changes a record an agent sees only when it reads the store; a consensus proposal
+ * binds nobody; a memory note is found by whoever searches memory. So no action here makes a running agent do something, and the card
+ * says so. Claude Code workflow agents have no ruflo record at all: the only honest paths are the memory note and a prepared prompt for
+ * the main session (resume or redirect), and the console cannot stop or message a running workflow.
+ */
+import { handoffClaim, type ActionSpec } from '../actions'
+import { hiveBroadcast, hivePropose } from '../hive'
+import { textArg } from '../ops'
+import { cleanText } from './wf-clean'
+import { membersOf } from './hive'
+import type { AgentRecord, ClaimRecord, HiveAgentRecord, HiveInfo, SwarmInfo, TaskRecord } from './parse'
+import { idOf, plain } from './parse'
+import type { WfAgent, WfRun } from './workflows'
+
+export type NestKind = 'swarm' | 'hive' | 'queen' | 'worker' | 'claim' | 'task' | 'note'
+export type NestRow = { depth: number; kind: NestKind; label: string; detail: string }
+
+const MAX_ROWS = 60
+const isOpenClaim = (claim: ClaimRecord): boolean => !/released|completed|cancel/i.test(claim.status)
+const isOpenTask = (task: TaskRecord): boolean => !/completed|failed|cancelled/i.test(task.status)
+
+/** swarm > hive (queen) > worker > claim > task, each level only from what the stores say; a missing level is a note, never invented. */
+export function nestingOf(input: { swarm: SwarmInfo | null; hive: HiveInfo | null; agents: readonly AgentRecord[]; hiveAgents: readonly HiveAgentRecord[]; claims: readonly ClaimRecord[]; tasks: readonly TaskRecord[] }): NestRow[] {
+ const { swarm, hive, agents, hiveAgents, claims, tasks } = input
+ const rows: NestRow[] = []
+
+ rows.push(swarm === null ? { depth: 0, kind: 'note', label: 'no swarm', detail: 'swarm init has not run here' } : { depth: 0, kind: 'swarm', label: swarm.id, detail: `${swarm.topology}${swarm.strategy === undefined ? '' : ` · ${swarm.strategy}`} · ${swarm.status} · ${swarm.agentIds.length} agents` })
+
+ if (hive === null) {
+ rows.push({ depth: 1, kind: 'note', label: 'no hive-mind', detail: 'no queen and no workers: agents are not grouped under a hive' })
+ } else {
+ rows.push({ depth: 1, kind: 'hive', label: hive.topology, detail: `${hive.strategy ?? 'consensus n/a'} · ${hive.workers.length} workers · ${hive.pending.length} open proposals` })
+ rows.push(hive.queen === undefined ? { depth: 2, kind: 'note', label: 'no queen', detail: 'none elected' } : { depth: 2, kind: 'queen', label: hive.queen, detail: `term ${hive.queenTerm ?? 'n/a'}` })
+
+ for (const member of membersOf(hive, hiveAgents, agents)) {
+ const inSwarm = swarm === null ? 'no swarm' : swarm.agentIds.includes(member.id) ? 'in the swarm' : 'not listed in the swarm'
+
+ rows.push({ depth: 2, kind: 'worker', label: `${member.type ?? 'worker'} ${member.id}`, detail: `${member.role} · ${member.status} · ${inSwarm}` })
+
+ const held = claims.filter(claim => claim.claimant.id === member.id && isOpenClaim(claim))
+ const assigned = tasks.filter(task => task.assignedTo.includes(member.id) && isOpenTask(task))
+
+ if (held.length === 0 && assigned.length === 0) rows.push({ depth: 3, kind: 'note', label: 'no claim, no task', detail: 'idle as far as the stores say' })
+
+ for (const claim of held) {
+ rows.push({ depth: 3, kind: 'claim', label: claim.issueId, detail: `${claim.status}${claim.progress === undefined ? '' : ` · ${claim.progress}%`}${claim.isStealable ? ' · stealable' : ''}` })
+
+ const task = tasks.find(candidate => candidate.id === claim.issueId)
+
+ rows.push(task === undefined ? { depth: 4, kind: 'note', label: 'no task record', detail: `the claim names ${claim.issueId}, which is not in the task store` } : { depth: 4, kind: 'task', label: task.id, detail: `${task.status} · ${plain(task.description, 60)}` })
+ }
+
+ for (const task of assigned.filter(candidate => !held.some(claim => claim.issueId === candidate.id))) rows.push({ depth: 3, kind: 'task', label: task.id, detail: `${task.status} · assigned, no claim · ${plain(task.description, 60)}` })
+ }
+
+ const outside = agents.filter(agent => !hive.workers.includes(agent.id) && (swarm?.agentIds.includes(agent.id) ?? false))
+
+ if (outside.length > 0) rows.push({ depth: 1, kind: 'note', label: `${outside.length} swarm agents outside the hive`, detail: outside.slice(0, 4).map(agent => agent.name ?? agent.type).join(', ') })
+ }
+
+ return rows.length > MAX_ROWS ? [...rows.slice(0, MAX_ROWS), { depth: 0, kind: 'note', label: `+${rows.length - MAX_ROWS} more rows`, detail: 'not drawn' }] : rows
+}
+
+/** The command line a spec runs, as the card shows it. */
+export const commandOf = (spec: ActionSpec): string => spec.shows ?? `ruflo ${spec.args.map(arg => (/^[\w.:/@=-]+$/.test(arg) ? arg : JSON.stringify(arg))).join(' ')}`
+
+export type Acts = 'record-only' | 'needs-votes' | 'pending-accept' | 'prompt-only'
+
+export type GuideAction = {
+ id: string
+ label: string
+ /** What is sent, exactly (the command, or the prepared prompt). */
+ sends: string
+ /** Whether anything acts on it, in words. */
+ acts: string
+ kind: Acts
+ spec: ActionSpec | null
+ /** Said when `spec` is null. */
+ why: string
+}
+
+export type GuideInput = {
+ text: string
+ run: WfRun
+ agent: WfAgent | null
+ hive: HiveInfo | null
+ agents: readonly AgentRecord[]
+ claims: readonly ClaimRecord[]
+ tasks: readonly TaskRecord[]
+ nowMs: number
+ /** Prepares text in the main session's prompt box (host.fillPrompt, or the slash path while idle). */
+ prepare: (text: string) => Promise<void>
+ /** True for a path under Claude Code's projects folder with no `..`. */
+ isRunPath: (path: string) => boolean
+}
+
+/** Free text for a card, a broadcast or a memory note: plain, bounded, no leading dash, and nothing a credential mask would change. */
+export function guardText(value: string, max: number): { ok: true; text: string } | { ok: false; why: string } {
+ const text = textArg(value, max)
+
+ if (text === null) return { ok: false, why: value.trim() === '' ? 'type the guidance first (the field above)' : 'the text cannot start with a dash' }
+ if (cleanText(text) !== text) return { ok: false, why: 'the text looks like it holds a credential: it is not sent' }
+
+ return { ok: true, text }
+}
+
+const none = (id: string, label: string, kind: Acts, why: string): GuideAction => ({ id, label, sends: 'nothing yet', acts: '', kind, spec: null, why })
+
+/** A task, claim and agent the guidance can name: the picked ruflo agent's open claim, its open task, and the next agent after it. */
+function picks(input: GuideInput): { agent: AgentRecord | null; claim: ClaimRecord | null; task: TaskRecord | null; next: AgentRecord | null } {
+ const agent = input.agent?.ruflo ?? null
+ const live = input.agents.filter(candidate => !/stop|terminat|offline/i.test(candidate.status))
+ const at = agent === null ? -1 : live.findIndex(candidate => candidate.id === agent.id)
+ const next = at < 0 || live.length < 2 ? null : (live[(at + 1) % live.length] ?? null)
+ const claim = agent === null ? null : (input.claims.find(candidate => candidate.claimant.id === agent.id && isOpenClaim(candidate)) ?? null)
+ const task = agent === null ? null : (input.tasks.find(candidate => candidate.assignedTo.includes(agent.id) && isOpenTask(candidate)) ?? null)
+
+ return { agent, claim, task, next }
+}
+
+/** The memory note: stored in the shared `guidance` namespace, found by a memory search; nothing pushes it into a running agent. */
+function memoryNote(input: GuideInput, text: string): ActionSpec | null {
+ const scope = cleanText(`${input.run.name} · ${input.agent?.label ?? 'whole run'}`)
+ const value = textArg(`guidance for ${scope}: ${text}`, 500)
+ const key = `guidance-${input.run.id.replace(/[^A-Za-z0-9]/g, '').slice(-8)}-${input.nowMs}`
+
+ return value === null ? null : { label: `store a guidance note for ${scope.slice(0, 40)} in namespace guidance`, args: ['memory', 'store', '--key', key, '--value', value, '--namespace', 'guidance'], expect: 'one more entry in the guidance memory namespace', note: 'Writes one memory entry. It is found by a memory search; nothing is pushed into a running agent.' }
+}
+
+/** The prompt for the main session: stop the run in Claude Code, then resume it with the guidance added. Text only; the console sends it nowhere else. */
+export function redirectText(run: WfRun, agent: WfAgent | null, text: string, isRunPath: (path: string) => boolean): string | null {
+ const session = run.dir === undefined || !isRunPath(run.dir) ? null : run.dir.replace(/\/subagents\/workflows\/[^/]+\/?$/, '')
+ const where = session === null ? 'its scripts folder (<session>/workflows/scripts)' : `${session}/workflows/scripts/${plain(run.name, 40)}-${plain(run.id, 40)}.js`
+
+ return idOf(run.id) === null ? null : `Redirect Claude Code workflow run ${run.id} (${plain(run.name, 40)}${agent === null ? '' : `, agent "${plain(agent.label, 60)}"`}): stop the run in the Workflows panel, then resume it with Workflow({ scriptPath: <${where}>, resumeFromRunId: "${run.id}" }) after adding this guidance to the affected agent's prompt: ${text}`
+}
+
+/** What the guide tab offers for the run and agent under the cursor, each with its exact send and whether anything acts on it. */
+export function guideActions(input: GuideInput): GuideAction[] {
+ const typed = guardText(input.text, 300)
+
+ if (!typed.ok) return [none('guide', 'guidance', 'record-only', typed.why)]
+
+ const text = typed.text
+ const out: GuideAction[] = []
+ const add = (id: string, label: string, kind: Acts, spec: ActionSpec | null, acts: string, why: string) => out.push({ id, label, kind, spec, acts, why, sends: spec === null ? 'nothing yet' : commandOf(spec) })
+
+ if (input.run.kind === 'ruflo-swarm') {
+ const { agent, claim, task, next } = picks(input)
+
+ add('broadcast', 'broadcast to the hive', 'record-only', input.hive === null ? null : hiveBroadcast(text), 'Appended to the hive shared memory (the last 100). No worker is interrupted: one sees it only if its own turn reads the hive memory.', input.hive === null ? 'there is no hive-mind to broadcast to' : 'that text cannot be passed to ruflo')
+ add('propose', 'propose it to the hive', 'needs-votes', input.hive === null ? null : hivePropose(input.hive, `guidance: ${text}`), 'Opens a proposal that workers vote on. A pass binds no agent to do anything; raft allows one open proposal per term.', input.hive === null ? 'there is no hive-mind to propose to' : 'raft already has a proposal open this term, or the text cannot be passed')
+
+ const handoff = claim === null || next === null ? null : handoffClaim(claim, next)
+
+ add('handoff', next === null ? 'hand its claim on' : `hand its claim to ${next.name ?? next.type}`, 'pending-accept', handoff, 'Marks a pending handoff on the claim. It takes effect only when the target accepts it (claims_accept-handoff); the current holder is not stopped.', agent === null ? 'pick a ruflo agent first (Agents column)' : claim === null ? 'the picked agent holds no open claim' : 'there is no other live agent to hand it to')
+
+ const taskId = task === null ? null : idOf(task.id)
+ const spec: ActionSpec | null =
+ task === null || taskId === null || task.resultText !== undefined
+ ? null
+ : { label: `note the guidance on task ${taskId}`, args: ['mcp', 'exec', '-t', 'task_update', '-p', JSON.stringify({ taskId, result: { guidance: text } })], expect: 'a result on the task record', note: 'Writes the task record. An agent sees it only when it reads the task.' }
+
+ add('task-note', 'note it on its task', 'record-only', spec, 'Stored as the task record\'s result. The agent is not told: it reads it only if it reads its task.', agent === null ? 'pick a ruflo agent first (Agents column)' : task === null ? 'the picked agent has no open task' : 'that task already has a result: a note would replace it')
+ }
+
+ add('memory', 'leave a note in shared memory', 'record-only', memoryNote(input, text), 'Stored in the guidance memory namespace. Found by a memory search (all namespaces, or --namespace guidance); nothing is pushed into a running agent. Whether an agent\'s turn searches memory is up to it.', 'that text cannot be passed to ruflo')
+
+ if (input.run.kind === 'workflow') {
+ const prompt = redirectText(input.run, input.agent, text, input.isRunPath)
+
+ add('redirect', 'prepare a redirect for the main session', 'prompt-only', prompt === null ? null : { label: 'prepare the redirect text in the main session\'s prompt box', args: [], shows: prompt.slice(0, 160), expect: 'the text in the prompt box (it is not sent)', note: 'Text only: it goes to the main Claude session, never to the running workflow. The console cannot stop or message a workflow; resuming applies to a stopped run.', run: () => input.prepare(prompt) }, 'Prepares text in your prompt box; you press Enter. The running workflow is not touched: stopping it is done in Claude Code\'s Workflows panel.', 'this run has no id the console can pass on')
+ }
+
+ return out
+}
diff --git a/plugins/ruflo-console/hooks/data/wf-links.ts b/plugins/ruflo-console/hooks/data/wf-links.ts
new file mode 100644
index 0000000000..3be17bc930
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/wf-links.ts
@@ -0,0 +1,162 @@
+/**
+ * Mission task <-> agent links (ADR-460). Pure: records in, a link index out. Only links the data really carries are made, and an
+ * agent or task with none is reported as unlinked, with the reason, never guessed from a similar word:
+ *
+ * ruflo agent WfAgent.ruflo.id is in a ruflo task's `assignedTo`, and that task carries the `mission:<id>` and `task:<id>` tags
+ * mission-specs.ts writes (or its id is a ledger task's `rufloTaskId`)
+ * workflow agent its journal label begins with the tag `[mission:<id> task:<id>]`, which a script drafted by data/wf-mission-script.ts
+ * puts there. A hand-written script has no such tag, so its agents are honestly unlinked.
+ */
+import type { MissionRecord } from '../mission-types'
+import type { Mission } from './missions'
+import { plain, type TaskRecord } from './parse'
+import type { WfRun } from './workflows'
+
+/** A mission task as either source names it: the console's ledger, or the ADR-406 observation. */
+export type MissionTaskRef = { missionId: string; taskId: string; title: string; rufloTaskId?: string }
+
+export type LinkVia = 'ruflo-task' | 'label-tag'
+
+export type AgentLink = {
+ missionId: string
+ taskId: string
+ title: string
+ runId: string
+ agentId: string
+ agentLabel: string
+ via: LinkVia
+ /** The ruflo task's own status, where the link came through one. */
+ taskStatus?: string
+ /** False when the mission or task is named by the agent's side only (it is in no ledger this console holds). */
+ isKnown: boolean
+}
+
+export type Unlinked = { runId: string; agentId: string; label: string; why: string }
+
+export type LinkIndex = {
+ links: AgentLink[]
+ unlinked: Unlinked[]
+ /** `<runId>/<agentId>` to that agent's links, open tasks first. */
+ byAgent: Map<string, AgentLink[]>
+ /** `<missionId>/<taskId>` to the agents on that task. */
+ byTask: Map<string, AgentLink[]>
+}
+
+const ID = '[A-Za-z0-9_.:-]{1,60}'
+const TAG = new RegExp(`^\\[mission:(${ID}) task:(${ID})\\]\\s*`)
+const PART = new RegExp(`^${ID}$`)
+
+export const agentKey = (runId: string, agentId: string): string => `${runId}/${agentId}`
+export const taskKey = (missionId: string, taskId: string): string => `${missionId}/${taskId}`
+
+/** The tag a drafted script puts at the front of an agent's label, or null when an id could not survive being read back. */
+export const labelTag = (missionId: string, taskId: string): string | null => (PART.test(missionId) && PART.test(taskId) ? `[mission:${missionId} task:${taskId}]` : null)
+
+/** The ids a label's leading tag names; `malformed` is true for a label that starts like a tag but is not one. */
+export function readLabelTag(label: string): { missionId: string; taskId: string; rest: string } | { malformed: true } | null {
+ const match = TAG.exec(label)
+
+ if (match !== null) return { missionId: match[1] as string, taskId: match[2] as string, rest: label.slice(match[0].length) }
+
+ return label.startsWith('[mission:') ? { malformed: true } : null
+}
+
+export function refsOfLedger(missions: Iterable<MissionRecord>): MissionTaskRef[] {
+ const out: MissionTaskRef[] = []
+
+ for (const mission of missions) {
+ for (const task of mission.tasks) out.push({ missionId: mission.id, taskId: task.id, title: task.title, ...(task.rufloTaskId !== undefined && { rufloTaskId: task.rufloTaskId }) })
+ }
+
+ return out
+}
+
+export const refsOfObservation = (missions: readonly Mission[] | null | undefined): MissionTaskRef[] => (missions ?? []).flatMap(mission => mission.plan.tasks.map(task => ({ missionId: mission.id, taskId: task.id, title: task.title })))
+
+/** Both sources in one list; where both name a task, the ledger's entry (it knows the ruflo task id) wins. */
+export function refsOf(ledger: Iterable<MissionRecord>, observed: readonly Mission[] | null | undefined): MissionTaskRef[] {
+ const out = new Map<string, MissionTaskRef>()
+
+ for (const ref of [...refsOfObservation(observed), ...refsOfLedger(ledger)]) out.set(taskKey(ref.missionId, ref.taskId), ref)
+
+ return [...out.values()]
+}
+
+const tagOf = (task: TaskRecord, prefix: 'mission' | 'task'): string | undefined => task.tags?.find(tag => tag.startsWith(`${prefix}:`))?.slice(prefix.length + 1)
+const isOpen = (status: string | undefined): boolean => status !== 'completed' && status !== 'failed' && status !== 'cancelled'
+
+/** Builds the index over every agent of `runs` (the ruflo swarm folded in as a run, as the page holds it). */
+export function linkAgents(refs: readonly MissionTaskRef[], runs: readonly WfRun[], tasks: readonly TaskRecord[]): LinkIndex {
+ const byKey = new Map(refs.map(ref => [taskKey(ref.missionId, ref.taskId), ref]))
+ const byRuflo = new Map(refs.flatMap(ref => (ref.rufloTaskId === undefined ? [] : [[ref.rufloTaskId, ref] as const])))
+ const links: AgentLink[] = []
+ const unlinked: Unlinked[] = []
+
+ for (const run of runs) {
+ for (const phase of run.phases) {
+ for (const agent of phase.agents) {
+ const mine: AgentLink[] = []
+ const base = { runId: run.id, agentId: agent.id, agentLabel: agent.label }
+
+ if (agent.ruflo !== undefined) {
+ for (const task of tasks.filter(candidate => candidate.assignedTo.includes(agent.id))) {
+ const known = byRuflo.get(task.id)
+ const missionId = known?.missionId ?? tagOf(task, 'mission')
+ const taskId = known?.taskId ?? tagOf(task, 'task')
+
+ if (missionId === undefined || taskId === undefined) continue
+
+ const ref = known ?? byKey.get(taskKey(missionId, taskId))
+
+ mine.push({ ...base, missionId, taskId, title: ref?.title ?? plain(task.description, 80), via: 'ruflo-task', taskStatus: task.status, isKnown: ref !== undefined })
+ }
+ } else {
+ const tag = readLabelTag(agent.label)
+
+ if (tag !== null && !('malformed' in tag)) {
+ const ref = byKey.get(taskKey(tag.missionId, tag.taskId))
+
+ mine.push({ ...base, missionId: tag.missionId, taskId: tag.taskId, title: ref?.title ?? plain(tag.rest, 80), via: 'label-tag', isKnown: ref !== undefined })
+ } else if (tag !== null) {
+ unlinked.push({ ...base, label: agent.label, why: 'its label starts like a mission tag but is not [mission:<id> task:<id>]' })
+ continue
+ }
+ }
+
+ if (mine.length === 0) {
+ unlinked.push({ ...base, label: agent.label, why: agent.ruflo !== undefined ? 'no ruflo task with mission:/task: tags is assigned to this agent' : 'its label has no [mission:<id> task:<id>] tag (a script the console drafts adds one)' })
+ continue
+ }
+
+ // Open tasks first: an agent shows the task it is on before the ones it finished.
+ links.push(...[...mine].sort((a, b) => Number(isOpen(b.taskStatus)) - Number(isOpen(a.taskStatus))))
+ }
+ }
+ }
+
+ const byAgent = new Map<string, AgentLink[]>()
+ const byTask = new Map<string, AgentLink[]>()
+
+ for (const link of links) {
+ for (const [map, key] of [[byAgent, agentKey(link.runId, link.agentId)], [byTask, taskKey(link.missionId, link.taskId)]] as const) map.set(key, [...(map.get(key) ?? []), link])
+ }
+
+ return { links, unlinked, byAgent, byTask }
+}
+
+/** The one line an agent row shows for its mission task, or says it is unlinked and why. */
+export function agentLinkLine(index: LinkIndex, runId: string, agentId: string): string {
+ const mine = index.byAgent.get(agentKey(runId, agentId)) ?? []
+ const first = mine[0]
+
+ if (first === undefined) return `unlinked: ${index.unlinked.find(entry => entry.runId === runId && entry.agentId === agentId)?.why ?? 'not read'}`
+
+ return `${first.missionId} / ${first.taskId}: ${first.title}${first.taskStatus === undefined ? '' : ` (${first.taskStatus})`}${first.isKnown ? '' : ' · not in this console\'s mission ledger'}${mine.length > 1 ? ` · +${mine.length - 1} more` : ''}`
+}
+
+/** The line a mission task shows for its agents, or says none is working on it. */
+export function taskLinkLine(index: LinkIndex, ref: MissionTaskRef): string {
+ const mine = index.byTask.get(taskKey(ref.missionId, ref.taskId)) ?? []
+
+ return mine.length === 0 ? 'unlinked: no ruflo agent or workflow agent names this task' : mine.map(link => `${link.agentLabel} (${link.via === 'ruflo-task' ? 'ruflo task' : 'label tag'})`).join(', ')
+}
diff --git a/plugins/ruflo-console/hooks/data/wf-mission-script.ts b/plugins/ruflo-console/hooks/data/wf-mission-script.ts
new file mode 100644
index 0000000000..2b34a9d597
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/wf-mission-script.ts
@@ -0,0 +1,173 @@
+/**
+ * "Run this mission as a workflow" (ADR-460): a native `.claude/workflows/<name>.js` script drafted from a mission's SPARC plan,
+ * for review, plus the dry-run estimate of what it would start. Pure text in, text out: nothing here writes a file or runs anything;
+ * the launch is views/wf-guide.ts's confirm card, which hands the reviewed text to the main Claude session.
+ *
+ * The script obeys the workflow-create skill: `meta` is a pure literal, the plan's tasks are data (JSON, so no mission text is ever
+ * code), tasks run level by level (a level is every task whose dependencies are all in earlier levels) with `parallel` inside a
+ * level, and nothing calls Date.now() or Math.random(). Each agent's label starts with the tag data/wf-links.ts reads back, so the
+ * run's agents link to their mission tasks. The estimate is counted from the plan only: tokens and cost are n/a, there is no data.
+ */
+import type { MissionRecord } from '../mission-types'
+import { cleanText } from './wf-clean'
+import { labelTag } from './wf-links'
+
+export type ScriptTask = { id: string; title: string; stage?: string; agent?: string; requirement?: string; dependsOn: readonly string[] }
+export type ScriptMission = { id: string; objective: string; tasks: readonly ScriptTask[] }
+
+export type Estimate = {
+ /** One agent per task. */
+ agents: number
+ /** Levels run one after another. */
+ levels: number
+ /** The most agents running at once (the widest level). */
+ widest: number
+ phases: string[]
+ /** Roles passed as `agentType`; the others ride in the prompt only. */
+ typed: number
+}
+
+export type Draft = { ok: true; name: string; path: string; source: string; estimate: Estimate; warnings: string[] } | { ok: false; why: string }
+
+/** More than this is not a script a person reviews in one sitting. */
+export const MAX_AGENTS = 30
+
+/** Subagent types a Claude Code session is known to resolve; any other role from the plan is named in the prompt instead. */
+const KNOWN_TYPES: ReadonlySet<string> = new Set(['coder', 'tester', 'reviewer', 'researcher', 'planner', 'security-auditor', 'security-architect', 'performance-engineer', 'cicd-engineer', 'api-docs'])
+const LABEL_MAX = 80
+
+export const scriptMissionOf = (mission: MissionRecord): ScriptMission => ({
+ id: mission.id,
+ objective: mission.objective,
+ tasks: mission.tasks.map(task => ({ id: task.id, title: task.title, stage: task.stage ?? task.phase, agent: task.agent, requirement: task.requirement, dependsOn: task.dependsOn })),
+})
+
+const clip = (value: string, max: number): string => (value.length <= max ? value : `${value.slice(0, max - 1)}…`)
+const clean = (value: string | undefined, max: number): string => clip(cleanText(value ?? '').replace(/\s+/g, ' ').trim(), max)
+const slug = (id: string): string => `mission-${id.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 36)}`.replace(/-+$/, '')
+
+/** Task indexes grouped by level, or null when the dependencies run in a circle. A dependency on an id the plan lacks is ignored (and reported). */
+export function levelsOf(tasks: readonly ScriptTask[]): number[][] | null {
+ const index = new Map(tasks.map((task, i) => [task.id, i]))
+ const depth: (number | undefined)[] = tasks.map(() => undefined)
+ const visiting = new Set<number>()
+ const visit = (i: number): number | null => {
+ const held = depth[i]
+
+ if (held !== undefined) return held
+ if (visiting.has(i)) return null
+
+ visiting.add(i)
+
+ let deepest = 0
+
+ for (const dep of (tasks[i] as ScriptTask).dependsOn) {
+ const at = index.get(dep)
+
+ if (at === undefined) continue
+
+ const d = visit(at)
+
+ if (d === null) return null
+
+ deepest = Math.max(deepest, d + 1)
+ }
+
+ visiting.delete(i)
+ depth[i] = deepest
+
+ return deepest
+ }
+
+ for (let i = 0; i < tasks.length; i++) if (visit(i) === null) return null
+
+ const levels: number[][] = []
+
+ tasks.forEach((_, i) => (levels[depth[i] as number] ??= []).push(i))
+
+ return levels
+}
+
+export function draftScript(mission: ScriptMission): Draft {
+ const tasks = mission.tasks
+
+ if (tasks.length === 0) return { ok: false, why: 'the mission has no tasks to run' }
+ if (tasks.length > MAX_AGENTS) return { ok: false, why: `${tasks.length} tasks is more than the ${MAX_AGENTS} one reviewed script holds` }
+ if (new Set(tasks.map(task => task.id)).size !== tasks.length) return { ok: false, why: 'two tasks share an id' }
+
+ const levels = levelsOf(tasks)
+
+ if (levels === null) return { ok: false, why: 'the tasks depend on each other in a circle' }
+
+ const warnings: string[] = []
+ const known = new Set(tasks.map(task => task.id))
+
+ for (const task of tasks) for (const dep of task.dependsOn) if (!known.has(dep)) warnings.push(`task ${clean(task.id, 40)} depends on ${clean(dep, 40)}, which the plan does not have: ignored`)
+
+ const objective = clean(mission.objective, 400)
+ const data = tasks.map(task => {
+ const tag = labelTag(mission.id, task.id)
+ const title = clean(task.title, 80)
+ const role = clean(task.agent, 40)
+ const isTyped = KNOWN_TYPES.has(role)
+
+ if (tag === null) warnings.push(`task ${clean(task.id, 40)} has an id that cannot be tagged: its agent will show as unlinked`)
+
+ return {
+ id: clean(task.id, 60),
+ label: clip(`${tag === null ? '' : `${tag} `}${title}`, LABEL_MAX),
+ ...(isTyped && { agentType: role }),
+ prompt: [`Mission: ${objective}`, `Your task ${clean(task.id, 60)}: ${title}`, role === '' ? '' : `Act as: ${role}.`, task.requirement === undefined ? '' : `It is done when: ${clean(task.requirement, 300)}`, 'Report done=true only if that is true, with a short summary and the evidence (files, commands, test output).'].filter(line => line !== '').join('\n'),
+ needs: task.dependsOn.flatMap(dep => (known.has(dep) ? [tasks.findIndex(other => other.id === dep)] : [])),
+ }
+ })
+ const phaseOf = (level: number[]): string => [...new Set(level.map(i => clean((tasks[i] as ScriptTask).stage, 30) || 'Run'))].join(' + ')
+ const plan = levels.map(ids => ({ phase: phaseOf(ids), ids }))
+ const phases = [...new Set(plan.map(level => level.phase))]
+ const name = slug(mission.id)
+ const lit = (value: unknown): string => JSON.stringify(value, null, 2)
+ const source = [
+ `// Drafted by ruflo-console from mission ${JSON.stringify(clean(mission.id, 60))}. Review it, then run it with Workflow({ scriptPath }).`,
+ 'export const meta = {',
+ ` name: ${JSON.stringify(name)},`,
+ ` description: ${JSON.stringify(clip(`Run mission: ${objective}`, 160))},`,
+ ` phases: ${JSON.stringify(phases.map(title => ({ title })))},`,
+ '}',
+ '',
+ `const MISSION = ${JSON.stringify(clean(mission.id, 60))}`,
+ `const TASKS = ${lit(data)}`,
+ `const LEVELS = ${lit(plan)}`,
+ "const SCHEMA = { type: 'object', additionalProperties: false, required: ['done', 'summary', 'evidence'], properties: { done: { type: 'boolean' }, summary: { type: 'string' }, evidence: { type: 'string' } } }",
+ '',
+ 'const results = []',
+ 'for (const level of LEVELS) {',
+ ' phase(level.phase)',
+ ' const batch = await parallel(level.ids.map((i) => () => {',
+ ' const t = TASKS[i]',
+ " const before = t.needs.map((n) => `${TASKS[n].id}: ${(results[n] && results[n].summary) || 'no report'}`).join('\\n')",
+ " const prompt = before ? `${t.prompt}\\n\\nAlready done before you:\\n${before}` : t.prompt",
+ ' return agent(prompt, { label: t.label, phase: level.phase, schema: SCHEMA, ...(t.agentType ? { agentType: t.agentType } : {}) })',
+ ' }))',
+ ' level.ids.forEach((i, k) => { results[i] = batch[k] })',
+ '}',
+ '',
+ 'const notDone = TASKS.filter((_, i) => !results[i] || !results[i].done).map((t) => t.id)',
+ 'log(`mission ${MISSION}: ${TASKS.length - notDone.length}/${TASKS.length} tasks reported done`)',
+ 'return { mission: MISSION, notDone, results: TASKS.map((t, i) => ({ id: t.id, report: results[i] || null })) }',
+ '',
+ ].join('\n')
+
+ return { ok: true, name, path: `.claude/workflows/${name}.js`, source, warnings, estimate: { agents: tasks.length, levels: levels.length, widest: Math.max(...levels.map(level => level.length)), phases, typed: data.filter(task => 'agentType' in task).length } }
+}
+
+/** The dry-run lines the review shows: counts from the plan, and what is not known. */
+export function estimateLines(draft: Extract<Draft, { ok: true }>): string[] {
+ const { agents, levels, widest, phases, typed } = draft.estimate
+
+ return [
+ `${agents} agents in ${levels} level${levels === 1 ? '' : 's'}, at most ${widest} at once · phases: ${phases.join(', ')}`,
+ `${typed} of ${agents} carry a subagent type; the rest take their role from the prompt`,
+ 'tokens, time and cost: n/a (the console has no measurement of a script that has not run)',
+ ...draft.warnings,
+ ]
+}
diff --git a/plugins/ruflo-console/hooks/views/wf-guide.ts b/plugins/ruflo-console/hooks/views/wf-guide.ts
new file mode 100644
index 0000000000..db8d4a332b
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/wf-guide.ts
@@ -0,0 +1,197 @@
+/**
+ * The links, nesting, mission-script and guidance parts of the Workflows page (ADR-460), plugged into the page only through its slot
+ * registry (views/wf-slots.ts): two boards, two inspector tabs and a notice slot, no hotkeys, no edit of any shared file. Importing this
+ * module registers them (the merge owner adds `import './wf-guide'` to views/wf-register.ts). Every number drawn is counted from the
+ * records the page already holds; an empty source says so. Every write is an ActionSpec through the page's confirm card.
+ */
+import type { RenderElement } from 'claude-code'
+
+import { activeMission, mcOf, missionWired, saveLedger } from '../mission-control'
+import { cleanText } from '../data/wf-clean'
+import { applyMissionEvents, eventsBetween } from '../data/wf-events'
+import { guideActions, nestingOf, type GuideAction, type NestKind } from '../data/wf-guide'
+import { agentKey, agentLinkLine, linkAgents, refsOf, taskLinkLine, type LinkIndex, type MissionTaskRef } from '../data/wf-links'
+import { draftScript, estimateLines, scriptMissionOf, type Draft } from '../data/wf-mission-script'
+import type { WfRun } from '../data/workflows'
+import type { ActionSpec } from '../actions'
+import type { Host } from '../host'
+import type { State } from '../state'
+import { isRunPath } from '../wf-actions'
+import { button, clip, col, kv, row, section, text, THEME, type Ctx } from './common'
+import { registerSlot, type Registered, type SlotEnv } from './wf-slots'
+
+const GLYPH: Record<NestKind, string> = { swarm: '◎', hive: '⬡', queen: '♛', worker: '●', claim: '⚑', task: '▪', note: '·' }
+/** The script review shows at most this many lines; the full text is what the launch prepares, and the page says how many it holds. */
+export const REVIEW_LINES = 80
+
+/** What the guide tab keeps between frames: the sentence typed. */
+const drafts = new WeakMap<State, { text: string }>()
+const draftOf = (state: State): { text: string } => {
+ let held = drafts.get(state)
+
+ if (held === undefined) {
+ held = { text: '' }
+ drafts.set(state, held)
+ }
+
+ return held
+}
+
+/** The link index for this frame: the ledger and the observed missions against every agent the page holds. */
+export function indexOf(env: SlotEnv): { index: LinkIndex; refs: MissionTaskRef[] } {
+ const state = env.ctx.state
+ const refs = refsOf(mcOf(state).missions.values(), state.snapshot?.missions?.missions)
+
+ return { index: linkAgents(refs, env.runs, state.snapshot?.tasks ?? []), refs }
+}
+
+/** Puts text in the main session's prompt box and says so on the outcome row; never sends it. */
+function prepareIn(state: State, label: string): (text: string) => Promise<void> {
+ return async text => {
+ const host = missionWired(state)?.host
+ const say = (ok: boolean, detail: string) => {
+ state.outcome = { label, ok, verified: 'n/a', detail, atMs: Date.now() }
+ host?.invalidate()
+ }
+
+ if (host === undefined) return say(false, 'the console is not wired to a host here')
+
+ say(await host.fillPrompt(text).catch(() => false), 'prepared in the prompt box: press Enter there to send it')
+ }
+}
+
+const line = (ctx: Ctx, value: string, props: { color?: string; dimColor?: boolean; bold?: boolean } = {}): RenderElement => text(ctx, cleanText(value), props)
+
+function linksBoard(env: SlotEnv): RenderElement[] {
+ const { ctx } = env
+ const { index, refs } = indexOf(env)
+ const rows: RenderElement[] = [line(ctx, `${index.links.length} agent-to-task links · ${index.unlinked.length} agents unlinked · ${refs.length} mission tasks known`, { dimColor: true })]
+
+ if (refs.length === 0) rows.push(line(ctx, 'No mission yet in the ledger or the observation: make one in Mission Control. Agents then link by their ruflo task tags (mission:<id> task:<id>) or by the label tag a drafted script adds.', { dimColor: true }))
+
+ for (const ref of refs.filter(entry => (index.byTask.get(`${entry.missionId}/${entry.taskId}`) ?? []).length > 0).slice(0, 8)) rows.push(line(ctx, ` ${ref.missionId}/${ref.taskId} ${ref.title} -> ${taskLinkLine(index, ref)}`))
+
+ const open = refs.filter(entry => (index.byTask.get(`${entry.missionId}/${entry.taskId}`) ?? []).length === 0).length
+
+ if (refs.length > 0) rows.push(line(ctx, `${open} mission tasks unlinked: no agent names them`, { dimColor: true }))
+
+ const why = [...new Set(index.unlinked.map(entry => entry.why))].slice(0, 2)
+
+ for (const reason of why) rows.push(line(ctx, ` agents unlinked: ${reason}`, { dimColor: true }))
+
+ return rows
+}
+
+function nestingBoard(env: SlotEnv): RenderElement[] {
+ const { ctx, run } = env
+ const snap = ctx.state.snapshot
+
+ if (run === null || run.kind !== 'ruflo-swarm') return [line(ctx, 'Pick the ruflo swarm run ([ ] to switch) to see how its swarm, hive, workers, claims and tasks nest.', { dimColor: true })]
+
+ const rows = nestingOf({ swarm: snap?.swarm ?? null, hive: snap?.hive ?? null, agents: snap?.agents ?? [], hiveAgents: snap?.hiveAgents ?? [], claims: snap?.claims ?? [], tasks: snap?.tasks ?? [] })
+
+ return rows.map(entry => line(ctx, `${' '.repeat(entry.depth)}${GLYPH[entry.kind]} ${entry.label} ${entry.detail}`, entry.kind === 'note' ? { dimColor: true } : entry.kind === 'queen' ? { color: THEME.warn } : {}))
+}
+
+/** The launch: the reviewed script, handed to the main session behind the confirm card (it writes the file and runs it when the person presses Enter there). */
+export function launchSpec(state: State, draft: Extract<Draft, { ok: true }>, missionId: string): ActionSpec {
+ const prompt = `Write exactly this script to ${draft.path} (create the folder if it is missing), then run it with Workflow({ name: "${draft.name}" }) and report what it returns.\n\n\`\`\`js\n${draft.source}\`\`\``
+
+ return {
+ label: `prepare the workflow for mission ${cleanText(missionId).slice(0, 40)} in the main session`,
+ args: [],
+ shows: `${draft.path}: ${draft.estimate.agents} agents in ${draft.estimate.levels} levels, ${draft.source.split('\n').length} lines, prepared in the prompt box`,
+ expect: 'the script text in the prompt box (it is not sent)',
+ note: 'Starts nothing here: the text waits in your prompt box. When you press Enter, Claude writes the file and runs the workflow, and every agent bills as a subagent does. The console cannot stop it afterwards.',
+ run: () => prepareIn(state, 'workflow script')(prompt),
+ }
+}
+
+function missionBoard(env: SlotEnv): RenderElement[] {
+ const { ctx } = env
+ const mission = activeMission(ctx.state)
+
+ if (mission === null) return [line(ctx, 'No active mission: create one in Mission Control, and its SPARC plan can be drafted here as a workflow script for review.', { dimColor: true })]
+
+ const draft = draftScript(scriptMissionOf(mission))
+
+ if (!draft.ok) return [line(ctx, `Mission ${mission.id} cannot be drafted: ${draft.why}`, { color: THEME.warn })]
+
+ const lines = draft.source.split('\n')
+ const shown = lines.slice(0, REVIEW_LINES)
+ const rows: RenderElement[] = [kv(ctx, 'mission', cleanText(`${mission.id} · ${clip(mission.objective, 60)}`)), kv(ctx, 'script', draft.path), ...estimateLines(draft).map(entry => line(ctx, ` ${entry}`, { dimColor: true }))]
+
+ rows.push(...section(ctx, 'wf-script', 'Review the script', `${shown.length} of ${lines.length} lines shown`, shown.map(entry => text(ctx, entry, { dimColor: true })), false))
+ if (lines.length > shown.length) rows.push(line(ctx, `${lines.length - shown.length} more lines are not drawn here; the prepared text holds all ${lines.length}.`, { dimColor: true }))
+ rows.push(row(ctx, [button(ctx, 'wf-mission-launch', 'Prepare to run as a workflow', () => ctx.act.workflows.ask(launchSpec(ctx.state, draft, mission.id), 'no script to prepare'))], 'wf-mission-run'))
+
+ return rows
+}
+
+function missionTab(env: SlotEnv): RenderElement[] {
+ const { ctx, run, agent } = env
+
+ if (run === null || agent === null) return [line(ctx, 'Pick an agent first.', { dimColor: true })]
+
+ const { index } = indexOf(env)
+ const mine = index.byAgent.get(agentKey(run.id, agent.id)) ?? []
+
+ return [
+ kv(ctx, 'agent', cleanText(agent.label)),
+ kv(ctx, 'mission task', agentLinkLine(index, run.id, agent.id), mine.length === 0 ? THEME.warn : undefined),
+ ...mine.slice(0, 6).map(link => line(ctx, ` ${link.missionId}/${link.taskId} ${link.title} · via ${link.via === 'ruflo-task' ? 'a ruflo task assigned to it' : 'its label tag'}${link.taskStatus === undefined ? '' : ` · task ${link.taskStatus}`}`, { dimColor: true })),
+ ]
+}
+
+function guideRows(ctx: Ctx, actions: readonly GuideAction[], run: WfRun): RenderElement[] {
+ const rows: RenderElement[] = []
+
+ for (const action of actions) {
+ rows.push(button(ctx, `wf-guide-${action.id}`, action.label, () => ctx.act.workflows.ask(action.spec, action.why)))
+ rows.push(line(ctx, ` sends: ${action.sends}`, { dimColor: true }))
+ if (action.acts !== '') rows.push(line(ctx, ` acts: ${action.acts}`, { dimColor: true }))
+ }
+
+ rows.push(line(ctx, run.kind === 'workflow' ? 'A running Claude Code workflow cannot be stopped or messaged from here: the console only reads it. The note is found by a memory search; the redirect is text for the main session.' : 'ruflo agents are not interrupted by any of these: each writes a record that an agent sees when it reads that store.', { dimColor: true }))
+
+ return rows
+}
+
+function guideTab(env: SlotEnv): RenderElement[] {
+ const { ctx, run, agent } = env
+
+ if (run === null) return [line(ctx, 'No run picked.', { dimColor: true })]
+
+ const draft = draftOf(ctx.state)
+ const snap = ctx.state.snapshot
+ const field = ctx.kit.Input === undefined ? line(ctx, 'this surface has no text field: the guide needs one', { dimColor: true }) : ctx.kit.Input({ key: 'wf-guide-text', label: 'guidance', placeholder: 'what the agents should know or do differently', submitLabel: 'set', onSubmit: value => { draft.text = value; ctx.act.workflows.setUi({}) } })
+ const actions = guideActions({ text: draft.text, run, agent, hive: snap?.hive ?? null, agents: snap?.agents ?? [], claims: snap?.claims ?? [], tasks: snap?.tasks ?? [], nowMs: env.nowMs, prepare: prepareIn(ctx.state, 'redirect'), isRunPath: path => isRunPath(path, ctx.state.configDir) })
+
+ return [field, line(ctx, draft.text === '' ? 'guidance: none typed yet' : `guidance: ${draft.text}`, { color: draft.text === '' ? undefined : THEME.info }), col(ctx, guideRows(ctx, actions, run), 'wf-guide-actions')]
+}
+
+/**
+ * For the merge owner, after a read: records the mission events the change between two reads raised into the ledger, once each, and
+ * saves it. Returns how many were recorded. It lives here, not in the notice slot, because only this side holds the state and host.
+ */
+export function recordRunEvents(state: State, host: Host, before: readonly WfRun[] | null, next: readonly WfRun[], nowMs: number): number {
+ const added = applyMissionEvents(mcOf(state).missions, eventsBetween(before, next).mission, nowMs)
+
+ if (added > 0) saveLedger(state, host)
+
+ return added
+}
+
+/** Registers this feature's slots. A refusal comes back as a reason (the registry never throws), so a clash is visible to the test. */
+export function registerGuide(): Registered[] {
+ return [
+ registerSlot({ kind: 'board', id: 'links', title: 'Mission links', order: 30, render: linksBoard }),
+ registerSlot({ kind: 'board', id: 'nesting', title: 'Swarm nesting', order: 40, render: nestingBoard }),
+ registerSlot({ kind: 'board', id: 'mission-run', title: 'Run a mission as a workflow', order: 50, render: missionBoard }),
+ registerSlot({ kind: 'tab', id: 'mission', label: 'mission', when: env => env.agent !== null, render: missionTab }),
+ registerSlot({ kind: 'tab', id: 'guide', label: 'guide', when: env => env.run !== null, render: guideTab }),
+ registerSlot({ kind: 'notice', id: 'links', between: (prev, next) => eventsBetween(prev, next).notices }),
+ ]
+}
+
+registerGuide()
diff --git a/plugins/ruflo-console/tests/wf-guide.spec.ts b/plugins/ruflo-console/tests/wf-guide.spec.ts
new file mode 100644
index 0000000000..de09d6a88f
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-guide.spec.ts
@@ -0,0 +1,354 @@
+/**
+ * Nesting, guidance actions and the Workflows page's links/guide slots (ADR-460). Pure data first, then the slots through the page's
+ * own registry with a recording kit. Run with
+ * npx vitest run plugins/ruflo-console/tests/wf-guide.spec.ts --testTimeout=30000
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+
+import type { ActionSpec } from '../hooks/actions'
+import { guardText, guideActions, nestingOf, redirectText, type GuideInput } from '../hooks/data/wf-guide'
+import { labelTag } from '../hooks/data/wf-links'
+import type { AgentRecord, ClaimRecord, HiveInfo, SwarmInfo, TaskRecord } from '../hooks/data/parse'
+import type { AgentState, WfAgent, WfRun } from '../hooks/data/workflows'
+import type { Host } from '../hooks/host'
+import { mcOf } from '../hooks/mission-control'
+import type { MissionRecord } from '../hooks/mission-types'
+import { newState, type State } from '../hooks/state'
+import type { Actions, Ctx, Kit } from '../hooks/views/common'
+import { launchSpec, recordRunEvents, registerGuide, REVIEW_LINES } from '../hooks/views/wf-guide'
+import { registerSlot, resetSlots, slotsFor, type SlotEnv } from '../hooks/views/wf-slots'
+import { draftScript, scriptMissionOf } from '../hooks/data/wf-mission-script'
+import { workflowsActions } from '../hooks/wf-actions'
+import { workflowsPage } from '../hooks/views/wf-page'
+
+type El = { kind: string; props: Record<string, unknown> }
+
+const kit = { Box: (props: Record<string, unknown>): El => ({ kind: 'Box', props }), Text: (props: Record<string, unknown>): El => ({ kind: 'Text', props }), Button: (props: Record<string, unknown>): El => ({ kind: 'Button', props }), Input: (props: Record<string, unknown>): El => ({ kind: 'Input', props }) } as unknown as Kit
+const flat = (node: unknown, out: El[] = []): El[] => {
+ if (Array.isArray(node)) node.forEach(child => flat(child, out))
+ else if (typeof node === 'object' && node !== null) {
+ out.push(node as El)
+ flat((node as El).props?.children, out)
+ }
+
+ return out
+}
+const words = (tree: unknown): string => flat(tree).filter(el => el.kind === 'Text' && typeof el.props.children === 'string').map(el => el.props.children as string).join('\n')
+const buttonOf = (tree: unknown, key: string): El | undefined => flat(tree).find(el => el.kind === 'Button' && el.props.key === key)
+
+const ruflo = (id: string, status = 'busy'): AgentRecord => ({ id, type: 'coder', name: `${id}-n`, status })
+const swarm: SwarmInfo = { id: 'swarm-1', topology: 'hierarchical', status: 'running', agentIds: ['agent-1', 'agent-2'] }
+const hive = (over: Partial<HiveInfo> = {}): HiveInfo => ({ topology: 'hierarchical-mesh', strategy: 'raft', queen: 'queen-1', queenTerm: 1, workers: ['agent-1'], pending: [], history: [], broadcasts: [], memoryKeys: [], ...over }) as HiveInfo
+const claim = (issueId: string, holder: string): ClaimRecord => ({ issueId, status: 'active', claimant: { kind: 'agent', id: holder, agentType: 'coder' }, isStealable: false })
+const task = (id: string, assignedTo: string[], over: Partial<TaskRecord> = {}): TaskRecord => ({ id, type: 'feature', description: `desc ${id}`, status: 'in_progress', assignedTo, ...over })
+
+describe('nestingOf', () => {
+ const base = { swarm, hive: hive(), agents: [ruflo('agent-1'), ruflo('agent-2')], hiveAgents: [], claims: [claim('task-1', 'agent-1')], tasks: [task('task-1', ['agent-1'])] }
+
+ it('nests swarm > hive > queen > worker > claim > task, each only from what the stores say', () => {
+ const rows = nestingOf(base)
+
+ expect(rows.map(row => `${row.depth}${row.kind}`)).toEqual(['0swarm', '1hive', '2queen', '2worker', '3claim', '4task', '1note'])
+ expect(rows[3]?.detail).toMatch(/in the swarm/)
+ expect(rows.at(-1)?.label).toMatch(/1 swarm agents outside the hive/)
+ })
+
+ it('says each missing level instead of drawing one: no swarm, no hive, no claim, a claim with no task record', () => {
+ expect(nestingOf({ ...base, swarm: null, hive: null, claims: [], tasks: [] }).map(row => row.label)).toEqual(['no swarm', 'no hive-mind'])
+ expect(nestingOf({ ...base, claims: [], tasks: [] }).some(row => row.label === 'no claim, no task')).toBe(true)
+ expect(nestingOf({ ...base, tasks: [] }).some(row => row.label === 'no task record')).toBe(true)
+ expect(nestingOf({ ...base, hive: hive({ queen: undefined }) }).some(row => row.label === 'no queen')).toBe(true)
+ })
+
+ it('a task assigned but unclaimed is shown as such, and a finished task is not shown as work', () => {
+ const rows = nestingOf({ ...base, claims: [], tasks: [task('task-2', ['agent-1']), task('task-3', ['agent-1'], { status: 'completed' })] })
+
+ expect(rows.filter(row => row.kind === 'task').map(row => row.label)).toEqual(['task-2'])
+ expect(rows.find(row => row.label === 'task-2')?.detail).toMatch(/assigned, no claim/)
+ })
+
+ it('caps a large hive and says how many rows it left out', () => {
+ const workers = Array.from({ length: 80 }, (_, i) => `agent-${i + 10}`)
+ const rows = nestingOf({ ...base, hive: hive({ workers }), agents: workers.map(id => ruflo(id)) })
+
+ expect(rows).toHaveLength(61)
+ expect(rows.at(-1)?.label).toMatch(/^\+\d+ more rows$/)
+ })
+})
+
+const flow = (state: AgentState = 'running'): WfAgent => ({ id: 'a1', label: `${labelTag('m1', 'implement')} Implement`, phase: 'Build', state, hasWorktree: false })
+const wfRun = (over: Partial<WfRun> = {}): WfRun => ({ id: 'wf_abc12345', name: 'my flow', kind: 'workflow', state: 'running', phases: [{ title: 'Build', agents: [flow()], 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 })
+const swarmRun = (): WfRun => wfRun({ id: 'swarm-1', kind: 'ruflo-swarm', dir: undefined, phases: [{ title: 'coder', agents: [{ id: 'agent-1', label: 'agent-1-n', phase: 'coder', state: 'running', hasWorktree: false, ruflo: ruflo('agent-1') }], done: 0, total: 1, running: 1, failed: 0 }] })
+
+const input = (over: Partial<GuideInput> = {}): GuideInput => {
+ const run = over.run ?? swarmRun()
+
+ return { text: 'use the cache', run, agent: run.phases[0]?.agents[0] ?? null, hive: hive(), agents: [ruflo('agent-1'), ruflo('agent-2')], claims: [claim('task-1', 'agent-1')], tasks: [task('task-1', ['agent-1'])], nowMs: 1_700_000_000_000, prepare: async () => undefined, isRunPath: path => path.startsWith('/home/u/.claude/projects/') && !path.includes('..'), ...over }
+}
+const byId = (actions: ReturnType<typeof guideActions>, id: string) => actions.find(action => action.id === id)
+
+describe('guideActions on a ruflo swarm', () => {
+ it('offers the real verbs as fixed argv, each saying what is sent and whether anything acts on it', () => {
+ const actions = guideActions(input())
+ const broadcast = byId(actions, 'broadcast') as NonNullable<ReturnType<typeof byId>>
+
+ expect(actions.map(action => action.id)).toEqual(['broadcast', 'propose', 'handoff', 'task-note', 'memory'])
+ expect(broadcast.spec?.args).toEqual(['mcp', 'exec', '-t', 'hive-mind_broadcast', '-p', JSON.stringify({ message: 'use the cache', priority: 'normal', fromId: 'console-operator' })])
+ expect(broadcast.acts).toMatch(/No worker is interrupted/)
+ expect(broadcast.sends).toContain('hive-mind_broadcast')
+ expect(byId(actions, 'propose')?.spec?.args.join(' ')).toContain('"type":"guidance"')
+ expect(byId(actions, 'propose')?.kind).toBe('needs-votes')
+ expect(byId(actions, 'handoff')?.spec?.args).toEqual(expect.arrayContaining(['claims_handoff']))
+ expect(byId(actions, 'handoff')?.spec?.args.join(' ')).toContain('"to":"agent:agent-2:coder"')
+ })
+
+ it('the task note is one fixed argv with the result as an object, and is refused when it would replace a result', () => {
+ const note = byId(guideActions(input()), 'task-note')?.spec as ActionSpec
+
+ expect(note.args).toEqual(['mcp', 'exec', '-t', 'task_update', '-p', JSON.stringify({ taskId: 'task-1', result: { guidance: 'use the cache' } })])
+
+ const held = byId(guideActions(input({ tasks: [task('task-1', ['agent-1'], { resultText: 'summary: done' })] })), 'task-note')
+
+ expect(held?.spec).toBeNull()
+ expect(held?.why).toMatch(/already has a result/)
+ })
+
+ it('refuses a proposal raft would refuse (one open per term), and says a missing hive or claim is missing', () => {
+ const open = hive({ pending: [{ id: 'p-1', type: 'general', status: 'pending', strategy: 'raft', votesFor: 0, votesAgainst: 0, ballots: [], byzantine: [], term: 1 }] })
+
+ expect(byId(guideActions(input({ hive: open })), 'propose')?.spec).toBeNull()
+ expect(byId(guideActions(input({ hive: null })), 'broadcast')?.why).toMatch(/no hive-mind/)
+ expect(byId(guideActions(input({ claims: [] })), 'handoff')?.why).toMatch(/no open claim/)
+ expect(byId(guideActions(input({ agents: [ruflo('agent-1')] })), 'handoff')?.why).toMatch(/no other live agent/)
+ })
+
+ it('the memory note goes to the guidance namespace and says nothing pushes it into a running agent', () => {
+ const memory = byId(guideActions(input()), 'memory')
+
+ expect(memory?.spec?.args.slice(0, 2)).toEqual(['memory', 'store'])
+ expect(memory?.spec?.args).toEqual(expect.arrayContaining(['--namespace', 'guidance']))
+ expect(memory?.spec?.args[3]).toMatch(/^guidance-[A-Za-z0-9]{1,8}-1700000000000$/)
+ expect(memory?.acts).toMatch(/nothing is pushed into a running agent/)
+ })
+})
+
+describe('guideActions on a Claude Code workflow', () => {
+ const actions = guideActions(input({ run: wfRun() }))
+
+ it('has only the memory note and a prepared redirect: no broadcast, handoff or task write exists for a workflow agent', () => {
+ expect(actions.map(action => action.id)).toEqual(['memory', 'redirect'])
+ })
+
+ it('the redirect only prepares text for the main session, and says the console cannot stop or message the run', async () => {
+ const sent: string[] = []
+ const redirect = byId(guideActions(input({ run: wfRun(), prepare: async text => void sent.push(text) })), 'redirect')
+ const spec = redirect?.spec as ActionSpec
+
+ expect(spec.args).toEqual([])
+ expect(spec.note).toMatch(/cannot stop or message a workflow/)
+ expect(redirect?.kind).toBe('prompt-only')
+ await spec.run?.()
+ expect(sent).toHaveLength(1)
+ expect(sent[0]).toContain('resumeFromRunId: "wf_abc12345"')
+ expect(sent[0]).toContain('/home/u/.claude/projects/-p/sess/workflows/scripts/my flow-wf_abc12345.js')
+ expect(sent[0]).toContain('use the cache')
+ })
+
+ it('a run directory outside Claude Code\'s projects folder, or with .. in it, is not shown as a path', () => {
+ const run = wfRun({ dir: '/home/u/.claude/projects/../../etc/subagents/workflows/wf_abc12345' })
+
+ expect(redirectText(run, null, 'x', path => !path.includes('..'))).toContain('<session>/workflows/scripts')
+ expect(redirectText(run, null, 'x', path => !path.includes('..'))).not.toContain('etc')
+ expect(redirectText({ ...run, id: 'bad id' }, null, 'x', () => true)).toBeNull()
+ })
+})
+
+describe('what may be sent', () => {
+ it('refuses empty text, text starting with a dash, and text that looks like a credential, with the reason', () => {
+ expect(guardText(' ', 100)).toMatchObject({ ok: false, why: expect.stringMatching(/type the guidance/) })
+ expect(guardText('--force', 100)).toMatchObject({ ok: false, why: expect.stringMatching(/dash/) })
+ expect(guardText('use sk-ABCDEFGHIJKLMNOPQRSTUVWX12345', 100)).toMatchObject({ ok: false, why: expect.stringMatching(/credential/) })
+ expect(guardText('use the cache', 100)).toEqual({ ok: true, text: 'use the cache' })
+
+ const refused = guideActions(input({ text: 'token=abcdefghijklmnop' }))
+
+ expect(refused).toHaveLength(1)
+ expect(refused[0]?.spec).toBeNull()
+ })
+
+ it('strips control characters and bounds the text to one argv element', () => {
+ const spec = byId(guideActions(input({ text: `a\u001b[31m ${'word '.repeat(100)}` })), 'broadcast')?.spec
+
+ expect(JSON.stringify(spec?.args)).not.toContain('\\u001b')
+ expect(spec?.args.length).toBe(6)
+ expect(JSON.parse(spec?.args[5] ?? '{}').message.length).toBeLessThanOrEqual(160)
+ })
+})
+
+describe('the slots', () => {
+ beforeEach(() => resetSlots())
+ afterEach(() => resetSlots())
+
+ it('register without a clash, with no hotkey, and a second registration is refused rather than thrown', () => {
+ expect(registerGuide().every(result => result.ok)).toBe(true)
+ expect(slotsFor('board').map(slot => slot.id)).toEqual(['links', 'nesting', 'mission-run'])
+ expect(slotsFor('tab').map(slot => slot.id)).toEqual(['mission', 'guide'])
+ expect(slotsFor('notice').map(slot => slot.id)).toEqual(['links'])
+ expect(slotsFor('key')).toEqual([])
+ expect(slotsFor('action')).toEqual([])
+ expect(registerGuide().every(result => !result.ok)).toBe(true)
+ expect(registerSlot({ kind: 'notice', id: 'links', between: () => [] })).toMatchObject({ ok: false })
+ })
+
+ const world = (): { state: State; ctx: Ctx; asked: { spec: ActionSpec | null; why: string }[] } => {
+ const state = newState({})
+ 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
+
+ return { state, ctx: { kit, state, nowMs: 1_000, columns: 120, pictures: new Map(), act }, asked }
+ }
+ const envOf = (ctx: Ctx, run: WfRun): SlotEnv => ({ ctx, runs: [run], run, phase: run.phases[0] ?? null, agent: run.phases[0]?.agents[0] ?? null, ui: { run: 0, phase: 0, agent: 0, column: 'agents', isInspecting: true }, nowMs: 1_000 })
+ const slot = <K extends 'board' | 'tab'>(kind: K, id: string) => slotsFor(kind).find(candidate => candidate.id === id) as never as { render: (env: SlotEnv) => unknown[]; when?: (env: SlotEnv) => boolean }
+ const ledger = (state: State): MissionRecord => {
+ const mission = { id: 'm1', objective: 'Ship it', profile: 'feature', rigor: 'standard', tasks: [{ id: 'implement', title: 'Implement', phase: 'R', stage: 'Build', agent: 'coder', requirement: 'it works', dependsOn: [] }], acceptance: [], events: [], paused: false, cancelled: false, auto: false, createdAtMs: 0 } as MissionRecord
+
+ mcOf(state).missions.set('m1', mission)
+ mcOf(state).active = 'm1'
+
+ return mission
+ }
+
+ it('the links board counts links and unlinked agents from the records, and says so when there is no mission', () => {
+ registerGuide()
+
+ const { ctx } = world()
+
+ const plain = wfRun({ phases: [{ title: 'Build', agents: [{ ...flow(), label: 'plain' }], done: 0, total: 1, running: 1, failed: 0 }] })
+
+ expect(words(slot('board', 'links').render(envOf(ctx, plain)))).toMatch(/0 agent-to-task links · 1 agents unlinked · 0 mission tasks known/)
+ expect(words(slot('board', 'links').render(envOf(ctx, plain)))).toMatch(/No mission yet/)
+
+ ledger(ctx.state)
+
+ const text = words(slot('board', 'links').render(envOf(ctx, wfRun())))
+
+ expect(text).toMatch(/1 agent-to-task links · 0 agents unlinked · 1 mission tasks known/)
+ expect(text).toMatch(/m1\/implement Implement -> .*\(label tag\)/)
+ })
+
+ it('the mission tab shows an agent\'s task, or that it is unlinked and why', () => {
+ registerGuide()
+
+ const { ctx } = world()
+
+ expect(words(slot('tab', 'mission').render(envOf(ctx, wfRun())))).toMatch(/m1 \/ implement/)
+ expect(words(slot('tab', 'mission').render(envOf(ctx, wfRun({ phases: [{ title: 'Build', agents: [{ ...flow(), label: 'plain' }], done: 0, total: 1, running: 1, failed: 0 }] }))))).toMatch(/unlinked: its label has no/)
+ })
+
+ it('the nesting board draws only for the ruflo swarm run', () => {
+ registerGuide()
+
+ const { ctx } = world()
+
+ expect(words(slot('board', 'nesting').render(envOf(ctx, wfRun())))).toMatch(/Pick the ruflo swarm run/)
+ expect(words(slot('board', 'nesting').render(envOf(ctx, swarmRun())))).toMatch(/no swarm/)
+ })
+
+ it('the mission board drafts the script for review, with the estimate, and its button asks (nothing runs until the confirm card)', () => {
+ registerGuide()
+
+ const { ctx, asked } = world()
+
+ expect(words(slot('board', 'mission-run').render(envOf(ctx, wfRun())))).toMatch(/No active mission/)
+ ledger(ctx.state)
+
+ const tree = slot('board', 'mission-run').render(envOf(ctx, wfRun()))
+ const text = words(tree)
+
+ expect(text).toMatch(/\.claude\/workflows\/mission-m1\.js/)
+ expect(text).toMatch(/1 agents in 1 level, at most 1 at once/)
+ expect(flat(tree).some(el => el.kind === 'Button' && String(el.props.label).includes('Review the script'))).toBe(true)
+ ;(buttonOf(tree, 'wf-mission-launch')?.props.onPress as () => void)()
+ expect(asked).toHaveLength(1)
+ expect(asked[0]?.spec?.args).toEqual([])
+ expect(asked[0]?.spec?.note).toMatch(/Starts nothing here/)
+ })
+
+ it('the launch reports "not wired" instead of pretending when there is no host to prepare the prompt in', async () => {
+ const { state } = world()
+ const mission = ledger(state)
+ const draft = draftScript(scriptMissionOf(mission))
+
+ if (!draft.ok) throw new Error('draft')
+
+ await launchSpec(state, draft, 'm1').run?.()
+ expect(state.outcome).toMatchObject({ label: 'workflow script', ok: false, detail: expect.stringMatching(/not wired/) })
+ expect(REVIEW_LINES).toBe(80)
+ })
+
+ it('a long script says how many lines the review does not draw', () => {
+ registerGuide()
+
+ const { ctx } = world()
+ const mission = ledger(ctx.state)
+
+ mission.tasks = Array.from({ length: 12 }, (_, i) => ({ id: `t${i}`, title: `T${i}`, phase: 'R', stage: 'Build', agent: 'coder', requirement: 'ok', dependsOn: [] }))
+
+ expect(words(slot('board', 'mission-run').render(envOf(ctx, wfRun())))).toMatch(/\d+ more lines are not drawn here/)
+ })
+
+ it('the guide tab lists each action with what it sends and whether it acts, and says a workflow cannot be stopped from here', () => {
+ registerGuide()
+
+ const { ctx } = world()
+ const tree = slot('tab', 'guide').render(envOf(ctx, wfRun()))
+ const text = words(tree)
+
+ expect(flat(tree).some(el => el.kind === 'Input')).toBe(true)
+ expect(text).toMatch(/guidance: none typed yet/)
+ expect(text).toMatch(/cannot be stopped or messaged from here/)
+ })
+
+ it('draws on the real page: the boards under the run board, and the tabs once the inspector is open', () => {
+ registerGuide()
+
+ const { state } = world()
+ const runner = { ask: () => undefined }
+ const host = { invalidate: () => undefined } as unknown as Host
+
+ state.view = 'workflows'
+ state.wf.read = { runs: [wfRun()], root: '/r', capBytes: 1, skipped: 0, more: 0 }
+ state.wf.ui = { run: 0, phase: 0, agent: 0, column: 'agents', isInspecting: true }
+
+ const act = { workflows: workflowsActions(state, host, runner as never) } as unknown as Actions
+ const text = words(workflowsPage({ kit, state, nowMs: 1_000, columns: 120, pictures: new Map(), act }))
+
+ expect(text).toMatch(/Mission links/)
+ expect(text).toMatch(/Run a mission as a workflow/)
+ expect(text).toMatch(/Swarm nesting/)
+ expect(flat(workflowsPage({ kit, state, nowMs: 1_000, columns: 120, pictures: new Map(), act })).some(el => el.kind === 'Button' && String(el.props.label).includes('guide'))).toBe(true)
+ })
+
+ it('the notice slot raises what changed between two reads, and survives odd input', () => {
+ registerGuide()
+
+ const between = (slotsFor('notice')[0] as { between: (prev: readonly WfRun[] | null, next: readonly WfRun[], nowMs: number) => { text: string }[] }).between
+
+ expect(between(null, [wfRun()], 0)).toEqual([])
+ expect(between([wfRun()], [wfRun({ phases: [{ title: 'Build', agents: [flow('failed')], done: 0, total: 1, running: 0, failed: 1 }] })], 0)[0]?.text).toMatch(/failed/)
+ })
+
+ it('recordRunEvents writes a mission event once and saves the ledger', () => {
+ const { state } = world()
+ const mission = ledger(state)
+ let saved = 0
+ const host = { storeSet: async () => void (saved += 1), invalidate: () => undefined } as unknown as Host
+ const after = [wfRun({ phases: [{ title: 'Build', agents: [flow('failed')], done: 0, total: 1, running: 0, failed: 1 }] })]
+
+ expect(recordRunEvents(state, host, [wfRun()], after, 5)).toBe(1)
+ expect(recordRunEvents(state, host, [wfRun()], after, 6)).toBe(0)
+ expect(saved).toBe(1)
+ expect(mission.events).toHaveLength(1)
+ expect(mission.events[0]).toMatchObject({ type: 'workflow', taskId: 'implement', status: 'agent-failed' })
+ })
+})
diff --git a/plugins/ruflo-console/tests/wf-links.spec.ts b/plugins/ruflo-console/tests/wf-links.spec.ts
new file mode 100644
index 0000000000..1370a88d14
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-links.spec.ts
@@ -0,0 +1,167 @@
+/**
+ * Mission task <-> agent links, and the run events that announce what changed (ADR-460). Links come only from data the records carry
+ * (a ruflo task's tags and assignment, a label's leading tag); anything else is "unlinked" with the reason. Run with
+ * npx vitest run plugins/ruflo-console/tests/wf-links.spec.ts --testTimeout=30000
+ */
+import { describe, expect, it } from 'vitest'
+
+import type { MissionRecord } from '../hooks/mission-types'
+import { applyMissionEvents, eventsBetween } from '../hooks/data/wf-events'
+import { agentLinkLine, labelTag, linkAgents, readLabelTag, refsOf, taskLinkLine, type MissionTaskRef } from '../hooks/data/wf-links'
+import type { AgentRecord, TaskRecord } from '../hooks/data/parse'
+import { STALE_MS, type AgentState, type RunState, type WfAgent, type WfRun } from '../hooks/data/workflows'
+
+const flowAgent = (id: string, label: string, state: AgentState = 'running'): WfAgent => ({ id, label, phase: 'Build', state, hasWorktree: false })
+const rufloAgent = (id: string): WfAgent => ({ id, label: id, phase: 'coder', state: 'running', hasWorktree: false, ruflo: { id, type: 'coder', status: 'busy' } as AgentRecord })
+
+function run(id: string, agents: WfAgent[], over: Partial<WfRun> = {}): WfRun {
+ return { id, name: `wf ${id}`, kind: 'workflow', state: 'running', phases: [{ title: 'Build', agents, done: 0, total: agents.length, running: 0, failed: 0 }], running: 0, done: 0, failed: 0, idle: 0, total: agents.length, totalTokens: null, isTokensPartial: false, hasRecord: false, ...over }
+}
+
+const task = (id: string, assignedTo: string[], tags: string[] | undefined, status = 'in_progress', over: Partial<TaskRecord> = {}): TaskRecord => ({ id, type: 'feature', description: `desc of ${id}`, status, assignedTo, ...(tags !== undefined && { tags }), ...over })
+const REFS: MissionTaskRef[] = [{ missionId: 'm1', taskId: 'implement', title: 'Implement it', rufloTaskId: 'task-9' }, { missionId: 'm1', taskId: 'review', title: 'Review it' }]
+
+describe('links', () => {
+ it('links a ruflo agent through the ruflo task assigned to it, by the mission:/task: tags', () => {
+ const index = linkAgents(REFS, [run('swarm', [rufloAgent('agent-1')], { kind: 'ruflo-swarm' })], [task('task-7', ['agent-1'], ['mission:m1', 'task:review', 'phase:X'])])
+
+ expect(index.links).toHaveLength(1)
+ expect(index.links[0]).toMatchObject({ missionId: 'm1', taskId: 'review', title: 'Review it', via: 'ruflo-task', taskStatus: 'in_progress', isKnown: true })
+ expect(agentLinkLine(index, 'swarm', 'agent-1')).toBe('m1 / review: Review it (in_progress)')
+ expect(taskLinkLine(index, REFS[1] as MissionTaskRef)).toBe('agent-1 (ruflo task)')
+ })
+
+ it('links by the ledger\'s rufloTaskId when the task has no tags, and shows open tasks before finished ones', () => {
+ const tasks = [task('task-9', ['agent-1'], undefined, 'completed'), task('task-7', ['agent-1'], ['mission:m1', 'task:review'], 'in_progress')]
+ const index = linkAgents(REFS, [run('swarm', [rufloAgent('agent-1')], { kind: 'ruflo-swarm' })], tasks)
+
+ expect(index.links.map(link => `${link.taskId}:${link.taskStatus}`)).toEqual(['review:in_progress', 'implement:completed'])
+ expect(agentLinkLine(index, 'swarm', 'agent-1')).toMatch(/\+1 more$/)
+ })
+
+ it('says a mission task the console does not hold is not in its ledger, rather than dropping it', () => {
+ const index = linkAgents([], [run('swarm', [rufloAgent('agent-1')], { kind: 'ruflo-swarm' })], [task('task-7', ['agent-1'], ['mission:other', 'task:t1'])])
+
+ expect(index.links[0]).toMatchObject({ missionId: 'other', taskId: 't1', isKnown: false, title: 'desc of task-7' })
+ expect(agentLinkLine(index, 'swarm', 'agent-1')).toMatch(/not in this console's mission ledger/)
+ })
+
+ it('links a workflow agent by the tag its label starts with', () => {
+ const tag = labelTag('m1', 'implement') as string
+ const index = linkAgents(REFS, [run('r1', [flowAgent('a1', `${tag} Implement it`)])], [])
+
+ expect(index.links[0]).toMatchObject({ missionId: 'm1', taskId: 'implement', via: 'label-tag', title: 'Implement it', isKnown: true })
+ })
+
+ it('leaves an agent unlinked, with the reason, when nothing the data carries names a task: no fuzzy match on a similar word', () => {
+ const index = linkAgents(REFS, [run('r1', [flowAgent('a1', 'implement it please'), flowAgent('a2', 'task:implement'), flowAgent('a3', '[mission:m1 task] broken')]), run('swarm', [rufloAgent('agent-2')], { kind: 'ruflo-swarm' })], [task('task-7', ['agent-1'], ['mission:m1', 'task:review'])])
+
+ expect(index.links).toEqual([])
+ expect(index.unlinked.map(entry => entry.agentId)).toEqual(['a1', 'a2', 'a3', 'agent-2'])
+ expect(index.unlinked.find(entry => entry.agentId === 'a3')?.why).toMatch(/not \[mission:<id> task:<id>\]/)
+ expect(index.unlinked.find(entry => entry.agentId === 'a1')?.why).toMatch(/no \[mission:<id> task:<id>\] tag/)
+ expect(index.unlinked.find(entry => entry.agentId === 'agent-2')?.why).toMatch(/no ruflo task/)
+ expect(agentLinkLine(index, 'r1', 'a1')).toMatch(/^unlinked: /)
+ })
+
+ it('a task nobody names reads unlinked, and the same ids on a run switch do not collide', () => {
+ const index = linkAgents(REFS, [run('r1', [flowAgent('a1', `${labelTag('m1', 'implement')} x`)]), run('r2', [flowAgent('a1', 'plain')])], [])
+
+ expect(taskLinkLine(index, REFS[1] as MissionTaskRef)).toMatch(/^unlinked/)
+ expect(agentLinkLine(index, 'r1', 'a1')).toMatch(/^m1 \/ implement/)
+ expect(agentLinkLine(index, 'r2', 'a1')).toMatch(/^unlinked/)
+ })
+
+ it('reads a tag back only when its ids survive; an id with a space cannot be tagged', () => {
+ expect(labelTag('m 1', 't')).toBeNull()
+ expect(readLabelTag('[mission:m1 task:t1] title')).toEqual({ missionId: 'm1', taskId: 't1', rest: 'title' })
+ expect(readLabelTag('plain')).toBeNull()
+ expect(readLabelTag('[mission:m1 task:]')).toEqual({ malformed: true })
+ })
+
+ it('merges the ledger and the observation, the ledger\'s entry winning', () => {
+ const ledger = [{ id: 'm1', tasks: [{ id: 't1', title: 'from ledger', rufloTaskId: 'task-1' }] }] as unknown as MissionRecord[]
+ const observed = [{ id: 'm1', plan: { tasks: [{ id: 't1', title: 'from observation' }, { id: 't2', title: 'only observed' }] } }] as never
+
+ const refs = refsOf(ledger, observed)
+
+ expect(refs.map(ref => `${ref.taskId}:${ref.title}`)).toEqual(['t1:from ledger', 't2:only observed'])
+ })
+})
+
+describe('run events', () => {
+ const tag = labelTag('m1', 'implement') as string
+ const before = (state: AgentState) => [run('wf_run1234567', [flowAgent('agent-aaaaaaaa', `${tag} Implement it`, state), flowAgent('agent-bbbbbbbb', 'plain', state)])]
+
+ it('announces nothing on the first read', () => {
+ expect(eventsBetween(null, before('failed'))).toEqual({ notices: [], mission: [] })
+ })
+
+ it('announces an agent that newly failed, once, and nothing when it stays failed', () => {
+ const changes = eventsBetween(before('running'), before('failed'))
+
+ expect(changes.notices.map(notice => notice.level)).toEqual(['bad', 'bad'])
+ expect(changes.notices[0]?.text).toMatch(/failed: Implement it \(mission m1, task implement\)/)
+ expect(changes.notices[1]?.text).toMatch(/failed: plain in wf wf_run1234567/)
+ expect(changes.mission).toHaveLength(1)
+ expect(eventsBetween(before('failed'), before('failed'))).toEqual({ notices: [], mission: [] })
+ })
+
+ it('announces a stuck agent with the stale window, and a run newly stalled, but not one already stalled', () => {
+ const stuck = eventsBetween(before('running'), before('stale'))
+
+ expect(stuck.notices[0]).toMatchObject({ level: 'warn' })
+ expect(stuck.notices[0]?.text).toContain(`${STALE_MS / 60_000} min quiet`)
+
+ const stalled = (state: RunState) => [run('wf_run1234567', [], { state })]
+
+ expect(eventsBetween(stalled('running'), stalled('stalled')).notices[0]?.text).toMatch(/looks stuck: nothing written for 15 min/)
+ expect(eventsBetween(stalled('stalled'), stalled('stalled')).notices).toEqual([])
+ expect(eventsBetween(null, stalled('stalled')).notices).toEqual([])
+ })
+
+ it('announces a finished agent only when a mission tagged it (the page already announces a run)', () => {
+ const changes = eventsBetween(before('running'), before('done'))
+
+ expect(changes.notices).toHaveLength(1)
+ expect(changes.notices[0]).toMatchObject({ level: 'ok' })
+ expect(changes.mission[0]).toMatchObject({ missionId: 'm1', taskId: 'implement', kind: 'agent-done' })
+ })
+
+ it('keys are short enough to survive the page\'s 40-character cut, and differ per agent and kind', () => {
+ const keys = [...eventsBetween(before('running'), before('failed')).notices, ...eventsBetween(before('running'), before('stale')).notices].map(notice => notice.key)
+
+ expect(keys.every(key => key.length <= 40)).toBe(true)
+ expect(new Set(keys).size).toBe(keys.length)
+ })
+
+ it('washes a credential and a control character out of what it announces', () => {
+ const dirty = [run('wf_run1234567', [flowAgent('a1', 'sk-ABCDEFGHIJKLMNOPQRSTUVWX12345 \u001b[31mred')], { name: 'n\u0007ame' })]
+ const text = eventsBetween([run('wf_run1234567', [flowAgent('a1', 'x', 'running')], { name: 'n' })], [{ ...dirty[0], phases: [{ ...(dirty[0] as WfRun).phases[0], agents: [flowAgent('a1', 'sk-ABCDEFGHIJKLMNOPQRSTUVWX12345 \u001b[31mred', 'failed')] }] } as WfRun]).notices[0]?.text ?? ''
+
+ expect(text).toContain('‹masked›')
+ expect(text).not.toContain('sk-ABCDEF')
+ expect(text).not.toContain('\u001b')
+ })
+})
+
+describe('applyMissionEvents', () => {
+ const ledger = (): Map<string, MissionRecord> => new Map([['m1', { id: 'm1', tasks: [{ id: 'implement' }], events: [] } as unknown as MissionRecord]])
+ const event = { missionId: 'm1', taskId: 'implement', kind: 'agent-failed' as const, note: 'workflow agent failed: x', key: 'a-1-f' }
+
+ it('records an event once, for a mission and task the ledger holds', () => {
+ const missions = ledger()
+
+ expect(applyMissionEvents(missions, [event, event], 1000)).toBe(1)
+ expect(applyMissionEvents(missions, [event], 2000)).toBe(0)
+ expect(missions.get('m1')?.events).toEqual([{ seq: 1, atMs: 1000, type: 'workflow', taskId: 'implement', status: 'agent-failed', evidenceRef: 'a-1-f', note: 'workflow agent failed: x' }])
+ })
+
+ it('ignores an unknown mission or task, and masks a credential in the note', () => {
+ const missions = ledger()
+
+ expect(applyMissionEvents(missions, [{ ...event, missionId: 'nope' }, { ...event, taskId: 'nope', key: 'k2' }], 1)).toBe(0)
+ applyMissionEvents(missions, [{ ...event, key: 'k3', note: 'token=abcdefghijklmnop' }], 1)
+ expect(missions.get('m1')?.events[0]?.note).toContain('‹masked›')
+ })
+})
diff --git a/plugins/ruflo-console/tests/wf-mission-script.spec.ts b/plugins/ruflo-console/tests/wf-mission-script.spec.ts
new file mode 100644
index 0000000000..d34b43b471
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-mission-script.spec.ts
@@ -0,0 +1,138 @@
+/**
+ * The drafted mission workflow script (ADR-460): it is valid, it runs level by level with the plan's dependencies respected, no
+ * mission text is ever code, secrets are masked, and the dry-run estimate counts only the plan. Run with
+ * npx vitest run plugins/ruflo-console/tests/wf-mission-script.spec.ts --testTimeout=30000
+ */
+import { describe, expect, it } from 'vitest'
+
+import { readLabelTag } from '../hooks/data/wf-links'
+import { draftScript, estimateLines, levelsOf, MAX_AGENTS, type Draft, type ScriptMission, type ScriptTask } from '../hooks/data/wf-mission-script'
+
+const task = (id: string, dependsOn: string[] = [], over: Partial<ScriptTask> = {}): ScriptTask => ({ id, title: `Do ${id}`, stage: 'Build', agent: 'coder', requirement: `${id} is finished`, dependsOn, ...over })
+const mission = (tasks: ScriptTask[], over: Partial<ScriptMission> = {}): ScriptMission => ({ id: 'mission-abc1', objective: 'Ship the thing', tasks, ...over })
+const ok = (draft: Draft): Extract<Draft, { ok: true }> => {
+ if (!draft.ok) throw new Error(`not drafted: ${draft.why}`)
+
+ return draft
+}
+
+const AsyncFunction = Object.getPrototypeOf(async () => undefined).constructor as new (...args: string[]) => (...values: unknown[]) => Promise<unknown>
+
+/** Runs the script the way Claude Code does: meta stripped to a const, the hooks injected, every agent answering done. */
+async function run(source: string): Promise<{ calls: { prompt: string; opts: Record<string, unknown> }[]; phases: string[]; returned: unknown }> {
+ const calls: { prompt: string; opts: Record<string, unknown> }[] = []
+ const phases: string[] = []
+ const agent = async (prompt: string, opts: Record<string, unknown>) => (calls.push({ prompt, opts }), { done: true, summary: `ran ${calls.length}`, evidence: 'e' })
+ const parallel = async (thunks: (() => Promise<unknown>)[]) => Promise.all(thunks.map(thunk => thunk()))
+ const body = source.replace(/^export const meta/m, 'const meta')
+ const fn = new AsyncFunction('agent', 'parallel', 'phase', 'log', 'args', body)
+ const returned = await fn(agent, parallel, (title: string) => phases.push(title), () => undefined, undefined)
+
+ return { calls, phases, returned }
+}
+
+describe('draftScript', () => {
+ it('writes a script that is valid, runs every task once, and meta is a pure literal', async () => {
+ const draft = ok(draftScript(mission([task('a'), task('b', ['a']), task('c', ['a'])])))
+ const { calls, phases, returned } = await run(draft.source)
+ const metaLiteral = /^export const meta = (\{[\s\S]*?\n\})/m.exec(draft.source)?.[1] ?? ''
+
+ expect(calls).toHaveLength(3)
+ expect(phases).toEqual(['Build', 'Build'])
+ expect(new Function(`return ${metaLiteral}`)()).toMatchObject({ name: 'mission-mission-abc1', phases: [{ title: 'Build' }] })
+ expect(returned).toMatchObject({ mission: 'mission-abc1', notDone: [] })
+ expect(draft.source).not.toMatch(/Date\.now|Math\.random/)
+ })
+
+ it('runs a task only after its dependencies, handing each the summaries of what ran before it', async () => {
+ const draft = ok(draftScript(mission([task('c', ['b']), task('a'), task('b', ['a'])])))
+ const { calls } = await run(draft.source)
+ const order = calls.map(call => /Your task (\w+)/.exec(call.prompt)?.[1])
+
+ expect(order).toEqual(['a', 'b', 'c'])
+ expect(calls[1]?.prompt).toMatch(/Already done before you:\na: ran 1/)
+ expect(calls[0]?.prompt).not.toMatch(/Already done/)
+ })
+
+ it('labels each agent with the tag the Workflows page reads back, within the 80 characters a journal keeps', () => {
+ const draft = ok(draftScript(mission([task('a', [], { title: 'x'.repeat(200) })])))
+ const labelOf = /"label": "([^"]*)"/.exec(draft.source)?.[1] ?? ''
+ const tag = readLabelTag(labelOf)
+
+ expect(labelOf.length).toBeLessThanOrEqual(80)
+ expect(tag).toMatchObject({ missionId: 'mission-abc1', taskId: 'a' })
+ })
+
+ it('counts the estimate from the plan: agents, levels, and the widest level at once', () => {
+ const draft = ok(draftScript(mission([task('a'), task('b'), task('c'), task('d', ['a', 'b', 'c'])])))
+
+ expect(draft.estimate).toMatchObject({ agents: 4, levels: 2, widest: 3, typed: 4 })
+ expect(estimateLines(draft).join('\n')).toMatch(/4 agents in 2 levels, at most 3 at once/)
+ expect(estimateLines(draft).join('\n')).toMatch(/tokens, time and cost: n\/a/)
+ })
+
+ it('one level of independent tasks is as wide as the plan', () => {
+ expect(ok(draftScript(mission([task('a'), task('b')]))).estimate).toMatchObject({ levels: 1, widest: 2 })
+ expect(ok(draftScript(mission([task('a'), task('b', ['a'])]))).estimate).toMatchObject({ levels: 2, widest: 1 })
+ })
+
+ it('refuses what cannot be one reviewed script: no tasks, a circle, a duplicate id, too many', () => {
+ expect(draftScript(mission([]))).toMatchObject({ ok: false, why: expect.stringMatching(/no tasks/) })
+ expect(draftScript(mission([task('a', ['b']), task('b', ['a'])]))).toMatchObject({ ok: false, why: expect.stringMatching(/circle/) })
+ expect(draftScript(mission([task('a'), task('a')]))).toMatchObject({ ok: false, why: expect.stringMatching(/share an id/) })
+ expect(draftScript(mission(Array.from({ length: MAX_AGENTS + 1 }, (_, i) => task(`t${i}`))))).toMatchObject({ ok: false })
+ expect(draftScript(mission(Array.from({ length: MAX_AGENTS }, (_, i) => task(`t${i}`)))).ok).toBe(true)
+ })
+
+ it('a dependency the plan lacks is ignored and reported, not fatal', () => {
+ const draft = ok(draftScript(mission([task('a', ['ghost'])])))
+
+ expect(draft.warnings.join('\n')).toMatch(/ghost/)
+ expect(draft.estimate.levels).toBe(1)
+ })
+
+ it('mission text is data, never code: quotes, backticks, ${} and newlines cannot break out', async () => {
+ const hostile = 'x"; process.exit(1); `${process.exit(2)}` \n */ //'
+ const draft = ok(draftScript(mission([task('a', [], { title: hostile, requirement: hostile })], { objective: hostile })))
+ const { calls } = await run(draft.source)
+
+ expect(calls).toHaveLength(1)
+ expect(calls[0]?.prompt).toContain('process.exit(1)')
+ })
+
+ it('masks a credential in the objective, title and requirement before it is in the script', () => {
+ const secret = 'sk-ABCDEFGHIJKLMNOPQRSTUVWX12345'
+ const draft = ok(draftScript(mission([task('a', [], { title: `use ${secret}`, requirement: `token=${secret}` })], { objective: `Bearer ${secret}` })))
+
+ expect(draft.source).not.toContain(secret)
+ expect(draft.source).toContain('‹masked›')
+ })
+
+ it('names the subagent type only for a role Claude Code is known to resolve; the rest ride in the prompt', async () => {
+ const draft = ok(draftScript(mission([task('a', [], { agent: 'coder' }), task('b', [], { agent: 'reasoningbank-learner' })])))
+ const { calls } = await run(draft.source)
+
+ expect(draft.estimate.typed).toBe(1)
+ expect(calls.find(call => call.prompt.includes('task a'))?.opts).toHaveProperty('agentType', 'coder')
+ expect(calls.find(call => call.prompt.includes('task b'))?.opts).not.toHaveProperty('agentType')
+ expect(calls.find(call => call.prompt.includes('task b'))?.prompt).toMatch(/Act as: reasoningbank-learner/)
+ })
+
+ it('an id that cannot be tagged still drafts, and says its agent will be unlinked', () => {
+ const draft = ok(draftScript(mission([task('has space')])))
+
+ expect(draft.warnings.join('\n')).toMatch(/unlinked/)
+ })
+
+ it('a stage per level names the phases once, in order', () => {
+ const draft = ok(draftScript(mission([task('a', [], { stage: 'Research' }), task('b', ['a'], { stage: 'Build' }), task('c', ['b'], { stage: 'Build' })])))
+
+ expect(draft.estimate.phases).toEqual(['Research', 'Build'])
+ })
+})
+
+describe('levelsOf', () => {
+ it('puts a task one level below its deepest dependency', () => {
+ expect(levelsOf([task('a'), task('b', ['a']), task('c', ['a', 'b'])])).toEqual([[0], [1], [2]])
+ })
+})
diff --git a/v3/docs/adr/ADR-460-workflow-links-nesting-and-guidance.md b/v3/docs/adr/ADR-460-workflow-links-nesting-and-guidance.md
new file mode 100644
index 0000000000..2dbccdd55a
--- /dev/null
+++ b/v3/docs/adr/ADR-460-workflow-links-nesting-and-guidance.md
@@ -0,0 +1,93 @@
+# ADR 460: Mission links, run events, mission-as-workflow and guidance on the Workflows page
+
+Status: Accepted
+
+Date: 2026-10-05
+
+Builds on: ADR-458 (the page), ADR-464 (slot seams), ADR-453 (confirm-gated verbs), ADR-406 (mission observation)
+
+Reserved and untouched: ADR-459, ADR-461 to ADR-463
+
+## 1. Context
+
+The Workflows page shows runs and agents, and Mission Control shows missions and tasks, but nothing relates them: a mission
+task does not say which agent works on it, an agent does not say which mission task it serves, a run that fails or goes quiet
+is only visible if the page is open, the swarm's nesting (swarm, hive, queen, worker, claim, task) is spread over three
+views, and the only way to say something to a swarm is to leave the page. Two facts shape what is honest here. First,
+ruflo's verbs write records: `hive-mind broadcast` appends to the hive's shared memory (the last 100), `task_update`
+and `claims_handoff` edit store files, a consensus proposal binds no one. None of them interrupts a running agent; an agent
+sees a record only when it reads that store. Second, a Claude Code workflow agent has no ruflo record at all, and the
+console has no verb that stops or messages a running workflow.
+
+## 2. Decision
+
+All of it plugs into the page through the slot registry (`views/wf-slots.ts`); no shared file is edited.
+
+**Links (`data/wf-links.ts`).** Only links the data carries are made. A ruflo agent links through a ruflo task whose
+`assignedTo` holds it and whose tags are `mission:<id>` and `task:<id>` (what `mission-specs.ts` writes), or whose id is a
+ledger task's `rufloTaskId`. A workflow agent links through a label that begins `[mission:<id> task:<id>]`, which a script
+drafted here puts there. Anything else is `unlinked`, with the reason on screen. There is no fuzzy match: a label that
+merely contains a task's word is unlinked. A tag whose ids the console does not hold is still shown, marked as not in its ledger.
+
+**Events (`data/wf-events.ts`).** Between two reads: an agent newly failed, an agent newly stale, a run newly stalled, and a
+finished agent only when a mission tagged it. A run finishing or failing stays with `wf-live.ts`, which already raises those
+(raising them again would show twice under a different key). The first read announces nothing. The same change is also
+returned as a mission event; `applyMissionEvents` records it once (its key is the event's `evidenceRef`) in the ledger.
+The notice slot has no `state`, so recording is a separate export the merge owner calls (section 5). The ruflo swarm is folded
+into the run list after the read, so it never reaches a notice slot; only workflow runs do.
+
+**Mission as a workflow (`data/wf-mission-script.ts`, board "Run a mission as a workflow").** `draftScript` turns the active
+mission's tasks into a `.claude/workflows/mission-<id>.js` script: `meta` a pure literal, the tasks as JSON data (no mission
+text is ever code), levels of tasks run with `parallel` inside a level, each agent labelled with the tag above, a role passed as
+`agentType` only if it is one a session is known to resolve (the rest ride in the prompt). Credentials are masked, a circle,
+a duplicate id, no tasks or more than 30 tasks refuse a draft. The dry run counts agents, levels and the widest level from the
+plan; tokens, time and cost are n/a. The script is shown for review (the first 80 lines, with the total) and launched only by
+a confirm card whose action prepares the text in the main session's prompt box: nothing starts until Enter there.
+
+**Nesting (`data/wf-guide.ts` `nestingOf`, board "Swarm nesting").** swarm > hive > queen > worker > claim > task, each
+level read from its store; a missing level is a note ("no hive-mind", "no claim", "no task record"), never drawn.
+
+**Guidance (`data/wf-guide.ts`, tab `guide`).** One typed sentence (bounded to 300, no leading dash, refused if a credential
+mask would change it), then actions, each a fixed argv through the confirm card, each showing what is sent and whether anything acts:
+
+| action | argv | acts? |
+|---|---|---|
+| broadcast to the hive | `mcp exec -t hive-mind_broadcast` | record only: no worker is interrupted |
+| propose to the hive | `mcp exec -t hive-mind_consensus` (`propose`, type `guidance`) | needs votes; a pass binds no agent; refused while raft has a proposal open this term |
+| hand its claim on | `mcp exec -t claims_handoff` | pending until the target accepts |
+| note it on its task | `mcp exec -t task_update` (`result`) | record only; refused if the task already has a result (it would be replaced) |
+| leave a note in shared memory | `memory store --namespace guidance` | found by a memory search; nothing is pushed |
+| prepare a redirect (workflow runs only) | none: prepares text in the prompt box | text for the main session; resume applies to a stopped run |
+
+The page says wherever it matters that a running Claude Code workflow cannot be stopped or messaged from here.
+
+## 3. Consequences
+
+- A mission task shows its agent and an agent its mission task, wherever the data links them, and says "unlinked" otherwise.
+ Workflow agents link only when their script was drafted here (or hand-tagged); that is the price of not guessing.
+- No action makes a running agent do anything; the cards say so. The memory note is "found by a memory search", not
+ "surfaced on later recalls": the intelligence hook's recall was not verified to search the `guidance` namespace.
+- The launch hands the script to Claude through the prompt box, so running it bills as a Claude turn plus its subagents
+ and cannot be stopped from the console.
+- Three new data modules and one view module, each under 500 lines; `controller.ts` is untouched.
+
+## 4. Test and benchmark plan
+
+Specs: `wf-links.spec.ts` (links, events, ledger recording), `wf-mission-script.spec.ts` (the script runs against stub hooks,
+levels respect dependencies, hostile text stays data, secrets masked, estimate counts), `wf-guide.spec.ts` (nesting, each action's
+argv, refusals, the slots on the real page). Mutation checks flip the stale window, the already-stalled guard, the malformed-tag
+rule, open-first ordering, the run-path check, the credential guard, the task-result guard, the widest-level count, level depth,
+the secret mask, the agent cap, the ledger dedupe and the not-wired report; each fails a test. Benchmark: the link index and
+script draft are linear in agents and tasks (at most 30 tasks drafted); they run once per frame while the page is open, never while it is closed.
+
+## 5. Merge owner wiring
+
+1. `views/wf-register.ts`: add `import './wf-guide'` (registers two boards, a nesting board, two tabs and a notice slot, no hotkeys).
+2. `wf-live.ts`, in `refreshWorkflows` after the notice-slot loop: `recordRunEvents(state, host, before, runs, nowMs)` (exported
+ from `views/wf-guide.ts`; it records into the mission ledger and saves it). Omit it and the notices still work; only the ledger events are lost.
+
+## 6. Rollback
+
+Remove the `import './wf-guide'` line (and the `recordRunEvents` call): the page returns to the board, tabs and slots it had.
+The new modules are inert without the import. Ledger events already recorded are `type: 'workflow'` rows that the mission views
+list and nothing derives from.