๐ The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(ruflo-console): autopilot envelope editor, parallel hand-over, spend windows, band segment, and the first live run (ADR-470)
ruv75b0188e0d84
diff --git a/plugins/ruflo-console/hooks/ap-live.ts b/plugins/ruflo-console/hooks/ap-live.tsindex aa980cbf28..8d0a6f6217 100644--- a/plugins/ruflo-console/hooks/ap-live.ts+++ b/plugins/ruflo-console/hooks/ap-live.ts@@ -9,19 +9,19 @@* 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 { activeMission, dispatchSpec, startable, type LedgerTask, 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 { tierOf, tunablesFrom } from './data/ap-adapt'import { adaptPass, rotate } from './ap-maint'import { checkPin, type Pin } from './data/ap-pin'import { loadPin, setPin } from './ap-pin-live'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, verifyPermission, type ToolCheck } from './data/ap-guard'+import { anatoleFact, killSeen, preflightAll, type ToolCheck } from './data/ap-guard'+import { effectsOf, pickTask, readSpend } from './ap-pick'import { appendArgv, encodeLine, JOURNAL_FILE, JOURNAL_MAX_BYTES, REFUSED_WHY, startedCount, touchArgv, type JournalEvent } from './data/ap-journal'import { digestText, emptyLoop, foldJournal, replayJournal, skipSet, tick, type EffectFact, type Facts, type LoopState, type TaskFact } from './data/ap-loop'import type { Preflight } from './data/ap-loop'@@ -32,6 +32,8 @@ const SPEND_EVERY_MS = 120_000const ADAPT_EVERY_MS = 600_000const PREFLIGHT_EVERY_MS = 60_000const STEP_TIMEOUT_MS = 30 * 60_000+/** Rounds after the cap that may only park tasks (a park hands nothing over). */+const MAX_PARKS_PER_PASS = 8/** A gap between ticks this long is a sleeping machine, not a slow tick. */const SLEEP_GAP_MS = 3 * TICK_MS@@ -43,6 +45,8 @@ export type Store = {journalBytes: numberspend: Spend | nullspendAtMs: number+ /** Why the spend is not known (no tracker, an older one, an unpriced model), or null. */+ spendWhy: string | nullkilled: booleanstatus: stringpreflight: Record<string, Preflight>@@ -78,7 +82,7 @@ export const activeOf = (): State | null => activeconst 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, pin: null, isPinLoaded: false, isPinPending: false, heldStop: null, lastTickMs: 0, slack: {} }).get(state)!+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, spendWhy: null, 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, pin: null, isPinLoaded: false, isPinPending: false, heldStop: null, lastTickMs: 0, slack: {} }).get(state)!export const hostOf = (state: State): Host | undefined => hosts.get(state)@@ -268,71 +272,39 @@ export async function writeEnvelope(state: State, host: Host, sealed: Sealed): Preturn 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> = {}+/**+ * Hands one journaled step to the session. Looked at again HERE (a verify run can take minutes): no kill flag, the phase still running, and+ * the journal, read within its cap, holds exactly one start for this step. The mission's own dispatch does the hand-over; only its+ * one-at-a-time check is replaced by `startable(..., cap)`. Returns true when the prompt went.+ */+async function handOver(state: State, host: Host, mission: MissionRecord, task: LedgerTask, stepId: string, nowMs: number, cap: number): Promise<boolean> {const store = storeOf(state)+ 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)- 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+ 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: stepId, why: 'stopped before the hand-over' }])- // The envelope's verify commands run through the console, not the engine: where the person's settings deny the test class they are never run, and each counts as a failed check (never as a pass).- for (const argv of env.verify) {- ran += 1+ return false+ }- // The console runs these itself, so the person's own permission rules are asked first (a refusal is a failed check, never run), and a kill flag ends the list.- if (store.preflight.test === 'deny' || (await verifyPermission(checks.get(state), argv)) === 'blocked' || (await killSeen(host.fs, state.cwd)) || store.loop.phase === 'stopped') {- failed += 1- continue- }+ if (journalNow === null || startedCount(journalNow, stepId) !== 1) {+ await appendEvents(state, host, [{ t: 'step.failed', at: Date.now(), id: stepId, why: 'not handed over: the journal is unreadable, over its cap or holds a second start of this step' }])- const result = await host.run(argv, 10 * 60_000).catch(() => ({ exitCode: 1 }))+ return false+ }- if (result.exitCode !== 0) failed += 1- }+ await dispatchSpec(state, host, mission, task, body => host.submitPrompt(body), (m, tasks, t) => startable(m, tasks, t, cap)).run?.()- store.verified.set(step.id, effectOf(stored, { ran, failed }))- if (store.verified.size > 500) for (const key of [...store.verified.keys()].slice(0, 100)) store.verified.delete(key)- }+ // 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 ((task.dispatchedAtMs ?? 0) < nowMs - 1000) {+ await appendEvents(state, host, [{ t: 'step.failed', at: Date.now(), id: stepId, why: REFUSED_WHY }])- out[step.id] = stored === 'completed' ? (store.verified.get(step.id) ?? 'unknown') : stored === 'failed' || stored === 'cancelled' ? 'failed' : stored === 'pending' || stored === undefined ? 'absent' : 'unknown'+ return false}- return out+ return true}/** One pass of the loop. Never rejects; a pass that is already running is skipped. */@@ -386,71 +358,68 @@ export async function apTick(state: State, host: Host, nowMs: number = Date.now(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)+ const reading = await readSpend(state, host, loop.startedAtMs, nowMs)++ store.spend = reading.spend+ store.spendWhy = reading.whystore.spendAtMs = nowMs}if (nowMs - store.preflightAtMs >= PREFLIGHT_EVERY_MS) {- store.preflight = await preflightAll(checks.get(state))+ store.preflight = await preflightAll(checks.get(state), env)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, nowMs),- 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,- slack: store.slack,- }-- let decision = tick(loop, facts)-- // Stop or pause may have been pressed while the facts were gathered (a verify command can run for minutes): the person's later word wins, and nothing starts.- if (decision.act !== null && (store.killed || (await killSeen(host.fs, state.cwd)) || store.loop.phase !== 'running')) decision = { events: decision.events.filter(event => event.t !== 'step.started'), act: null, status: 'stopped or paused while this pass ran: nothing started' }-- store.status = decision.status+ // How many steps may be in flight: the envelope's cap, narrowed by adaptation. The mission's own rules (dependencies, nothing past a failed task, no paused or cancelled mission) are kept by `startable`.+ const cap = env === null || tunables === null ? 1 : Math.max(1, Math.min(env.concurrency, tunables.parallelism))+ const effects = env === null ? {} : await effectsOf(state, host, store, checks.get(state), loop, mission, env)+ const orphans = new Set(loop.steps.filter(step => step.status === 'started' && step.startedAt < store.bootMs).map(step => step.id))+ let handed = 0++ // One step is decided, journaled and handed over per round; the loop goes round again while there is room (up to the cap) and after a park (so a parked task does not hold the others back).+ for (let round = 0; round < cap + MAX_PARKS_PER_PASS && handed < cap; round++) {+ const picked = mission === null || mission.cancelled ? null : pickTask(mission, state, skipSet(store.loop), cap)++ const facts: Facts = {+ nowMs,+ killSeen: store.killed,+ envelope: env,+ anatole: anatoleFact(state.snapshot?.anatole, nowMs),+ spend: store.spend,+ task: picked?.fact ?? null,+ effects,+ orphans,+ tunables: { parallelism: tunables?.parallelism ?? 1, retries: tunables?.retries ?? 0, stepTimeoutMs: STEP_TIMEOUT_MS, tierOf: cls => (tunables === null ? 'mid' : tierOf(tunables, cls)) },+ preflight: store.preflight,+ slack: store.slack,+ }- // 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)+ let decision = tick(store.loop, facts)- for (const event of wrote ? 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' })- }+ // Stop or pause may have been pressed while the facts were gathered (a verify command can run for minutes): the person's later word wins, and nothing starts.+ if (decision.act !== null && (store.killed || (await killSeen(host.fs, state.cwd)) || store.loop.phase !== 'running')) decision = { events: decision.events.filter(event => event.t !== 'step.started'), act: null, status: 'stopped or paused while this pass ran: nothing started' }- if (wrote && decision.act !== null && mission !== null && picked !== 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)+ store.status = decision.status.startsWith('waiting: spend not read') && store.spendWhy !== null ? `waiting: spend not read: ${store.spendWhy}` : decision.status- 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' }])+ // 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)- return+ for (const event of wrote ? 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 (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: the journal is unreadable, over its cap or holds a second start of this step' }])+ if (!wrote) break- return- }+ if (decision.act === null || mission === null || picked === null) {+ if (decision.events.some(event => event.t === 'parked')) continue- // 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?.()+ break+ }- // 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: REFUSED_WHY }])+ if (await handOver(state, host, mission, picked.ledger, decision.act.id, nowMs, cap)) handed += 1+ else break}if (env !== null && tunables !== null && store.loop.phase === 'running' && nowMs - store.adaptAtMs >= ADAPT_EVERY_MS) {diff --git a/plugins/ruflo-console/hooks/ap-pick.ts b/plugins/ruflo-console/hooks/ap-pick.tsnew file mode 100644index 0000000000..1d2eeafb1a--- /dev/null+++ b/plugins/ruflo-console/hooks/ap-pick.ts@@ -0,0 +1,106 @@+/**+ * What one autopilot pass reads before it decides (ADR-466, ADR-470): the next task the mission would hand over, the spend reading, and the+ * effect of each step in flight. Split from ap-live.ts (file limit). The task store's status is a claim, so a step is only `done` when the+ * envelope's own verify commands also pass.+ */+import { derive, rufloTaskOf, startable, type MissionRecord } from './mission-control'+import type { Host } from './host'+import type { State } from './state'+import { classifyTask, effectOf, killSeen, verifyPermission, type ToolCheck } from './data/ap-guard'+import type { Envelope, Spend } from './data/ap-envelope'+import type { EffectFact, LoopState, TaskFact } from './data/ap-loop'+import { readingOf, spendSource, windowArgvs } from './data/ap-spend'+import type { Store } from './ap-live'++/**+ * The mission's next ready task that is not parked, denied or already stepped. The mission's own rules hold: nothing is handed over past a+ * failed task, a task waits for its dependencies, a paused or cancelled mission hands out nothing. Only the one-at-a-time limit is widened,+ * to `cap` (the envelope's concurrency, further narrowed by adaptation): tasks the store shows running and tasks handed over a moment ago+ * both count against it.+ */+export function pickTask(mission: MissionRecord, state: State, skip: ReadonlySet<string>, cap = 1): { ledger: MissionRecord['tasks'][number]; fact: TaskFact } | null {+ const tasks = state.snapshot?.tasks ?? []+ const ledger = mission.tasks.find(task => !skip.has(task.id) && startable(mission, tasks, task, cap))++ return ledger === undefined ? null : { ledger, fact: classifyTask(ledger.id, ledger.title, ledger.requirement) }+}++/** The hour, day and run windows from the ledger, or why not. Never a guess: an unread spend stops the loop from starting anything. */+export async function readSpend(state: State, host: Host, startMs: number, nowMs: number): Promise<{ spend: Spend | null; why: string | null }> {+ const source = spendSource(state)++ if (source.kind === 'unavailable') return { spend: null, why: source.why }++ const argvs = windowArgvs(source.root, startMs, nowMs, state.cwd)++ if (argvs.hour === null || argvs.day === null || argvs.total === null) return { spend: null, why: 'a ledger window or the project path failed its checks' }++ 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)]++ if (hour.exitCode !== 0 || day.exitCode !== 0 || total.exitCode !== 0) return { spend: null, why: 'the ledger exited with an error' }++ return readingOf({ hour: hour.stdout, day: day.stdout, total: total.stdout })+ } catch {+ return { spend: null, why: 'the ledger could not be run' }+ }+}++/** 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. */+/** True once the loop is stopped; a function, so a check after an await is not narrowed by a check before it. */+const isStopped = (store: Store): boolean => store.loop.phase === 'stopped'++export async function effectsOf(state: State, host: Host, store: Store, check: ToolCheck | undefined, loop: LoopState, mission: MissionRecord | null, env: Envelope): Promise<Record<string, EffectFact>> {+ const out: Record<string, EffectFact> = {}++ 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)) {+ // A stopped loop (or a kill flag) verifies nothing, and what it did not verify is NOT remembered: the first version counted the skipped+ // checks as failures and cached them, so a step that finished after a Stop was recorded failed on the next Start (found in the live run).+ if (store.killed || isStopped(store) || (await killSeen(host.fs, state.cwd))) {+ out[step.id] = 'unknown'+ continue+ }++ let ran = 0+ let failed = 0+ let isCut = false++ // The envelope's verify commands run through the console, not the engine: where the person's settings deny the test class they are never run, and each counts as a failed check (never as a pass).+ for (const argv of env.verify) {+ ran += 1++ // A stop pressed while the list runs ends it, without a result.+ if (isStopped(store) || (await killSeen(host.fs, state.cwd))) {+ isCut = true+ break+ }++ // The console runs these itself, so the person's own permission rules are asked first (a refusal is a failed check, never run).+ if (store.preflight.test === 'deny' || (await verifyPermission(check, argv)) === 'blocked') {+ failed += 1+ continue+ }++ const result = await host.run(argv, 10 * 60_000).catch(() => ({ exitCode: 1 }))++ if (result.exitCode !== 0) failed += 1+ }++ if (isCut) {+ out[step.id] = 'unknown'+ continue+ }++ store.verified.set(step.id, effectOf(stored, { ran, failed }))+ if (store.verified.size > 500) for (const key of [...store.verified.keys()].slice(0, 100)) store.verified.delete(key)+ }++ out[step.id] = stored === 'completed' ? (store.verified.get(step.id) ?? 'unknown') : stored === 'failed' || stored === 'cancelled' ? 'failed' : stored === 'pending' || stored === undefined ? 'absent' : 'unknown'+ }++ return out+}diff --git a/plugins/ruflo-console/hooks/data/ap-edit.ts b/plugins/ruflo-console/hooks/data/ap-edit.tsnew file mode 100644index 0000000000..1138dbdc3f--- /dev/null+++ b/plugins/ruflo-console/hooks/data/ap-edit.ts@@ -0,0 +1,89 @@+/**+ * The envelope editor's pure half (ADR-470 ยง2.1): adding and removing one entry of a list field (folders, repos, network hosts, secret+ * variable names, verify commands) on a DRAFT. Nothing here has a rule of its own: an edit is accepted only if the result raises no+ * error that the draft did not already have, under `validateEnvelope`, the SAME validator the sealed file is opened with (verify argv+ * rules, host, repo, variable and path rules, protected folders, limits). So an edit can never produce a draft the loader would refuse,+ * and a rule added to the validator later reaches the editor with no change here. The draft is only a proposal: Start still asks.+ */+import { hashOf, narrowed, validateEnvelope, widened, type Envelope } from './ap-envelope'++export const LIST_KEYS = ['paths', 'repos', 'network', 'secretEnv', 'verify'] as const+export type ListKey = (typeof LIST_KEYS)[number]+export type Draft = Record<string, unknown>+export type Edited = { ok: true; value: Draft } | { ok: false; why: string }++const clone = (draft: Draft): Draft => JSON.parse(JSON.stringify(draft)) as Draft++const errorsOf = (draft: Draft): string[] => {+ const checked = validateEnvelope(draft)++ return checked.ok ? [] : checked.errors+}++/** What is typed for one entry, as the value stored in the draft; a string is the reason it cannot be read. */+export function entryOf(key: ListKey, raw: string): { value: string | string[] } | { why: string } {+ const text = raw.trim()++ if (text === '') return { why: 'type an entry first' }+ if (text.length > 300) return { why: 'too long (300 characters at most)' }++ if (key !== 'verify') return { value: key === 'network' ? text.toLowerCase() : text }++ // A verify command is a program and its arguments, split on spaces. Quoting is not interpreted (there is no shell), so a quote mark would be passed literally: refused rather than misread.+ if (/["'`\\]/.test(text)) return { why: 'no quotes or backslashes: a verify command is a program and its arguments split on spaces (a part cannot contain a space)' }++ return { value: text.split(/\s+/) }+}++const sameEntry = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b)++/** The draft with one entry added, or why not. The validator's own first new error is the reason. */+export function addEntry(draft: Draft, key: ListKey, raw: string): Edited {+ const entry = entryOf(key, raw)++ if ('why' in entry) return { ok: false, why: entry.why }++ const next = clone(draft)+ const have = Array.isArray(next[key]) ? (next[key] as unknown[]) : []++ if (have.some(item => sameEntry(item, entry.value))) return { ok: false, why: 'already in the list' }++ next[key] = [...have, entry.value]++ const before = new Set(errorsOf(draft))+ const fresh = errorsOf(next).filter(error => !before.has(error))++ return fresh.length > 0 ? { ok: false, why: fresh[0] as string } : { ok: true, value: next }+}++/** The draft with entry `index` of the list removed, or why not (removing the last folder would leave a draft the loader refuses). */+export function removeEntry(draft: Draft, key: ListKey, index: number): Edited {+ const have = Array.isArray(draft[key]) ? (draft[key] as unknown[]) : []++ if (!Number.isInteger(index) || index < 0 || index >= have.length) return { ok: false, why: 'no such entry' }++ const next = clone(draft)++ next[key] = have.filter((_, i) => i !== index)++ const before = new Set(errorsOf(draft))+ const fresh = errorsOf(next).filter(error => !before.has(error))++ return fresh.length > 0 ? { ok: false, why: fresh[0] as string } : { ok: true, value: next }+}++/** Rows saying how the draft differs from the approved envelope: what it adds (needs the confirm), what it takes away, or that it is the same. */+export function diffRows(approved: Envelope | null, draft: Draft): string[] {+ const checked = validateEnvelope(draft)++ if (!checked.ok) return ['the draft is not valid yet: no comparison']+ if (approved === null) return ['no approved envelope yet: Start would be the first approval']++ const grew = widened(approved, checked.envelope)+ const shrank = narrowed(approved, checked.envelope)++ if (hashOf(approved) === hashOf(checked.envelope)) return ['same as the approved envelope']+ if (grew.length === 0 && shrank.length === 0) return ['differs from the approved envelope only in its name (a new Start would still ask)']++ return [...grew.map(line => `+ ${line}`), ...shrank.map(line => `- ${line}`)]+}diff --git a/plugins/ruflo-console/hooks/data/ap-envelope.ts b/plugins/ruflo-console/hooks/data/ap-envelope.tsindex bfbb6b9ef7..5ff32f50a9 100644--- a/plugins/ruflo-console/hooks/data/ap-envelope.ts+++ b/plugins/ruflo-console/hooks/data/ap-envelope.ts@@ -308,6 +308,31 @@ export function widened(prev: Envelope, next: Envelope): string[] {return out}+/** Dimensions in which `next` grants LESS than `prev` (the diff the confirm card and the editor show beside `widened`). */+export function narrowed(prev: Envelope, next: Envelope): string[] {+ const out: string[] = []+ const shrank = (label: string, before: readonly string[], after: readonly string[]): void => {+ const removed = before.filter(item => !after.includes(item))++ if (removed.length > 0) out.push(`${label}: removes ${removed.slice(0, 4).join(', ')}${removed.length > 4 ? 'โฆ' : ''}`)+ }++ shrank('tool classes', prev.toolClasses, next.toolClasses)+ shrank('paths', prev.paths, next.paths)+ shrank('repos', prev.repos, next.repos)+ shrank('network', prev.network, next.network)+ shrank('secret env', prev.secretEnv, next.secretEnv)+ shrank('verify commands', prev.verify.map(argv => argv.join(' ')), next.verify.map(argv => argv.join(' ')))++ for (const key of ['hourUsd', 'dayUsd', 'totalUsd'] as const) if (next.spend[key] < prev.spend[key]) out.push(`${key}: ${prev.spend[key]} to ${next.spend[key]}`)++ if (next.concurrency < prev.concurrency) out.push(`concurrency: ${prev.concurrency} to ${next.concurrency}`)+ if (next.maxDurationMs < prev.maxDurationMs) out.push('duration: shorter')+ if (!next.acceptWithoutAnatole && prev.acceptWithoutAnatole) out.push('no longer runs without Project Anatole')++ return out+}+/** A path is inside the envelope when it is one of its folders or below one (compared at a folder boundary, so /a/bc is not inside /a/b). */export const pathAllowed = (envelope: Envelope, path: string): boolean => !path.split('/').includes('..') && !isProtectedPath(path) && envelope.paths.some(root => path === root || path.startsWith(`${root}/`))diff --git a/plugins/ruflo-console/hooks/data/ap-guard.ts b/plugins/ruflo-console/hooks/data/ap-guard.tsindex 3d6e2a8294..e7369df71b 100644--- a/plugins/ruflo-console/hooks/data/ap-guard.ts+++ b/plugins/ruflo-console/hooks/data/ap-guard.ts@@ -9,7 +9,7 @@ import { ESCAPES, HIDDEN, INVISIBLE } from './parse'import { ANATOLE_STALE_MS } from './anatole'import type { EffectFact, Preflight, TaskFact } from './ap-loop'import type { AnatoleFacts } from './anatole'-import type { Spend } from './ap-envelope'+import type { Envelope, Spend } from './ap-envelope'import type { ReaderFs } from './files'const DENIES = DENY_PATTERNS@@ -107,7 +107,27 @@ export type ToolCheck = (tool: string, input?: unknown) => Promise<{ decision?:/** The tool a class is checked through. A class whose representative tool the person's settings would block is parked, never tried. */export const PREFLIGHT_TOOL: Record<ToolClass, string> = { read: 'Read', test: 'Bash', edit: 'Edit', 'git-local': 'Bash', 'git-branch': 'Bash', spawn: 'Agent', mcp: 'mcp__plugin_ruflo-core_ruflo__task_update', network: 'WebFetch' }-export async function preflightAll(check: ToolCheck | undefined): Promise<Record<string, Preflight>> {+/**+ * The input the engine is asked about for a class. The engine decides on a call's INPUT (a path rule, a command prefix rule), so a probe with+ * no input is answered `ask` for everything (found live: with acceptEdits and the test command allowed, an empty-input Read, Edit and+ * Bash all said ask, and every task was parked). The input is a call the envelope itself allows: a file in its first folder, its first+ * verify command, a host from its network list. A class the envelope has nothing representative for is asked with no input, as before.+ */+export function preflightInput(cls: ToolClass, env: Envelope | null): unknown {+ const root = env?.paths[0]++ if (env === null || root === undefined) return {}+ if (cls === 'read') return { file_path: `${root}/preflight-probe` }+ if (cls === 'edit') return { file_path: `${root}/preflight-probe`, old_string: 'a', new_string: 'b' }+ if (cls === 'test') return env.verify[0] === undefined ? {} : { command: env.verify[0].join(' ') }+ if (cls === 'git-local') return { command: 'git status' }+ if (cls === 'git-branch') return { command: 'git switch -c preflight-probe' }+ if (cls === 'network') return env.network[0] === undefined ? {} : { url: `https://${env.network[0]}/` }++ return {}+}++export async function preflightAll(check: ToolCheck | undefined, env: Envelope | null = null): Promise<Record<string, Preflight>> {const out: Record<string, Preflight> = {}for (const cls of TOOL_CLASSES) {@@ -117,7 +137,7 @@ export async function preflightAll(check: ToolCheck | undefined): Promise<Record}try {- const answer = await check(PREFLIGHT_TOOL[cls])+ const answer = await check(PREFLIGHT_TOOL[cls], preflightInput(cls, env))const decision = typeof answer === 'string' ? answer : answer?.decisionout[cls] = decision === 'allow' ? 'allow' : decision === 'deny' ? 'deny' : decision === 'ask' ? 'ask' : 'unwired'diff --git a/plugins/ruflo-console/hooks/data/ap-loop.ts b/plugins/ruflo-console/hooks/data/ap-loop.tsindex 20ad0153e1..f823206376 100644--- a/plugins/ruflo-console/hooks/data/ap-loop.ts+++ b/plugins/ruflo-console/hooks/data/ap-loop.ts@@ -264,8 +264,11 @@ export function tick(s: LoopState, f: Facts): Decision {events.push({ t: 'step.failed', at: now, id: step.id, why: 'timed out' })failures += 1lastFailure = now- } else if (f.orphans.has(step.id) && effect === 'absent') {+ } else if (f.orphans.has(step.id) && (effect === 'absent' || effect === 'unknown')) {+ // A step from before a restart whose task the store still shows in progress (or not at all): nobody is working it, and waiting out its 30 minute deadline would then RETRY it without a question (found in the live run). Settle it now; a lost step parks its task (see `wasLost`).events.push({ t: 'step.failed', at: now, id: step.id, why: 'lost on restart: no effect found' })+ // The store still shows it in progress, so the picker will never offer this task again: park it here, with a question that says what to do.+ if (effect === 'unknown') events.push({ t: 'parked', at: now, id: parkId(step.task, 'lost'), task: step.task, question: 'a step for this task was in flight when the console restarted, and the task store still shows it in progress with nobody working it. It may have run: check the work, set the task back to pending to retry it (then approve once), or deny.' })failures += 1lastFailure = now} else stillOpen += 1diff --git a/plugins/ruflo-console/hooks/data/ap-spend.ts b/plugins/ruflo-console/hooks/data/ap-spend.tsnew file mode 100644index 0000000000..62ba374919--- /dev/null+++ b/plugins/ruflo-console/hooks/data/ap-spend.ts@@ -0,0 +1,63 @@+/**+ * What the autopilot can honestly say about spend (ADR-470 ยง2.3). The cost ledger (ruflo-cost-tracker's ledger.mjs) filters rows by time+ * window and project (`--from --to --project`); it has NO per-session or per-process filter, so a reading is "every Claude Code turn in this+ * project in the window, priced at list price", yours included. That is the strictest reading the ledger can give and the one the ceilings+ * are enforced on: it over-counts rather than under-counts. Two things are made exact here that were not: a window never reaches back past+ * the Start (an hour window started 10 minutes ago no longer counts the 50 minutes before it), and a reading that cannot be trusted says+ * why (no tracker, an older tracker without the window filters, a model with no price) instead of waiting in silence.+ */+import { bumpKind, parseSemver } from '../updates'+import type { State } from '../state'+import { COST_PLUGIN, trackerOf } from './cost-ledger'+import { MISSION_COST_FROM } from './cost-probes'+import { missionCostArgv, parseMissionCost } from './mission-cost'+import type { Spend } from './ap-envelope'++/** Said wherever a spend figure is drawn. */+export const SPEND_BASIS = 'estimate at list price: every Claude Code turn in this project since Start, yours too (the ledger has no per-session reading)'++export type SpendSource = { kind: 'ready'; root: string } | { kind: 'unavailable'; why: string }++/** Whether the ledger can be asked for a window at all, and if not, the reason. */+export function spendSource(state: Pick<State, 'snapshot'>): SpendSource {+ const tracker = trackerOf(state)++ if (tracker.kind === 'absent') return { kind: 'unavailable', why: 'the ruflo-cost-tracker plugin is not installed, so there is no ledger to read' }+ if (tracker.kind === 'old') return { kind: 'unavailable', why: `ruflo-cost-tracker ${tracker.version} is older than the first release with the ledger` }++ const version = state.snapshot?.plugins.installed?.find(plugin => plugin.id === COST_PLUGIN)?.version ?? ''++ if (parseSemver(version) === null || bumpKind(version, MISSION_COST_FROM) !== null) return { kind: 'unavailable', why: `ruflo-cost-tracker ${version || '?'} lacks the window filters (needs ${MISSION_COST_FROM} or newer)` }++ return { kind: 'ready', root: tracker.root }+}++export type SpendArgvs = { hour: readonly string[] | null; day: readonly string[] | null; total: readonly string[] | null }++/** The three ledger commands. No window starts before the Start: the hour and day are `max(now - span, start)`. */+export function windowArgvs(root: string, startMs: number, nowMs: number, project: string): SpendArgvs {+ const at = (spanMs: number): number => Math.max(startMs, nowMs - spanMs)+ // Claude Code only: the hand-over is a prompt to this session, and a Codex reading adds nothing but rows (the ledger overflowed its stack on this machine's Codex history for a wide window).+ const claude = (argv: readonly string[] | null): readonly string[] | null => (argv === null ? null : [...argv, '--provider', 'claude'])++ return { hour: claude(missionCostArgv(root, at(3_600_000), null, project)), day: claude(missionCostArgv(root, at(86_400_000), null, project)), total: claude(missionCostArgv(root, startMs, null, project)) }+}++export type Reading = { spend: Spend; why: null } | { spend: null; why: string }++/**+ * The three ledger outputs as one reading. Unknown is never zero: a window that did not parse, or whose total is unknown, makes the whole+ * reading unknown, and so does a model with no price (its spend is missing from the total, so the total would under-count a ceiling).+ */+export function readingOf(out: { hour: string; day: string; total: string }): Reading {+ const [hour, day, total] = [parseMissionCost(out.hour), parseMissionCost(out.day), parseMissionCost(out.total)]++ if (hour === null || day === null || total === null) return { spend: null, why: 'the ledger did not answer with a reading' }++ const unpriced = [...new Set([...hour.unpriced, ...day.unpriced, ...total.unpriced])]++ if (unpriced.length > 0) return { spend: null, why: `no list price for ${unpriced.slice(0, 2).join(', ')}: the total would under-count, so it is not used` }+ if (hour.usd === null || day.usd === null || total.usd === null) return { spend: null, why: 'a window total is unknown' }++ return { spend: { hourUsd: hour.usd, dayUsd: day.usd, totalUsd: total.usd }, why: null }+}diff --git a/plugins/ruflo-console/hooks/mission-control.ts b/plugins/ruflo-console/hooks/mission-control.tsindex 0ef8e91265..69ff403f5f 100644--- a/plugins/ruflo-console/hooks/mission-control.ts+++ b/plugins/ruflo-console/hooks/mission-control.ts@@ -91,6 +91,22 @@ export function nextTask(mission: MissionRecord, tasks: readonly TaskRecord[]):return mission.tasks.find(task => status.get(task.id) === 'ready' && task.rufloTaskId !== undefined) ?? null}+/**+ * Autopilot's narrow door (ADR-470 ยง2.2): the mission's own rule for handing a task over, with the one-at-a-time limit widened to `cap`.+ * Everything else is `nextTask`'s: not paused or cancelled, nothing failed, the task ready (its dependencies done) and in the task store.+ * `running` counts tasks the store shows in progress plus tasks handed over in the last seconds (the store has not refreshed yet).+ * `startable(m, tasks, t, 1)` is exactly `nextTask(m, tasks)?.id === t.id` as far as the running rule goes.+ */+export function startable(mission: MissionRecord, tasks: readonly TaskRecord[], task: LedgerTask, cap: number): boolean {+ if (mission.paused || mission.cancelled || task.rufloTaskId === undefined || isInflight(task)) return false++ const status = derive(mission, tasks)+ const values = [...status.values()]+ const running = mission.tasks.filter(candidate => status.get(candidate.id) === 'running' || (candidate !== task && isInflight(candidate))).length++ return !values.includes('failed') && status.get(task.id) === 'ready' && running < Math.max(1, cap)+}+export const progressOf = (mission: MissionRecord, tasks: readonly TaskRecord[]) => {const status = derive(mission, tasks)diff --git a/plugins/ruflo-console/hooks/mission-specs.ts b/plugins/ruflo-console/hooks/mission-specs.tsindex 547a61263e..3a74fac8b1 100644--- a/plugins/ruflo-console/hooks/mission-specs.ts+++ b/plugins/ruflo-console/hooks/mission-specs.ts@@ -139,7 +139,8 @@ const inflight = new WeakSet<LedgerTask>()export const isInflight = (task: LedgerTask): boolean => inflight.has(task)-export function dispatchSpec(state: State, host: Host, mission: MissionRecord, task: LedgerTask, send: (text: string) => Promise<void>): ActionSpec {+/** `isReady` replaces the one-at-a-time check for a caller that has its own bound (autopilot's `startable`); without it the mission's own `nextTask` rule applies. */+export function dispatchSpec(state: State, host: Host, mission: MissionRecord, task: LedgerTask, send: (text: string) => Promise<void>, isReady?: (mission: MissionRecord, tasks: readonly TaskRecord[], task: LedgerTask) => boolean): ActionSpec {const text = instructionOf(mission, task)return {@@ -151,7 +152,7 @@ export function dispatchSpec(state: State, host: Host, mission: MissionRecord, tnote: 'Starts a Claude Code turn on your plan (billed as any turn is); the prompt is visible and Claude records the result with task_complete.',run: async () => {// The ask stays open for a while: the mission may have moved (paused, cancelled, auto-run took it, a double press).- if (mission.paused || mission.cancelled || inflight.has(task) || nextTask(mission, state.snapshot?.tasks ?? [])?.id !== task.id) {+ if (mission.paused || mission.cancelled || inflight.has(task) || !(isReady === undefined ? nextTask(mission, state.snapshot?.tasks ?? [])?.id === task.id : isReady(mission, state.snapshot?.tasks ?? [], task))) {mcOf(state).last = { label: `task ${task.id} not handed over`, ok: false, detail: 'the mission changed since you asked (paused, cancelled, or that task already went)' }host.invalidate()diff --git a/plugins/ruflo-console/hooks/views/ap-band.ts b/plugins/ruflo-console/hooks/views/ap-band.tsnew file mode 100644index 0000000000..79664ac92e--- /dev/null+++ b/plugins/ruflo-console/hooks/views/ap-band.ts@@ -0,0 +1,27 @@+/**+ * The autopilot's segment of the band (ADR-470 ยง2.4): `autopilot day 3 ยท $12/$40 ยท 2 parked`, drawn on the band's first row through+ * `registerBarSource` (views/bar.ts), the same composer every other part goes through. Every figure is from the journal, the sealed+ * envelope and the ledger reading; an unread spend is `$n/a`, never `$0`. Nothing is drawn while autopilot has never started.+ */+import { storeOf } from '../ap-live'+import { bandText, summarize } from '../data/ap-loop'+import type { State } from '../state'+import { registerBarSource, type BarPart } from './bar'++export function autopilotPart(state: State, nowMs: number): BarPart | null {+ const store = storeOf(state)+ const loop = store.loop+ const text = bandText(loop, nowMs, store.spend?.totalUsd ?? null, store.sealed !== null && store.sealed.hash === loop.envHash ? store.sealed.envelope : null)++ if (text === '') return null++ const sum = summarize(loop, nowMs)++ return { text, tone: sum.phase === 'paused' || (sum.phase === 'running' && sum.parked > 0) ? 'attention' : sum.phase === 'running' ? 'live' : 'plain', go: 'workflows' }+}++registerBarSource((state, nowMs) => {+ const part = autopilotPart(state, nowMs)++ return part === null ? [] : [part]+})diff --git a/plugins/ruflo-console/hooks/views/ap-draft.ts b/plugins/ruflo-console/hooks/views/ap-draft.tsnew file mode 100644index 0000000000..2eca1e3364--- /dev/null+++ b/plugins/ruflo-console/hooks/views/ap-draft.ts@@ -0,0 +1,19 @@+/**+ * The autopilot's envelope DRAFT: the one object the panel's buttons and the list editor (views/ap-editor.ts) both change. It is a+ * proposal held in memory; nothing is granted until the confirmed Start seals it. Split from ap-panel.ts (file limit, and so the editor+ * and the panel need not import each other).+ */+import type { State } from '../state'++export type DraftState = { value: Record<string, unknown>; fromFile: string | null; /** The last edit the list editor refused, with its reason. */ refused: string | null }++const DAY = 86_400_000+const drafts = new WeakMap<State, DraftState>()++/** 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): DraftState => drafts.get(state) ?? drafts.set(state, { value: defaultDraft(state.cwd), fromFile: null, refused: null }).get(state)!++/** A duration as the person reads it: hours under a day (the minimum is an hour, which used to read "0 d"), days above. */+export const spanText = (ms: number): string => (ms < DAY ? `${Math.max(1, Math.round(ms / 3_600_000))} h` : `${Math.round(ms / DAY)} d`)diff --git a/plugins/ruflo-console/hooks/views/ap-editor.ts b/plugins/ruflo-console/hooks/views/ap-editor.tsnew file mode 100644index 0000000000..ad66a069bb--- /dev/null+++ b/plugins/ruflo-console/hooks/views/ap-editor.ts@@ -0,0 +1,96 @@+/**+ * The envelope's list editor (ADR-470 ยง2.1): folders, repositories, network hosts, secret variable NAMES and verify commands, each a list+ * of rows with a remove button and one field to add an entry, on the draft the panel's other buttons also change. Every edit is checked+ * by the same validator the sealed file is opened with (data/ap-edit.ts); a refused edit changes nothing and says why. Below the lists:+ * the draft as a diff against the approved envelope, and the verify commands in full, which is also what the Start card will list. This+ * edits a proposal in memory: nothing is granted until the confirmed Start.+ */+import type { RenderElement } from 'claude-code'++import { hostOf } from '../ap-live'+import { addEntry, diffRows, LIST_KEYS, removeEntry, type ListKey } from '../data/ap-edit'+import { validateEnvelope, type Envelope } from '../data/ap-envelope'+import { cleanText } from '../data/wf-clean'+import type { DraftState } from './ap-draft'+import { button, clip, row, text, THEME, type Ctx } from './common'++const LABEL: Record<ListKey, { name: string; hint: string }> = {+ paths: { name: 'folders', hint: 'an absolute folder, e.g. /home/me/project' },+ repos: { name: 'repos', hint: 'owner/name, e.g. ruvnet/ruflo' },+ network: { name: 'network hosts', hint: 'a lowercase hostname, no port: api.github.com' },+ secretEnv: { name: 'secret env names', hint: 'a variable NAME (never a value): GH_TOKEN' },+ verify: { name: 'verify commands', hint: 'program and arguments split on spaces: node --test' },+}++/** Adds an entry to the draft when the validator accepts the result; the reason it did not is kept on the draft. */+export function applyAdd(d: DraftState, key: ListKey, raw: string): boolean {+ const done = addEntry(d.value, key, raw)++ d.refused = done.ok ? null : `${LABEL[key].name}: ${cleanText(done.why).replace(/^(paths|repos|network|secretEnv|verify): /, '').slice(0, 160)}`+ if (done.ok) {+ d.value = done.value+ d.fromFile = null+ }++ return done.ok+}++export function applyRemove(d: DraftState, key: ListKey, index: number): boolean {+ const done = removeEntry(d.value, key, index)++ d.refused = done.ok ? null : `${LABEL[key].name}: ${cleanText(done.why).replace(/^(paths|repos|network|secretEnv|verify): /, '').slice(0, 160)}`+ if (done.ok) {+ d.value = done.value+ d.fromFile = null+ }++ return done.ok+}++const show = (key: ListKey, item: unknown): string => (key === 'verify' && Array.isArray(item) ? (item as string[]).join(' ') : String(item))++/** The list rows, the refusal, the diff against the approved envelope and the verify commands in full. */+export function editorLists(ctx: Ctx, d: DraftState, approved: Envelope | null): RenderElement[] {+ const host = hostOf(ctx.state)+ const rows: RenderElement[] = [text(ctx, ' lists (every edit is checked by the validator the sealed envelope is opened with; a refused edit changes nothing)', { dimColor: true })]++ for (const key of LIST_KEYS) {+ const items = Array.isArray(d.value[key]) ? (d.value[key] as unknown[]) : []++ rows.push(text(ctx, ` ${LABEL[key].name}${items.length === 0 ? ': none' : ''}`, { dimColor: true }))++ for (const [i, item] of items.entries()) {+ rows.push(row(ctx, [+ button(ctx, `ap-rm-${key}-${i}`, ' remove ', () => {+ applyRemove(d, key, i)+ host?.invalidate()+ }),+ text(ctx, ` ${clip(cleanText(show(key, item)), Math.max(20, ctx.columns - 20))}`),+ ], `ap-row-${key}-${i}`))+ }++ rows.push(ctx.kit.Input === undefined+ ? text(ctx, ` (no text field on this surface: edit ${key} in the draft file)`, { dimColor: true })+ : ctx.kit.Input({+ key: `ap-add-${key}`,+ label: `add to ${LABEL[key].name}`,+ placeholder: LABEL[key].hint,+ submitLabel: 'add',+ onSubmit: value => {+ applyAdd(d, key, value)+ host?.invalidate()+ },+ }))+ }++ if (d.refused !== null) rows.push(text(ctx, ` refused: ${d.refused}`, { color: THEME.bad }))++ rows.push(text(ctx, ' against the approved envelope:', { dimColor: true }))+ for (const line of diffRows(approved, d.value)) rows.push(text(ctx, ` ${cleanText(line)}`, { color: line.startsWith('+') ? THEME.warn : undefined, dimColor: !line.startsWith('+') }))++ const checked = validateEnvelope(d.value)++ rows.push(text(ctx, checked.ok && checked.envelope.verify.length > 0 ? ` Start will run, after each step, through this console: ${checked.envelope.verify.map(argv => cleanText(argv.join(' '))).join(' ; ')}` : ' no verify command: steps will be recorded as unverified', { dimColor: true }))++ return rows+}diff --git a/plugins/ruflo-console/hooks/views/ap-panel.ts b/plugins/ruflo-console/hooks/views/ap-panel.tsindex 83b13e4eef..9454c973a1 100644--- a/plugins/ruflo-console/hooks/views/ap-panel.ts+++ b/plugins/ruflo-console/hooks/views/ap-panel.ts@@ -12,31 +12,28 @@ import { activeOf, apTick, appendEvents, clearKill, drainNotices, hostOf, pauseNimport { 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 { SPEND_BASIS, spendSource } from '../data/ap-spend'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 { draftOf, defaultDraft, spanText, type DraftState } from './ap-draft'+import { editorLists } from './ap-editor'+import './ap-band'import './ap-parked'import { registerSlot, type SlotEnv } from './wf-slots'+export { defaultDraft, draftOf }+const START_WHY = 'the envelope draft is not valid, or nothing changed since the running one, or autopilot is not wired into this console'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>) })+const spendOf = (d: DraftState): 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 {+export function editDraft(d: DraftState, 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.valueif (edit.kind === 'class') {@@ -83,6 +80,7 @@ export async function loadDraftFile(state: State): Promise<string> {d.value = JSON.parse(JSON.stringify(checked.envelope)) as Record<string, unknown>d.fromFile = DRAFT_FILE+ d.refused = nullhost.invalidate()return 'draft loaded'@@ -100,10 +98,14 @@ function gates(ctx: Ctx, env: Envelope | null): RenderElement[] {const classes = Object.entries(store.preflight)const denied = classes.filter(([, v]) => v === 'deny' || v === 'ask').map(([k]) => k)+ const source = spendSource(ctx.state)+ const why = store.spendWhy ?? (source.kind === 'unavailable' ? source.why : null)+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 decides every call, never 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, 'permissions', !store.hasCheck ? 'preflight not wired: the engine still decides every call, never bypassed' : classes.length === 0 ? 'not checked yet (the first pass asks the engine)' : 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${why === null ? '' : `: ${cleanText(why)}`}; nothing starts until it is)` : ' (estimate, see below)'}`),+ ...(store.spend === null ? [] : [text(ctx, ` ${SPEND_BASIS}`, { dimColor: true })]),kv(ctx, 'journal', `${Math.round(store.journalBytes / 1000)} kB of 1500 kB cap${store.badLines > 0 ? ` ยท ${store.badLines} unusable lines` : ''}`),]}@@ -117,7 +119,7 @@ function envelopeRows(ctx: Ctx, nowMs: number): RenderElement[] {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'} ยท 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, ` classes ${e.toolClasses.join(' ') || 'none'} ยท up to ${e.concurrency} at once ยท ${spanText(e.maxDurationMs)} ยท ${e.verify.length} verify command${e.verify.length === 1 ? '' : 's'}`, { dimColor: true }),text(ctx, ` folders ${e.paths.map(cleanText).join(', ')}`, { dimColor: true }),text(ctx, ` network ${e.network.join(',') || 'none'} ยท repos ${e.repos.join(',') || 'none'} ยท secret names ${e.secretEnv.join(',') || 'none'}`, { dimColor: true }),text(ctx, ' checked against what a task SAYS: its class, paths, URLs and repos', { dimColor: true }),@@ -144,11 +146,13 @@ function editor(ctx: Ctx): RenderElement[] {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, [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, ` ${spanText(Number(d.value.maxDurationMs))} `, { bold: true }), button(ctx, 'ap-d-more', ' + ', set({ kind: 'days', by: 1 }))], 'ap-conc'))rows.push(flow(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))], 'ap-draft-row'))- rows.push(text(ctx, ` ${DRAFT_FILE} holds paths, repos, network, verify`, { dimColor: true }))+ rows.push(text(ctx, ` ${DRAFT_FILE} can load all the lists in one go`, { dimColor: true }))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 }))+ rows.push(...editorLists(ctx, d, storeOf(ctx.state).sealed?.envelope ?? null))+return rows}@@ -182,14 +186,16 @@ export function boardRows(env: SlotEnv): RenderElement[] {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 }))- // Stop's key (9) is the key slot's: a second button on the same key would run it twice.+ // Stop has no hotkey: the digits and letters are views' keys (a hotkey here would open another page). The button and /ruflo autopilot stop are the ways.rows.push(flow(ctx, [- button(ctx, 'ap-stop', 'Stop (9)', () => void stopNow(ctx.state, host)),+ // Start lives here too: the page draws its action row only when a workflow run is selected, and a project with no run (a plain scratch repo) would have no way to start.+ button(ctx, 'ap-start-btn', 'Start autopilot', () => ctx.act.workflows.ask(startSpec(env), START_WHY), { primary: true }),+ button(ctx, 'ap-stop', 'Stop', () => void stopNow(ctx.state, host)),...(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)),], 'ap-controls'))- rows.push(text(ctx, ' Start is the action row (key 8) and asks first ยท Stop asks nothing', { dimColor: true }))+ rows.push(text(ctx, ' Start asks first (the card lists every command) ยท Stop asks nothing, and so does /ruflo autopilot stop', { dimColor: true }))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))@@ -219,7 +225,7 @@ export function startSpec(env: SlotEnv): ActionSpec | null {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)`,+ label: `start autopilot "${next.name}" (${next.toolClasses.join(' ')} ยท up to ${money(next.spend.totalUsd)} ยท ${spanText(next.maxDurationMs)})`,scope: 'workflows',args: [],declared: 'spend',@@ -269,13 +275,8 @@ export function startSpec(env: SlotEnv): ActionSpec | null {/** 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 })+ // No hotkeys (ADR-470 live finding): every digit and letter is a view's key or the page's own, and a slot hotkey that equals a view key loses to it (8 opened MetaHarness, 9 opened Memory, so the advertised Stop key never ran). Stop is a button and /ruflo autopilot stop.+ registerSlot({ kind: 'action', id: 'ap-start', label: 'start autopilot', why: START_WHY, spec: startSpec })registerSlot({kind: 'notice',id: 'autopilot',diff --git a/plugins/ruflo-console/hooks/views/bar.ts b/plugins/ruflo-console/hooks/views/bar.tsindex 235db58a4e..1ee0b1de18 100644--- a/plugins/ruflo-console/hooks/views/bar.ts+++ b/plugins/ruflo-console/hooks/views/bar.ts@@ -93,6 +93,14 @@ export function missionPart(state: State): BarPart | null {return { text: `๐ฏ ${done}/${total}${mission.paused ? ' paused' : running !== undefined ? ` ยท ${running.id} ${clip(running.title, 28)}` : ''} (1)`, tone: running !== undefined ? 'live' : 'plain', go: 'missions' }}+/**+ * A module's own band parts (the autopilot's segment, views/ap-band.ts): registered once at import, drawn on the first row after the+ * mission. A source returns nothing when it has nothing to say, and one that throws is skipped, so it can never blank the band.+ */+const sources: ((state: State, nowMs: number) => BarPart[])[] = []++export const registerBarSource = (source: (state: State, nowMs: number) => BarPart[]): void => void (sources.includes(source) || sources.push(source))+export function barParts(state: State, nowMs: number = Date.now()): BarPart[] {const snap = state.snapshotconst parts: BarPart[] = []@@ -109,6 +117,14 @@ export function barParts(state: State, nowMs: number = Date.now()): BarPart[] {if (missing !== null) parts.push(missing)+ for (const source of sources) {+ try {+ parts.push(...source(state, nowMs))+ } catch {+ // A source that fails draws nothing.+ }+ }+// What is happening now: how long Claude has been on this turn, agents at work, the AI terminal's runs, and the newest event while it is fresh.if (state.turnActive && state.turnStartedMs !== null) parts.push({ text: `โถ Claude working${since(state.turnStartedMs, nowMs)}`, tone: 'live', go: 'events' })diff --git a/plugins/ruflo-console/tests/ap-complete.spec.ts b/plugins/ruflo-console/tests/ap-complete.spec.tsnew file mode 100644index 0000000000..e237039a46--- /dev/null+++ b/plugins/ruflo-console/tests/ap-complete.spec.ts@@ -0,0 +1,290 @@+/**+ * ADR-470: the envelope list editor, and what the live run found (hotkeys, the permission probe, restart, stop).+ * Pure and in-memory (the ap-rig disk and fake host). Run with+ * npx vitest run plugins/ruflo-console/tests/ap-complete.spec.ts --testTimeout=30000+ */++import { describe, expect, it } from 'vitest'+import { apTick, storeOf, wireAutopilot } from '../hooks/ap-live'+import { addEntry, diffRows, entryOf, removeEntry } from '../hooks/data/ap-edit'+import { hashOf, narrowed, validateEnvelope, widened, type Envelope } from '../hooks/data/ap-envelope'+import { VIEWS } from '../hooks/state'+import { slotsFor } from '../hooks/views/wf-slots'+import { draftOf, defaultDraft, spanText } from '../hooks/views/ap-draft'+import { preflightAll, preflightInput } from '../hooks/data/ap-guard'+import { applyAdd, applyRemove, editorLists } from '../hooks/views/ap-editor'+import { boardRows } from '../hooks/views/ap-panel'+import '../hooks/views/wf-register'+import { CWD, ENV, J, T0, buttons, ctxOf, envOf, flat, journal, rig, started, stateWith, task, words } from './fixtures/ap-rig'++const base = (): Record<string, unknown> => defaultDraft(CWD)++describe('the envelope list editor: every edit goes through the loader\'s own validator', () => {+ it('accepts a valid entry in each list and the result is still a valid envelope', () => {+ let d = base()++ for (const [key, raw] of [['paths', `${CWD}/src`], ['repos', 'ruvnet/ruflo'], ['network', 'API.GitHub.com'], ['secretEnv', 'GH_TOKEN'], ['verify', 'node --test']] as const) {+ const done = addEntry(d, key, raw)++ expect(done.ok, `${key}: ${done.ok ? '' : done.why}`).toBe(true)+ if (done.ok) d = done.value+ }++ const checked = validateEnvelope(d)++ expect(checked.ok).toBe(true)+ expect(checked.ok && checked.envelope.network).toEqual(['api.github.com'])+ expect(checked.ok && checked.envelope.verify).toEqual([['node', '--test']])+ })++ it('refuses what the sealed file would refuse, with the validator\'s own reason, and changes nothing', () => {+ const d = base()+ const before = JSON.stringify(d)+ const bad: [Parameters<typeof addEntry>[1], string, string][] = [+ ['verify', 'bash -c ls', 'shell'],+ ['verify', 'curl http://x', 'network tool'],+ ['verify', 'npm publish', 'never'],+ ['verify', 'node a;b', 'metacharacter'],+ ['paths', '/', 'absolute folder'],+ ['paths', 'relative/dir', 'absolute folder'],+ ['paths', `${CWD}/../etc`, 'absolute folder'],+ ['paths', '/w/.claude-flow/console/autopilot', 'own folder'],+ ['repos', 'not-a-repo', 'owner/name'],+ ['network', 'https://x.com', 'hostname'],+ ['network', '*.evil.com', 'hostname'],+ ['secretEnv', 'lowercase', 'variable name'],+ ['secretEnv', 'GH_TOKEN=abc', 'variable name'],+ ]++ for (const [key, raw, because] of bad) {+ const done = addEntry(d, key, raw)++ expect(done.ok, `${key} ${raw}`).toBe(false)+ expect(!done.ok && done.why.toLowerCase(), `${key} ${raw}`).toContain(because)+ }++ expect(JSON.stringify(d)).toBe(before)+ })++ it('reads a verify command as a program and its arguments, with no quoting to misread', () => {+ expect(entryOf('verify', ' node --test tests/a.js ')).toEqual({ value: ['node', '--test', 'tests/a.js'] })+ expect('why' in entryOf('verify', 'node -e "x y"')).toBe(true)+ expect('why' in entryOf('verify', ' ')).toBe(true)+ expect('why' in entryOf('paths', 'x'.repeat(301))).toBe(true)+ })++ it('refuses a duplicate, caps the verify list at six, and never removes the last folder', () => {+ let d = base()++ expect(addEntry(d, 'paths', CWD).ok).toBe(false)++ for (let i = 0; i < 6; i++) {+ const done = addEntry(d, 'verify', `node --test t${i}.js`)++ expect(done.ok).toBe(true)+ if (done.ok) d = done.value+ }++ expect(addEntry(d, 'verify', 'node --test t7.js').ok).toBe(false)++ const last = removeEntry(d, 'paths', 0)++ expect(last.ok).toBe(false)+ expect(!last.ok && last.why).toContain('at least one')+ expect(removeEntry(d, 'verify', 99).ok).toBe(false)+ expect(removeEntry(d, 'verify', 0).ok).toBe(true)+ })++ it('shows the draft as a diff against the approved envelope, and the widening is what Start will warn about', () => {+ const approved = ENV+ const draft = { ...JSON.parse(JSON.stringify(ENV)) } as Record<string, unknown>+ const grown = addEntry(draft, 'network', 'api.github.com')+ const shrunk = removeEntry(JSON.parse(JSON.stringify(ENV)) as Record<string, unknown>, 'verify', 0)++ expect(diffRows(approved, draft)).toEqual(['same as the approved envelope'])+ expect(grown.ok && diffRows(approved, grown.value)).toEqual(['+ network: adds api.github.com'])+ expect(shrunk.ok && diffRows(approved, shrunk.value)).toEqual(['- verify commands: removes true'])+ expect(diffRows(null, draft)[0]).toContain('first approval')+ expect(diffRows(approved, { ...draft, spend: {} })[0]).toContain('not valid')++ const a = ENV+ const b: Envelope = { ...ENV, network: ['x.com'], concurrency: 4 }++ expect(widened(a, b)).toEqual(expect.arrayContaining(['network: adds x.com', 'concurrency: 1 to 4']))+ expect(narrowed(b, a)).toEqual(expect.arrayContaining(['network: removes x.com', 'concurrency: 4 to 1']))+ expect(narrowed(a, a)).toEqual([])+ })++ it('draws a row and a remove button per entry, an add field per list, and the refusal; the panel puts it on the board', () => {+ const state = stateWith([])++ wireAutopilot(state, rig().host)++ const d = draftOf(state)++ expect(applyAdd(d, 'verify', 'node --test')).toBe(true)+ expect(applyAdd(d, 'verify', 'sh -c x')).toBe(false)+ expect(d.refused).toContain('verify commands')+ expect(applyAdd(d, 'repos', 'ruvnet/ruflo')).toBe(true)+ expect(d.refused).toBeNull()++ const ctx = { ...ctxOf(state, T0), kit: { ...ctxOf(state, T0).kit, Input: (props: Record<string, unknown>) => ({ kind: 'Input', props }) } }+ const tree = editorLists(ctx as never, d, null)+ const inputs = flat(tree).filter(el => el.kind === 'Input').map(el => el.props.key)++ expect(inputs).toEqual(['ap-add-paths', 'ap-add-repos', 'ap-add-network', 'ap-add-secretEnv', 'ap-add-verify'])+ expect(buttons(tree)).toEqual(expect.arrayContaining(['remove', 'remove'].map(label => ` ${label} `)))+ expect(words(tree)).toContain('Start will run, after each step, through this console: node --test')+ expect(words(tree)).toContain('first approval')+ expect(words(boardRows(envOf(state, T0)))).toContain('lists (every edit is checked')++ expect(applyRemove(d, 'verify', 0)).toBe(true)+ expect(words(editorLists(ctx as never, d, null))).toContain('no verify command')+ })++ it('the draft Start offers is the edited one: its card lists the new verify argv and what it widens', async () => {+ const { startSpec } = await import('../hooks/views/ap-panel')+ const r = rig()+ const state = stateWith([])++ started(r)+ wireAutopilot(state, r.host)+ await (await import('../hooks/ap-live')).refreshAutopilot(state, r.host, T0)+ draftOf(state).value = JSON.parse(JSON.stringify(ENV)) as Record<string, unknown>+ applyAdd(draftOf(state), 'network', 'api.github.com')+ applyAdd(draftOf(state), 'verify', 'node --test tests/a.test.js')++ const spec = startSpec(envOf(state, T0))++ expect(spec?.shows).toContain('node --test tests/a.test.js')+ expect(spec?.shows).toContain('network api.github.com')+ expect(spec?.shows).toContain('WIDENS: network: adds api.github.com')+ expect(hashOf(validateEnvelope(draftOf(state).value).ok ? (validateEnvelope(draftOf(state).value) as { ok: true; envelope: Envelope }).envelope : ENV)).not.toBe(hashOf(ENV))+ })+})++describe('live findings (ADR-470 ยง4)', () => {+ it('no autopilot slot takes a hotkey that is a view key: such a key opens that page instead (8 opened MetaHarness, 9 Memory, so Stop never ran)', () => {+ const viewKeys = new Set(VIEWS.map(view => view.key).filter(key => key !== ''))+ const mine = [...slotsFor('key'), ...slotsFor('action')].filter(slot => slot.id.startsWith('ap-'))++ for (const slot of mine) {+ const key = slot.kind === 'key' ? slot.key : slot.kind === 'action' ? slot.hotkey : undefined++ expect(key === undefined || !viewKeys.has(key), `${slot.id} uses view key ${key}`).toBe(true)+ }++ // The Stop button is on the board, with no key; the command still stops.+ expect(slotsFor('action').some(slot => slot.id === 'ap-start')).toBe(true)+ })++ it('before the first preflight pass the panel does not claim your settings allow every class', () => {+ const state = stateWith([])++ wireAutopilot(state, rig().host, { toolCheck: async () => ({ decision: 'allow' }) })++ const text = words(boardRows(envOf(state, T0)))++ expect(text).not.toContain('allow every class')+ expect(text).toContain('not checked yet')+ })++ it('Start is a button on the autopilot board itself: the page draws its action row only when a workflow run is selected, so a project with none could not start', () => {+ const state = stateWith([])+ const asked: { spec: { label: string } | null; why?: string }[] = []++ wireAutopilot(state, rig().host)++ const env = envOf(state, T0)++ ;(env.ctx.act as unknown as { workflows: unknown }).workflows = { ask: (spec: { label: string } | null, why?: string) => asked.push({ spec, why }) }++ const start = flat(boardRows(env)).find(el => el.kind === 'Button' && el.props.label === 'Start autopilot')++ expect(start).toBeDefined()+ ;(start?.props.onPress as () => void)()+ expect(asked[0]?.spec?.label).toContain('start autopilot "autopilot"')+ })++ it('a step in flight when the console died, whose task the store still shows in progress, is settled as lost and its task parked with a question: never waited out and retried', async () => {+ const r = rig()+ const state = stateWith([task('r1', 'in_progress'), task('r2', 'pending'), task('r3', 'pending')])++ started(r, [{ t: 'step.started', at: T0 + 10, id: 's-midflight00001', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 30 * 60_000, 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-midflight00001' && e.why.includes('lost on restart'))).toBe(true)++ // The task was left in progress by the dead session: it is parked with a question in the same pass, and nothing is handed over for it.+ expect(journal(r).find(e => e.t === 'parked' && e.task === 't1')).toMatchObject({ question: expect.stringContaining('may have run') })+ storeOf(state).spendAtMs = T0 + 2000+ await apTick(state, r.host, T0 + 2000)+ expect(r.prompts.join('\n')).not.toContain('Fix the parser bug')+ })++ it('a step that finishes after a Stop is verified on the next Start, not recorded failed from checks that were skipped while stopped', 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-afterstop000001', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 1e9, tier: 'mid' }, { t: 'stop', at: T0 + 20, reason: 'stopped by you' }])+ wireAutopilot(state, r.host)+ storeOf(state).bootMs = T0 - 1+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }+ storeOf(state).spendAtMs = T0 + 1000+ // Two passes while stopped: nothing is verified, run or remembered.+ await apTick(state, r.host, T0 + 1000)+ await apTick(state, r.host, T0 + 2000)+ expect(r.runs.some(a => a[0] === 'true')).toBe(false)+ expect(storeOf(state).verified.size).toBe(0)+ expect(journal(r).some(e => e.t === 'step.failed')).toBe(false)++ // Start again: the step is settled by running the checks, and it passes.+ const { encodeLine: line } = await import('../hooks/data/ap-journal')++ r.files.set(J, (r.files.get(J) as string) + line({ t: 'start', at: T0 + 3000, envHash: hashOf(ENV), revision: 2, anatole: 'on' }))+ storeOf(state).pin = { envHash: hashOf(ENV), starts: 2 }+ state.cache.clear()+ storeOf(state).spendAtMs = T0 + 3500+ await apTick(state, r.host, T0 + 4000)+ expect(r.runs.some(a => a[0] === 'true')).toBe(true)+ expect(journal(r).find(e => e.t === 'step.done')).toMatchObject({ id: 's-afterstop000001', verified: true })+ })++ it('an envelope of one hour reads 1 h, not 0 d', () => {+ expect(spanText(3_600_000)).toBe('1 h')+ expect(spanText(7 * 86_400_000)).toBe('7 d')+ expect(spanText(36 * 3_600_000)).toBe('2 d')+ })++ it('the permission probe is given a call the envelope allows, since the engine decides on the input (an empty probe said ask for everything and parked every task)', async () => {+ const seen: Record<string, unknown> = {}+ const answered = await preflightAll(async (tool, input) => {+ seen[tool + JSON.stringify(input)] = input++ return { decision: JSON.stringify(input) === '{}' ? 'ask' : 'allow' }+ }, { ...ENV, verify: [['node', '--test']], network: ['api.github.com'] })++ expect(answered.read).toBe('allow')+ expect(answered.edit).toBe('allow')+ expect(answered.test).toBe('allow')+ expect(answered.network).toBe('allow')+ expect(Object.values(seen)).toContainEqual({ file_path: `${CWD}/preflight-probe` })+ expect(Object.values(seen)).toContainEqual({ command: 'node --test' })+ expect(preflightInput('read', null)).toEqual({})+ // Spawn and mcp have nothing representative: they are still asked with no input, as before.+ expect(answered.spawn).toBe('ask')+ })++ it('a refused edit says why without repeating the field name', () => {+ const state = stateWith([])++ wireAutopilot(state, rig().host)+ applyAdd(draftOf(state), 'verify', 'sh -c ls')+ expect(draftOf(state).refused?.startsWith('verify commands: "sh"')).toBe(true)+ })+})+diff --git a/plugins/ruflo-console/tests/ap-live.spec.ts b/plugins/ruflo-console/tests/ap-live.spec.tsindex f237a24bea..51b2cdf7ce 100644--- a/plugins/ruflo-console/tests/ap-live.spec.ts+++ b/plugins/ruflo-console/tests/ap-live.spec.ts@@ -176,13 +176,15 @@ describe('a tick', () => {const parked = journal(r).find(e => e.t === 'parked')expect(parked).toMatchObject({ t: 'parked', task: 't2' })- expect(r.prompts).toEqual([])+ // ADR-470: a park does not hold the others back, so the same pass goes on to the next ready task (the parked one was never handed over).+ expect(r.prompts.length).toBe(1)+ expect(r.prompts[0]).toContain('Review the module')+ expect(r.prompts.join()).not.toContain('Publish the package')storeOf(state).adaptAtMs = T0 + 2000await 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 () => {@@ -304,11 +306,12 @@ describe('registration', () => {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')+ // ADR-470: no hotkeys. Digits and letters are view keys, and a slot hotkey equal to one loses to it.+ expect(slotsFor('key').find(s => s.id === 'ap-stop-key')).toBeUndefined()+ expect(slotsFor('action').find(s => s.id === 'ap-start')?.hotkey).toBeUndefined()expect(slotsFor('notice').map(s => s.id)).toContain('autopilot')- const keys = [...before, ...slotsFor('action').map(s => s.hotkey)]+ const keys = [...before, ...slotsFor('action').map(s => s.hotkey)].filter(key => key !== undefined)expect(new Set(keys).size).toBe(keys.length)resetSlots()diff --git a/plugins/ruflo-console/tests/ap-parallel.spec.ts b/plugins/ruflo-console/tests/ap-parallel.spec.tsnew file mode 100644index 0000000000..eb8b82ded7--- /dev/null+++ b/plugins/ruflo-console/tests/ap-parallel.spec.ts@@ -0,0 +1,289 @@+/**+ * ADR-470: bounded parallel hand-over, the spend reading and the band segment.+ * Pure and in-memory (the ap-rig disk and fake host). Run with+ * npx vitest run plugins/ruflo-console/tests/ap-parallel.spec.ts --testTimeout=30000+ */++import { describe, expect, it } from 'vitest'+import { apTick, storeOf, wireAutopilot } from '../hooks/ap-live'+import { pickTask, readSpend } from '../hooks/ap-pick'+import { DEFAULTS, promote } from '../hooks/data/ap-adapt'+import { hashOf, seal, type Envelope } from '../hooks/data/ap-envelope'+import { readingOf, spendSource, windowArgvs } from '../hooks/data/ap-spend'+import { startedCount } from '../hooks/data/ap-journal'+import { mcOf, nextTask, startable, type MissionRecord } from '../hooks/mission-control'+import { barParts } from '../hooks/views/bar'+import { autopilotPart } from '../hooks/views/ap-band'+import { boardRows } from '../hooks/views/ap-panel'+import type { ReadCache } from '../hooks/data/files'+import { readSnapshot } from '../hooks/data/snapshot'+import { newState } from '../hooks/state'+import { RUFLO_FILES } from './fixtures/ruflo-run'+import '../hooks/views/wf-register'+import { CWD, E, ENV, J, KILL, T0, envOf, journal, rig, started, stateWith, task, words } from './fixtures/ap-rig'++const three: MissionRecord['tasks'] = [+ { id: 'a', title: 'Fix the parser bug', phase: 'S', agent: 'coder', requirement: 'tests pass', dependsOn: [], rufloTaskId: 'ra' },+ { id: 'b', title: 'Review the module', phase: 'S', agent: 'coder', requirement: 'a summary', dependsOn: [], rufloTaskId: 'rb' },+ { id: 'c', title: 'Publish the package to npm', phase: 'A', agent: 'coder', requirement: 'it is published', dependsOn: [], rufloTaskId: 'rc' },+ { id: 'd', title: 'Update the docs', phase: 'A', agent: 'coder', requirement: 'docs say so', dependsOn: ['a'], rufloTaskId: 'rd' },+ { id: 'e', title: 'Add a test for the lexer', phase: 'A', agent: 'coder', requirement: 'a test', dependsOn: [], rufloTaskId: 're' },+]++function parallelRig(concurrency: number, parallelism: number, statuses: Record<string, string> = {}) {+ const r = rig()+ const env: Envelope = { ...ENV, concurrency, verify: [] }+ const state = stateWith(three.map(t => task(t.rufloTaskId as string, statuses[t.rufloTaskId as string] ?? 'pending')))+ const mission: MissionRecord = { ...(mcOf(state).missions.get('msn_0123456789abcdef01234567') as MissionRecord), tasks: three.map(t => ({ ...t })) }++ mcOf(state).missions.set(mission.id, mission)++ const receipt = parallelism > 1 ? promote({ id: 'par', change: { path: 'parallelism', from: '1', to: String(parallelism) }, direction: 'aggressive', reason: 'forced for the test' }, { verdict: 'supported', evidence: 'forced' }, DEFAULTS, env, 'genesis', T0) : null++ // The start line and the sealed file must name the same envelope.+ r.files.set(E, JSON.stringify(seal(env, 1, T0)))+ r.files.set(J, journalWith(r, env, receipt?.ok === true ? receipt.receipt : null))+ wireAutopilot(state, r.host)+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }+ storeOf(state).spendAtMs = T0 + 1000++ return { r, state, mission, env }+}++import { encodeLine } from '../hooks/data/ap-journal'++function journalWith(_r: ReturnType<typeof rig>, env: Envelope, receipt: unknown): string {+ const events = [{ t: 'start', at: T0, envHash: hashOf(env), revision: 1, anatole: 'on' }, ...(receipt === null ? [] : [{ t: 'adapt', at: T0 + 1, receipt }])] as Parameters<typeof encodeLine>[0][]++ return events.map(encodeLine).join('')+}++describe('bounded parallel hand-over (ADR-470 ยง2.2)', () => {+ it('hands over up to the cap in one pass, parks what the envelope forbids, and never starts a task whose dependency is not done', async () => {+ const { r, state } = parallelRig(3, 3)++ await apTick(state, r.host, T0 + 2000)++ const starts = journal(r).filter(e => e.t === 'step.started')++ expect(starts.map(e => (e as { task: string }).task)).toEqual(['a', 'b', 'e'])+ expect(r.prompts.length).toBe(3)+ expect(r.prompts.join('\n')).not.toContain('Publish the package')+ expect(r.prompts.join('\n')).not.toContain('Update the docs')+ expect(journal(r).filter(e => e.t === 'parked').map(e => (e as { task: string }).task)).toEqual(['c'])++ // The journal holds exactly one start per step, and every start came before its prompt (the journal is written first).+ for (const s of starts) expect(startedCount(r.files.get(J) as string, (s as { id: string }).id)).toBe(1)++ // A second pass starts nothing more: all three are in flight, so the cap is full.+ await apTick(state, r.host, T0 + 3000)+ expect(r.prompts.length).toBe(3)+ expect(journal(r).filter(e => e.t === 'step.started').length).toBe(3)+ })++ it('stays at one at a time when the envelope (or adaptation) says so', async () => {+ const one = parallelRig(3, 1)++ await apTick(one.state, one.r.host, T0 + 2000)+ expect(one.r.prompts.length).toBe(1)++ const capped = parallelRig(1, 1)++ await apTick(capped.state, capped.r.host, T0 + 2000)+ expect(capped.r.prompts.length).toBe(1)+ })++ it('counts tasks the store already shows running against the cap, and runs nothing past a failed task', async () => {+ const busy = parallelRig(3, 3, { ra: 'in_progress', rb: 'in_progress' })++ await apTick(busy.state, busy.r.host, T0 + 2000)+ expect(busy.r.prompts.length).toBe(1)+ expect(busy.r.prompts[0]).toContain('Add a test for the lexer')++ // Two tasks running in the store fill a cap of two even though autopilot started neither: the dependent task waits.+ const full = parallelRig(2, 2, { ra: 'completed', rb: 'in_progress', re: 'in_progress' })++ await apTick(full.state, full.r.host, T0 + 2000)+ expect(full.r.prompts).toEqual([])+ expect(journal(full.r).filter(e => e.t === 'step.started')).toEqual([])++ const failed = parallelRig(3, 3, { rb: 'failed' })++ await apTick(failed.state, failed.r.host, T0 + 2000)+ expect(failed.r.prompts).toEqual([])+ })++ it('a paused mission, a kill flag and a stopped loop hand nothing over', async () => {+ const paused = parallelRig(3, 3)++ paused.mission.paused = true+ await apTick(paused.state, paused.r.host, T0 + 2000)+ expect(paused.r.prompts).toEqual([])++ const killed = parallelRig(3, 3)++ killed.r.files.set(KILL, '')+ await apTick(killed.state, killed.r.host, T0 + 2000)+ expect(killed.r.prompts).toEqual([])+ expect(journal(killed.r).at(-1)).toMatchObject({ t: 'stop', reason: 'kill switch' })+ })++ it('startable(โฆ, 1) is the mission\'s own one-at-a-time rule; the cap only widens the running limit', () => {+ const state = stateWith([])+ const mission = { ...(mcOf(state).missions.get('msn_0123456789abcdef01234567') as MissionRecord), tasks: three.map(t => ({ ...t })) }+ const statuses = [{}, { ra: 'in_progress' }, { rb: 'failed' }, { ra: 'completed' }, { ra: 'completed', rd: 'in_progress' }] as Record<string, string>[]++ for (const s of statuses) {+ const tasks = three.map(t => task(t.rufloTaskId as string, s[t.rufloTaskId as string] ?? 'pending'))+ const next = nextTask(mission, tasks)+ // At a cap of one the first startable task is the one the mission's own rule would hand over, and none is when it hands over none.+ const first = mission.tasks.find(t => startable(mission, tasks, t, 1))++ expect(first?.id ?? null, JSON.stringify(s)).toBe(next?.id ?? null)+ }++ const running = three.map(t => task(t.rufloTaskId as string, t.id === 'a' ? 'in_progress' : 'pending'))++ expect(startable(mission, running, mission.tasks[1] as never, 1)).toBe(false)+ expect(startable(mission, running, mission.tasks[1] as never, 2)).toBe(true)+ expect(startable({ ...mission, paused: true }, running, mission.tasks[1] as never, 8)).toBe(false)+ expect(startable(mission, running, mission.tasks[3] as never, 8)).toBe(false)+ })++ it('pickTask skips parked and stepped tasks and respects the cap', () => {+ const state = stateWith(three.map(t => task(t.rufloTaskId as string, 'pending')))+ const mission = { ...(mcOf(state).missions.get('msn_0123456789abcdef01234567') as MissionRecord), tasks: three.map(t => ({ ...t })) }++ expect(pickTask(mission, state, new Set(['a']), 2)?.ledger.id).toBe('b')+ expect(pickTask(mission, state, new Set(['a', 'b', 'c', 'e']), 2)).toBeNull()+ })+})++describe('the spend reading (ADR-470 ยง2.3)', () => {+ const tracker = (version: string) => ({ snapshot: { plugins: { installed: [{ id: 'ruflo-cost-tracker@ruflo', version, installPath: '/p/tracker' }], missingFromClone: [] } } }) as never++ it('says why it cannot read, for each cause', () => {+ expect(spendSource({ snapshot: { plugins: { installed: [], missingFromClone: [] } } } as never)).toMatchObject({ kind: 'unavailable', why: expect.stringContaining('not installed') })+ expect(spendSource(tracker('0.26.0'))).toMatchObject({ kind: 'unavailable', why: expect.stringContaining('older') })+ expect(spendSource(tracker('0.27.0'))).toMatchObject({ kind: 'unavailable', why: expect.stringContaining('window filters') })+ expect(spendSource(tracker('0.27.1'))).toEqual({ kind: 'ready', root: '/p/tracker' })+ })++ it('never reaches back before the Start: the hour and day windows begin at the Start when it is newer', () => {+ const now = Date.parse('2026-10-06T12:00:00Z')+ const start = now - 10 * 60_000+ const fresh = windowArgvs('/p/tracker', start, now, '/w')+ const old = windowArgvs('/p/tracker', now - 3 * 86_400_000, now, '/w')+ const from = (argv: readonly string[] | null): string => (argv as string[])[(argv as string[]).indexOf('--from') + 1] as string++ expect(from(fresh.hour)).toBe(new Date(start).toISOString())+ expect(from(fresh.day)).toBe(new Date(start).toISOString())+ expect(from(fresh.total)).toBe(new Date(start).toISOString())+ expect(from(old.hour)).toBe(new Date(now - 3_600_000).toISOString())+ expect(from(old.day)).toBe(new Date(now - 86_400_000).toISOString())+ expect(from(old.total)).toBe(new Date(now - 3 * 86_400_000).toISOString())+ expect((fresh.hour as string[]).slice(-4)).toEqual(['--project', '/w', '--provider', 'claude'])+ expect((fresh.total as string[]).slice(-2)).toEqual(['--provider', 'claude'])+ })++ const out = (usd: number | null, extra: Record<string, unknown> = {}): string => JSON.stringify({ totals: usd === null ? {} : { usd }, rows: 4, unpriced: {}, ...extra })++ it('reads three windows into a spend, and refuses a reading it cannot trust: unpriced models, an unknown total, no answer', () => {+ expect(readingOf({ hour: out(0.1), day: out(0.5), total: out(1.5) })).toEqual({ spend: { hourUsd: 0.1, dayUsd: 0.5, totalUsd: 1.5 }, why: null })+ expect(readingOf({ hour: out(0.1), day: out(0.5, { unpriced: { 'mystery-9': { messages: 2 } } }), total: out(1.5) }).why).toContain('mystery-9')+ expect(readingOf({ hour: out(0.1), day: out(null), total: out(1.5) }).spend).toBeNull()+ expect(readingOf({ hour: 'junk', day: out(0.5), total: out(1.5) }).why).toContain('did not answer')+ })++ it('a zero-row window is a true $0, not unknown', () => {+ expect(readingOf({ hour: JSON.stringify({ totals: {}, rows: 0 }), day: JSON.stringify({ totals: {}, rows: 0 }), total: JSON.stringify({ totals: {}, rows: 0 }) }).spend).toEqual({ hourUsd: 0, dayUsd: 0, totalUsd: 0 })+ })++ it('readSpend runs the three windows, and says why when the ledger is missing or errors; the loop waits and says why', async () => {+ const r = rig()+ const state = stateWith([])++ state.snapshot = { ...(state.snapshot as object), plugins: { installed: [{ id: 'ruflo-cost-tracker@ruflo', version: '0.27.1', installPath: '/p/tracker' }], missingFromClone: [] } } as never+ r.host.run = (async (argv: readonly string[]) => ({ exitCode: 0, stdout: out(argv.includes('--from') ? 0.25 : 9), stderr: '' })) as never++ const ok = await readSpend(state, r.host, T0, T0 + 5000)++ expect(ok.spend).toEqual({ hourUsd: 0.25, dayUsd: 0.25, totalUsd: 0.25 })++ r.host.run = (async () => ({ exitCode: 2, stdout: '', stderr: 'ledger: bad' })) as never+ expect((await readSpend(state, r.host, T0, T0 + 5000)).why).toContain('error')++ const none = stateWith([])+ const waiting = rig()++ started(waiting)+ wireAutopilot(none, waiting.host)+ await apTick(none, waiting.host, T0 + 1000)+ expect(storeOf(none).status).toContain('waiting: spend not read: the ruflo-cost-tracker plugin is not installed')+ expect(waiting.prompts).toEqual([])+ expect(words(boardRows(envOf(none, T0 + 1000)))).toContain('ledger not read: the ruflo-cost-tracker')+ })++ it('the panel says what the figure is once it is read', () => {+ const state = stateWith([])++ wireAutopilot(state, rig().host)+ storeOf(state).spend = { hourUsd: 0.1, dayUsd: 0.2, totalUsd: 0.3 }+ expect(words(boardRows(envOf(state, T0)))).toContain('every Claude Code turn in this project since Start')+ })+})++const memoryFs = (files: Record<string, string>) => ({+ read: async (path: string) => files[path] ?? Promise.reject(new Error('ENOENT')),+ stat: async (path: string) => (files[path] !== undefined ? { mtimeMs: 1, size: files[path].length } : Promise.reject(new Error('ENOENT'))),+ list: async () => Promise.reject(new Error('ENOENT')),+})++/** A console state with a real snapshot (the band reads alerts from it), cwd at the rig's folder. */+async function bandState() {+ const state = newState({})++ state.snapshot = await readSnapshot(memoryFs(Object.fromEntries(Object.entries(RUFLO_FILES).map(([path, text]) => [`/work/${path}`, text]))), new Map() as ReadCache, '/work', '/home/dev', {}, 0)+ state.cwd = CWD++ return state+}++describe('the band segment (ADR-470 ยง2.4)', () => {+ it('draws nothing before autopilot starts, then the exact band text, and $n/a until the spend is read', async () => {+ const r = rig()+ const state = await bandState()++ wireAutopilot(state, r.host)+ await new Promise(resolve => setTimeout(resolve, 10)) // wiring reads the (then missing) files in the background+ expect(autopilotPart(state, T0)).toBeNull()+ expect(barParts(state, T0).some(p => p.text.startsWith('autopilot'))).toBe(false)++ started(r, [{ t: 'parked', at: T0 + 1, id: 'p-1', task: 't2', question: 'q' }, { t: 'parked', at: T0 + 2, id: 'p-2', task: 't3', question: 'q' }])+ state.cache.clear() // wiring read the (then missing) files in the background+ await (await import('../hooks/ap-live')).refreshAutopilot(state, r.host, T0 + 2 * 86_400_000)++ const unread = barParts(state, T0 + 2 * 86_400_000).find(p => p.text.startsWith('autopilot'))++ expect(unread?.text).toBe('autopilot day 3 ยท $n/a/$40 ยท 2 parked')+ expect(unread?.text).not.toContain('$0')+ expect(unread?.tone).toBe('attention')+ expect(unread?.go).toBe('workflows')++ storeOf(state).spend = { hourUsd: 1, dayUsd: 5, totalUsd: 12 }+ expect(barParts(state, T0 + 2 * 86_400_000).find(p => p.text.startsWith('autopilot'))?.text).toBe('autopilot day 3 ยท $12/$40 ยท 2 parked')+ })++ it('says paused when paused, and a failing source cannot blank the band', async () => {+ const r = rig()+ const state = await bandState()++ started(r, [{ t: 'pause', at: T0 + 1, reason: 'x' }])+ wireAutopilot(state, r.host)+ await (await import('../hooks/ap-live')).refreshAutopilot(state, r.host, T0 + 1000)+ expect(autopilotPart(state, T0 + 1000)?.text).toContain('autopilot paused day 1')+ expect(autopilotPart(state, T0 + 1000)?.tone).toBe('attention')+ expect(barParts(state, T0 + 1000).some(p => p.text.startsWith('autopilot paused'))).toBe(true)+ })+})+diff --git a/plugins/ruflo-console/tests/ap-review.spec.ts b/plugins/ruflo-console/tests/ap-review.spec.tsindex 603ac6f5e7..1d46e8a8be 100644--- a/plugins/ruflo-console/tests/ap-review.spec.ts+++ b/plugins/ruflo-console/tests/ap-review.spec.ts@@ -218,7 +218,7 @@ describe('what adaptation learns', () => {})describe('the panel', () => {- it('has one Stop key: the key slot owns 9 and the board button carries none, so a press cannot run it twice', () => {+ it('the Stop button carries no hotkey (the digits are view keys), so no key can open another page instead of stopping', () => {const r = rig()const state = stateWith([])diff --git a/plugins/ruflo-console/tests/wf-merge.spec.ts b/plugins/ruflo-console/tests/wf-merge.spec.tsindex a34bc86ca1..0d0e638dd4 100644--- a/plugins/ruflo-console/tests/wf-merge.spec.ts+++ b/plugins/ruflo-console/tests/wf-merge.spec.ts@@ -30,7 +30,7 @@ describe('registration', () => {expect(slotsFor('key').find(s => s.key === 't')?.id).toBe('wf-template-next')expect(slotsFor('action').find(s => s.hotkey === 'g')?.id).toBe('wf-template-launch')expect(slotsFor('key').filter(s => s.id.startsWith('drill-')).length).toBe(8)- const hotkeys = slotsFor('action').map(s => s.hotkey)+ const hotkeys = slotsFor('action').flatMap(s => (s.hotkey === undefined ? [] : [s.hotkey]))expect(hotkeys).toEqual(expect.arrayContaining(['c', 'g']))expect(new Set([...keys, ...hotkeys]).size).toBe(keys.length + hotkeys.length)diff --git a/v3/docs/adr/ADR-470-autopilot-completion-and-live-run.md b/v3/docs/adr/ADR-470-autopilot-completion-and-live-run.mdnew file mode 100644index 0000000000..fa07f735e0--- /dev/null+++ b/v3/docs/adr/ADR-470-autopilot-completion-and-live-run.md@@ -0,0 +1,171 @@+# ADR 470: Autopilot completion, and the first live run++Status: Accepted++Date: 2026-10-06++Builds on: ADR-466 (mission autopilot), ADR-467 (security audit), ADR-443 (mission control), ADR-437 (cost ledger)++## 1. Context++ADR-466 shipped the loop with five things outstanding (an in-console editor for the envelope's lists, hand-over of more than one task at+a time, a spend reading that is not the whole project at list price, a band segment that was computed but never drawn, and a decision on+ruflo's own `autopilot_*` tools) and with one gap that mattered more than any of them: it had never run in a live interactive session.+All of its tests were pure. This ADR closes the five and records the first live run, which found seven defects the tests could not.++## 2. Decision++### 2.1 Envelope list editor (`data/ap-edit.ts`, `views/ap-editor.ts`, `views/ap-draft.ts`)++Folders, repos, network hosts, secret variable names and verify commands are each a list of rows with a remove button and one field to+add an entry, on the draft the panel's buttons already change. There is **no validator of its own**: an edit is accepted only if the+result raises no error the draft did not already have under `validateEnvelope`, the function the sealed file is opened with. So the verify+argv rules (`verifyProblem`), host, repo and variable regexes, the protected folders, the path rules and every limit apply to an edit+exactly as to a load, and a rule added to the validator later reaches the editor with no change. A refused edit changes nothing and shows+the validator's reason. Removing the last folder is refused for the same reason (the draft would stop validating). A verify entry is split+on spaces; quotes and backslashes are refused rather than half-interpreted (there is no shell). Below the lists the draft is shown as a+diff against the approved envelope (`+` widens, from `widened`; `-` narrows, from the new `narrowed`; `same`), and the verify commands in+full. Start is unchanged: it asks, and its card lists the exact argv, repos, hosts and variable names and what the change WIDENS. The+fields are `kit.Input` with `onSubmit`, as `startField` is (the palette's `field()` routes through confirm-gated writes; a draft edit is+not a write). Every figure the editor draws comes from the draft; nothing is granted until a confirmed Start seals it.++### 2.2 Parallel hand-over (`hooks/ap-pick.ts`, `startable` in `mission-control.ts`)++`tick` stays pure and still starts at most one step per call. `apTick` now goes round up to the cap: decide, journal, re-check, hand over,+and again while there is room. The cap is `min(envelope.concurrency, tunables.parallelism)`, so adaptation still starts at one and may+only raise it (aggressive change, with a trial) up to the envelope. After a park the loop goes on to the next task in the same pass, so a+parked task no longer holds the others back for a minute. Every round repeats the safety checks (kill flag, phase, exactly one `start`+line in the journal for the step) before its hand-over.++The mission's rules are kept, not copied: the one exported addition is `startable(mission, tasks, task, cap)`, which is `nextTask`'s+rule (not paused or cancelled, **nothing failed**, the task ready because its dependencies are done and it is in the task store) with the+running limit raised from one to `cap`. Tasks the store shows running AND tasks handed over seconds ago (the store has not refreshed) count+against it. `dispatchSpec` gains an optional last parameter, a readiness predicate defaulting to the mission's own `nextTask` check, so+`Run next` and auto-run are byte-for-byte as before (`startable(โฆ, 1)` is proven equal to `nextTask` over a table of states). The old+"shadow mission with the picked task first" is gone. **Two prompts into one interactive session are queued turns, not parallel work**+unless the step spawns agents itself; the cap bounds what is handed over and in flight, not wall-clock speed-up.++### 2.3 Spend (`data/ap-spend.ts`)++The ledger (`ledger.mjs`) filters by time window and project; it has **no per-session or per-process filter**, so a precise+"this loop's spend" is not readable, and the tracker is not ours to change. What is made exact:++- A window never reaches back past the Start (`hour = max(now - 1h, start)`, same for the day): a loop started ten minutes ago no longer+ counts the fifty minutes before it.+- The reading is `--provider claude` only. Autopilot hands prompts to this Claude Code session, so Codex rows are irrelevant to it and only slow the ledger down. (A manual probe without `--from` read all history of both providers and overflowed the ledger's stack on this machine's Codex history; the loop always passes `--from`, so it was never exposed to that.)+- A model with no list price makes the reading unknown (it would under-count a ceiling), as does an unparsed or erroring window.+- The tracker must be new enough for the window filters (0.27.1). The old code asked a 0.27.0 tracker for `--from`, which exits 2; this+ machine's installed tracker IS 0.27.0, so on it the loop would have waited on an unread spend forever, silently.++Still estimated, and now said so wherever it is drawn: "estimate at list price: every Claude Code turn in this project since Start, yours+too (the ledger has no per-session reading)". It is the figure the ceilings are enforced on, and it over-counts. When it cannot be read the+loop keeps waiting (never guessing) and says why: `waiting: spend not read: the ruflo-cost-tracker plugin is not installed`, in the+status line and the panel.++### 2.4 Band segment (`views/ap-band.ts`, `registerBarSource` in `views/bar.ts`)++`bar.ts` gets ONE exported function, `registerBarSource`, and one call site in `barParts` (a source that throws is skipped; nothing else in+the file changed). `autopilot day 3 ยท $12/$40 ยท 2 parked` is drawn on the band's first row after the mission part, from the journal, the+sealed envelope and the spend reading; `$n/a` until the spend is read, nothing while autopilot has never started, `paused` in the text and+the attention colour when paused or when something is parked. A click opens Workflows. The band only draws in a ruflo project unless+`/ruflo band on`.++### 2.5 ruflo's `autopilot_*` tools: not used, with evidence++Probed on this machine, 2026-10-06 18:12 local, through the registered MCP tools:++```+autopilot_status -> {"enabled": true, "sessionId": "05d83b08-โฆ", "iterations": 0, "maxIterations": 50, "timeoutMinutes": 240,+ "elapsedMs": 7443277535, "tasks": {"completed": 0, "total": 0, "percent": 100}, "taskSources": [...]}+autopilot_progress -> {"overall": {"completed": 0, "total": 0, "percent": 100}, "bySource": {}}+autopilot_log -> [{"ts": 1783881469131, "event": "enabled", "sessionId": "05d83b08-โฆ"}] (one entry, July)+```++`elapsedMs` is 86 days: a stale session record, the same finding as ADR-466 ยง1, unchanged. 0 of 0 reads as 100%. And `autopilot_log` takes+only `last`; none of the four tools accepts a step outcome, so "log the loop's outcomes through them" is not even possible. What they offer+beyond reading is `autopilot_enable`, which re-engages agents when tasks remain incomplete: a **second authority that acts outside the+envelope**. Decision: the loop neither reads nor writes them. Its own journal (append-only, masked, pinned) is the audit log.++## 3. The live run++Method: a throwaway repo `/tmp/ap-live`, an interactive `claude --model haiku --plugin-dir โฆ/ruflo-console` in a private tmux server with an+isolated config (credentials copied 0600, shredded at the end), the ruflo MCP server passed with `--mcp-config` so the session could call+`task_complete`, permissions `acceptEdits` plus `Bash(node --test:*)` and `mcp__ruflo__*` (nothing else allowed), a mission of four seeded+tasks (implement `add`, a notes file at `/tmp/other/notes.txt`, a test, run the tests), and an envelope of read/edit/test, folder+`/tmp/ap-live`, no network, no secrets, $1 a run, one at a time, accept-running-without-Anatole, verify `node --test` (added through the+pane's own editor field). The duration is one hour, not 30 minutes: 1 h is the validator's minimum. Everything outside `/tmp/ap-live` and+the isolated config stayed untouched; `/tmp/other` was never created.++What was observed, in three runs (journals kept in the scratchpad):++| Step | Observed |+|---|---|+| Editor | `sh -c ls` refused with the validator's reason, `node --test` accepted; "Start will run โฆ node --test" drawn. |+| Start | A confirm card listed the envelope hash, classes, folder, network none, `$1/h $1/day $1 total`, one at once, the verify command, Anatole accepted. Nothing started before Yes. |+| Hand-over | The step was journaled (`step.started`) before the prompt reached the session; haiku wrote the files, ran `node --test`, called `task_complete` through the MCP server. |+| Verify | The next tick ran `node --test` through the console: `step.done verified:true`. |+| Parking | The task naming `/tmp/other/notes.txt` was `parked` with a question (outside the envelope), the loop went on to the next task in the same pass, and the file was never created. |+| Stop | The Stop button mid-step: `stop` in the journal and the `KILL` file within 0.2 s, no further prompt for 100 s while the in-flight turn finished. |+| KILL flag | `touch KILL` with a running loop: `stop: kill switch` journaled 49 s later (one 60 s tick). |+| Resume | Closed and reopened the session: the loop read `running` from the journal and the pin, settled the in-flight step by its effect (`done verified:true`) and did not run it twice. |+| Kill -9 mid-step | Killed the `claude` process one second after the hand-over of the third task; after relaunch the step was settled `lost on restart`, its task **parked with a question**, and no prompt was sent. After the task was set back to pending and approved once, the retry ran and verified. |+| Spend | Read live ($0/$1, then $0.03/$1), and equal to the ledger run over the isolated config's own logs. |+| Band | `autopilot day 1 ยท $0.03/$1 ยท 2 parked` on the band (after `/ruflo band on`). |++Real spend, from the ledger over the isolated config at list price: run 1 $0.075, run 2 $0.173, run 3 $0.108, **$0.356 in total** (cap+$1.50), all `claude-haiku-4-5`.++### Defects the run found, each fixed with a regression test (`tests/ap-complete.spec.ts`, `tests/ap-parallel.spec.ts`)++1. **The Start key `8` and Stop key `9` never worked.** Every digit and letter is a view's key (8 is MetaHarness, 9 is Memory) and a slot+ hotkey that equals one loses to it: pressing 9 opened Memory and wrote no KILL file. The registry only checks slot against slot. Both+ hotkeys are gone; Stop is a button and `/ruflo autopilot stop`. (A test now fails if an autopilot slot takes a view key.)+2. **Start was unreachable in a project with no workflow run.** The page draws its action row only when a run is selected. Start is now a+ button on the autopilot board itself.+3. **The permission probe asked the engine with no input, which answers `ask` for everything**: with `acceptEdits` and the test command+ allowed, Read, Edit and Bash all said ask and every task was parked. The probe now carries a call the envelope allows (a file in its+ first folder, its first verify command, a host from its list; with no verify command or host to use, a class is asked with no input, as before).+4. **A step that finished after a Stop was recorded failed on the next Start.** A stopped loop still computed effects; its verify commands+ were skipped as "stopped" and counted as failures, and the failure was cached for the process. A stopped or killed loop now verifies+ nothing and remembers nothing; a stop pressed mid-list ends it without a result.+5. **A step in flight when the console died, whose task the store still showed in progress, was waited out to its 30 minute deadline and+ then retried without a question** (the lost-step rule only covered "no effect found"). It is now settled at once and its task parked with+ a question that says what to do (found by reading the run's restart; the live relaunch then confirmed the new behaviour).+6. **The panel said "your settings allow every class" before the first check had run.** It now says "not checked yet".+7. Smaller: a one-hour envelope read "0 d"; a refused edit repeated the field name; the spend reading could fail for good on this machine+ (ยง2.3).++### Found in other lanes, not touched++`views/wf-page.ts` draws the action row only when a run is selected, so every action slot (worktree clean, template launch, Stop) is absent+in a project with no run. The worktree key `w` and template key `t`, and the action hotkeys `c` and `g`, are also view keys (x.ruv.io,+Self-Evolution, Cost, Timeline), so they have the same defect as 1. `tests/wf-merge.spec.ts` needed a one-line change (a second slot without+a hotkey collapsed a `Set`); nothing else there.++## 4. Unverified++- **Parallel hand-over was not run live**: the live envelope was one at a time, as specified. It is covered by the specs (cap, running+ and in-flight counts, dependencies, a failed task, pause, kill) but two concurrent turns in one interactive session were never watched,+ and they are queued turns anyway (ยง2.2).+- The spend figure was checked against the ledger over the isolated config's logs, but only for a session that was the whole project.+ "Yours too" is by construction, not observed.+- Only one model (haiku) and one engine permission set were exercised; the real settings of a person with deny rules were not.+- The `/ruflo autopilot stop|pause|resume` command and the notice slot (toasts) were not driven; the band and the buttons were.+- `tsc --noEmit -p plugins/ruflo-console` (16 GB heap; Claude Code wrote the type declarations on load): every error in the files this change touches or adds is fixed; 12 remain, all in code this change did not write (`snapshot.ts`, `mission-control.ts` line 260 (MissionActions), `mission-list.ts`, `model-tools.ts`, `register.ts`, `spinner.ts`, `bar.ts` line 45, and test files `anatole`, `band`, `memmap`, `ap-review` line 120).+- Spend ceilings (80% pause, 100% stop, the hour and day holds) were never approached: $0.36 against a $1 envelope. The Anatole pause gate was never exercised (the envelope accepted running without it). When a workflow run is selected, Start appears twice (the action row and the board); both are confirm-gated, so no double run, but this was not observed.+ Claude Code 2.1.289 and `claude plugin validate` passes.+- Adaptation ran no live proposal (it needs 6 to 12 verified steps).++## 5. Test plan++`tests/ap-complete.spec.ts` (editor and the live findings) and `tests/ap-parallel.spec.ts` (parallel, spend, band): 29 tests. Mutation checks, each+turned its test red: the editor's validator call, `startable`'s failed-task rule, the cap in `startable` and in the pass, the window+clamp, the stop guards in the verifier (both together), the lost-step rule, the permission probe's input, a hotkey on the Start slot, the+"not checked yet" text, the unpriced-model rule, the band's empty case. Existing autopilot, security and mission specs are unchanged except+three lines in `ap-live.spec.ts` / `ap-review.spec.ts` that asserted the old hotkeys and that a park used a whole tick, and one in+`wf-merge.spec.ts`. Console suite: 1912 passed, 3 skipped; smoke 16/16.++## 6. Rollback++Revert the commit. The new modules are inert without their imports (`views/ap-band.ts` registers one bar source; `views/ap-editor.ts` is+drawn by the panel). `dispatchSpec`'s new parameter is optional and `startable` is only called by autopilot.