Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

fix(console): pin the recorded stop, bound the hand-over read, mask zero-width-split keys at parse, ADR-467

ruv19fbfdc120f0
diff --git a/plugins/ruflo-console/hooks/ap-live.ts b/plugins/ruflo-console/hooks/ap-live.ts
index 659fd17d45..bce215ef5f 100644
--- a/plugins/ruflo-console/hooks/ap-live.ts
+++ b/plugins/ruflo-console/hooks/ap-live.ts
@@ -162,10 +162,10 @@ export function appendEvents(state: State, host: Host, events: readonly JournalE
return false
}
- // A file this console just wrote is no longer "missing" for the next read.
- state.cache.delete(path)
+ state.cache.delete(path) // a file just written is no longer "missing" for the next read
store.loop = foldJournal(events, store.loop)
store.error = null
+ if (store.pin !== null && store.pin.stopped !== true && events.some(e => e.t === 'stop')) await setPin(store, host, state.cwd, { ...store.pin, stopped: true })
return true
} catch {
@@ -399,8 +399,10 @@ export async function apTick(state: State, host: Host, nowMs: number = Date.now(
}
if (wrote && decision.act !== null && mission !== null && picked !== null) {
- // The kill switch and a second session are looked at again HERE, after every await since the tick began (a verify run can take minutes): a step is handed over only if no flag appeared and this journal holds exactly one start line for it.
- const journalNow = await host.fs.read(pathOf(state, JOURNAL_FILE)).catch(() => null)
+ // Kill flag and a second session are looked at again HERE (a verify run can take minutes): hand over only if no flag appeared and the journal, read within its cap, holds exactly one start for this step.
+ const at = pathOf(state, JOURNAL_FILE)
+ const size = await host.fs.stat(at).catch(() => undefined)
+ const journalNow = size === undefined || size.isLink === true || (size.size ?? JOURNAL_MAX_BYTES + 1) > JOURNAL_MAX_BYTES ? null : await host.fs.read(at).catch(() => null)
if ((await killSeen(host.fs, state.cwd)) || store.loop.phase === 'stopped' || store.loop.phase === 'paused') {
await appendEvents(state, host, [{ t: 'step.failed', at: Date.now(), id: decision.act.id, why: 'stopped before the hand-over' }])
@@ -409,7 +411,7 @@ export async function apTick(state: State, host: Host, nowMs: number = Date.now(
}
if (journalNow === null || startedCount(journalNow, decision.act.id) !== 1) {
- await appendEvents(state, host, [{ t: 'step.failed', at: Date.now(), id: decision.act.id, why: 'not handed over: another session started the same step' }])
+ await appendEvents(state, host, [{ t: 'step.failed', at: Date.now(), id: decision.act.id, why: 'not handed over: the journal is unreadable, over its cap or holds a second start of this step' }])
return
}
diff --git a/plugins/ruflo-console/hooks/data/ap-pin.ts b/plugins/ruflo-console/hooks/data/ap-pin.ts
index ee8ce39cf2..1093240286 100644
--- a/plugins/ruflo-console/hooks/data/ap-pin.ts
+++ b/plugins/ruflo-console/hooks/data/ap-pin.ts
@@ -7,7 +7,7 @@
*/
import type { LoopState } from './ap-loop'
-export type Pin = { envHash: string; starts: number }
+export type Pin = { envHash: string; starts: number; /** True once a stop was journaled: a journal that then reads as running had its stop line deleted. */ stopped?: boolean }
export type PinVerdict = { ok: true } | { ok: false; why: string }
export const pinKey = (cwd: string): string => `autopilot-pin:${cwd.slice(0, 200)}`
@@ -18,7 +18,7 @@ export function parsePin(value: unknown): Pin | null {
const r = value as Record<string, unknown>
- return typeof r.envHash === 'string' && /^[0-9a-f]{64}$/.test(r.envHash) && typeof r.starts === 'number' && Number.isInteger(r.starts) && r.starts >= 0 && r.starts < 1_000_000 ? { envHash: r.envHash, starts: r.starts } : null
+ return typeof r.envHash === 'string' && /^[0-9a-f]{64}$/.test(r.envHash) && typeof r.starts === 'number' && Number.isInteger(r.starts) && r.starts >= 0 && r.starts < 1_000_000 ? { envHash: r.envHash, starts: r.starts, ...(r.stopped === true && { stopped: true }) } : null
}
/** Does the journal's fold agree with what the person approved? An idle loop (no start) has nothing to compare. */
@@ -26,6 +26,7 @@ export function checkPin(pin: Pin | null, loop: LoopState, isPending = false): P
if (loop.phase === 'idle') return { ok: true }
if (pin === null) return { ok: false, why: 'no recorded approval for this run: confirm Start again' }
if (loop.envHash !== pin.envHash) return { ok: false, why: 'the journal names an envelope other than the one you approved: it was changed outside the console' }
+ if (pin.stopped === true && loop.phase !== 'stopped' && !isPending) return { ok: false, why: 'the journal reads as running, but a stop was recorded: its stop line was removed outside the console' }
if (loop.starts !== pin.starts && !isPending) return { ok: false, why: `the journal holds ${loop.starts} start lines, you confirmed ${pin.starts}: one was added or removed outside the console` }
return { ok: true }
diff --git a/plugins/ruflo-console/hooks/data/parse.ts b/plugins/ruflo-console/hooks/data/parse.ts
index faf95c9dbc..3ecc5fce34 100644
--- a/plugins/ruflo-console/hooks/data/parse.ts
+++ b/plugins/ruflo-console/hooks/data/parse.ts
@@ -29,7 +29,7 @@ export function plain(value: unknown, max = 200): string {
return ''
}
- const cleaned = value.replace(ESCAPES, '').replace(HIDDEN, ' ').replace(/\s+/g, ' ').trim()
+ const cleaned = value.replace(ESCAPES, '').replace(INVISIBLE, '').replace(HIDDEN, ' ').replace(/\s+/g, ' ').trim()
return cleaned.length <= max ? cleaned : `${cleaned.slice(0, Math.max(0, max - 1))}…`
}
diff --git a/plugins/ruflo-console/hooks/data/wf-activity.ts b/plugins/ruflo-console/hooks/data/wf-activity.ts
index f9bc4ddb91..41764346b6 100644
--- a/plugins/ruflo-console/hooks/data/wf-activity.ts
+++ b/plugins/ruflo-console/hooks/data/wf-activity.ts
@@ -9,6 +9,7 @@
* still reads as the lines it was; ids and paths are not masked (a 36 character session id would read as a key to the mask).
*/
import { maskSecrets, jsonLines } from './workflows'
+import { INVISIBLE } from './parse'
/** Characters kept per field (an input, an output, a message). The page shows how many of how many, never a silent cut. */
export const FIELD_CAP = 6000
@@ -26,7 +27,7 @@ const HIDE = new RegExp('[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u00ad\\
/** Washed text for a block: escapes and controls out (the newline stays), credentials masked, cut to `cap` characters with the original length kept. */
export function cleanBlock(raw: string, cap = FIELD_CAP): Capped {
// The mask runs over a little more than the cap, so a token that straddles the cut is masked whole before the cut is made.
- const head = raw.slice(0, cap + 256).replace(ANSI, '').replace(/\r\n?/g, '\n').replace(/\t/g, ' ').replace(HIDE, ' ')
+ const head = raw.slice(0, cap + 256).replace(ANSI, '').replace(INVISIBLE, '').replace(/\r\n?/g, '\n').replace(/\t/g, ' ').replace(HIDE, ' ')
const text = maskSecrets(head).slice(0, cap)
return { text, total: raw.length, isCut: raw.length > cap }
diff --git a/plugins/ruflo-console/hooks/data/wf-triage.ts b/plugins/ruflo-console/hooks/data/wf-triage.ts
index 10c635ca05..fe2cec84f6 100644
--- a/plugins/ruflo-console/hooks/data/wf-triage.ts
+++ b/plugins/ruflo-console/hooks/data/wf-triage.ts
@@ -7,14 +7,14 @@
* result (the page says so). A result that merely MENTIONS an error is not an error: for an agent that finished, only a result that begins
* with one is.
*/
-import { ESCAPES, HIDDEN } from './parse'
+import { ESCAPES, HIDDEN, INVISIBLE } from './parse'
import { maskSecrets, jsonLines, type WfAgent, type WfRun } from './workflows'
export type TriageKind = 'ok' | 'empty' | 'error' | 'timeout' | 'stale' | 'pending'
export type Triage = { kind: TriageKind; /** One short reason, for the row. */ why: string; /** The first error line of the result, masked and without control characters. */ firstError?: string }
-const tidy = (value: string, max: number): string => maskSecrets(value.replace(ESCAPES, '').replace(HIDDEN, ' ').replace(/\s+/g, ' ').trim()).slice(0, max)
+const tidy = (value: string, max: number): string => maskSecrets(value.replace(ESCAPES, '').replace(INVISIBLE, '').replace(HIDDEN, ' ').replace(/\s+/g, ' ').trim()).slice(0, max)
const ERROR_START = /^\W{0,3}(?:[A-Z][A-Za-z]*Error\s*[:(]|error\s*[:(]|fatal\s*[:(]|panic(?:ked)?\b|exception\s*[:(]|traceback \(most recent|npm ERR!|✖|✗)/i
const ERROR_ANYWHERE = /\b(?:[A-Z][A-Za-z]*Error|ENOENT|EACCES|EPERM|ECONN[A-Z]+|ETIMEDOUT|ENOSPC)\b|\b(?:error|fatal|panic|failed|exception)\s*[:(]|\bTraceback\b|\bcould not\b|\bunable to\b|\bcannot\b/i
diff --git a/plugins/ruflo-console/hooks/data/workflows.ts b/plugins/ruflo-console/hooks/data/workflows.ts
index 81de876617..a7ed352c44 100644
--- a/plugins/ruflo-console/hooks/data/workflows.ts
+++ b/plugins/ruflo-console/hooks/data/workflows.ts
@@ -11,7 +11,7 @@
* Unknown event types and keys are ignored, a half-written last line is dropped, and a missing source is a missing fact:
* nothing here is estimated.
*/
-import { agentLabels, ESCAPES, HIDDEN, shortId, type AgentRecord, type SwarmInfo } from './parse'
+import { agentLabels, ESCAPES, HIDDEN, INVISIBLE, shortId, type AgentRecord, type SwarmInfo } from './parse'
export type AgentState = 'running' | 'done' | 'failed' | 'stale' | 'idle' | 'queued'
@@ -67,7 +67,7 @@ const asRecord = (value: unknown): Record<string, unknown> | null => (typeof val
/** Escape sequences go whole (an OSC title or a hyperlink would otherwise leave its text behind), then control, zero-width and bidi-override characters (they reorder or hide text) become spaces: every string a file supplies passes here. */
const CONTROL = HIDDEN
const str = (value: unknown, max = 200): string | undefined => {
- const clean = typeof value === 'string' ? value.replace(ESCAPES, '').replace(CONTROL, ' ').slice(0, max) : ''
+ const clean = typeof value === 'string' ? value.replace(ESCAPES, '').replace(INVISIBLE, '').replace(CONTROL, ' ').slice(0, max) : ''
return clean === '' ? undefined : clean
}
@@ -134,7 +134,7 @@ export function parseJournal(text: string | null): { isLaunched: boolean; agents
byId.set(id, { agentId: id, label: str(event.label, 80) ?? id, hasResult: false, ...(phase !== undefined && { phase }) })
} else if (event.type === 'result' && id !== undefined) {
const held = byId.get(id) ?? { agentId: id, label: id, hasResult: false }
- const preview = typeof event.result === 'string' ? maskSecrets(event.result.replace(ESCAPES, '').replace(CONTROL, ' ').replace(/\s+/g, ' ')).slice(0, 160) : asRecord(event.result) !== null ? `structured result (${Object.keys(event.result as object).length} fields)` : undefined
+ const preview = typeof event.result === 'string' ? maskSecrets(event.result.replace(ESCAPES, '').replace(INVISIBLE, '').replace(CONTROL, ' ').replace(/\s+/g, ' ')).slice(0, 160) : asRecord(event.result) !== null ? `structured result (${Object.keys(event.result as object).length} fields)` : undefined
byId.set(id, { ...held, hasResult: true, ...(preview !== undefined && preview !== '' && { resultPreview: preview }) })
}
diff --git a/plugins/ruflo-console/tests/fixtures/security-rig.ts b/plugins/ruflo-console/tests/fixtures/security-rig.ts
new file mode 100644
index 0000000000..2ab6f18f03
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/security-rig.ts
@@ -0,0 +1,97 @@
+/** In-memory disk, fake host and mission fixtures shared by the security audit specs. */
+import { seal, type Envelope } from '../../hooks/data/ap-envelope'
+import { encodeLine, JOURNAL_FILE, parseJournal, type JournalEvent } from '../../hooks/data/ap-journal'
+import type { TaskRecord } from '../../hooks/data/parse'
+import type { Host } from '../../hooks/host'
+import { mcOf, type MissionRecord } from '../../hooks/mission-control'
+import { newState, type State } from '../../hooks/state'
+import { storeOf } from '../../hooks/ap-live'
+import type { Ctx, Kit } from '../../hooks/views/common'
+import type { SlotEnv } from '../../hooks/views/wf-slots'
+
+export const CWD = '/w'
+export const T0 = Date.parse('2026-10-06T00:00:00.000Z')
+export const AP = `${CWD}/.claude-flow/console/autopilot`
+export const J = `${CWD}/${JOURNAL_FILE}`
+export const E = `${AP}/envelope.json`
+export const KILL = `${AP}/KILL`
+export const ENV: Envelope = { name: 'night', toolClasses: ['edit', 'read', 'test'], paths: [CWD], repos: [], network: [], secretEnv: [], spend: { hourUsd: 2, dayUsd: 10, totalUsd: 40 }, concurrency: 4, maxDurationMs: 7 * 86_400_000, verify: [['true']], acceptWithoutAnatole: true }
+
+export type Rig = { files: Map<string, string>; runs: string[][]; prompts: string[]; host: Host; onRun: { fn: ((argv: readonly string[]) => void) | null }; onAppend: { fn: ((text: string) => string) | null } }
+
+export function rig(): Rig {
+ const files = new Map<string, string>()
+ const runs: string[][] = []
+ const prompts: string[] = []
+ const onRun: Rig['onRun'] = { fn: null }
+ const onAppend: Rig['onAppend'] = { fn: null }
+
+ const host = {
+ fs: {
+ read: async (p: string) => files.get(p) ?? Promise.reject(new Error('ENOENT')),
+ stat: async (p: string) => (files.has(p) ? { mtimeMs: 1, size: (files.get(p) as string).length, kind: 'file', isLink: false } : [...files.keys()].some(k => k.startsWith(`${p}/`)) ? { kind: 'dir', isLink: false } : Promise.reject(new Error('ENOENT'))),
+ list: async () => [],
+ },
+ run: async (argv: readonly string[], _t: number, stdin?: string) => {
+ runs.push([...argv])
+ onRun.fn?.(argv)
+
+ if (argv[0] === 'dd') {
+ const path = (argv.find(a => a.startsWith('of=')) as string).slice(3)
+ const add = argv.includes('oflag=append') && onAppend.fn !== null ? onAppend.fn(stdin ?? '') : (stdin ?? '')
+
+ files.set(path, argv.includes('oflag=append') ? `${files.get(path) ?? ''}${add}` : (stdin ?? ''))
+ } else if (argv[0] === 'install') files.set(argv.at(-1) as string, argv.includes('/dev/null') ? '' : (stdin ?? ''))
+ else if (argv[0] === 'rm') files.delete(argv.at(-1) as string)
+ else if (argv[0] === 'cp') files.set(argv.at(-1) as string, files.get(argv.at(-2) as string) ?? '')
+
+ return { exitCode: 0, stdout: '', stderr: '' }
+ },
+ invalidate: () => undefined,
+ toast: () => undefined,
+ every: () => ({ cancel: () => undefined }),
+ after: () => ({ cancel: () => undefined }),
+ storeSet: async () => undefined,
+ submitPrompt: async (t: string) => void prompts.push(t),
+ } as unknown as Host
+
+ return { files, runs, prompts, host, onRun, onAppend }
+}
+
+export const task = (id: string, status: string): TaskRecord => ({ id, type: 'feature', description: '', status, assignedTo: [], tags: [] })
+
+export const mission = (): MissionRecord => ({
+ id: 'msn_0123456789abcdef01234567', objective: 'tidy the parser', profile: 'feature', rigor: 'standard',
+ tasks: [
+ { id: 't1', title: 'Fix the parser bug', phase: 'S', agent: 'coder', requirement: 'tests pass', dependsOn: [], rufloTaskId: 'r1' },
+ { id: 't2', title: 'Update the changelog', phase: 'A', agent: 'coder', requirement: 'a line', dependsOn: [], rufloTaskId: 'r2' },
+ { id: 't3', title: 'Review the module', phase: 'P', agent: 'coder', requirement: 'a summary', dependsOn: [], rufloTaskId: 'r3' },
+ ],
+ acceptance: [], events: [], paused: false, cancelled: false, auto: false, createdAtMs: 1,
+})
+
+export function stateWith(tasks: TaskRecord[], anatole: Record<string, unknown> = { mode: 'notify', updatedMs: T0, degraded: false }): State {
+ const state = newState({})
+
+ state.cwd = CWD
+ state.snapshot = { tasks, agents: [], claims: [], swarm: null, plugins: { missingFromClone: [], installed: [] }, alerts: [], anatole: { present: true, status: anatole, modeOverride: null, overrides: {}, alerts: [], refused: [], badAlerts: 0 } } as never
+ mcOf(state).missions.set('msn_0123456789abcdef01234567', mission())
+ mcOf(state).active = 'msn_0123456789abcdef01234567'
+
+ return state
+}
+
+export function started(r: Rig, extra: JournalEvent[] = [], env: Envelope = ENV): void {
+ const sealed = seal(env, 1, T0)
+
+ r.files.set(E, JSON.stringify(sealed))
+ r.files.set(J, [{ t: 'start', at: T0, envHash: sealed.hash, revision: 1, anatole: 'on' } as JournalEvent, ...extra].map(encodeLine).join(''))
+}
+
+export const journal = (r: Rig): JournalEvent[] => parseJournal(r.files.get(J) ?? '').events
+export const kit = { Box: (props: Record<string, unknown>) => ({ kind: 'Box', props }), Text: (props: Record<string, unknown>) => ({ kind: 'Text', props }), Button: (props: Record<string, unknown>) => ({ kind: 'Button', props }) } as unknown as Kit
+export const envOf = (state: State, nowMs: number): SlotEnv => ({ ctx: { kit, state, nowMs, columns: 120, pictures: new Map(), act: {} as never } as Ctx, runs: [], run: null, phase: null, agent: null, ui: {} as never, nowMs })
+export const ready = (state: State, nowMs: number): void => { storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }; storeOf(state).spendAtMs = nowMs; storeOf(state).adaptAtMs = nowMs }
+export const settle = async (state: State): Promise<void> => { while (storeOf(state).isTicking) await new Promise(resolve => setTimeout(resolve, 1)) }
+export const dangling = (id = 's-dangling00001'): JournalEvent => ({ t: 'step.started', at: T0 + 10, id, task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 1e9, tier: 'mid' })
+
diff --git a/plugins/ruflo-console/tests/pure.spec.ts b/plugins/ruflo-console/tests/pure.spec.ts
index 65936a5ac7..4e39f70e64 100644
--- a/plugins/ruflo-console/tests/pure.spec.ts
+++ b/plugins/ruflo-console/tests/pure.spec.ts
@@ -59,7 +59,7 @@ describe('readers', () => {
})
it('plain strips control and bidi characters; idOf admits only id-shaped strings', () => {
- expect(plain('a\u001b[31m‮b\u0000c')).toBe('a b c')
+ expect(plain('a\u001b[31m‮b\u0000c')).toBe('ab c')
expect(plain('x'.repeat(50), 10)).toHaveLength(10)
expect(idOf('agent-1790903032181-97m25s')).toBe('agent-1790903032181-97m25s')
for (const bad of ['bad id!', '-rf', '', 'a'.repeat(200), '../etc', 42]) expect(idOf(bad)).toBeNull()
diff --git a/plugins/ruflo-console/tests/security-audit-live.spec.ts b/plugins/ruflo-console/tests/security-audit-live.spec.ts
new file mode 100644
index 0000000000..1d68c80d6d
--- /dev/null
+++ b/plugins/ruflo-console/tests/security-audit-live.spec.ts
@@ -0,0 +1,253 @@
+/**
+ * The security audit, live half (ADR-465, ADR-466): the autopilot loop on an in-memory disk and a fake host, attacked through the files
+ * the steps can write. Each case failed before its fix and fails again if the fix is taken out. Run with
+ * npx vitest run plugins/ruflo-console/tests/security-audit-live.spec.ts --testTimeout=30000
+ */
+import { describe, expect, it } from 'vitest'
+
+import { apTick, stopNow, storeOf, wireAutopilot } from '../hooks/ap-live'
+import { seal } from '../hooks/data/ap-envelope'
+import { encodeLine, type JournalEvent } from '../hooks/data/ap-journal'
+import { foldJournal } from '../hooks/data/ap-loop'
+import { draftOf, startSpec } from '../hooks/views/ap-panel'
+import '../hooks/views/wf-register'
+import { dangling, E, ENV, envOf, J, journal, KILL, ready, rig, settle, started, stateWith, T0, task } from './fixtures/security-rig'
+
+describe('live: policy that depends on a fresh Anatole', () => {
+ it('a loop whose envelope does not accept running without Anatole pauses on a stale status, in a real tick', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')], { mode: 'enforce', updatedMs: T0 - 30 * 3_600_000, degraded: false })
+
+ started(r, [], { ...ENV, acceptWithoutAnatole: false })
+ wireAutopilot(state, r.host)
+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
+ storeOf(state).spendAtMs = T0 + 1000
+ await apTick(state, r.host, T0 + 1000)
+ expect(r.prompts).toEqual([])
+ expect(journal(r).at(-1)).toMatchObject({ t: 'pause' })
+ })
+})
+
+describe('the confirm card shows what it grants', () => {
+ it('lists every verify argv, the repos and the secret variable NAMES, not a count', () => {
+ const r = rig()
+ const state = stateWith([])
+
+ wireAutopilot(state, r.host)
+ draftOf(state).value = { ...ENV, verify: [['npx', 'vitest', 'run', 'tests/x.spec.ts']], repos: ['ruvnet/ruflo'], secretEnv: ['OPENROUTER_API_KEY'] } as never
+
+ const shows = startSpec(envOf(state, T0))?.shows ?? ''
+
+ expect(shows).toContain('npx vitest run tests/x.spec.ts')
+ expect(shows).toContain('ruvnet/ruflo')
+ expect(shows).toContain('OPENROUTER_API_KEY')
+ })
+})
+
+describe('live: tampering with the files the steps can write', () => {
+ it('an extra start line appended after a confirmed Start (a replay of the stop-then-start trick) stops the loop and hands nothing over', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ wireAutopilot(state, r.host)
+ await startSpec(envOf(state, T0))?.run?.()
+ await settle(state)
+ expect(journal(r)[0]).toMatchObject({ t: 'start' })
+ expect(storeOf(state).pin).toMatchObject({ starts: 1 })
+
+ const first = journal(r)[0] as Extract<JournalEvent, { t: 'start' }>
+
+ r.files.set(J, `${r.files.get(J)}${encodeLine({ t: 'stop', at: Date.now(), reason: 'you' })}${encodeLine(first)}`)
+ state.cache.clear()
+ ready(state, Date.now())
+ await apTick(state, r.host, Date.now() + 1000)
+
+ expect(r.prompts).toEqual([])
+ expect(journal(r).at(-1)).toMatchObject({ t: 'stop', reason: expect.stringContaining('2 start lines') })
+ })
+
+ it('an envelope rewritten with a matching hash and a start line for it (the hash is not a MAC) is not the one the person approved', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ wireAutopilot(state, r.host)
+ await startSpec(envOf(state, T0))?.run?.()
+ await settle(state)
+
+ const wider = seal({ ...ENV, concurrency: 8, spend: { hourUsd: 900, dayUsd: 900, totalUsd: 900 } }, 2, Date.now())
+
+ r.files.set(E, JSON.stringify(wider))
+ r.files.set(J, `${r.files.get(J)}${encodeLine({ t: 'start', at: Date.now(), envHash: wider.hash, revision: 2, anatole: 'on' })}`)
+ state.cache.clear()
+ ready(state, Date.now())
+ await apTick(state, r.host, Date.now() + 1000)
+
+ expect(r.prompts).toEqual([])
+ expect(journal(r).at(-1)).toMatchObject({ t: 'stop' })
+ })
+
+ it('a running journal with no recorded approval in a readable host store is stopped; an unreadable store adopts what is there and says nothing is lost', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r)
+ ;(r.host as { storeGet?: unknown }).storeGet = async () => undefined
+ wireAutopilot(state, r.host)
+ ready(state, T0 + 1000)
+ await apTick(state, r.host, T0 + 1000)
+ expect(r.prompts).toEqual([])
+ expect(journal(r).at(-1)).toMatchObject({ t: 'stop', reason: expect.stringContaining('no recorded approval') })
+
+ const r2 = rig()
+ const s2 = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r2)
+ wireAutopilot(s2, r2.host)
+ ready(s2, T0 + 1000)
+ await apTick(s2, r2.host, T0 + 1000)
+ expect(r2.prompts.length).toBe(1)
+ })
+})
+
+describe('live: kill-switch latency and TOCTOU', () => {
+ it('a kill flag that appears while the verify commands run (minutes) stops the hand-over of the next task in the same tick', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'completed'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r, [dangling()])
+ wireAutopilot(state, r.host)
+ storeOf(state).bootMs = T0 - 1
+ ready(state, T0 + 1000)
+ r.onRun.fn = argv => { if (argv[0] === 'true') r.files.set(KILL, '') }
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(r.runs.some(a => a[0] === 'true')).toBe(true)
+ expect(r.prompts).toEqual([])
+ expect(journal(r).some(e => e.t === 'step.failed' && e.why.includes('stopped before the hand-over'))).toBe(true)
+ })
+
+ it('a stop pressed while the tick is mid-flight is not outrun: the in-memory stop blocks the hand-over too', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'completed'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r, [dangling()])
+ wireAutopilot(state, r.host)
+ storeOf(state).bootMs = T0 - 1
+ ready(state, T0 + 1000)
+ r.onRun.fn = argv => { if (argv[0] === 'true') storeOf(state).loop = foldJournal([{ t: 'stop', at: T0 + 500, reason: 'you pressed stop' }], storeOf(state).loop) }
+ await apTick(state, r.host, T0 + 1000)
+ expect(r.prompts).toEqual([])
+ })
+})
+
+describe('live: double execution', () => {
+ it('two sessions that both start the same step: neither hands it over', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r)
+ wireAutopilot(state, r.host)
+ ready(state, T0 + 1000)
+ // The other session's identical line lands in the same append window.
+ r.onAppend.fn = text => (text.includes('step.started') ? text + text : text)
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(r.prompts).toEqual([])
+ expect(journal(r).some(e => e.t === 'step.failed' && e.why.includes('second start'))).toBe(true)
+ })
+
+ it('a step lost to a restart is not run again by the next tick: its task is parked with the question', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r, [dangling()])
+ wireAutopilot(state, r.host)
+ storeOf(state).bootMs = T0 + 100
+ ready(state, T0 + 1000)
+ await apTick(state, r.host, T0 + 1000)
+ ready(state, T0 + 600_000)
+ await apTick(state, r.host, T0 + 600_000)
+
+ expect(journal(r).some(e => e.t === 'parked' && e.question.includes('may have run'))).toBe(true)
+ expect(r.prompts.some(p => p.includes('Fix the parser bug'))).toBe(false)
+ })
+})
+
+describe('live: permission laundering', () => {
+ it('a verify command the engine would deny is never run by the console, and the step fails rather than counting as verified', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'completed'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r, [dangling()])
+ wireAutopilot(state, r.host, { toolCheck: async tool => ({ decision: tool === 'Bash' ? 'deny' : 'allow' }) })
+ storeOf(state).bootMs = T0 - 1
+ ready(state, T0 + 1000)
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(r.runs.some(a => a[0] === 'true')).toBe(false)
+ expect(journal(r).some(e => e.t === 'step.failed' && e.id === 's-dangling00001')).toBe(true)
+ expect(journal(r).some(e => e.t === 'step.done')).toBe(false)
+ })
+})
+
+describe('live: the journal rotation cannot lose the old journal to a pre-made archive name', () => {
+ it('an archive that already exists stops the rotation: the long journal stays', async () => {
+ const r = rig()
+ const state = stateWith([])
+
+ started(r, Array.from({ length: 42_000 }, (_, i) => ({ t: 'beat', at: T0 + i }) as JournalEvent))
+ expect((r.files.get(J) as string).length).toBeGreaterThan(1_200_000)
+ expect((r.files.get(J) as string).length).toBeLessThan(1_500_000)
+
+ const now = T0 + 100_000_000
+ const stamp = new Date(now).toISOString().replace(/[^0-9]/g, '').slice(0, 14)
+
+ r.files.set(`${J}.${stamp}`, 'planted')
+ wireAutopilot(state, r.host)
+ ready(state, now)
+ await apTick(state, r.host, now)
+
+ expect((r.files.get(J) as string).length).toBeGreaterThan(1_200_000)
+ expect(r.files.get(`${J}.${stamp}`)).toBe('planted')
+ })
+})
+
+describe('live: bounded reads and deleted stop lines', () => {
+ it('a journal that grows past its cap between the append and the hand-over is not read: the step is not handed over', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r)
+ wireAutopilot(state, r.host)
+ ready(state, T0 + 1000)
+ r.onAppend.fn = text => (text.includes('step.started') ? `${text}${'x'.repeat(2_000_000)}\n` : text)
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(r.prompts).toEqual([])
+ expect(journal(r).some(e => e.t === 'step.failed' && e.why.includes('over its cap'))).toBe(true)
+ })
+
+ it('deleting the stop line and the kill flag does not bring a stopped loop back: the recorded stop is pinned outside the project', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ wireAutopilot(state, r.host)
+ await startSpec(envOf(state, T0))?.run?.()
+ await settle(state)
+ await stopNow(state, r.host, 'you pressed stop')
+ expect(storeOf(state).pin).toMatchObject({ stopped: true })
+
+ // The step removes the flag and cuts the journal back to its first line (a start): hash and start count still match the pin.
+ const first = (r.files.get(J) as string).split('\n')[0] as string
+
+ r.files.set(J, `${first}\n`)
+ r.files.delete(KILL)
+ state.cache.clear()
+ storeOf(state).loop = foldJournal([])
+ ready(state, Date.now())
+ await apTick(state, r.host, Date.now() + 1000)
+
+ expect(r.prompts).toEqual([])
+ expect(journal(r).at(-1)).toMatchObject({ t: 'stop', reason: expect.stringContaining('stop line was removed') })
+ })
+})
diff --git a/plugins/ruflo-console/tests/security-audit.spec.ts b/plugins/ruflo-console/tests/security-audit.spec.ts
index 367d1dc4fd..c8171d4de3 100644
--- a/plugins/ruflo-console/tests/security-audit.spec.ts
+++ b/plugins/ruflo-console/tests/security-audit.spec.ts
@@ -1,40 +1,23 @@
/**
* The security audit of the control plane, the bridge and the autopilot (ADR-465, ADR-466), adversarially: each case is an attack that
- * worked before its fix, and fails again if the fix is taken out. Pure cases first, then the live loop on an in-memory disk. Run with
+ * worked before its fix, and fails again if the fix is taken out. The pure cases; the live loop on an in-memory disk is security-audit-live.spec.ts. Run with
* npx vitest run plugins/ruflo-console/tests/security-audit.spec.ts --testTimeout=30000
*/
import { describe, expect, it } from 'vitest'
-import { apTick, refreshAutopilot, storeOf, wireAutopilot } from '../hooks/ap-live'
+import { classAllowed, hashOf, isProtectedPath, pathAllowed, validateEnvelope, type Envelope } from '../hooks/data/ap-envelope'
import { applyChange, DEFAULTS, GENESIS, promote, tunablesFrom, type Proposal } from '../hooks/data/ap-adapt'
-import { classAllowed, hashOf, isProtectedPath, pathAllowed, seal, validateEnvelope, type Envelope } from '../hooks/data/ap-envelope'
import { anatoleFact, classifyTask, seen, verifyPermission } from '../hooks/data/ap-guard'
-import { encodeLine, JOURNAL_FILE, parseJournal, startedCount, wash, type JournalEvent, type Receipt } from '../hooks/data/ap-journal'
+import { encodeLine, parseJournal, startedCount, wash, type JournalEvent, type Receipt } from '../hooks/data/ap-journal'
import { emptyLoop, foldJournal, tick, whyParked, type Facts } from '../hooks/data/ap-loop'
import { checkPin } from '../hooks/data/ap-pin'
-import type { TaskRecord } from '../hooks/data/parse'
import { cleanText } from '../hooks/data/wf-clean'
import { addMessage, applyFetch, fromBbs, FETCH_MAX, lastAnswer, newConvo, recordSend, relayBody } from '../hooks/data/wf-convo'
import { payloadOf, sendTo, type SendDeps } from '../hooks/data/wf-send'
import { isBaseUrl, parseConfig, targetsOf, type Target } from '../hooks/data/wf-targets'
-import type { Host } from '../hooks/host'
-import { mcOf, type MissionRecord } from '../hooks/mission-control'
-import { newState, type State } from '../hooks/state'
-import { startSpec, draftOf } from '../hooks/views/ap-panel'
-import { resetSlots } from '../hooks/views/wf-slots'
-import type { Ctx, Kit } from '../hooks/views/common'
-import type { SlotEnv } from '../hooks/views/wf-slots'
-import '../hooks/views/wf-register'
-
-void resetSlots
-
-const CWD = '/w'
-const T0 = Date.parse('2026-10-06T00:00:00.000Z')
-const AP = `${CWD}/.claude-flow/console/autopilot`
-const J = `${CWD}/${JOURNAL_FILE}`
-const E = `${AP}/envelope.json`
-const KILL = `${AP}/KILL`
-const ENV: Envelope = { name: 'night', toolClasses: ['edit', 'read', 'test'], paths: [CWD], repos: [], network: [], secretEnv: [], spend: { hourUsd: 2, dayUsd: 10, totalUsd: 40 }, concurrency: 4, maxDurationMs: 7 * 86_400_000, verify: [['true']], acceptWithoutAnatole: true }
+import { parseJournal as parseRunJournal } from '../hooks/data/workflows'
+import { CWD, E, ENV, KILL, T0 } from './fixtures/security-rig'
+
const GOOD = (over: Record<string, unknown> = {}): unknown => ({ ...ENV, ...over })
const errsOf = (raw: unknown): string => { const c = validateEnvelope(raw); return c.ok ? '' : c.errors.join('\n') }
@@ -112,19 +95,6 @@ describe('Project Anatole: a forged, stale or failed-open status is not "on"', (
expect(anatoleFact(facts(null, { modeOverride: 'enforce' }), T0)).toBe('absent')
expect(anatoleFact(facts({ mode: 'off', updatedMs: T0 - 99 * 3_600_000, degraded: false }), T0)).toBe('off')
})
-
- it('a loop whose envelope does not accept running without Anatole pauses on a stale status, in a real tick', async () => {
- const r = rig()
- const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')], { mode: 'enforce', updatedMs: T0 - 30 * 3_600_000, degraded: false })
-
- started(r, [], { ...ENV, acceptWithoutAnatole: false })
- wireAutopilot(state, r.host)
- storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
- storeOf(state).spendAtMs = T0 + 1000
- await apTick(state, r.host, T0 + 1000)
- expect(r.prompts).toEqual([])
- expect(journal(r).at(-1)).toMatchObject({ t: 'pause' })
- })
})
describe('the journal: a line cannot tune, replay or resurrect the loop', () => {
@@ -169,6 +139,19 @@ describe('the journal: a line cannot tune, replay or resurrect the loop', () =>
expect(parseJournal(encodeLine({ t: 'stop', at: 1, reason: `ghp_${'a'.repeat(20)}⁠${'b'.repeat(20)}` })).events[0]).not.toMatchObject({ reason: expect.stringMatching(/b{5}/) })
})
+ it('a result preview in a run journal masks a credential split by a zero-width character (the parse stage must not turn it into a space first)', () => {
+ const key = `sk-ant-api03-${'A'.repeat(14)}\u200b${'B'.repeat(14)}`
+ const line = JSON.stringify({ type: 'result', agentId: 'agent-1', result: `done ${key} end` })
+ const agent = parseRunJournal(line).agents[0]
+
+ expect(agent?.resultPreview).toBeDefined()
+ expect(agent?.resultPreview).not.toMatch(/B{5}/)
+
+ const label = parseRunJournal(JSON.stringify({ type: 'started', agentId: 'agent-2', label: `x ${key} y` })).agents[0]?.label ?? ''
+
+ expect(cleanText(label)).not.toMatch(/B{5}/)
+ })
+
it('a step is handed over only when the journal holds exactly one start line for it', () => {
const line = encodeLine({ t: 'step.started', at: 1, id: 's-abc', task: 't1', cls: 'edit', attempt: 1, deadline: 9, tier: 'mid' })
@@ -204,22 +187,6 @@ describe('crash-resume: a step that may have run is not retried on its own', ()
})
})
-describe('the confirm card shows what it grants', () => {
- it('lists every verify argv, the repos and the secret variable NAMES, not a count', () => {
- const r = rig()
- const state = stateWith([])
-
- wireAutopilot(state, r.host)
- draftOf(state).value = { ...ENV, verify: [['npx', 'vitest', 'run', 'tests/x.spec.ts']], repos: ['ruvnet/ruflo'], secretEnv: ['OPENROUTER_API_KEY'] } as never
-
- const shows = startSpec(envOf(state, T0))?.shows ?? ''
-
- expect(shows).toContain('npx vitest run tests/x.spec.ts')
- expect(shows).toContain('ruvnet/ruflo')
- expect(shows).toContain('OPENROUTER_API_KEY')
- })
-})
-
describe('the conversation bridge: where the key and the text go', () => {
const t = (name: string): Target => targetsOf({ agents: [], peers: [], config: parseConfig('endpoint:gw=https://gw.example.com/v1|COG_KEY|m'), hasHive: false, hasCodex: false }).find(x => x.id === name) as Target
const deps = (over: Partial<SendDeps> = {}): SendDeps => ({ cli: ['ruflo'], helper: '/h/federation.sh', trustedPeers: new Set(), cwd: '/w', hive: null, config: parseConfig('endpoint:gw=https://gw.example.com/v1|COG_KEY|m'), run: async () => ({ exitCode: 0, stdout: 'k-plain-9981\n', stderr: '' }), httpSend: async () => ({ ok: true, status: 200, text: '{}' }), submitPrompt: async () => undefined, ...over }) as SendDeps
@@ -301,250 +268,3 @@ describe('the permission the console must not launder', () => {
})
})
-// ---------------------------------------------------------------- live: an in-memory disk and a fake host
-type Rig = { files: Map<string, string>; runs: string[][]; prompts: string[]; host: Host; onRun: { fn: ((argv: readonly string[]) => void) | null }; onAppend: { fn: ((text: string) => string) | null } }
-
-function rig(): Rig {
- const files = new Map<string, string>()
- const runs: string[][] = []
- const prompts: string[] = []
- const onRun: Rig['onRun'] = { fn: null }
- const onAppend: Rig['onAppend'] = { fn: null }
-
- const host = {
- fs: {
- read: async (p: string) => files.get(p) ?? Promise.reject(new Error('ENOENT')),
- stat: async (p: string) => (files.has(p) ? { mtimeMs: 1, size: (files.get(p) as string).length, kind: 'file', isLink: false } : [...files.keys()].some(k => k.startsWith(`${p}/`)) ? { kind: 'dir', isLink: false } : Promise.reject(new Error('ENOENT'))),
- list: async () => [],
- },
- run: async (argv: readonly string[], _t: number, stdin?: string) => {
- runs.push([...argv])
- onRun.fn?.(argv)
-
- if (argv[0] === 'dd') {
- const path = (argv.find(a => a.startsWith('of=')) as string).slice(3)
- const add = argv.includes('oflag=append') && onAppend.fn !== null ? onAppend.fn(stdin ?? '') : (stdin ?? '')
-
- files.set(path, argv.includes('oflag=append') ? `${files.get(path) ?? ''}${add}` : (stdin ?? ''))
- } else if (argv[0] === 'install') files.set(argv.at(-1) as string, argv.includes('/dev/null') ? '' : (stdin ?? ''))
- else if (argv[0] === 'rm') files.delete(argv.at(-1) as string)
- else if (argv[0] === 'cp') files.set(argv.at(-1) as string, files.get(argv.at(-2) as string) ?? '')
-
- return { exitCode: 0, stdout: '', stderr: '' }
- },
- invalidate: () => undefined,
- toast: () => undefined,
- every: () => ({ cancel: () => undefined }),
- after: () => ({ cancel: () => undefined }),
- storeSet: async () => undefined,
- submitPrompt: async (t: string) => void prompts.push(t),
- } as unknown as Host
-
- return { files, runs, prompts, host, onRun, onAppend }
-}
-
-const task = (id: string, status: string): TaskRecord => ({ id, type: 'feature', description: '', status, assignedTo: [], tags: [] })
-
-const mission = (): MissionRecord => ({
- id: 'msn_0123456789abcdef01234567', objective: 'tidy the parser', profile: 'feature', rigor: 'standard',
- tasks: [
- { id: 't1', title: 'Fix the parser bug', phase: 'S', agent: 'coder', requirement: 'tests pass', dependsOn: [], rufloTaskId: 'r1' },
- { id: 't2', title: 'Update the changelog', phase: 'A', agent: 'coder', requirement: 'a line', dependsOn: [], rufloTaskId: 'r2' },
- { id: 't3', title: 'Review the module', phase: 'P', agent: 'coder', requirement: 'a summary', dependsOn: [], rufloTaskId: 'r3' },
- ],
- acceptance: [], events: [], paused: false, cancelled: false, auto: false, createdAtMs: 1,
-})
-
-function stateWith(tasks: TaskRecord[], anatole: Record<string, unknown> = { mode: 'notify', updatedMs: T0, degraded: false }): State {
- const state = newState({})
-
- state.cwd = CWD
- state.snapshot = { tasks, agents: [], claims: [], swarm: null, plugins: { missingFromClone: [], installed: [] }, alerts: [], anatole: { present: true, status: anatole, modeOverride: null, overrides: {}, alerts: [], refused: [], badAlerts: 0 } } as never
- mcOf(state).missions.set('msn_0123456789abcdef01234567', mission())
- mcOf(state).active = 'msn_0123456789abcdef01234567'
-
- return state
-}
-
-function started(r: Rig, extra: JournalEvent[] = [], env: Envelope = ENV): void {
- const sealed = seal(env, 1, T0)
-
- r.files.set(E, JSON.stringify(sealed))
- r.files.set(J, [{ t: 'start', at: T0, envHash: sealed.hash, revision: 1, anatole: 'on' } as JournalEvent, ...extra].map(encodeLine).join(''))
-}
-
-const journal = (r: Rig): JournalEvent[] => parseJournal(r.files.get(J) ?? '').events
-const kit = { Box: (props: Record<string, unknown>) => ({ kind: 'Box', props }), Text: (props: Record<string, unknown>) => ({ kind: 'Text', props }), Button: (props: Record<string, unknown>) => ({ kind: 'Button', props }) } as unknown as Kit
-const envOf = (state: State, nowMs: number): SlotEnv => ({ ctx: { kit, state, nowMs, columns: 120, pictures: new Map(), act: {} as never } as Ctx, runs: [], run: null, phase: null, agent: null, ui: {} as never, nowMs })
-const ready = (state: State, nowMs: number): void => { storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }; storeOf(state).spendAtMs = nowMs; storeOf(state).adaptAtMs = nowMs }
-const settle = async (state: State): Promise<void> => { while (storeOf(state).isTicking) await new Promise(resolve => setTimeout(resolve, 1)) }
-const dangling = (id = 's-dangling00001'): JournalEvent => ({ t: 'step.started', at: T0 + 10, id, task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 1e9, tier: 'mid' })
-
-describe('live: tampering with the files the steps can write', () => {
- it('an extra start line appended after a confirmed Start (a replay of the stop-then-start trick) stops the loop and hands nothing over', async () => {
- const r = rig()
- const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
-
- wireAutopilot(state, r.host)
- await startSpec(envOf(state, T0))?.run?.()
- await settle(state)
- expect(journal(r)[0]).toMatchObject({ t: 'start' })
- expect(storeOf(state).pin).toMatchObject({ starts: 1 })
-
- const first = journal(r)[0] as Extract<JournalEvent, { t: 'start' }>
-
- r.files.set(J, `${r.files.get(J)}${encodeLine({ t: 'stop', at: Date.now(), reason: 'you' })}${encodeLine(first)}`)
- state.cache.clear()
- ready(state, Date.now())
- await apTick(state, r.host, Date.now() + 1000)
-
- expect(r.prompts).toEqual([])
- expect(journal(r).at(-1)).toMatchObject({ t: 'stop', reason: expect.stringContaining('2 start lines') })
- })
-
- it('an envelope rewritten with a matching hash and a start line for it (the hash is not a MAC) is not the one the person approved', async () => {
- const r = rig()
- const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
-
- wireAutopilot(state, r.host)
- await startSpec(envOf(state, T0))?.run?.()
- await settle(state)
-
- const wider = seal({ ...ENV, concurrency: 8, spend: { hourUsd: 900, dayUsd: 900, totalUsd: 900 } }, 2, Date.now())
-
- r.files.set(E, JSON.stringify(wider))
- r.files.set(J, `${r.files.get(J)}${encodeLine({ t: 'start', at: Date.now(), envHash: wider.hash, revision: 2, anatole: 'on' })}`)
- state.cache.clear()
- ready(state, Date.now())
- await apTick(state, r.host, Date.now() + 1000)
-
- expect(r.prompts).toEqual([])
- expect(journal(r).at(-1)).toMatchObject({ t: 'stop' })
- })
-
- it('a running journal with no recorded approval in a readable host store is stopped; an unreadable store adopts what is there and says nothing is lost', async () => {
- const r = rig()
- const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
-
- started(r)
- ;(r.host as { storeGet?: unknown }).storeGet = async () => undefined
- wireAutopilot(state, r.host)
- ready(state, T0 + 1000)
- await apTick(state, r.host, T0 + 1000)
- expect(r.prompts).toEqual([])
- expect(journal(r).at(-1)).toMatchObject({ t: 'stop', reason: expect.stringContaining('no recorded approval') })
-
- const r2 = rig()
- const s2 = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
-
- started(r2)
- wireAutopilot(s2, r2.host)
- ready(s2, T0 + 1000)
- await apTick(s2, r2.host, T0 + 1000)
- expect(r2.prompts.length).toBe(1)
- })
-})
-
-describe('live: kill-switch latency and TOCTOU', () => {
- it('a kill flag that appears while the verify commands run (minutes) stops the hand-over of the next task in the same tick', async () => {
- const r = rig()
- const state = stateWith([task('r1', 'completed'), task('r2', 'pending'), task('r3', 'pending')])
-
- started(r, [dangling()])
- wireAutopilot(state, r.host)
- storeOf(state).bootMs = T0 - 1
- ready(state, T0 + 1000)
- r.onRun.fn = argv => { if (argv[0] === 'true') r.files.set(KILL, '') }
- await apTick(state, r.host, T0 + 1000)
-
- expect(r.runs.some(a => a[0] === 'true')).toBe(true)
- expect(r.prompts).toEqual([])
- expect(journal(r).some(e => e.t === 'step.failed' && e.why.includes('stopped before the hand-over'))).toBe(true)
- })
-
- it('a stop pressed while the tick is mid-flight is not outrun: the in-memory stop blocks the hand-over too', async () => {
- const r = rig()
- const state = stateWith([task('r1', 'completed'), task('r2', 'pending'), task('r3', 'pending')])
-
- started(r, [dangling()])
- wireAutopilot(state, r.host)
- storeOf(state).bootMs = T0 - 1
- ready(state, T0 + 1000)
- r.onRun.fn = argv => { if (argv[0] === 'true') storeOf(state).loop = foldJournal([{ t: 'stop', at: T0 + 500, reason: 'you pressed stop' }], storeOf(state).loop) }
- await apTick(state, r.host, T0 + 1000)
- expect(r.prompts).toEqual([])
- })
-})
-
-describe('live: double execution', () => {
- it('two sessions that both start the same step: neither hands it over', async () => {
- const r = rig()
- const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
-
- started(r)
- wireAutopilot(state, r.host)
- ready(state, T0 + 1000)
- // The other session's identical line lands in the same append window.
- r.onAppend.fn = text => (text.includes('step.started') ? text + text : text)
- await apTick(state, r.host, T0 + 1000)
-
- expect(r.prompts).toEqual([])
- expect(journal(r).some(e => e.t === 'step.failed' && e.why.includes('another session'))).toBe(true)
- })
-
- it('a step lost to a restart is not run again by the next tick: its task is parked with the question', async () => {
- const r = rig()
- const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
-
- started(r, [dangling()])
- wireAutopilot(state, r.host)
- storeOf(state).bootMs = T0 + 100
- ready(state, T0 + 1000)
- await apTick(state, r.host, T0 + 1000)
- ready(state, T0 + 600_000)
- await apTick(state, r.host, T0 + 600_000)
-
- expect(journal(r).some(e => e.t === 'parked' && e.question.includes('may have run'))).toBe(true)
- expect(r.prompts.some(p => p.includes('Fix the parser bug'))).toBe(false)
- })
-})
-
-describe('live: permission laundering', () => {
- it('a verify command the engine would deny is never run by the console, and the step fails rather than counting as verified', async () => {
- const r = rig()
- const state = stateWith([task('r1', 'completed'), task('r2', 'pending'), task('r3', 'pending')])
-
- started(r, [dangling()])
- wireAutopilot(state, r.host, { toolCheck: async tool => ({ decision: tool === 'Bash' ? 'deny' : 'allow' }) })
- storeOf(state).bootMs = T0 - 1
- ready(state, T0 + 1000)
- await apTick(state, r.host, T0 + 1000)
-
- expect(r.runs.some(a => a[0] === 'true')).toBe(false)
- expect(journal(r).some(e => e.t === 'step.failed' && e.id === 's-dangling00001')).toBe(true)
- expect(journal(r).some(e => e.t === 'step.done')).toBe(false)
- })
-})
-
-describe('live: the journal rotation cannot lose the old journal to a pre-made archive name', () => {
- it('an archive that already exists stops the rotation: the long journal stays', async () => {
- const r = rig()
- const state = stateWith([])
-
- started(r, Array.from({ length: 42_000 }, (_, i) => ({ t: 'beat', at: T0 + i }) as JournalEvent))
- expect((r.files.get(J) as string).length).toBeGreaterThan(1_200_000)
- expect((r.files.get(J) as string).length).toBeLessThan(1_500_000)
-
- const now = T0 + 100_000_000
- const stamp = new Date(now).toISOString().replace(/[^0-9]/g, '').slice(0, 14)
-
- r.files.set(`${J}.${stamp}`, 'planted')
- wireAutopilot(state, r.host)
- ready(state, now)
- await apTick(state, r.host, now)
-
- expect((r.files.get(J) as string).length).toBeGreaterThan(1_200_000)
- expect(r.files.get(`${J}.${stamp}`)).toBe('planted')
- void refreshAutopilot
- })
-})
diff --git a/v3/docs/adr/ADR-467-control-plane-and-autopilot-security-audit.md b/v3/docs/adr/ADR-467-control-plane-and-autopilot-security-audit.md
new file mode 100644
index 0000000000..6a52d2d86b
--- /dev/null
+++ b/v3/docs/adr/ADR-467-control-plane-and-autopilot-security-audit.md
@@ -0,0 +1,67 @@
+# ADR 467: Security audit of the control plane, the bridge and the autopilot
+
+Status: Accepted
+
+Date: 2026-10-06
+
+Builds on: ADR-465 (control plane and multi-model bridge), ADR-466 (mission autopilot), ADR-453 (Project Anatole)
+
+## 1. Context
+
+ADR-466 stores the autopilot's envelope, its journal and its kill flag under `.claude-flow/console/autopilot/` in the project. Every
+step the autopilot starts runs as the session, with the session's file permissions, and can write there. The envelope's hash is not a
+MAC (whoever can write the file recomputes it), and ADR-465's bridge sends text and a key to hosts named by an option string. An
+adversarial pass over the merged tip found real defects, each proven by a test that fails without its fix:
+
+- Envelope, journal, kill flag and Anatole's status were reachable by steps; a forged `start` line, an envelope rewritten with a
+ matching hash, or a deleted `stop` line resurrected or widened a stopped loop.
+- The envelope's `verify` argv ran through the host's process API, outside the engine's permission check (launders a deny), and could be
+ a shell, `rm`, `curl` or `npm publish`.
+- The kill flag was read once at the start of a tick; a verify run of minutes left the hand-over unguarded. Two sessions on one project
+ could both hand over the same step. A step lost to a restart was retried automatically although it may have run.
+- Task classification matched raw text: a zero-width character split `publish`; a second path, `~/`, `$HOME` or `..` bypassed the
+ folder gate; `push`/`install`/`upload` ran under a milder class. Anatole counted as "on" from a stale or failed-open status file.
+- A forged adaptation receipt tuned the loop (the chain was drawn but not enforced).
+- Base URLs allowed link-local and metadata hosts and any `100.x`; a key variable could name any credential; the confirm card cut a
+ payload at 700 characters while sending all of it; a relayed reply was framed so its own quote could pose as the person; credentials
+ split by zero-width characters survived masking at parse time; a poll answer was parsed at any size; a pre-made archive name could
+ make journal rotation discard the old journal.
+
+## 2. Decision
+
+1. **The approval pin (new invariant).** What the person confirmed is remembered outside the project folder: the envelope hash, the
+ count of `start` lines and whether a stop was recorded (`data/ap-pin.ts`), in this process and in the host store (`$.store`, key
+ `autopilot-pin:<cwd>`). Every tick compares the folded journal to the pin; a different hash, another start count, or a running
+ journal after a recorded stop stops the loop. A readable store that holds no pin for a running journal also stops it.
+2. **Steps cannot be pointed at the loop's own files.** `.claude-flow/console` and `.claude-flow/protector-mod` are protected: an
+ envelope naming them is invalid, `pathAllowed` refuses them, and a task naming them (or the kill flag) is the `envelope-edit` hard
+ deny, which "approve once" never lifts.
+3. **Verify commands** may not be shells, wrappers, destructive or network tools, carry shell metacharacters or name a hard deny; each
+ is asked of the engine as the Bash call it is and runs only on `allow`. The Start card lists every argv, repo and variable name.
+4. **Hand-over re-check.** Immediately before a step is handed over: the kill flag, the in-memory phase, and the journal (read within
+ its cap, regular file) holding exactly one start line for the step. A step lost to a restart parks its task with a question.
+5. **Classification** runs on normalised text (NFKC, zero-width removed); every named path is checked, home/variable/parent paths are
+ never inside a folder, and unplaced verbs park the task. Anatole is "on" only for a fresh, not-degraded status.
+6. **Receipts** are applied only along their intact hash chain; adaptation stops when it is broken.
+7. **Bridge**: base URLs refuse link-local, metadata, unspecified, multicast, IPv6-literal (but `::1`) and non-tailnet `100.x`; an
+ endpoint is never given a cloud, source-host, registry or ssh credential variable; the card shows the whole payload or the send is
+ refused; a relayed reply is one JSON string named as untrusted data; polls over 1,000,000 characters are not parsed.
+8. **Masking** removes zero-width and format characters before it masks, at parse, wash and clean.
+
+## 3. Consequences
+
+- A step can still do what the session's permissions let it do: the pin makes the loop's own state tamper-evident, not the project
+ safe from the session. The recommended companion is permission rules denying `.claude-flow/console/**` and `protector-mod/**`.
+- Two consoles on one project each hold their own pin; a Start or rotation in one stops the other (fail closed).
+- A first run after this change with a readable but empty store stops a running journal; the person confirms Start again.
+
+## 4. Test and benchmark plan
+
+`tests/security-audit.spec.ts` (pure), `tests/security-audit-live.spec.ts` (in-memory disk and fake host). Each
+fix was mutation-checked: removing it fails its test. Cost: one `stat`, one bounded read and string checks per tick; no benchmark is
+needed, the tick runs once a minute.
+
+## 5. Rollback
+
+Revert the commit. The pin is one store key (`autopilot-pin:<cwd>`); deleting it with the code in place makes an unreadable store adopt
+the journal, and a readable one require a confirmed Start.