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): autopilot live loop, panel, parked queue and tests (ADR-466)

ruvb08c7b28c76b
diff --git a/plugins/ruflo-console/hooks/ap-live.ts b/plugins/ruflo-console/hooks/ap-live.ts
new file mode 100644
index 0000000000..79ef7fba25
--- /dev/null
+++ b/plugins/ruflo-console/hooks/ap-live.ts
@@ -0,0 +1,432 @@
+/**
+ * The autopilot's live half (ADR-466): reads the sealed envelope and the journal, gathers the facts for one tick, appends what the
+ * step machine decided, and hands a started step to the session through the console's existing mission dispatch (the same `dispatchSpec`
+ * path and `submitPrompt`, no executor of its own). Wired once with `wireAutopilot(state, host, { toolCheck })` where the other actions
+ * are wired; it then ticks on `host.every`. The loop's liveness over days comes from the session itself staying up (the mission's
+ * `/loop` re-arm); this module adds the per-tick checks, never a scheduler.
+ *
+ * Every write is the host's `run` of a fixed argv (the host's fs is read-only), after `checkNoLinks`, one at a time, and a write that
+ * fails is a tick that does not act. Stopping and pausing need no confirm (they only narrow authority); starting and any change of the
+ * envelope go through the confirm card (views/ap-panel.ts).
+ */
+import { activeMission, derive, dispatchSpec, rufloTaskOf, type MissionRecord } from './mission-control'
+import type { Host } from './host'
+import type { State } from './state'
+import { readBounded, under } from './data/files'
+import { checkNoLinks, dirOf, removeFileArgv, replaceFileArgv } from './data/wf-file'
+import { cleanText } from './data/wf-clean'
+import { trackerOf } from './data/cost-ledger'
+import { evaluate, outcomesOf, promote, propose, reviewTrials, tierOf, tunablesFrom, lastHash } from './data/ap-adapt'
+import { AUTOPILOT_DIR, ENVELOPE_FILE, KILL_FILE, open, type Envelope, type Sealed, type Spend } from './data/ap-envelope'
+import { anatoleFact, classifyTask, effectOf, killSeen, preflightAll, spendArgvs, spendOf, type ToolCheck } from './data/ap-guard'
+import { appendArgv, encodeLine, JOURNAL_FILE, JOURNAL_MAX_BYTES, parseJournal, touchArgv, type JournalEvent } from './data/ap-journal'
+import { digestText, emptyLoop, foldJournal, skipSet, snapshotEvents, tick, type EffectFact, type Facts, type LoopState, type TaskFact } from './data/ap-loop'
+import type { Preflight } from './data/ap-loop'
+import type { NoticeDraft } from './notices'
+
+export const TICK_MS = 60_000
+const SPEND_EVERY_MS = 120_000
+const ADAPT_EVERY_MS = 600_000
+const PREFLIGHT_EVERY_MS = 60_000
+const STEP_TIMEOUT_MS = 30 * 60_000
+
+export type Store = {
+ sealed: Sealed | null
+ envWhy: string | null
+ loop: LoopState
+ badLines: number
+ journalBytes: number
+ spend: Spend | null
+ spendAtMs: number
+ killed: boolean
+ status: string
+ preflight: Record<string, Preflight>
+ preflightAtMs: number
+ hasCheck: boolean
+ adaptAtMs: number
+ bootMs: number
+ isTicking: boolean
+ error: string | null
+ readAtMs: number
+ notices: NoticeDraft[]
+ verified: Map<string, EffectFact>
+ chain: Promise<unknown>
+ isTimerOn: boolean
+}
+
+const stores = new WeakMap<State, Store>()
+const hosts = new WeakMap<State, Host>()
+let active: State | null = null
+
+/** The console state the notice slot reads for (one per console). */
+export const activeOf = (): State | null => active
+
+const checks = new WeakMap<State, ToolCheck | undefined>()
+
+export const storeOf = (state: State): Store => stores.get(state) ?? stores.set(state, { sealed: null, envWhy: null, loop: emptyLoop(), badLines: 0, journalBytes: 0, spend: null, spendAtMs: 0, killed: false, status: 'not wired', preflight: {}, preflightAtMs: 0, hasCheck: false, adaptAtMs: 0, bootMs: Date.now(), isTicking: false, error: null, readAtMs: 0, notices: [], verified: new Map(), chain: Promise.resolve(), isTimerOn: false }).get(state)!
+
+export const hostOf = (state: State): Host | undefined => hosts.get(state)
+
+const pathOf = (state: State, rel: string): string => `${state.cwd.replace(/\/+$/, '')}/${rel}`
+
+/** Wires the host and, when the engine offers one, its permission check (`$.tool.check`); starts the tick timer once. */
+export function wireAutopilot(state: State, host: Host, deps: { toolCheck?: ToolCheck } = {}): void {
+ hosts.set(state, host)
+ active = state
+ checks.set(state, deps.toolCheck)
+
+ const store = storeOf(state)
+
+ store.hasCheck = deps.toolCheck !== undefined
+ store.status = 'wired'
+
+ if (!store.isTimerOn) {
+ store.isTimerOn = true
+
+ try {
+ host.every(TICK_MS, () => void apTick(state, host))
+ } catch {
+ store.error = 'the host refused a timer: autopilot ticks only when asked'
+ }
+ }
+
+ void refreshAutopilot(state, host)
+}
+
+/** Reads the envelope and the journal; never rejects. A file that is too big or not regular is a said problem, not a guess. */
+export async function refreshAutopilot(state: State, host: Host, nowMs: number = Date.now()): Promise<void> {
+ const store = storeOf(state)
+
+ try {
+ const env = await readBounded(host.fs, state.cache, under(state.cwd, ENVELOPE_FILE), 65_536, true)
+ const opened = open(env.text)
+
+ store.sealed = opened.ok ? opened.sealed : null
+ store.envWhy = opened.ok ? null : env.text === null && env.reason === 'missing' ? null : opened.why
+
+ const journal = await readBounded(host.fs, state.cache, under(state.cwd, JOURNAL_FILE), JOURNAL_MAX_BYTES, true)
+
+ if (journal.text === null) {
+ store.loop = journal.reason === 'missing' ? emptyLoop() : store.loop
+ store.error = journal.reason === 'missing' ? null : `the journal was not read: ${journal.reason}`
+ store.journalBytes = journal.reason === 'too-large' ? (journal.size ?? JOURNAL_MAX_BYTES) : 0
+ } else {
+ const parsed = parseJournal(journal.text)
+
+ store.loop = foldJournal(parsed.events)
+ store.badLines = parsed.bad
+ store.journalBytes = journal.text.length
+ store.error = null
+ }
+
+ store.killed = await killSeen(host.fs, state.cwd)
+ store.readAtMs = nowMs
+ } catch {
+ store.error = 'the autopilot files were not read'
+ } finally {
+ host.invalidate()
+ }
+}
+
+/** One append at a time. Resolves false (and says why in `store.error`) when the write did not happen. */
+export function appendEvents(state: State, host: Host, events: readonly JournalEvent[]): Promise<boolean> {
+ const store = storeOf(state)
+
+ if (events.length === 0) return Promise.resolve(true)
+
+ const job = store.chain.then(async (): Promise<boolean> => {
+ try {
+ const path = pathOf(state, JOURNAL_FILE)
+ const clear = await checkNoLinks(host.fs, path, { cwd: state.cwd }, { allowExisting: true })
+
+ if (!clear.ok) {
+ store.error = cleanText(clear.why).slice(0, 100)
+
+ return false
+ }
+
+ if ((await host.fs.stat(path).catch(() => undefined)) === undefined) await host.run(touchArgv(path), 10_000)
+
+ const result = await host.run(appendArgv(path), 10_000, events.map(encodeLine).join(''))
+
+ if (result.exitCode !== 0) {
+ store.error = `the journal write exited ${result.exitCode}`
+
+ return false
+ }
+
+ store.loop = foldJournal(events, store.loop)
+ store.error = null
+
+ return true
+ } catch {
+ store.error = 'the journal write was refused'
+
+ return false
+ } finally {
+ host.invalidate()
+ }
+ })
+
+ store.chain = job.catch(() => undefined)
+
+ return job
+}
+
+/** Queues a notice (drained by the slot in views/ap-panel.ts) and says it in a toast, which is what reaches a person away from the page. */
+function say(state: State, host: Host, draft: NoticeDraft): void {
+ const store = storeOf(state)
+
+ store.notices.push({ ...draft, text: cleanText(draft.text).slice(0, 140) })
+ store.notices.splice(0, Math.max(0, store.notices.length - 10))
+
+ try {
+ host.toast(cleanText(draft.text).slice(0, 120), 8000)
+ } catch {
+ // A toast is a courtesy.
+ }
+}
+
+export const drainNotices = (state: State): NoticeDraft[] => storeOf(state).notices.splice(0)
+
+/** The kill switch and the plain stop: journal a stop AND leave the flag file, so a loop in another session halts too. No confirm: it only narrows authority. */
+export async function stopNow(state: State, host: Host, reason = 'stopped by you'): Promise<void> {
+ const store = storeOf(state)
+ const flag = pathOf(state, KILL_FILE)
+
+ store.loop = foldJournal([{ t: 'stop', at: Date.now(), reason }], store.loop)
+ store.killed = true
+ host.invalidate()
+
+ const clear = await checkNoLinks(host.fs, flag, { cwd: state.cwd }, { allowExisting: true }).catch(() => ({ ok: false as const, why: 'unchecked' }))
+
+ if (clear.ok) await host.run(touchArgv(flag), 10_000).catch(() => undefined)
+
+ await appendEvents(state, host, [{ t: 'stop', at: Date.now(), reason }])
+ say(state, host, { level: 'warn', text: `autopilot stopped: ${reason}`, key: 'ap-stop', go: 'missions' })
+}
+
+export async function pauseNow(state: State, host: Host, reason = 'paused by you'): Promise<void> {
+ await appendEvents(state, host, [{ t: 'pause', at: Date.now(), reason }])
+}
+
+export async function resumeNow(state: State, host: Host): Promise<void> {
+ await appendEvents(state, host, [{ t: 'resume', at: Date.now() }])
+ void apTick(state, host)
+}
+
+export async function answerParked(state: State, host: Host, id: string, answer: 'once' | 'deny'): Promise<void> {
+ await appendEvents(state, host, [{ t: 'answered', at: Date.now(), id, answer }])
+}
+
+/** Clears the kill flag; part of the confirmed start, never a button of its own. */
+export const clearKill = (state: State, host: Host): Promise<unknown> => host.run(removeFileArgv(pathOf(state, KILL_FILE)), 10_000).catch(() => undefined)
+
+/** Writes the sealed envelope (replacing the file). Only the confirmed start/change calls this. */
+export async function writeEnvelope(state: State, host: Host, sealed: Sealed): Promise<boolean> {
+ const path = pathOf(state, ENVELOPE_FILE)
+ const clear = await checkNoLinks(host.fs, path, { cwd: state.cwd }, { allowExisting: true })
+
+ if (!clear.ok) {
+ storeOf(state).error = cleanText(clear.why).slice(0, 100)
+
+ return false
+ }
+
+ const hasDir = (await host.fs.stat(dirOf(path)).catch(() => undefined)) !== undefined
+ const result = await host.run(replaceFileArgv(path, hasDir), 10_000, `${JSON.stringify(sealed, null, 2)}\n`)
+
+ if (result.exitCode === 0) storeOf(state).sealed = sealed
+
+ return result.exitCode === 0
+}
+
+/** The mission's next ready task that is not parked, denied or already stepped: the picker the loop uses. */
+export function pickTask(mission: MissionRecord, state: State, skip: ReadonlySet<string>): { ledger: MissionRecord['tasks'][number]; fact: TaskFact } | null {
+ const status = derive(mission, state.snapshot?.tasks ?? [])
+
+ // The mission's own dispatch hands out one task at a time and not past a failed one; autopilot does not pretend otherwise.
+ if ([...status.values()].some(value => value === 'running' || value === 'failed') || mission.paused) return null
+ const ledger = mission.tasks.find(task => status.get(task.id) === 'ready' && task.rufloTaskId !== undefined && !skip.has(task.id))
+
+ return ledger === undefined ? null : { ledger, fact: classifyTask(ledger.id, ledger.title, ledger.requirement) }
+}
+
+async function readSpend(state: State, host: Host, startMs: number, nowMs: number): Promise<Spend | null> {
+ const tracker = trackerOf(state)
+
+ if (tracker.kind !== 'ready') return null
+
+ const argvs = spendArgvs(tracker.root, startMs, nowMs, state.cwd)
+
+ if (argvs.hour === null || argvs.day === null || argvs.total === null) return null
+
+ try {
+ const [hour, day, total] = [await host.run(argvs.hour, 60_000), await host.run(argvs.day, 60_000), await host.run(argvs.total, 60_000)]
+
+ return spendOf({ hour: hour.stdout, day: day.stdout, total: total.stdout })
+ } catch {
+ return null
+ }
+}
+
+/** The effect of each in-flight step, from the task store AND the envelope's verify commands. The store's status alone is a claim. */
+async function effectsOf(state: State, host: Host, loop: LoopState, mission: MissionRecord | null, env: Envelope): Promise<Record<string, EffectFact>> {
+ const out: Record<string, EffectFact> = {}
+ const store = storeOf(state)
+
+ for (const step of loop.steps.filter(entry => entry.status === 'started')) {
+ const ledger = mission?.tasks.find(task => task.id === step.task)
+ const stored = ledger === undefined ? undefined : rufloTaskOf(state.snapshot?.tasks ?? [], ledger)?.status
+
+ if (stored === 'completed' && !store.verified.has(step.id)) {
+ let ran = 0
+ let failed = 0
+
+ for (const argv of env.verify) {
+ ran += 1
+
+ const result = await host.run(argv, 10 * 60_000).catch(() => ({ exitCode: 1 }))
+
+ if (result.exitCode !== 0) failed += 1
+ }
+
+ store.verified.set(step.id, effectOf(stored, { ran, failed }))
+ }
+
+ out[step.id] = stored === 'completed' ? (store.verified.get(step.id) ?? 'unknown') : stored === 'failed' || stored === 'cancelled' ? 'failed' : stored === 'pending' || stored === undefined ? 'absent' : 'unknown'
+ }
+
+ return out
+}
+
+/** One pass of the loop. Never rejects; a pass that is already running is skipped. */
+export async function apTick(state: State, host: Host, nowMs: number = Date.now()): Promise<void> {
+ const store = storeOf(state)
+
+ if (store.isTicking) return
+
+ store.isTicking = true
+
+ try {
+ await refreshAutopilot(state, host, nowMs)
+
+ const loop = store.loop
+
+ if (loop.phase === 'idle') {
+ store.status = 'not started'
+
+ return
+ }
+
+ if (store.killed && loop.phase !== 'stopped') {
+ await appendEvents(state, host, [{ t: 'stop', at: nowMs, reason: 'kill switch' }])
+ say(state, host, { level: 'warn', text: 'autopilot halted by the kill switch', key: 'ap-kill', go: 'missions' })
+ store.status = 'stopped: kill switch'
+
+ return
+ }
+
+ const sealed = store.sealed
+ const env = sealed !== null && sealed.hash === loop.envHash ? sealed.envelope : null
+ const mission = activeMission(state)
+
+ if (nowMs - store.spendAtMs >= SPEND_EVERY_MS && loop.phase === 'running' && loop.startedAtMs !== null) {
+ store.spend = await readSpend(state, host, loop.startedAtMs, nowMs)
+ store.spendAtMs = nowMs
+ }
+
+ if (nowMs - store.preflightAtMs >= PREFLIGHT_EVERY_MS) {
+ store.preflight = await preflightAll(checks.get(state))
+ store.preflightAtMs = nowMs
+ }
+
+ const tunables = env === null ? null : tunablesFrom(loop.receipts, env)
+ const picked = mission === null || mission.cancelled ? null : pickTask(mission, state, skipSet(loop))
+
+ const facts: Facts = {
+ nowMs,
+ killSeen: store.killed,
+ envelope: env,
+ anatole: anatoleFact(state.snapshot?.anatole),
+ spend: store.spend,
+ task: picked?.fact ?? null,
+ effects: env === null ? {} : await effectsOf(state, host, loop, mission, env),
+ orphans: new Set(loop.steps.filter(step => step.status === 'started' && step.startedAt < store.bootMs).map(step => step.id)),
+ tunables: { parallelism: tunables?.parallelism ?? 1, retries: tunables?.retries ?? 0, stepTimeoutMs: STEP_TIMEOUT_MS, tierOf: cls => (tunables === null ? 'mid' : tierOf(tunables, cls)) },
+ preflight: store.preflight,
+ }
+
+ const decision = tick(loop, facts)
+
+ store.status = decision.status
+
+ // The decision is journaled BEFORE the step is handed over: a crash between the two leaves a started step that the next pass settles by its effect, never a step that ran unrecorded.
+ const wrote = await appendEvents(state, host, decision.events)
+
+ for (const event of decision.events) {
+ if (event.t === 'stop' || event.t === 'pause') say(state, host, { level: event.t === 'stop' ? 'bad' : 'warn', text: `autopilot ${event.t === 'stop' ? 'stopped' : 'paused'}: ${event.reason}`, key: `ap-${event.t}`, go: 'missions' })
+ if (event.t === 'parked') say(state, host, { level: 'info', text: `autopilot parked ${event.task}: a question is waiting`, key: `ap-park-${event.task}`, go: 'missions' })
+ }
+
+ if (wrote && decision.act !== null && mission !== null && picked !== null) {
+ // The existing dispatch only hands out the first ready task of its own list; a shadow record with the picked task first lets autopilot work on past a parked one, over the same events and tasks.
+ const shadow: MissionRecord = { ...mission, tasks: [picked.ledger, ...mission.tasks.filter(task => task !== picked.ledger)] }
+ await dispatchSpec(state, host, shadow, picked.ledger, body => host.submitPrompt(body)).run?.()
+
+ // The dispatch refuses (and says so in the mission view) when the mission moved; that is a step that never started, not a failure to learn from.
+ if (decision.act !== null && (picked.ledger.dispatchedAtMs ?? 0) < nowMs - 1000) await appendEvents(state, host, [{ t: 'step.failed', at: Date.now(), id: decision.act.id, why: 'the mission refused the hand-over' }])
+ }
+
+ if (env !== null && tunables !== null && store.loop.phase === 'running' && nowMs - store.adaptAtMs >= ADAPT_EVERY_MS) {
+ store.adaptAtMs = nowMs
+ await adaptPass(state, host, env, nowMs)
+ }
+
+ const day = new Date(nowMs).toISOString().slice(0, 10)
+
+ if (store.loop.phase === 'running' && store.loop.lastDigestDay !== day && store.loop.lastDigestDay !== null) {
+ await appendEvents(state, host, [{ t: 'digest', at: nowMs, day }])
+ say(state, host, { level: 'info', text: digestText(store.loop, nowMs, store.spend?.dayUsd ?? null), key: `ap-digest-${day}`, go: 'missions' })
+ } else if (store.loop.lastDigestDay === null && store.loop.phase === 'running') await appendEvents(state, host, [{ t: 'digest', at: nowMs, day }])
+
+ if (store.journalBytes > JOURNAL_MAX_BYTES * 0.8) await rotate(state, host, nowMs)
+ } catch {
+ store.error = 'a tick failed; nothing was started'
+ } finally {
+ store.isTicking = false
+ host.invalidate()
+ }
+}
+
+/** Propose, replay-evaluate, and promote under the gate; then revert any trial that did worse. At most one receipt a pass. */
+async function adaptPass(state: State, host: Host, env: Envelope, nowMs: number): Promise<void> {
+ const store = storeOf(state)
+ const outcomes = outcomesOf(store.loop.steps)
+ const current = tunablesFrom(store.loop.receipts, env)
+ const prev = lastHash(store.loop.receipts)
+ const reverts = reviewTrials(store.loop.receipts, outcomes)
+ const candidate = reverts[0] ?? propose(outcomes, current, env).find(p => evaluate(p, outcomes, current).verdict === 'supported')
+
+ if (candidate === undefined) return
+
+ const verdict = reverts[0] === undefined ? evaluate(candidate, outcomes, current) : { verdict: 'supported' as const, evidence: 'the trial did worse than the setting it replaced' }
+ const result = promote(candidate, verdict, current, env, prev, nowMs)
+
+ if (result.ok) await appendEvents(state, host, [{ t: 'adapt', at: nowMs, receipt: result.receipt }])
+}
+
+/** Archives the journal and starts a new one from its snapshot, so weeks of running stay readable. The old file is kept beside it. */
+async function rotate(state: State, host: Host, nowMs: number): Promise<void> {
+ const path = pathOf(state, JOURNAL_FILE)
+ const archive = `${path}.${new Date(nowMs).toISOString().replace(/[^0-9]/g, '').slice(0, 14)}`
+ const lines = snapshotEvents(storeOf(state).loop).map(encodeLine).join('')
+
+ if (lines === '') return
+
+ const copied = await host.run(['cp', '--no-clobber', '--', path, archive], 30_000).catch(() => ({ exitCode: 1 }))
+
+ if (copied.exitCode === 0) await storeOf(state).chain.then(() => host.run(replaceFileArgv(path, true), 10_000, lines)).catch(() => undefined)
+}
+
+export { AUTOPILOT_DIR }
diff --git a/plugins/ruflo-console/hooks/data/ap-loop.ts b/plugins/ruflo-console/hooks/data/ap-loop.ts
index bf75a73d8d..2f7ad21cf3 100644
--- a/plugins/ruflo-console/hooks/data/ap-loop.ts
+++ b/plugins/ruflo-console/hooks/data/ap-loop.ts
@@ -325,3 +325,13 @@ export function snapshotEvents(s: LoopState): JournalEvent[] {
return out
}
+
+/** The daily digest line: what the last 24 hours did, from the steps the journal still holds. Spend is drawn only when it was read. */
+export function digestText(s: LoopState, nowMs: number, spendUsd: number | null): string {
+ const since = nowMs - 86_400_000
+ const day = s.steps.filter(step => (step.endedAt ?? step.startedAt) >= since)
+ const done = day.filter(step => step.status === 'done')
+ const adapted = s.receipts.filter(r => r.at >= since).length
+
+ return `autopilot digest: ${done.filter(step => step.verified === true).length} verified, ${done.filter(step => step.verified !== true).length} unverified, ${day.filter(step => step.status === 'failed').length} failed ยท ${s.parked.filter(p => p.answer === undefined).length} parked ยท ${adapted} adaptation${adapted === 1 ? '' : 's'} ยท spend ${spendUsd === null ? 'n/a' : `$${Math.round(spendUsd * 100) / 100}`}`
+}
diff --git a/plugins/ruflo-console/hooks/views/ap-panel.ts b/plugins/ruflo-console/hooks/views/ap-panel.ts
new file mode 100644
index 0000000000..d26497be99
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/ap-panel.ts
@@ -0,0 +1,286 @@
+/**
+ * The autopilot panel in the Workflows board (ADR-466 ยง6): status and the band line, the gates (Project Anatole, permission preflight,
+ * spend, journal), the sealed envelope and a draft editor with validation, start / pause / resume / stop, the adaptation history with
+ * its receipts, and the digest. Registered through the slot seams (views/wf-slots.ts); `import './ap-panel'` in views/wf-register.ts and
+ * `wireAutopilot(state, host, { toolCheck })` once beside the other wires. Every figure is read from a file or a reply; where one was
+ * not read the panel says `n/a`, never `$0`. Start is the one confirm; Stop and Pause only narrow authority and ask nothing.
+ */
+import type { RenderElement } from 'claude-code'
+
+import type { ActionSpec } from '../actions'
+import { activeOf, apTick, appendEvents, clearKill, drainNotices, hostOf, pauseNow, refreshAutopilot, resumeNow, stopNow, storeOf, writeEnvelope } from '../ap-live'
+import { DEFAULTS, tierOf, tunablesFrom, verifyReceipts } from '../data/ap-adapt'
+import { AUTOPILOT_DIR, hashOf, HARD_DENIES, MAX_DURATION_MS, MIN_DURATION_MS, seal, TOOL_CLASSES, validateEnvelope, widened, type Envelope, type ToolClass } from '../data/ap-envelope'
+import { anatoleFact } from '../data/ap-guard'
+import { bandText, summarize } from '../data/ap-loop'
+import { cleanText } from '../data/wf-clean'
+import { readBounded, under } from '../data/files'
+import type { NoticeDraft } from '../notices'
+import type { State } from '../state'
+import { ago, button, clip, kv, row, text, THEME, type Ctx } from './common'
+import './ap-parked'
+import { registerSlot, type SlotEnv } from './wf-slots'
+
+export const DRAFT_FILE = `${AUTOPILOT_DIR}/envelope.draft.json`
+const DAY = 86_400_000
+
+type Draft = { value: Record<string, unknown>; fromFile: string | null }
+
+const drafts = new WeakMap<State, Draft>()
+
+/** The first envelope offered: the project only, read/edit/test/local git, no network, no secrets, modest ceilings, a week. */
+export const defaultDraft = (cwd: string): Record<string, unknown> => ({ name: 'autopilot', toolClasses: ['read', 'edit', 'test', 'git-local'], paths: [cwd.replace(/\/+$/, '')], repos: [], network: [], secretEnv: [], spend: { hourUsd: 2, dayUsd: 10, totalUsd: 40 }, concurrency: 1, maxDurationMs: 7 * DAY, verify: [], acceptWithoutAnatole: false })
+
+export const draftOf = (state: State): Draft => drafts.get(state) ?? drafts.set(state, { value: defaultDraft(state.cwd), fromFile: null }).get(state)!
+
+const spendOf = (d: Draft): Record<string, number> => ({ ...(d.value.spend as Record<string, number>) })
+
+/** One edit of the draft by the editor's buttons. Pure on the draft object it is given. */
+export function editDraft(d: Draft, edit: { kind: 'class'; cls: ToolClass } | { kind: 'spend'; key: 'hourUsd' | 'dayUsd' | 'totalUsd'; by: 1 | -1 } | { kind: 'concurrency'; by: 1 | -1 } | { kind: 'days'; by: 1 | -1 } | { kind: 'anatole' }): void {
+ const v = d.value
+
+ if (edit.kind === 'class') {
+ const have = (v.toolClasses as string[]) ?? []
+
+ v.toolClasses = have.includes(edit.cls) ? have.filter(c => c !== edit.cls) : [...have, edit.cls]
+ } else if (edit.kind === 'spend') {
+ const spend = spendOf(d)
+ const now = spend[edit.key] ?? 1
+ const step = now >= 100 ? 25 : now >= 10 ? 5 : 1
+
+ spend[edit.key] = Math.max(1, now + edit.by * step)
+ v.spend = spend
+ } else if (edit.kind === 'concurrency') v.concurrency = Math.max(1, Math.min(8, Number(v.concurrency ?? 1) + edit.by))
+ else if (edit.kind === 'days') v.maxDurationMs = Math.max(MIN_DURATION_MS, Math.min(MAX_DURATION_MS, Number(v.maxDurationMs ?? DAY) + edit.by * DAY))
+ else v.acceptWithoutAnatole = v.acceptWithoutAnatole !== true
+
+ d.fromFile = null
+}
+
+/** Reads the draft file (paths, repos, network and verify are written there: they are lists, not buttons). Validated on the way in; a bad file changes nothing. */
+export async function loadDraftFile(state: State): Promise<string> {
+ const host = hostOf(state)
+
+ if (host === undefined) return 'not wired into this console yet'
+
+ const read = await readBounded(host.fs, state.cache, under(state.cwd, DRAFT_FILE), 65_536, true)
+
+ if (read.text === null) return read.reason === 'missing' ? `no ${DRAFT_FILE} to load` : `the draft file was refused: ${read.reason}`
+
+ let parsed: unknown
+
+ try {
+ parsed = JSON.parse(read.text)
+ } catch {
+ return 'the draft file is not JSON'
+ }
+
+ const checked = validateEnvelope(parsed)
+
+ if (!checked.ok) return `the draft file does not validate: ${cleanText(checked.errors[0] ?? '')}`
+
+ const d = draftOf(state)
+
+ d.value = JSON.parse(JSON.stringify(checked.envelope)) as Record<string, unknown>
+ d.fromFile = DRAFT_FILE
+ host.invalidate()
+
+ return 'draft loaded'
+}
+
+const money = (n: number | undefined | null): string => (n === undefined || n === null ? 'n/a' : `$${Math.round(n * 100) / 100}`)
+const COLOR = { running: THEME.ok, paused: THEME.warn, stopped: THEME.bad, idle: undefined } as const
+
+function gates(ctx: Ctx, env: Envelope | null): RenderElement[] {
+ const store = storeOf(ctx.state)
+ const anatole = anatoleFact(ctx.state.snapshot?.anatole)
+ const classes = Object.entries(store.preflight)
+ const denied = classes.filter(([, v]) => v === 'deny' || v === 'ask').map(([k]) => k)
+
+ return [
+ kv(ctx, 'Anatole', anatole === 'on' ? 'on' : anatole === 'off' ? 'OFF: autopilot pauses' : 'not installed', anatole === 'on' ? THEME.ok : THEME.warn),
+ kv(ctx, 'permissions', !store.hasCheck ? 'preflight not wired: the engine still asks per call; a step it would deny fails, it is not bypassed' : denied.length === 0 ? 'your settings allow every class' : `would ask or deny: ${denied.join(', ')} (parked)`, store.hasCheck ? undefined : THEME.warn),
+ kv(ctx, 'spend', `hour ${money(store.spend?.hourUsd)}/${money(env?.spend.hourUsd)} ยท day ${money(store.spend?.dayUsd)}/${money(env?.spend.dayUsd)} ยท total ${money(store.spend?.totalUsd)}/${money(env?.spend.totalUsd)}${store.spend === null ? ' (ledger not read)' : ' (list-price estimate, whole project)'}`),
+ kv(ctx, 'journal', `${Math.round(store.journalBytes / 1000)} kB of 1500 kB cap${store.badLines > 0 ? ` ยท ${store.badLines} unusable lines` : ''}`),
+ ]
+}
+
+function envelopeRows(ctx: Ctx, nowMs: number): RenderElement[] {
+ const store = storeOf(ctx.state)
+
+ if (store.sealed === null) return [text(ctx, store.envWhy === null ? ' no envelope approved yet: set one below and press Start' : ` envelope refused: ${cleanText(store.envWhy)}`, { color: store.envWhy === null ? undefined : THEME.bad })]
+
+ const e = store.sealed.envelope
+
+ return [
+ text(ctx, ` "${cleanText(e.name)}" revision ${store.sealed.revision} ยท hash ${store.sealed.hash.slice(0, 12)} ยท approved ${ago(store.sealed.approvedAtMs, nowMs)}`),
+ text(ctx, ` classes ${e.toolClasses.join(' ') || 'none'} ยท ${e.paths.length} folder${e.paths.length === 1 ? '' : 's'} ยท ${e.repos.length} repos ยท network ${e.network.join(',') || 'none'} ยท secrets ${e.secretEnv.join(',') || 'none'} ยท up to ${e.concurrency} at once ยท ${Math.round(e.maxDurationMs / DAY)} d ยท ${e.verify.length} verify command${e.verify.length === 1 ? '' : 's'}`, { dimColor: true }),
+ text(ctx, ` never granted: ${HARD_DENIES.join(', ')}`, { dimColor: true }),
+ ]
+}
+
+function editor(ctx: Ctx): RenderElement[] {
+ const d = draftOf(ctx.state)
+ const host = hostOf(ctx.state)
+ const have = (d.value.toolClasses as string[]) ?? []
+ const spend = spendOf(d)
+ const checked = validateEnvelope(d.value)
+ const set = (edit: Parameters<typeof editDraft>[1]): (() => void) => () => {
+ editDraft(d, edit)
+ host?.invalidate()
+ }
+
+ const rows: RenderElement[] = [
+ row(ctx, [text(ctx, ' classes ', { dimColor: true }), ...TOOL_CLASSES.map(cls => button(ctx, `ap-c-${cls}`, `${have.includes(cls) ? 'โ—' : 'โ—‹'} ${cls}`, set({ kind: 'class', cls })))], 'ap-classes'),
+ ]
+
+ for (const key of ['hourUsd', 'dayUsd', 'totalUsd'] as const) rows.push(row(ctx, [text(ctx, ` ${key.replace('Usd', '').padEnd(8)} `, { dimColor: true }), button(ctx, `ap-s-${key}-less`, ' โˆ’ ', set({ kind: 'spend', key, by: -1 })), text(ctx, ` ${money(spend[key])} `, { bold: true }), button(ctx, `ap-s-${key}-more`, ' + ', set({ kind: 'spend', key, by: 1 }))], `ap-spend-${key}`))
+
+ rows.push(row(ctx, [text(ctx, ' at once ', { dimColor: true }), button(ctx, 'ap-n-less', ' โˆ’ ', set({ kind: 'concurrency', by: -1 })), text(ctx, ` ${String(d.value.concurrency)} `, { bold: true }), button(ctx, 'ap-n-more', ' + ', set({ kind: 'concurrency', by: 1 })), text(ctx, ' duration ', { dimColor: true }), button(ctx, 'ap-d-less', ' โˆ’ ', set({ kind: 'days', by: -1 })), text(ctx, ` ${Math.round(Number(d.value.maxDurationMs) / DAY)} d `, { bold: true }), button(ctx, 'ap-d-more', ' + ', set({ kind: 'days', by: 1 }))], 'ap-conc'))
+ rows.push(row(ctx, [button(ctx, 'ap-anatole', `${d.value.acceptWithoutAnatole === true ? 'โ—' : 'โ—‹'} accept running without Anatole`, set({ kind: 'anatole' })), button(ctx, 'ap-load', 'load draft file', () => void loadDraftFile(ctx.state)), text(ctx, ` ${DRAFT_FILE} holds paths, repos, network, verify`, { dimColor: true })], 'ap-draft-row'))
+ rows.push(text(ctx, checked.ok ? ` draft is valid ยท hash ${hashOf(checked.envelope).slice(0, 12)}${d.fromFile === null ? '' : ' ยท from file'} ยท ${(d.value.paths as string[]).join(', ')}` : ` draft is not valid: ${cleanText(checked.errors.slice(0, 2).join('; '))}`, { color: checked.ok ? undefined : THEME.bad }))
+
+ return rows
+}
+
+function adaptRows(ctx: Ctx, env: Envelope | null): RenderElement[] {
+ const { receipts } = storeOf(ctx.state).loop
+ const chain = verifyReceipts(receipts)
+
+ if (receipts.length === 0) return [text(ctx, ' no adaptation yet: it needs 6 or more verified steps on a setting that is failing (or 12 clean ones) before it proposes anything', { dimColor: true })]
+
+ const t = env === null ? DEFAULTS : tunablesFrom(receipts, env)
+
+ return [
+ text(ctx, ` now: parallelism ${t.parallelism} ยท retries ${t.retries} ยท default tier ${t.defaultTier}${Object.keys(t.tiers).length === 0 ? '' : ` ยท ${Object.keys(t.tiers).map(cls => `${cls}โ†’${tierOf(t, cls)}`).join(' ')}`} ยท chain ${chain.ok ? 'intact' : `BROKEN at ${chain.badAt}`}`, { color: chain.ok ? undefined : THEME.bad }),
+ ...receipts.slice(-5).map(r => text(ctx, ` ${r.hash.slice(0, 8)} ${r.path} ${r.from}โ†’${r.to} (${r.direction}) ยท ${clip(cleanText(r.evidence), Math.max(30, ctx.columns - 50))}`, { dimColor: true })),
+ ]
+}
+
+export function boardRows(env: SlotEnv): RenderElement[] {
+ const { ctx, nowMs } = env
+ const store = storeOf(ctx.state)
+ const host = hostOf(ctx.state)
+
+ if (host === undefined) return [text(ctx, ' autopilot: not wired into this console yet (wireAutopilot)', { color: THEME.warn })]
+
+ const s = store.loop
+ const sum = summarize(s, nowMs)
+ const e = store.sealed !== null && store.sealed.hash === s.envHash ? store.sealed.envelope : null
+ const band = bandText(s, nowMs, store.spend?.totalUsd ?? null, e)
+ const rows: RenderElement[] = [text(ctx, ` ${band === '' ? 'autopilot is off' : band}${store.killed ? ' ยท KILL flag present' : ''}`, { color: COLOR[sum.phase], bold: true })]
+
+ rows.push(text(ctx, ` ${sum.phase}${sum.reason === null ? '' : `: ${cleanText(sum.reason)}`} ยท ${store.status} ยท ${sum.running} running ยท ${sum.done} done (${sum.unverified} unverified) ยท ${sum.failed} failed${store.readAtMs > 0 ? ` ยท read ${ago(store.readAtMs, nowMs)}` : ''}`, { dimColor: true }))
+ if (store.error !== null) rows.push(text(ctx, ` ${cleanText(store.error)}`, { color: THEME.warn }))
+
+ rows.push(row(ctx, [
+ button(ctx, 'ap-stop', 'Stop', () => void stopNow(ctx.state, host), { hotkey: '9' }),
+ ...(sum.phase === 'running' ? [button(ctx, 'ap-pause', 'Pause', () => void pauseNow(ctx.state, host))] : []),
+ ...(sum.phase === 'paused' ? [button(ctx, 'ap-resume', 'Resume', () => void resumeNow(ctx.state, host), { primary: true })] : []),
+ button(ctx, 'ap-tick', 'Check now', () => void apTick(ctx.state, host)),
+ text(ctx, ' Start is the action row (key 8) and asks first ยท Stop asks nothing', { dimColor: true }),
+ ], 'ap-controls'))
+
+ rows.push(...gates(ctx, e), ...envelopeRows(ctx, nowMs), ...adaptRows(ctx, e))
+ rows.push(text(ctx, ' next envelope (a change asks again):', { dimColor: true }), ...editor(ctx))
+ rows.push(text(ctx, ' Inside the envelope autopilot does not ask this console. It does not bypass Claude Code\'s permission dialog, and it is not a scheduler: it runs while the session lives (re-arm the mission /loop).', { dimColor: true }))
+
+ return rows
+}
+
+/** The confirm card for Start (and for any change of the envelope). Null when the draft is invalid or nothing changed, with the reason on the action row. */
+export function startSpec(env: SlotEnv): ActionSpec | null {
+ const { state } = env.ctx
+ const host = hostOf(state)
+ const d = draftOf(state)
+ const checked = validateEnvelope(d.value)
+
+ if (host === undefined || !checked.ok) return null
+
+ const store = storeOf(state)
+ const next = checked.envelope
+ const prev = store.sealed?.envelope ?? null
+ const hash = hashOf(next)
+
+ if (store.loop.phase === 'running' && store.sealed?.hash === hash) return null
+
+ const grew = prev === null ? [] : widened(prev, next)
+ const anatole = anatoleFact(state.snapshot?.anatole)
+
+ return {
+ label: `start autopilot "${next.name}" (${next.toolClasses.join(' ')} ยท up to ${money(next.spend.totalUsd)} ยท ${Math.round(next.maxDurationMs / DAY)} d)`,
+ scope: 'workflows',
+ args: [],
+ declared: 'spend',
+ shows: `envelope ${hash.slice(0, 12)}: classes ${next.toolClasses.join(' ')}; folders ${next.paths.join(', ')}; network ${next.network.join(',') || 'none'}; ${money(next.spend.hourUsd)}/h ${money(next.spend.dayUsd)}/day ${money(next.spend.totalUsd)} total; ${next.concurrency} at once; ${next.verify.length} verify commands; Anatole ${anatole}${next.acceptWithoutAnatole ? ' (running without it accepted)' : ''}${grew.length > 0 ? `; WIDENS: ${grew.join('; ')}` : ''}; never: ${HARD_DENIES.join(', ')}`,
+ expect: 'a start line in the autopilot journal, then steps handed to the session',
+ note: 'After this, steps inside the envelope run WITHOUT asking this console, for days if the session lives, and spend money. Claude Code\'s own permission dialog still applies and is never bypassed: anything it would ask about is parked. Stop, the KILL file or /ruflo autopilot stop halts it within one tick.',
+ run: async () => {
+ const now = Date.now()
+ const sealed = seal(next, (store.sealed?.revision ?? 0) + 1, now)
+ const mode = anatoleFact(state.snapshot?.anatole)
+
+ if (mode !== 'on' && !next.acceptWithoutAnatole) {
+ store.error = `not started: Project Anatole is ${mode === 'off' ? 'off' : 'not installed'}; turn it on, or accept running without it in the envelope`
+ host.invalidate()
+
+ return
+ }
+
+ if (!(await writeEnvelope(state, host, sealed))) {
+ store.error = 'not started: the envelope could not be written'
+ host.invalidate()
+
+ return
+ }
+
+ await clearKill(state, host)
+ store.killed = false
+ store.spend = null
+ store.spendAtMs = 0
+
+ if (await appendEvents(state, host, [{ t: 'start', at: now, envHash: sealed.hash, revision: sealed.revision, anatole: mode === 'on' ? 'on' : 'accepted-without' }])) void apTick(state, host)
+ },
+ }
+}
+
+/** Registers this module's slots; a repeat is refused harmlessly. */
+export function registerAutopilotSlots(): void {
+ registerSlot({ kind: 'board', id: 'autopilot', title: 'Mission autopilot', order: 5, render: boardRows })
+ registerSlot({ kind: 'key', id: 'ap-stop-key', key: '9', label: 'autopilot stop', run: env => {
+ const host = hostOf(env.ctx.state)
+
+ if (host !== undefined) void stopNow(env.ctx.state, host)
+ },
+ })
+ registerSlot({ kind: 'action', id: 'ap-start', label: 'start autopilot', hotkey: '8', why: 'the envelope draft is not valid, or nothing changed since the running one, or autopilot is not wired into this console', spec: startSpec })
+ registerSlot({
+ kind: 'notice',
+ id: 'autopilot',
+ between: (): NoticeDraft[] => {
+ const state = activeOf()
+ const host = state === null ? undefined : hostOf(state)
+
+ if (state === null || host === undefined) return []
+
+ void refreshAutopilot(state, host)
+
+ return drainNotices(state)
+ },
+ })
+}
+
+registerAutopilotSlots()
+
+/** The `/ruflo autopilot stop|pause|resume|status` command's work, for the command surface to call. Never starts anything: Start is confirm-only. */
+export async function autopilotCommand(state: State, host: ReturnType<typeof hostOf> & object, args: string): Promise<string> {
+ const word = args.trim().toLowerCase()
+
+ if (word === 'stop') return (await stopNow(state, host, 'stopped by command'), 'autopilot stopped; the KILL flag is set until the next confirmed start')
+ if (word === 'pause') return (await pauseNow(state, host, 'paused by command'), 'autopilot paused')
+ if (word === 'resume') return (await resumeNow(state, host), 'resume asked; the next tick re-checks every gate')
+
+ const s = storeOf(state)
+
+ return word === 'status' || word === '' ? (bandText(s.loop, Date.now(), s.spend?.totalUsd ?? null, s.sealed?.envelope ?? null) || 'autopilot is off') : 'usage: /ruflo autopilot stop | pause | resume | status (start is on the Workflows page and asks first)'
+}
diff --git a/plugins/ruflo-console/hooks/views/ap-parked.ts b/plugins/ruflo-console/hooks/views/ap-parked.ts
new file mode 100644
index 0000000000..540f882c22
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/ap-parked.ts
@@ -0,0 +1,50 @@
+/**
+ * The autopilot's parked queue (ADR-466 ยง4), a board section: what the loop would not do on its own, each with the question it asked,
+ * and buttons to approve it once or deny it. A park for a hard deny has no approve button (autopilot can never do it; the loop
+ * ignores such an answer too). Nothing drawn here is made up: it is the journal's `parked` and `answered` lines, washed on the way in.
+ */
+import type { RenderElement } from 'claude-code'
+
+import { answerParked, hostOf, storeOf } from '../ap-live'
+import { cleanText } from '../data/wf-clean'
+import { button, clip, row, text, THEME, type Ctx } from './common'
+import { registerSlot, type SlotEnv } from './wf-slots'
+
+/** Parks drawn at once; the rest are counted. */
+export const SHOWN = 6
+
+export const isHardDenyQuestion = (question: string): boolean => question.includes('can never do')
+
+export function parkedRows(env: SlotEnv): RenderElement[] {
+ const { ctx } = env
+ const store = storeOf(ctx.state)
+ const host = hostOf(ctx.state)
+ const open = store.loop.parked.filter(p => p.answer === undefined)
+ const answered = store.loop.parked.length - open.length
+
+ if (store.loop.phase === 'idle' && store.loop.parked.length === 0) return [text(ctx, ' autopilot has not started: nothing is parked', { dimColor: true })]
+ if (open.length === 0) return [text(ctx, ` nothing parked${answered > 0 ? ` ยท ${answered} answered earlier` : ''}`, { dimColor: true })]
+
+ const rows: RenderElement[] = []
+
+ for (const park of open.slice(0, SHOWN)) {
+ const hard = isHardDenyQuestion(park.question)
+
+ rows.push(text(ctx, ` ${clip(cleanText(park.task), 24)} ${clip(cleanText(park.question), Math.max(30, ctx.columns - 36))}`, { color: hard ? THEME.warn : undefined }))
+ rows.push(row(ctx, [
+ ...(hard || host === undefined ? [] : [button(ctx, `ap-once-${park.id}`, 'approve once', () => void answerParked(ctx.state, host, park.id, 'once'))]),
+ ...(host === undefined ? [] : [button(ctx, `ap-deny-${park.id}`, 'deny', () => void answerParked(ctx.state, host, park.id, 'deny'))]),
+ text(ctx, hard ? ' never grantable' : ' once = this task only, then the envelope applies again', { dimColor: true }),
+ ], `ap-park-${park.id}`))
+ }
+
+ if (open.length > SHOWN) rows.push(text(ctx, ` +${open.length - SHOWN} more parked, not drawn`, { dimColor: true }))
+
+ return rows
+}
+
+export function registerParkedSlots(): void {
+ registerSlot({ kind: 'board', id: 'ap-parked', title: 'Autopilot, parked for you', order: 6, render: parkedRows })
+}
+
+registerParkedSlots()
diff --git a/plugins/ruflo-console/tests/ap-live.spec.ts b/plugins/ruflo-console/tests/ap-live.spec.ts
new file mode 100644
index 0000000000..01b85cb71b
--- /dev/null
+++ b/plugins/ruflo-console/tests/ap-live.spec.ts
@@ -0,0 +1,424 @@
+/**
+ * The autopilot's live half and its panel (ADR-466): the start confirm and what it writes, the kill switch through the files, a tick
+ * that hands a step over only after journaling it, crash-resume through a fresh process, parked questions, masking, and the slots.
+ * An in-memory disk and a fake host: no engine. Run with
+ * npx vitest run plugins/ruflo-console/tests/ap-live.spec.ts --testTimeout=30000
+ */
+import { describe, expect, it } from 'vitest'
+
+import { apTick, appendEvents, answerParked, refreshAutopilot, storeOf, stopNow, wireAutopilot } from '../hooks/ap-live'
+import { hashOf, 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 { boardRows, defaultDraft, draftOf, editDraft, registerAutopilotSlots, startSpec } from '../hooks/views/ap-panel'
+import { parkedRows } from '../hooks/views/ap-parked'
+import type { Ctx, Kit } from '../hooks/views/common'
+import { resetSlots, slotsFor, type SlotEnv } from '../hooks/views/wf-slots'
+import '../hooks/views/wf-register'
+
+const CWD = '/w'
+const T0 = Date.parse('2026-10-06T00:00:00.000Z')
+const J = `${CWD}/${JOURNAL_FILE}`
+const E = `${CWD}/.claude-flow/console/autopilot/envelope.json`
+const KILL = `${CWD}/.claude-flow/console/autopilot/KILL`
+
+const ENV: Envelope = { name: 'night', toolClasses: ['edit', 'read', 'test'], paths: [CWD], repos: [], network: [], secretEnv: [], spend: { hourUsd: 2, dayUsd: 10, totalUsd: 40 }, concurrency: 1, maxDurationMs: 7 * 86_400_000, verify: [['true']], acceptWithoutAnatole: true }
+
+type Rig = { files: Map<string, string>; runs: string[][]; prompts: string[]; toasts: string[]; host: Host; failVerify: { on: boolean } }
+
+function rig(): Rig {
+ const files = new Map<string, string>()
+ const runs: string[][] = []
+ const prompts: string[] = []
+ const toasts: string[] = []
+ const failVerify = { on: false }
+
+ 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])
+
+ if (argv[0] === 'dd') {
+ const path = (argv.find(a => a.startsWith('of=')) as string).slice(3)
+
+ files.set(path, argv.includes('oflag=append') ? `${files.get(path) ?? ''}${stdin ?? ''}` : (stdin ?? ''))
+ } else if (argv[0] === 'install') {
+ const path = argv.at(-1) as string
+
+ files.set(path, 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) ?? '')
+ else if (argv[0] === 'true' || argv[0] === 'false') return { exitCode: failVerify.on ? 1 : 0, stdout: '', stderr: '' }
+
+ return { exitCode: 0, stdout: '', stderr: '' }
+ },
+ invalidate: () => undefined,
+ toast: (t: string) => void toasts.push(t),
+ 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, toasts, host, failVerify }
+}
+
+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: 'Publish the package to npm', phase: 'A', agent: 'coder', requirement: 'it is published', 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: 'on' | 'off' | 'absent' = 'on'): State {
+ const state = newState({})
+
+ state.cwd = CWD
+ state.snapshot = { tasks, agents: [], claims: [], swarm: null, plugins: { missingFromClone: [], installed: [] }, alerts: [], anatole: anatole === 'absent' ? undefined : { present: true, status: { mode: anatole === 'on' ? 'notify' : 'off' }, modeOverride: null, overrides: {}, alerts: [], refused: [], badAlerts: 0 } } as never
+ mcOf(state).missions.set('msn_0123456789abcdef01234567', mission())
+ mcOf(state).active = 'msn_0123456789abcdef01234567'
+
+ return state
+}
+
+/** Seeds an approved, started autopilot on the rig's disk. */
+function started(r: Rig, extra: JournalEvent[] = []): 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 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 ctxOf = (state: State, nowMs: number): Ctx => ({ kit, state, nowMs, columns: 120, pictures: new Map(), act: {} as never })
+
+type El = { kind: string; props: Record<string, unknown> }
+
+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 buttons = (tree: unknown): string[] => flat(tree).filter(el => el.kind === 'Button').map(el => String(el.props.label))
+const envOf = (state: State, nowMs: number): SlotEnv => ({ ctx: ctxOf(state, nowMs), runs: [], run: null, phase: null, agent: null, ui: {} as never, nowMs })
+const journal = (r: Rig): JournalEvent[] => parseJournal(r.files.get(J) ?? '').events
+
+describe('the panel before and after wiring', () => {
+ it('says it is not wired, then that autopilot is off, with no invented number', () => {
+ const state = stateWith([])
+
+ expect(words(boardRows(envOf(state, T0)))).toContain('not wired')
+
+ const r = rig()
+
+ wireAutopilot(state, r.host)
+
+ const text = words(boardRows(envOf(state, T0)))
+
+ expect(text).toContain('autopilot is off')
+ expect(text).toContain('no envelope approved yet')
+ expect(text).toContain('preflight not wired')
+ expect(text).not.toContain('$0')
+ expect(text).toContain('ledger not read')
+ })
+
+ it('draws the band line from the journal, spend n/a until read, and the parked count', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending')])
+
+ started(r, [{ t: 'parked', at: T0 + 1, id: 'p-1', task: 't2', question: 'needs "publish", which autopilot can never do. Do it yourself, or deny it.' }])
+ wireAutopilot(state, r.host)
+ await refreshAutopilot(state, r.host, T0 + 2 * 86_400_000)
+
+ const text = words(boardRows(envOf(state, T0 + 2 * 86_400_000 + 10)))
+
+ expect(text).toContain('autopilot day 3 ยท $n/a/$40 ยท 1 parked')
+ expect(text).toContain(`hash ${hashOf(ENV).slice(0, 12)}`)
+ })
+})
+
+describe('start: the one confirm', () => {
+ it('offers no spec for an invalid draft and one with the hash, the ceilings and the never-list for a valid one', () => {
+ const state = stateWith([])
+
+ wireAutopilot(state, rig().host)
+ expect(startSpec(envOf(state, T0))).not.toBeNull()
+
+ draftOf(state).value.spend = { hourUsd: 9, dayUsd: 2, totalUsd: 1 }
+ expect(startSpec(envOf(state, T0))).toBeNull()
+ expect(words(boardRows(envOf(state, T0)))).toContain('draft is not valid')
+
+ draftOf(state).value = defaultDraft(CWD)
+
+ const spec = startSpec(envOf(state, T0))
+
+ expect(spec?.declared).toBe('spend')
+ expect(spec?.shows).toContain('never: publish, release, deploy, force-push, secret-access')
+ expect(spec?.note).toContain('never bypassed')
+ })
+
+ it('refuses to start without Anatole unless the envelope accepted that; with it, writes the envelope, clears the flag and journals the start', async () => {
+ const r = rig()
+ const state = stateWith([], 'off')
+
+ wireAutopilot(state, r.host)
+ r.files.set(KILL, '')
+
+ await startSpec(envOf(state, T0))?.run?.()
+ expect(r.files.has(E)).toBe(false)
+ expect(storeOf(state).error).toContain('Project Anatole is off')
+
+ editDraft(draftOf(state), { kind: 'anatole' })
+ await startSpec(envOf(state, T0))?.run?.()
+
+ expect(r.files.has(E)).toBe(true)
+ expect(r.files.has(KILL)).toBe(false)
+ expect(journal(r)[0]).toMatchObject({ t: 'start', anatole: 'accepted-without', revision: 1 })
+ })
+
+ it('a changed envelope shows what it widens, and an unchanged running one has no spec', async () => {
+ const r = rig()
+ const state = stateWith([])
+
+ started(r)
+ wireAutopilot(state, r.host)
+ await refreshAutopilot(state, r.host, T0)
+ draftOf(state).value = JSON.parse(JSON.stringify(ENV)) as Record<string, unknown>
+ expect(startSpec(envOf(state, T0))).toBeNull()
+
+ editDraft(draftOf(state), { kind: 'concurrency', by: 1 })
+ expect(startSpec(envOf(state, T0))?.shows).toContain('WIDENS: concurrency: 1 to 2')
+ })
+})
+
+describe('stop is immediate and needs no confirm', () => {
+ it('journals a stop and leaves the flag file, and a tick in another process then never acts', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r)
+ wireAutopilot(state, r.host)
+ await refreshAutopilot(state, r.host, T0)
+ await stopNow(state, r.host, 'because')
+
+ expect(r.files.has(KILL)).toBe(true)
+ expect(journal(r).at(-1)).toMatchObject({ t: 'stop', reason: 'because' })
+ expect(r.toasts.join()).toContain('autopilot stopped')
+
+ const other = stateWith([task('r1', 'pending')])
+
+ wireAutopilot(other, r.host)
+ await apTick(other, r.host, T0 + 1000)
+ expect(r.prompts).toEqual([])
+ })
+
+ it('the flag file alone halts a running loop within one tick, before anything is handed over', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r)
+ r.files.set(KILL, '')
+ wireAutopilot(state, r.host)
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(r.prompts).toEqual([])
+ expect(journal(r).at(-1)).toMatchObject({ t: 'stop', reason: 'kill switch' })
+ })
+})
+
+describe('a tick', () => {
+ it('journals the step first, then hands the task to the session; and parks the publish task instead of running it', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r)
+ wireAutopilot(state, r.host)
+ // Spend is read from the ledger, which this rig has not got: unknown spend waits, it never runs on a guess.
+ await apTick(state, r.host, T0 + 1000)
+ expect(r.prompts).toEqual([])
+ expect(storeOf(state).status).toContain('spend not read')
+
+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
+ storeOf(state).spendAtMs = T0 + 1000
+ await apTick(state, r.host, T0 + 2000)
+
+ expect(r.prompts.length).toBe(1)
+ expect(r.prompts[0]).toContain('Fix the parser bug')
+
+ const events = journal(r)
+
+ expect(events.map(e => e.t)).toContain('step.started')
+ expect(events.findIndex(e => e.t === 'step.started')).toBeLessThan(events.length)
+ })
+
+ it('parks the hard-deny task with a question and carries on with the next ready one', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'completed'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r)
+ wireAutopilot(state, r.host)
+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
+ storeOf(state).spendAtMs = T0 + 1000
+ await apTick(state, r.host, T0 + 2000)
+
+ const parked = journal(r).find(e => e.t === 'parked')
+
+ expect(parked).toMatchObject({ t: 'parked', task: 't2' })
+ expect(r.prompts).toEqual([])
+
+ storeOf(state).adaptAtMs = T0 + 2000
+ await apTick(state, r.host, T0 + 3000)
+
+ expect(r.prompts.length).toBe(1)
+ expect(r.prompts[0]).toContain('Review the module')
+ })
+
+ it('crash-resume: a started step left by a dead process is settled by its effect, never run twice', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r, [{ t: 'step.started', at: T0 + 10, id: 's-dangling00001', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 1e9, tier: 'mid' }])
+ wireAutopilot(state, r.host)
+ storeOf(state).bootMs = T0 + 100
+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
+ storeOf(state).spendAtMs = T0 + 1000
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(journal(r).some(e => e.t === 'step.failed' && e.id === 's-dangling00001' && e.why.includes('lost on restart'))).toBe(true)
+ // The lost step is settled; the tick did not also start a step in the same pass.
+ expect(r.prompts).toEqual([])
+ expect(journal(r).filter(e => e.t === 'step.started').length).toBe(1)
+ })
+
+ it('a task the store calls completed is only "done" when the verify commands pass; otherwise it fails and nothing is learned from it', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'completed'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r, [{ t: 'step.started', at: T0 + 10, id: 's-verifyme0000001', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 1e9, tier: 'mid' }])
+ wireAutopilot(state, r.host)
+ storeOf(state).bootMs = T0 - 1
+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
+ storeOf(state).spendAtMs = T0 + 1000
+ r.failVerify.on = true
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(r.runs.some(a => a[0] === 'true')).toBe(true)
+ expect(journal(r).some(e => e.t === 'step.failed' && e.id === 's-verifyme0000001')).toBe(true)
+ expect(journal(r).some(e => e.t === 'step.done')).toBe(false)
+ })
+
+ it('and with the verify commands passing the step is done and verified', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'completed'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r, [{ t: 'step.started', at: T0 + 10, id: 's-verifyme0000002', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 1e9, tier: 'mid' }])
+ 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(journal(r).find(e => e.t === 'step.done')).toMatchObject({ id: 's-verifyme0000002', verified: true })
+ })
+
+ it('refuses to run on an envelope whose hash is not the one the start recorded', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending')])
+
+ started(r)
+ r.files.set(E, JSON.stringify(seal({ ...ENV, spend: { hourUsd: 2, dayUsd: 10, totalUsd: 4000 } }, 2, T0)))
+ wireAutopilot(state, r.host)
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(r.prompts).toEqual([])
+ expect(journal(r).at(-1)).toMatchObject({ t: 'stop' })
+ })
+})
+
+describe('the parked queue', () => {
+ it('shows the question washed, approve-once and deny for an ordinary park, only deny for a hard deny, and journals the answer', async () => {
+ const r = rig()
+ const state = stateWith([])
+
+ started(r, [
+ { t: 'parked', at: T0 + 1, id: 'p-net', task: 't9', question: 'needs "network" \u001b[31mred\u001b[0m sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789. Approve once, or deny.' },
+ { t: 'parked', at: T0 + 2, id: 'p-pub', task: 't2', question: 'needs "publish", which autopilot can never do. Do it yourself, or deny it.' },
+ ])
+ wireAutopilot(state, r.host)
+ await refreshAutopilot(state, r.host, T0 + 5)
+
+ const tree = parkedRows(envOf(state, T0 + 5))
+ const text = words(tree)
+
+ expect(text).not.toContain('\u001b')
+ expect(text).not.toContain('sk-ant-api03-abcdef')
+ expect(buttons(tree)).toEqual(['approve once', 'deny', 'deny'])
+
+ await answerParked(state, r.host, 'p-net', 'once')
+ expect(journal(r).at(-1)).toMatchObject({ t: 'answered', id: 'p-net', answer: 'once' })
+ expect(storeOf(state).loop.parked.find(p => p.id === 'p-net')?.answer).toBe('once')
+ })
+
+ it('has honest empty states', () => {
+ const state = stateWith([])
+
+ wireAutopilot(state, rig().host)
+ expect(words(parkedRows(envOf(state, T0)))).toContain('has not started')
+ })
+})
+
+describe('writes', () => {
+ it('append through one fixed argv, the path a single element, and never through a link', async () => {
+ const r = rig()
+ const state = stateWith([])
+
+ wireAutopilot(state, r.host)
+ expect(await appendEvents(state, r.host, [{ t: 'beat', at: T0 }])).toBe(true)
+
+ const dd = r.runs.find(a => a[0] === 'dd')
+
+ expect(dd).toEqual(['dd', `of=${J}`, 'oflag=append', 'conv=notrunc', 'status=none'])
+
+ const linked = rig()
+
+ linked.host.fs.stat = async (p: string) => (p === `${CWD}/.claude-flow` ? { kind: 'dir', isLink: true } : Promise.reject(new Error('ENOENT')))
+ wireAutopilot(state, linked.host)
+ expect(await appendEvents(state, linked.host, [{ t: 'beat', at: T0 }])).toBe(false)
+ expect(linked.runs.filter(a => a[0] === 'dd')).toEqual([])
+ })
+})
+
+describe('registration', () => {
+ it('registers its board, key, action and notice slots with no refusal and no hotkey clash against the merged features', () => {
+ const before = slotsFor('key').map(s => s.key)
+
+ expect(slotsFor('board').map(s => s.id)).toEqual(expect.arrayContaining(['autopilot', 'ap-parked']))
+ expect(slotsFor('key').find(s => s.id === 'ap-stop-key')?.key).toBe('9')
+ expect(slotsFor('action').find(s => s.id === 'ap-start')?.hotkey).toBe('8')
+ expect(slotsFor('notice').map(s => s.id)).toContain('autopilot')
+
+ const keys = [...before, ...slotsFor('action').map(s => s.hotkey)]
+
+ expect(new Set(keys).size).toBe(keys.length)
+ resetSlots()
+ registerAutopilotSlots()
+ expect(slotsFor('board').length).toBe(1)
+ })
+})