Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

fix(console): autopilot adversarial review - stop wins races and a full disk, sleep/clock-safe timeouts, envelope checks every path/host/repo, deny is not liftable, narrow-width rows, verify commands on the confirm card (ADR-466)

ruv7fbb4569696c
diff --git a/plugins/ruflo-console/hooks/ap-live.ts b/plugins/ruflo-console/hooks/ap-live.ts
index 79ef7fba25..66df4a9db2 100644
--- a/plugins/ruflo-console/hooks/ap-live.ts
+++ b/plugins/ruflo-console/hooks/ap-live.ts
@@ -19,7 +19,7 @@ import { trackerOf } from './data/cost-ledger'
import { evaluate, outcomesOf, promote, propose, reviewTrials, tierOf, tunablesFrom, lastHash } from './data/ap-adapt'
import { AUTOPILOT_DIR, ENVELOPE_FILE, KILL_FILE, open, type Envelope, type Sealed, type Spend } from './data/ap-envelope'
import { anatoleFact, classifyTask, effectOf, killSeen, preflightAll, spendArgvs, spendOf, type ToolCheck } from './data/ap-guard'
-import { appendArgv, encodeLine, JOURNAL_FILE, JOURNAL_MAX_BYTES, parseJournal, touchArgv, type JournalEvent } from './data/ap-journal'
+import { appendArgv, encodeLine, JOURNAL_FILE, JOURNAL_MAX_BYTES, parseJournal, REFUSED_WHY, touchArgv, type JournalEvent } from './data/ap-journal'
import { digestText, emptyLoop, foldJournal, skipSet, snapshotEvents, tick, type EffectFact, type Facts, type LoopState, type TaskFact } from './data/ap-loop'
import type { Preflight } from './data/ap-loop'
import type { NoticeDraft } from './notices'
@@ -29,6 +29,8 @@ const SPEND_EVERY_MS = 120_000
const ADAPT_EVERY_MS = 600_000
const PREFLIGHT_EVERY_MS = 60_000
const STEP_TIMEOUT_MS = 30 * 60_000
+/** A gap between ticks this long is a sleeping machine, not a slow tick. */
+const SLEEP_GAP_MS = 3 * TICK_MS
export type Store = {
sealed: Sealed | null
@@ -52,6 +54,11 @@ export type Store = {
verified: Map<string, EffectFact>
chain: Promise<unknown>
isTimerOn: boolean
+ /** A stop that reached neither the journal nor the flag file (a full disk): held in memory so the next read cannot undo it. */
+ heldStop: string | null
+ lastTickMs: number
+ /** Time each in-flight step is forgiven for the machine having slept, by step id. */
+ slack: Record<string, number>
}
const stores = new WeakMap<State, Store>()
@@ -63,7 +70,7 @@ export const activeOf = (): State | null => active
const checks = new WeakMap<State, ToolCheck | undefined>()
-export const storeOf = (state: State): Store => stores.get(state) ?? stores.set(state, { sealed: null, envWhy: null, loop: emptyLoop(), badLines: 0, journalBytes: 0, spend: null, spendAtMs: 0, killed: false, status: 'not wired', preflight: {}, preflightAtMs: 0, hasCheck: false, adaptAtMs: 0, bootMs: Date.now(), isTicking: false, error: null, readAtMs: 0, notices: [], verified: new Map(), chain: Promise.resolve(), isTimerOn: false }).get(state)!
+export const 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, heldStop: null, lastTickMs: 0, slack: {} }).get(state)!
export const hostOf = (state: State): Host | undefined => hosts.get(state)
@@ -119,7 +126,9 @@ export async function refreshAutopilot(state: State, host: Host, nowMs: number =
store.error = null
}
- store.killed = await killSeen(host.fs, state.cwd)
+ store.killed = (await killSeen(host.fs, state.cwd)) || store.heldStop !== null
+
+ if (store.heldStop !== null && store.loop.phase !== 'idle' && store.loop.phase !== 'stopped') store.loop = foldJournal([{ t: 'stop', at: nowMs, reason: store.heldStop }], store.loop)
store.readAtMs = nowMs
} catch {
store.error = 'the autopilot files were not read'
@@ -199,11 +208,12 @@ export async function stopNow(state: State, host: Host, reason = 'stopped by you
host.invalidate()
const clear = await checkNoLinks(host.fs, flag, { cwd: state.cwd }, { allowExisting: true }).catch(() => ({ ok: false as const, why: 'unchecked' }))
+ const flagged = clear.ok ? await host.run(touchArgv(flag), 10_000).then(result => result.exitCode === 0, () => false) : false
+ const journaled = await appendEvents(state, host, [{ t: 'stop', at: Date.now(), reason }])
- if (clear.ok) await host.run(touchArgv(flag), 10_000).catch(() => undefined)
-
- await appendEvents(state, host, [{ t: 'stop', at: Date.now(), reason }])
- say(state, host, { level: 'warn', text: `autopilot stopped: ${reason}`, key: 'ap-stop', go: 'missions' })
+ // Neither write landed (a full disk, a read-only folder): the stop is held in memory so a re-read of the files cannot undo it, and it is said.
+ if (!flagged && !journaled) store.heldStop = reason
+ say(state, host, { level: 'warn', text: flagged || journaled ? `autopilot stopped: ${reason}` : `autopilot stopped in this session only: the stop could not be written (${reason})`, key: 'ap-stop', go: 'missions' })
}
export async function pauseNow(state: State, host: Host, reason = 'paused by you'): Promise<void> {
@@ -220,7 +230,11 @@ export async function answerParked(state: State, host: Host, id: string, answer:
}
/** Clears the kill flag; part of the confirmed start, never a button of its own. */
-export const clearKill = (state: State, host: Host): Promise<unknown> => host.run(removeFileArgv(pathOf(state, KILL_FILE)), 10_000).catch(() => undefined)
+export function clearKill(state: State, host: Host): Promise<unknown> {
+ storeOf(state).heldStop = null
+
+ return host.run(removeFileArgv(pathOf(state, KILL_FILE)), 10_000).catch(() => undefined)
+}
/** Writes the sealed envelope (replacing the file). Only the confirmed start/change calls this. */
export async function writeEnvelope(state: State, host: Host, sealed: Sealed): Promise<boolean> {
@@ -283,7 +297,8 @@ async function effectsOf(state: State, host: Host, loop: LoopState, mission: Mis
let ran = 0
let failed = 0
- for (const argv of env.verify) {
+ // The envelope's verify commands run through the console, not the engine: where the person's settings deny the test class they are not run (the step is then unverified).
+ for (const argv of store.preflight.test === 'deny' ? [] : env.verify) {
ran += 1
const result = await host.run(argv, 10 * 60_000).catch(() => ({ exitCode: 1 }))
@@ -311,6 +326,15 @@ export async function apTick(state: State, host: Host, nowMs: number = Date.now(
try {
await refreshAutopilot(state, host, nowMs)
+ // A long gap since the last pass is a machine that slept: steps in flight are forgiven that time before they can count as timed out.
+ const gap = store.lastTickMs > 0 ? nowMs - store.lastTickMs : 0
+
+ store.lastTickMs = nowMs
+
+ if (gap > SLEEP_GAP_MS) for (const step of store.loop.steps.filter(entry => entry.status === 'started')) store.slack[step.id] = (store.slack[step.id] ?? 0) + gap
+
+ if (store.heldStop !== null && store.loop.phase === 'stopped' && (await appendEvents(state, host, [{ t: 'stop', at: nowMs, reason: store.heldStop }]))) store.heldStop = null
+
const loop = store.loop
if (loop.phase === 'idle') {
@@ -355,16 +379,20 @@ export async function apTick(state: State, host: Host, nowMs: number = Date.now(
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,
}
- const decision = tick(loop, facts)
+ 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
// The decision is journaled BEFORE the step is handed over: a crash between the two leaves a started step that the next pass settles by its effect, never a step that ran unrecorded.
const wrote = await appendEvents(state, host, decision.events)
- for (const event of decision.events) {
+ 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' })
}
@@ -375,7 +403,7 @@ export async function apTick(state: State, host: Host, nowMs: number = Date.now(
await dispatchSpec(state, host, shadow, picked.ledger, body => host.submitPrompt(body)).run?.()
// The dispatch refuses (and says so in the mission view) when the mission moved; that is a step that never started, not a failure to learn from.
- if (decision.act !== null && (picked.ledger.dispatchedAtMs ?? 0) < nowMs - 1000) await appendEvents(state, host, [{ t: 'step.failed', at: Date.now(), id: decision.act.id, why: 'the mission refused the hand-over' }])
+ if (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 (env !== null && tunables !== null && store.loop.phase === 'running' && nowMs - store.adaptAtMs >= ADAPT_EVERY_MS) {
@@ -406,7 +434,7 @@ async function adaptPass(state: State, host: Host, env: Envelope, nowMs: number)
const current = tunablesFrom(store.loop.receipts, env)
const prev = lastHash(store.loop.receipts)
const reverts = reviewTrials(store.loop.receipts, outcomes)
- const candidate = reverts[0] ?? propose(outcomes, current, env).find(p => evaluate(p, outcomes, current).verdict === 'supported')
+ const candidate = reverts[0] ?? propose(outcomes, current, env, store.loop.receipts).find(p => evaluate(p, outcomes, current).verdict === 'supported')
if (candidate === undefined) return
@@ -418,15 +446,23 @@ async function adaptPass(state: State, host: Host, env: Envelope, nowMs: number)
/** Archives the journal and starts a new one from its snapshot, so weeks of running stay readable. The old file is kept beside it. */
async function rotate(state: State, host: Host, nowMs: number): Promise<void> {
+ const store = storeOf(state)
const path = pathOf(state, JOURNAL_FILE)
const archive = `${path}.${new Date(nowMs).toISOString().replace(/[^0-9]/g, '').slice(0, 14)}`
- const lines = snapshotEvents(storeOf(state).loop).map(encodeLine).join('')
- if (lines === '') return
+ // Inside the write chain, so a stop or pause pressed meanwhile lands before the snapshot is taken and cannot be lost to the replace.
+ const job = store.chain.then(async () => {
+ const lines = snapshotEvents(store.loop).map(encodeLine).join('')
+
+ if (lines === '') return
- const copied = await host.run(['cp', '--no-clobber', '--', path, archive], 30_000).catch(() => ({ exitCode: 1 }))
+ const copied = await host.run(['cp', '--no-clobber', '--', path, archive], 30_000).catch(() => ({ exitCode: 1 }))
- if (copied.exitCode === 0) await storeOf(state).chain.then(() => host.run(replaceFileArgv(path, true), 10_000, lines)).catch(() => undefined)
+ if (copied.exitCode === 0) await host.run(replaceFileArgv(path, true), 10_000, lines).catch(() => undefined)
+ })
+
+ store.chain = job.catch(() => undefined)
+ await store.chain
}
export { AUTOPILOT_DIR }
diff --git a/plugins/ruflo-console/hooks/data/ap-adapt.ts b/plugins/ruflo-console/hooks/data/ap-adapt.ts
index a4d24dfccc..05a46b73c6 100644
--- a/plugins/ruflo-console/hooks/data/ap-adapt.ts
+++ b/plugins/ruflo-console/hooks/data/ap-adapt.ts
@@ -13,7 +13,7 @@
* finished without a verified effect are neither success nor failure here: an unverified step teaches nothing.
*/
import { canonical, sha256, type Envelope } from './ap-envelope'
-import type { Receipt } from './ap-journal'
+import { REFUSED_WHY, type Receipt } from './ap-journal'
import type { StepRec } from './ap-loop'
export const TIERS = ['low', 'mid', 'high'] as const
@@ -92,6 +92,8 @@ export function outcomesOf(steps: readonly StepRec[]): Outcome[] {
const ok = step.status === 'done' && step.verified === true
if (!ok && step.status !== 'failed') return []
+ // A hand-over the mission refused never ran: it says nothing about the setting it was started under.
+ if (step.status === 'failed' && step.why === REFUSED_WHY) return []
return [{ at: step.endedAt ?? step.startedAt, cls: step.cls, tier: step.tier, par: step.par ?? 1, attempt: step.attempt, ok, durationMs: Math.max(0, (step.endedAt ?? step.startedAt) - step.startedAt) }]
})
@@ -105,7 +107,7 @@ const pct = (n: number): string => `${Math.round(n * 100)}%`
const nextTier = (tier: string, step: 1 | -1): Tier | null => TIERS[(TIERS as readonly string[]).indexOf(tier) + step] ?? null
/** What the measured outcomes suggest, as proposals only. Nothing is applied here. */
-export function propose(outcomes: readonly Outcome[], t: Tunables, env: Envelope): Proposal[] {
+export function propose(outcomes: readonly Outcome[], t: Tunables, env: Envelope, receipts: readonly Receipt[] = []): Proposal[] {
const out: Proposal[] = []
const classes = [...new Set(outcomes.map(o => o.cls))]
@@ -131,7 +133,10 @@ export function propose(outcomes: readonly Outcome[], t: Tunables, env: Envelope
if (retried.length >= MIN_SAMPLES && 1 - rate(retried) >= 0.6 && t.retries < RANGE.retries[1]) out.push({ id: `retries-${t.retries + 1}`, change: { path: 'retries', from: String(t.retries), to: String(t.retries + 1) }, direction: 'conservative', reason: `${pct(1 - rate(retried))} of retried steps succeed` })
- return out.filter(p => applyChange(t, p.change) !== null)
+ // A setting a trial was reverted away from is not tried again: the old clean history that proposed it is the very history the trial contradicted.
+ const reverted = new Set(receipts.filter(r => r.id.startsWith('revert-')).map(r => `${r.path}=${r.from}`))
+
+ return out.filter(p => applyChange(t, p.change) !== null && !(p.direction === 'aggressive' && reverted.has(`${p.change.path}=${p.change.to}`)))
}
/** Replays the proposal over what the journal holds: does the evidence about the setting being left support leaving it? */
diff --git a/plugins/ruflo-console/hooks/data/ap-guard.ts b/plugins/ruflo-console/hooks/data/ap-guard.ts
index 85975644d4..27ad2a4cdb 100644
--- a/plugins/ruflo-console/hooks/data/ap-guard.ts
+++ b/plugins/ruflo-console/hooks/data/ap-guard.ts
@@ -35,6 +35,14 @@ const CLASS_WORDS: readonly [ToolClass, RegExp][] = [
// eslint-disable-next-line no-control-regex
const PATH = /(?:^|[\s"'`(])(\/(?:[A-Za-z0-9._@-]+\/)*[A-Za-z0-9._@-]+)/
+const PATHS = new RegExp(PATH.source, 'g')
+const URLS = /\bhttps?:\/\/([A-Za-z0-9.-]{1,253})(?::\d+)?((?:\/[A-Za-z0-9._~%@-]*){0,3})/gi
+
+const repoOf = (urlPath: string): string | null => {
+ const match = /^\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)/.exec(urlPath)
+
+ return match === null ? null : `${match[1]}/${(match[2] as string).replace(/\.git$/, '')}`
+}
/** A task's text as the facts the loop needs. The class is the most privileged one the words suggest; none is `null`, never a default. */
export function classifyTask(id: string, title: string, requirement = ''): TaskFact {
@@ -42,9 +50,12 @@ export function classifyTask(id: string, title: string, requirement = ''): TaskF
const hardDeny = DENIES.find(([, pattern]) => pattern.test(text))?.[0] ?? null
const hits = CLASS_WORDS.filter(([, pattern]) => pattern.test(text)).map(([cls]) => cls)
const cls = hits.length === 0 ? null : (hits.at(-1) as ToolClass)
- const path = PATH.exec(text)?.[1] ?? null
+ const found = [...text.matchAll(PATHS)].map(match => match[1] as string)
+ const urls = [...text.matchAll(URLS)]
+ const hosts = [...new Set(urls.map(match => (match[1] as string).toLowerCase()))].slice(0, 8)
+ const repos = [...new Set(urls.flatMap(match => ((match[1] as string).toLowerCase() === 'github.com' ? [repoOf(match[2] as string)] : []).filter((name): name is string => name !== null)))].slice(0, 8)
- return { id, title: title.slice(0, 160), cls, hardDeny, path }
+ return { id, title: title.slice(0, 160), cls, hardDeny, path: found[0] ?? null, ...(found.length > 1 && { paths: [...new Set(found.slice(1))].slice(0, 8) }), ...(hosts.length > 0 && { hosts }), ...(repos.length > 0 && { repos }) }
}
/** Anatole's state for the gate: `on` only when its status says a mode other than off, `off` when it says off, else `absent`. */
diff --git a/plugins/ruflo-console/hooks/data/ap-journal.ts b/plugins/ruflo-console/hooks/data/ap-journal.ts
index 8a038ebca7..4431ba70ba 100644
--- a/plugins/ruflo-console/hooks/data/ap-journal.ts
+++ b/plugins/ruflo-console/hooks/data/ap-journal.ts
@@ -13,6 +13,8 @@ export const JOURNAL_FILE = `${AUTOPILOT_DIR}/journal.jsonl`
/** A journal over this is read no further (the cap is drawn): the loop then compacts by checkpoint (data/ap-loop.ts `compactState`). */
export const JOURNAL_MAX_BYTES = 1_500_000
export const LINE_MAX = 2_000
+/** Why a step is journaled failed when the mission would not take it: a step that never started, which adaptation must not learn from. */
+export const REFUSED_WHY = 'the mission refused the hand-over'
export type Receipt = { id: string; at: number; path: string; from: string; to: string; direction: 'conservative' | 'aggressive'; evidence: string; prev: string; hash: string }
export type Anatole = 'on' | 'accepted-without'
diff --git a/plugins/ruflo-console/hooks/data/ap-loop.ts b/plugins/ruflo-console/hooks/data/ap-loop.ts
index 2f7ad21cf3..3a0bbc51d3 100644
--- a/plugins/ruflo-console/hooks/data/ap-loop.ts
+++ b/plugins/ruflo-console/hooks/data/ap-loop.ts
@@ -8,7 +8,7 @@
* is considered; budget, Anatole and the failure ladder all sit between "settled" and "act". A step is started at most once per id,
* and a task with a started or done step is never started again.
*/
-import { classAllowed, pathAllowed, sha256, type Envelope, type Spend } from './ap-envelope'
+import { classAllowed, hostAllowed, pathAllowed, sha256, type Envelope, type Spend } from './ap-envelope'
import type { Anatole, JournalEvent, Receipt } from './ap-journal'
export type Phase = 'idle' | 'running' | 'paused' | 'stopped'
@@ -125,7 +125,7 @@ export function compactState(s: LoopState): LoopState {
return { ...s, steps: s.steps.filter(step => keep.has(step)), parked: s.parked.slice(-200), receipts: s.receipts.slice(-200) }
}
-export type TaskFact = { id: string; title: string; /** The envelope class the task needs, or null when it cannot be classified (it is parked, never guessed). */ cls: string | null; /** A hard deny the task text names, or null. */ hardDeny: string | null; /** A path the task names, when one can be read from it. */ path: string | null }
+export type TaskFact = { id: string; title: string; /** The envelope class the task needs, or null when it cannot be classified (it is parked, never guessed). */ cls: string | null; /** A hard deny the task text names, or null. */ hardDeny: string | null; /** A path the task names, when one can be read from it. */ path: string | null; /** Every other absolute path the text names (at most 8). */ paths?: string[]; /** Hosts of the URLs the text names, lowercase. */ hosts?: string[]; /** `owner/name` of the GitHub repositories the text names by URL. */ repos?: string[] }
export type EffectFact = 'done' | 'done-unverified' | 'failed' | 'absent' | 'unknown'
export type Preflight = 'allow' | 'deny' | 'ask' | 'unwired'
export type Tunables = { parallelism: number; retries: number; stepTimeoutMs: number; tierOf: (cls: string) => string }
@@ -145,6 +145,8 @@ export type Facts = {
orphans: ReadonlySet<string>
tunables: Tunables
preflight: Readonly<Record<string, Preflight>>
+ /** Milliseconds each in-flight step is forgiven for time the machine was asleep (a gap between ticks), by step id. Absent means none. */
+ slack?: Readonly<Record<string, number>>
}
export type Decision = { events: JournalEvent[]; act: { id: string; task: TaskFact; cls: string; attempt: number; tier: string; deadline: number } | null; status: string }
@@ -166,8 +168,21 @@ export function whyParked(task: TaskFact, env: Envelope, preflight: Readonly<Rec
if (task.hardDeny !== null) return `needs "${task.hardDeny}", which autopilot can never do. Do it yourself, or deny it.`
if (task.cls === null) return 'cannot tell which kind of action this needs, and autopilot does not guess. Which class is it?'
if (!classAllowed(env, task.cls)) return `needs "${task.cls}", which the envelope does not allow. Approve once, or deny.`
- if (task.path !== null && !pathAllowed(env, task.path)) return `touches ${task.path.slice(0, 80)}, outside the envelope's folders. Approve once, or deny.`
- if (preflight[task.cls] === 'deny' || preflight[task.cls] === 'ask') return `your permission settings would not allow "${task.cls}" without asking. Approve once here (the engine still decides), or deny.`
+
+ const outside = [task.path, ...(task.paths ?? [])].find(path => path !== null && path !== undefined && !pathAllowed(env, path))
+
+ if (outside !== undefined && outside !== null) return `touches ${outside.slice(0, 80)}, outside the envelope's folders. Approve once, or deny.`
+
+ const host = (task.hosts ?? []).find(name => !hostAllowed(env, name))
+
+ if (host !== undefined) return `names the host ${host.slice(0, 60)}, which is not on the envelope's network list. Approve once, or deny.`
+
+ const repo = (task.repos ?? []).find(name => !env.repos.includes(name))
+
+ if (repo !== undefined) return `names the repository ${repo.slice(0, 60)}, which is not on the envelope's repo list. Approve once, or deny.`
+ // A deny from the person's own settings is not the console's to lift: no approve button, and an old approval is ignored for it.
+ if (preflight[task.cls] === 'deny') return `your permission settings deny "${task.cls}", which autopilot can never do on your behalf. Change your settings, or deny it.`
+ if (preflight[task.cls] === 'ask') return `your permission settings would ask before "${task.cls}". Approve once here (the engine still decides), or deny.`
return null
}
@@ -198,7 +213,7 @@ export function tick(s: LoopState, f: Facts): Decision {
events.push({ t: 'step.failed', at: now, id: step.id, why: 'the task reported failure' })
failures += 1
lastFailure = now
- } else if (now > step.deadline) {
+ } else if (now > step.deadline + (f.slack?.[step.id] ?? 0)) {
events.push({ t: 'step.failed', at: now, id: step.id, why: 'timed out' })
failures += 1
lastFailure = now
@@ -228,7 +243,8 @@ export function tick(s: LoopState, f: Facts): Decision {
// 4. Failure ladder: a budget that pauses, a backoff that waits.
if (failures >= FAILURE_BUDGET) return pauseWith(`${failures} failures in a row`)
- if (failures > 0 && lastFailure !== null && now - lastFailure < backoffMs(failures)) return { events, act: null, status: `backing off after ${failures} failure${failures === 1 ? '' : 's'}` }
+ // A clock set back after a failure must not hold the loop for the size of the jump: a negative age counts as the full wait.
+ if (failures > 0 && lastFailure !== null && now >= lastFailure && now - lastFailure < backoffMs(failures)) return { events, act: null, status: `backing off after ${failures} failure${failures === 1 ? '' : 's'}` }
// 5. Room to start one.
if (stillOpen >= Math.min(f.envelope.concurrency, Math.max(1, f.tunables.parallelism))) return { events, act: null, status: `${stillOpen} step${stillOpen === 1 ? '' : 's'} running` }
@@ -246,7 +262,7 @@ export function tick(s: LoopState, f: Facts): Decision {
const attempt = 1 + s.steps.filter(step => step.task === task.id && step.status === 'failed').length
// A hard deny can never be approved once: the answer is ignored for it.
- const answeredOnce = task.hardDeny === null && s.parked.some(p => p.task === task.id && p.answer === 'once' && p.isUsed !== true)
+ const answeredOnce = task.hardDeny === null && f.preflight[task.cls ?? ''] !== 'deny' && s.parked.some(p => p.task === task.id && p.answer === 'once' && p.isUsed !== true)
if (!answeredOnce && attempt > 1 + f.tunables.retries) {
const why = whyParked({ ...task, cls: task.cls }, f.envelope, f.preflight) ?? `failed ${attempt - 1} times, past the retry policy. Retry once, or deny.`
diff --git a/plugins/ruflo-console/hooks/views/ap-panel.ts b/plugins/ruflo-console/hooks/views/ap-panel.ts
index d26497be99..0e096846dc 100644
--- a/plugins/ruflo-console/hooks/views/ap-panel.ts
+++ b/plugins/ruflo-console/hooks/views/ap-panel.ts
@@ -88,6 +88,9 @@ export async function loadDraftFile(state: State): Promise<string> {
return 'draft loaded'
}
+/** Buttons that wrap onto more lines when the page is narrow, so none is pushed off the edge where a click cannot reach it. */
+const flow = (ctx: Ctx, parts: readonly RenderElement[], key: string): RenderElement => ctx.kit.Box({ flexDirection: 'row', flexWrap: 'wrap', key, children: [...parts] })
+
const money = (n: number | undefined | null): string => (n === undefined || n === null ? 'n/a' : `$${Math.round(n * 100) / 100}`)
const COLOR = { running: THEME.ok, paused: THEME.warn, stopped: THEME.bad, idle: undefined } as const
@@ -99,7 +102,7 @@ function gates(ctx: Ctx, env: Envelope | null): RenderElement[] {
return [
kv(ctx, 'Anatole', anatole === 'on' ? 'on' : anatole === 'off' ? 'OFF: autopilot pauses' : 'not installed', anatole === 'on' ? THEME.ok : THEME.warn),
- kv(ctx, 'permissions', !store.hasCheck ? 'preflight not wired: the engine still asks per call; a step it would deny fails, it is not bypassed' : denied.length === 0 ? 'your settings allow every class' : `would ask or deny: ${denied.join(', ')} (parked)`, store.hasCheck ? undefined : THEME.warn),
+ kv(ctx, '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, 'journal', `${Math.round(store.journalBytes / 1000)} kB of 1500 kB cap${store.badLines > 0 ? ` ยท ${store.badLines} unusable lines` : ''}`),
]
@@ -114,7 +117,11 @@ 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'} ยท ${e.paths.length} folder${e.paths.length === 1 ? '' : 's'} ยท ${e.repos.length} repos ยท network ${e.network.join(',') || 'none'} ยท secrets ${e.secretEnv.join(',') || 'none'} ยท up to ${e.concurrency} at once ยท ${Math.round(e.maxDurationMs / DAY)} d ยท ${e.verify.length} verify command${e.verify.length === 1 ? '' : 's'}`, { dimColor: true }),
+ text(ctx, ` 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, ` 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 }),
+ text(ctx, ' enforced: spend, concurrency, duration, verify. Secret names are a record only.', { dimColor: true }),
text(ctx, ` never granted: ${HARD_DENIES.join(', ')}`, { dimColor: true }),
]
}
@@ -131,13 +138,15 @@ function editor(ctx: Ctx): RenderElement[] {
}
const rows: RenderElement[] = [
- row(ctx, [text(ctx, ' classes ', { dimColor: true }), ...TOOL_CLASSES.map(cls => button(ctx, `ap-c-${cls}`, `${have.includes(cls) ? 'โ—' : 'โ—‹'} ${cls}`, set({ kind: 'class', cls })))], 'ap-classes'),
+ text(ctx, ' classes', { dimColor: true }),
+ flow(ctx, TOOL_CLASSES.map(cls => button(ctx, `ap-c-${cls}`, `${have.includes(cls) ? 'โ—' : 'โ—‹'} ${cls}`, set({ kind: 'class', cls }))), 'ap-classes'),
]
for (const key of ['hourUsd', 'dayUsd', 'totalUsd'] as const) rows.push(row(ctx, [text(ctx, ` ${key.replace('Usd', '').padEnd(8)} `, { dimColor: true }), button(ctx, `ap-s-${key}-less`, ' โˆ’ ', set({ kind: 'spend', key, by: -1 })), text(ctx, ` ${money(spend[key])} `, { bold: true }), button(ctx, `ap-s-${key}-more`, ' + ', set({ kind: 'spend', key, by: 1 }))], `ap-spend-${key}`))
rows.push(row(ctx, [text(ctx, ' at once ', { dimColor: true }), button(ctx, 'ap-n-less', ' โˆ’ ', set({ kind: 'concurrency', by: -1 })), text(ctx, ` ${String(d.value.concurrency)} `, { bold: true }), button(ctx, 'ap-n-more', ' + ', set({ kind: 'concurrency', by: 1 })), text(ctx, ' duration ', { dimColor: true }), button(ctx, 'ap-d-less', ' โˆ’ ', set({ kind: 'days', by: -1 })), text(ctx, ` ${Math.round(Number(d.value.maxDurationMs) / DAY)} d `, { bold: true }), button(ctx, 'ap-d-more', ' + ', set({ kind: 'days', by: 1 }))], 'ap-conc'))
- rows.push(row(ctx, [button(ctx, 'ap-anatole', `${d.value.acceptWithoutAnatole === true ? 'โ—' : 'โ—‹'} accept running without Anatole`, set({ kind: 'anatole' })), button(ctx, 'ap-load', 'load draft file', () => void loadDraftFile(ctx.state)), text(ctx, ` ${DRAFT_FILE} holds paths, repos, network, verify`, { dimColor: true })], 'ap-draft-row'))
+ rows.push(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, checked.ok ? ` draft is valid ยท hash ${hashOf(checked.envelope).slice(0, 12)}${d.fromFile === null ? '' : ' ยท from file'} ยท ${(d.value.paths as string[]).join(', ')}` : ` draft is not valid: ${cleanText(checked.errors.slice(0, 2).join('; '))}`, { color: checked.ok ? undefined : THEME.bad }))
return rows
@@ -173,17 +182,19 @@ 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 }))
- rows.push(row(ctx, [
- button(ctx, 'ap-stop', 'Stop', () => void stopNow(ctx.state, host), { hotkey: '9' }),
+ // Stop's key (9) is the key slot's: a second button on the same key would run it twice.
+ rows.push(flow(ctx, [
+ button(ctx, 'ap-stop', 'Stop (9)', () => 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)),
- text(ctx, ' Start is the action row (key 8) and asks first ยท Stop asks nothing', { dimColor: true }),
], 'ap-controls'))
+ rows.push(text(ctx, ' Start is the action row (key 8) and asks first ยท Stop asks nothing', { 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))
- rows.push(text(ctx, ' Inside the envelope autopilot does not ask this console. It does not bypass Claude Code\'s permission dialog, and it is not a scheduler: it runs while the session lives (re-arm the mission /loop).', { dimColor: true }))
+ rows.push(text(ctx, ' Inside the envelope autopilot does not ask this console. It never bypasses Claude Code\'s permission dialog.', { dimColor: true }))
+ rows.push(text(ctx, ' It is not a sandbox (the envelope gates what a task says) and not a scheduler: it runs while the session lives.', { dimColor: true }))
return rows
}
@@ -212,7 +223,7 @@ export function startSpec(env: SlotEnv): ActionSpec | null {
scope: 'workflows',
args: [],
declared: 'spend',
- shows: `envelope ${hash.slice(0, 12)}: classes ${next.toolClasses.join(' ')}; folders ${next.paths.join(', ')}; network ${next.network.join(',') || 'none'}; ${money(next.spend.hourUsd)}/h ${money(next.spend.dayUsd)}/day ${money(next.spend.totalUsd)} total; ${next.concurrency} at once; ${next.verify.length} verify commands; Anatole ${anatole}${next.acceptWithoutAnatole ? ' (running without it accepted)' : ''}${grew.length > 0 ? `; WIDENS: ${grew.join('; ')}` : ''}; never: ${HARD_DENIES.join(', ')}`,
+ shows: `envelope ${hash.slice(0, 12)}: classes ${next.toolClasses.join(' ')}; folders ${next.paths.join(', ')}; network ${next.network.join(',') || 'none'}; ${money(next.spend.hourUsd)}/h ${money(next.spend.dayUsd)}/day ${money(next.spend.totalUsd)} total; ${next.concurrency} at once; ${next.verify.length === 0 ? 'no verify commands (steps will be unverified)' : `verify commands run by this console after each step: ${next.verify.map(argv => clip(cleanText(argv.join(' ')), 80)).join(' ; ')}`}; repos ${next.repos.join(',') || 'none'}; Anatole ${anatole}${next.acceptWithoutAnatole ? ' (running without it accepted)' : ''}${grew.length > 0 ? `; WIDENS: ${grew.join('; ')}` : ''}; never: ${HARD_DENIES.join(', ')}`,
expect: 'a start line in the autopilot journal, then steps handed to the session',
note: 'After this, steps inside the envelope run WITHOUT asking this console, for days if the session lives, and spend money. Claude Code\'s own permission dialog still applies and is never bypassed: anything it would ask about is parked. Stop, the KILL file or /ruflo autopilot stop halts it within one tick.',
run: async () => {
diff --git a/plugins/ruflo-console/tests/ap-live.spec.ts b/plugins/ruflo-console/tests/ap-live.spec.ts
index 01b85cb71b..f237a24bea 100644
--- a/plugins/ruflo-console/tests/ap-live.spec.ts
+++ b/plugins/ruflo-console/tests/ap-live.spec.ts
@@ -6,120 +6,14 @@
*/
import { describe, expect, it } from 'vitest'
+import { hashOf, seal } from '../hooks/data/ap-envelope'
import { apTick, appendEvents, answerParked, refreshAutopilot, storeOf, stopNow, wireAutopilot } from '../hooks/ap-live'
-import { hashOf, seal, type Envelope } from '../hooks/data/ap-envelope'
-import { encodeLine, JOURNAL_FILE, parseJournal, type JournalEvent } from '../hooks/data/ap-journal'
-import type { TaskRecord } from '../hooks/data/parse'
-import type { Host } from '../hooks/host'
-import { mcOf, type MissionRecord } from '../hooks/mission-control'
-import { newState, type State } from '../hooks/state'
import { boardRows, defaultDraft, draftOf, editDraft, registerAutopilotSlots, startSpec } from '../hooks/views/ap-panel'
import { parkedRows } from '../hooks/views/ap-parked'
-import type { Ctx, Kit } from '../hooks/views/common'
-import { resetSlots, slotsFor, type SlotEnv } from '../hooks/views/wf-slots'
+import { resetSlots, slotsFor } from '../hooks/views/wf-slots'
import '../hooks/views/wf-register'
-const CWD = '/w'
-const T0 = Date.parse('2026-10-06T00:00:00.000Z')
-const J = `${CWD}/${JOURNAL_FILE}`
-const E = `${CWD}/.claude-flow/console/autopilot/envelope.json`
-const KILL = `${CWD}/.claude-flow/console/autopilot/KILL`
-
-const ENV: Envelope = { name: 'night', toolClasses: ['edit', 'read', 'test'], paths: [CWD], repos: [], network: [], secretEnv: [], spend: { hourUsd: 2, dayUsd: 10, totalUsd: 40 }, concurrency: 1, maxDurationMs: 7 * 86_400_000, verify: [['true']], acceptWithoutAnatole: true }
-
-type Rig = { files: Map<string, string>; runs: string[][]; prompts: string[]; toasts: string[]; host: Host; failVerify: { on: boolean } }
-
-function rig(): Rig {
- const files = new Map<string, string>()
- const runs: string[][] = []
- const prompts: string[] = []
- const toasts: string[] = []
- const failVerify = { on: false }
-
- const host = {
- fs: {
- read: async (p: string) => files.get(p) ?? Promise.reject(new Error('ENOENT')),
- stat: async (p: string) => (files.has(p) ? { mtimeMs: 1, size: (files.get(p) as string).length, kind: 'file', isLink: false } : [...files.keys()].some(k => k.startsWith(`${p}/`)) ? { kind: 'dir', isLink: false } : Promise.reject(new Error('ENOENT'))),
- list: async () => [],
- },
- run: async (argv: readonly string[], _t: number, stdin?: string) => {
- runs.push([...argv])
-
- if (argv[0] === 'dd') {
- const path = (argv.find(a => a.startsWith('of=')) as string).slice(3)
-
- files.set(path, argv.includes('oflag=append') ? `${files.get(path) ?? ''}${stdin ?? ''}` : (stdin ?? ''))
- } else if (argv[0] === 'install') {
- const path = argv.at(-1) as string
-
- files.set(path, argv.includes('/dev/null') ? '' : (stdin ?? ''))
- } else if (argv[0] === 'rm') files.delete(argv.at(-1) as string)
- else if (argv[0] === 'cp') files.set(argv.at(-1) as string, files.get(argv.at(-2) as string) ?? '')
- else if (argv[0] === 'true' || argv[0] === 'false') return { exitCode: failVerify.on ? 1 : 0, stdout: '', stderr: '' }
-
- return { exitCode: 0, stdout: '', stderr: '' }
- },
- invalidate: () => undefined,
- toast: (t: string) => void toasts.push(t),
- every: () => ({ cancel: () => undefined }),
- after: () => ({ cancel: () => undefined }),
- storeSet: async () => undefined,
- submitPrompt: async (t: string) => void prompts.push(t),
- } as unknown as Host
-
- return { files, runs, prompts, toasts, host, failVerify }
-}
-
-const task = (id: string, status: string): TaskRecord => ({ id, type: 'feature', description: '', status, assignedTo: [], tags: [] })
-
-const mission = (): MissionRecord => ({
- id: 'msn_0123456789abcdef01234567', objective: 'tidy the parser', profile: 'feature', rigor: 'standard',
- tasks: [
- { id: 't1', title: 'Fix the parser bug', phase: 'S', agent: 'coder', requirement: 'tests pass', dependsOn: [], rufloTaskId: 'r1' },
- { id: 't2', title: 'Publish the package to npm', phase: 'A', agent: 'coder', requirement: 'it is published', dependsOn: [], rufloTaskId: 'r2' },
- { id: 't3', title: 'Review the module', phase: 'P', agent: 'coder', requirement: 'a summary', dependsOn: [], rufloTaskId: 'r3' },
- ],
- acceptance: [], events: [], paused: false, cancelled: false, auto: false, createdAtMs: 1,
-})
-
-function stateWith(tasks: TaskRecord[], anatole: 'on' | 'off' | 'absent' = 'on'): State {
- const state = newState({})
-
- state.cwd = CWD
- state.snapshot = { tasks, agents: [], claims: [], swarm: null, plugins: { missingFromClone: [], installed: [] }, alerts: [], anatole: anatole === 'absent' ? undefined : { present: true, status: { mode: anatole === 'on' ? 'notify' : 'off' }, modeOverride: null, overrides: {}, alerts: [], refused: [], badAlerts: 0 } } as never
- mcOf(state).missions.set('msn_0123456789abcdef01234567', mission())
- mcOf(state).active = 'msn_0123456789abcdef01234567'
-
- return state
-}
-
-/** Seeds an approved, started autopilot on the rig's disk. */
-function started(r: Rig, extra: JournalEvent[] = []): void {
- const sealed = seal(ENV, 1, T0)
-
- r.files.set(E, JSON.stringify(sealed))
- r.files.set(J, [{ t: 'start', at: T0, envHash: sealed.hash, revision: 1, anatole: 'on' } as JournalEvent, ...extra].map(encodeLine).join(''))
-}
-
-const kit = { Box: (props: Record<string, unknown>) => ({ kind: 'Box', props }), Text: (props: Record<string, unknown>) => ({ kind: 'Text', props }), Button: (props: Record<string, unknown>) => ({ kind: 'Button', props }) } as unknown as Kit
-const ctxOf = (state: State, nowMs: number): Ctx => ({ kit, state, nowMs, columns: 120, pictures: new Map(), act: {} as never })
-
-type El = { kind: string; props: Record<string, unknown> }
-
-const flat = (node: unknown, out: El[] = []): El[] => {
- if (Array.isArray(node)) node.forEach(child => flat(child, out))
- else if (typeof node === 'object' && node !== null) {
- out.push(node as El)
- flat((node as El).props?.children, out)
- }
-
- return out
-}
-
-const words = (tree: unknown): string => flat(tree).filter(el => el.kind === 'Text' && typeof el.props.children === 'string').map(el => el.props.children as string).join('\n')
-const buttons = (tree: unknown): string[] => flat(tree).filter(el => el.kind === 'Button').map(el => String(el.props.label))
-const envOf = (state: State, nowMs: number): SlotEnv => ({ ctx: ctxOf(state, nowMs), runs: [], run: null, phase: null, agent: null, ui: {} as never, nowMs })
-const journal = (r: Rig): JournalEvent[] => parseJournal(r.files.get(J) ?? '').events
+import { CWD, E, ENV, J, KILL, T0, buttons, ctxOf, envOf, flat, journal, rig, started, stateWith, task, words } from './fixtures/ap-rig'
describe('the panel before and after wiring', () => {
it('says it is not wired, then that autopilot is off, with no invented number', () => {
diff --git a/plugins/ruflo-console/tests/ap-review.spec.ts b/plugins/ruflo-console/tests/ap-review.spec.ts
new file mode 100644
index 0000000000..04e4d542c3
--- /dev/null
+++ b/plugins/ruflo-console/tests/ap-review.spec.ts
@@ -0,0 +1,242 @@
+/**
+ * The adversarial review of the mission autopilot (ADR-466): each test is a defect the review found, written to fail on the code as it
+ * was merged. Pure rules first, then the live loop on the shared in-memory rig (fixtures/ap-rig.ts). Run with
+ * npx vitest run plugins/ruflo-console/tests/ap-review.spec.ts --testTimeout=30000
+ */
+import { describe, expect, it } from 'vitest'
+
+import { apTick, refreshAutopilot, storeOf, stopNow, wireAutopilot } from '../hooks/ap-live'
+import { outcomesOf, propose, reversal, type Tunables, DEFAULTS } from '../hooks/data/ap-adapt'
+import { hashOf, type Envelope } from '../hooks/data/ap-envelope'
+import { classifyTask } from '../hooks/data/ap-guard'
+import { encodeLine, REFUSED_WHY, type JournalEvent } from '../hooks/data/ap-journal'
+import { foldJournal, tick, whyParked, type Facts, type TaskFact } from '../hooks/data/ap-loop'
+import { boardRows, defaultDraft, draftOf, startSpec } from '../hooks/views/ap-panel'
+import { CWD, ENV, J, T0, envOf, flat, journal, rig, started, stateWith, task, words } from './fixtures/ap-rig'
+
+const H = 3_600_000
+const PURE: Envelope = { ...ENV, paths: ['/work/repo'], network: ['github.com'], repos: ['ruvnet/ruflo'], toolClasses: ['edit', 'read', 'test', 'network'], concurrency: 2 }
+const fact = (id: string, over: Partial<TaskFact> = {}): TaskFact => ({ id, title: `do ${id}`, cls: 'edit', hardDeny: null, path: '/work/repo/a.ts', ...over })
+const facts = (over: Partial<Facts> = {}): Facts => ({ nowMs: T0, killSeen: false, envelope: PURE, anatole: 'on', spend: { hourUsd: 0, dayUsd: 0, totalUsd: 0 }, task: fact('t1'), effects: {}, orphans: new Set(), tunables: { parallelism: 1, retries: 1, stepTimeoutMs: 600_000, tierOf: () => 'mid' }, preflight: {}, ...over })
+const start = (env: Envelope = PURE): JournalEvent => ({ t: 'start', at: T0, envHash: hashOf(env), revision: 1, anatole: 'on' })
+
+describe('what the envelope really checks', () => {
+ it('reads every path, URL host and GitHub repository a task names, not only the first path', () => {
+ const t = classifyTask('t1', 'Fix /work/repo/a.ts and copy it to /etc/cron.d/x', 'see https://evil.example.com/x and https://github.com/someone/else.git')
+
+ expect(t.path).toBe('/work/repo/a.ts')
+ expect(t.paths).toEqual(['/etc/cron.d/x'])
+ expect(t.hosts).toEqual(['evil.example.com', 'github.com'])
+ expect(t.repos).toEqual(['someone/else'])
+ })
+
+ it('parks a task whose second path, host or repo is outside the envelope, and passes one that is inside', () => {
+ expect(whyParked(fact('a', { paths: ['/etc/passwd'] }), PURE, {})).toContain('/etc/passwd')
+ expect(whyParked(fact('b', { cls: 'network', hosts: ['evil.example.com'] }), PURE, {})).toContain('network list')
+ expect(whyParked(fact('c', { cls: 'network', hosts: ['github.com'], repos: ['someone/else'] }), PURE, {})).toContain('repo list')
+ expect(whyParked(fact('d', { cls: 'network', paths: ['/work/repo/b.ts'], hosts: ['github.com'], repos: ['ruvnet/ruflo'] }), PURE, {})).toBeNull()
+ })
+})
+
+describe('a permission deny is not the console to lift', () => {
+ it('ignores an approve-once for a class the settings deny, and still lets one lift a class the settings only ask about', () => {
+ const base = foldJournal([start(), { t: 'parked', at: T0 + 1, id: 'p-x', task: 't1', question: 'q' }, { t: 'answered', at: T0 + 2, id: 'p-x', answer: 'once' }])
+ const asked = tick(base, facts({ nowMs: T0 + 5, preflight: { edit: 'ask' } }))
+ const denied = tick(base, facts({ nowMs: T0 + 5, preflight: { edit: 'deny' } }))
+
+ expect(asked.act).not.toBeNull()
+ expect(denied.act).toBeNull()
+ expect(denied.events.find(e => e.t === 'parked')).toMatchObject({ question: expect.stringContaining('can never do') })
+ })
+})
+
+describe('clocks and sleep', () => {
+ it('a clock set back after a failure does not hold the loop for the size of the jump', () => {
+ const s = foldJournal([start(), { t: 'step.started', at: T0, id: 's-1', task: 'old', cls: 'edit', attempt: 1, deadline: T0 + 1, tier: 'mid' }, { t: 'step.failed', at: T0 + 10 * H, id: 's-1', why: 'x' }])
+ const back = tick(s, facts({ nowMs: T0 + 2 * H, task: fact('t2') }))
+
+ expect(back.act?.task.id).toBe('t2')
+ })
+
+ it('forgives a step the time the machine slept before it counts as timed out', () => {
+ const s = foldJournal([start(), { t: 'step.started', at: T0, id: 's-1', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 1000, tier: 'mid' }])
+
+ expect(tick(s, facts({ nowMs: T0 + 5000 })).events.some(e => e.t === 'step.failed')).toBe(true)
+ expect(tick(s, facts({ nowMs: T0 + 5000, slack: { 's-1': 8 * H } })).events.some(e => e.t === 'step.failed')).toBe(false)
+ })
+
+ it('apTick credits a long gap between passes to the steps in flight', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending')])
+
+ started(r, [{ t: 'step.started', at: T0 + 10, id: 's-sleeper0000001', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 100_000, tier: 'mid' }])
+ wireAutopilot(state, r.host)
+ storeOf(state).bootMs = T0 - 1
+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
+ storeOf(state).spendAtMs = T0 + 1
+ await apTick(state, r.host, T0 + 50_000)
+ await apTick(state, r.host, T0 + 8 * H)
+
+ expect(storeOf(state).slack['s-sleeper0000001']).toBe(8 * H - 50_000)
+ expect(journal(r).some(e => e.t === 'step.failed')).toBe(false)
+ })
+})
+
+describe('stop is never undone', () => {
+ it('a stop pressed while a pass gathers its facts wins: no step starts after it', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'completed'), task('r2', 'completed'), task('r3', 'pending')])
+
+ started(r, [{ t: 'step.started', at: T0 + 10, id: 's-verifyme0000009', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 1e9, tier: 'mid' }])
+
+ const run = r.host.run
+
+ r.host.run = (async (argv: readonly string[], timeout: number, stdin?: string) => {
+ if (argv[0] === 'true') await stopNow(state, r.host, 'pressed during verify')
+
+ return run(argv, timeout, stdin)
+ }) as typeof r.host.run
+ wireAutopilot(state, r.host)
+ storeOf(state).bootMs = T0 - 1
+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
+ storeOf(state).spendAtMs = T0 + 1000
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(r.prompts).toEqual([])
+ expect(journal(r).filter(e => e.t === 'step.started').length).toBe(1)
+ })
+
+ it('a stop that reaches neither the journal nor the flag is held and said, and a re-read does not resume the loop', async () => {
+ const r = rig()
+ const state = stateWith([task('r1', 'pending'), task('r2', 'pending'), task('r3', 'pending')])
+
+ started(r)
+ wireAutopilot(state, r.host)
+ await refreshAutopilot(state, r.host, T0)
+
+ const run = r.host.run
+
+ r.host.run = (async () => ({ exitCode: 1, stdout: '', stderr: 'no space left on device' })) as typeof r.host.run
+ await stopNow(state, r.host, 'disk is full')
+ expect(r.toasts.join()).toContain('this session only')
+
+ r.host.run = run
+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
+ storeOf(state).spendAtMs = T0 + 1000
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(r.prompts).toEqual([])
+ expect(storeOf(state).loop.phase).toBe('stopped')
+ // Once the disk answers again the held stop is written, so a new process sees it too.
+ expect(journal(r).at(-1)).toMatchObject({ t: 'stop', reason: 'disk is full' })
+ })
+
+ it('no verify command is run for a class the person\'s settings deny', 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-verifyme0000008', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 1e9, tier: 'mid' }])
+ wireAutopilot(state, r.host, { toolCheck: async () => 'deny' })
+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
+ storeOf(state).spendAtMs = T0 + 1000
+ await apTick(state, r.host, T0 + 1000)
+
+ expect(r.runs.some(a => a[0] === 'true')).toBe(false)
+ expect(journal(r).find(e => e.t === 'step.done')).toMatchObject({ id: 's-verifyme0000008', verified: false })
+ })
+})
+
+describe('the journal over a long run', () => {
+ it('rotates a journal past 80% of its cap into an archive and a snapshot that folds to the same state', async () => {
+ const r = rig()
+ const state = stateWith([])
+
+ started(r, [])
+ r.files.set(J, `${r.files.get(J) as string}${encodeLine({ t: 'beat', at: T0 + 1 }).repeat(42_000)}`)
+ wireAutopilot(state, r.host)
+ storeOf(state).spend = { hourUsd: 0, dayUsd: 0, totalUsd: 0 }
+ storeOf(state).spendAtMs = T0 + 1000
+ await apTick(state, r.host, T0 + 2000)
+
+ const names = [...r.files.keys()].filter(name => name.startsWith(`${J}.`))
+
+ expect(names.length).toBe(1)
+ expect((r.files.get(J) as string).length).toBeLessThan(2_000)
+ await refreshAutopilot(state, r.host, T0 + 3000)
+ expect(storeOf(state).loop.phase).toBe('running')
+ expect(storeOf(state).loop.startedAtMs).toBe(T0)
+ })
+})
+
+describe('what adaptation learns', () => {
+ const step = (over: Record<string, unknown>) => ({ id: 's', task: 't', cls: 'edit', attempt: 1, startedAt: 0, deadline: 1, status: 'failed' as const, tier: 'mid', par: 1, endedAt: 10, ...over })
+
+ it('a hand-over the mission refused is a step that never ran and teaches nothing', () => {
+ expect(outcomesOf([step({ why: REFUSED_WHY }), step({ why: 'timed out' })]).length).toBe(1)
+ })
+
+ it('does not propose again a setting a trial was reverted away from', () => {
+ const outcomes = Array.from({ length: 14 }, (_, i) => ({ at: i, cls: 'edit', tier: 'mid', par: 1, attempt: 1, ok: true, durationMs: 1 }))
+ const t: Tunables = { ...DEFAULTS }
+ const before = propose(outcomes, t, PURE)
+
+ expect(before.some(p => p.change.path === 'tier.edit' && p.change.to === 'low')).toBe(true)
+
+ const trial = { id: 'tier-edit-low', at: 1, path: 'tier.edit', from: 'mid', to: 'low', direction: 'aggressive' as const, evidence: 'e', prev: 'genesis', hash: 'a'.repeat(64) }
+ const revert = { ...reversal(trial), at: 2, path: 'tier.edit', from: 'low', to: 'mid', direction: 'conservative' as const, evidence: 'e', prev: 'a'.repeat(64), hash: 'b'.repeat(64) }
+
+ expect(propose(outcomes, t, PURE, [trial, revert]).some(p => p.change.path === 'tier.edit' && p.change.to === 'low')).toBe(false)
+ })
+})
+
+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', () => {
+ const r = rig()
+ const state = stateWith([])
+
+ wireAutopilot(state, r.host)
+
+ const hotkeys = flat(boardRows(envOf(state, T0))).filter(el => el.kind === 'Button' && el.props.hotkey !== undefined).map(el => el.props.hotkey)
+
+ expect(hotkeys).not.toContain('9')
+ })
+
+ it('wraps its button rows so none is pushed off an 80 column page', () => {
+ const r = rig()
+ const state = stateWith([])
+
+ wireAutopilot(state, r.host)
+
+ const wrapped = flat(boardRows(envOf(state, T0))).filter(el => el.kind === 'Box' && el.props.flexWrap === 'wrap')
+
+ expect(wrapped.length).toBeGreaterThanOrEqual(3)
+ })
+
+ it('shows the confirm card the exact verify commands this console will run after every step', () => {
+ const r = rig()
+ const state = stateWith([])
+
+ wireAutopilot(state, r.host)
+ draftOf(state).value = { ...defaultDraft(CWD), verify: [['npm', 'test'], ['cargo', 'test', '--workspace']] }
+
+ const spec = startSpec(envOf(state, T0))
+
+ expect(spec?.shows).toContain('npm test')
+ expect(spec?.shows).toContain('cargo test --workspace')
+ expect(spec?.shows).toContain('run by this console')
+ })
+
+ it('says plainly that network, repos and secret names are checked against what a task says, not sandboxed', async () => {
+ const r = rig()
+ const state = stateWith([])
+
+ started(r)
+ wireAutopilot(state, r.host)
+ await refreshAutopilot(state, r.host, T0)
+
+ const text = words(boardRows(envOf(state, T0)))
+
+ expect(text).toContain('is not a sandbox')
+ expect(text).toContain('Secret names are a record only')
+ })
+})
diff --git a/plugins/ruflo-console/tests/fixtures/ap-rig.ts b/plugins/ruflo-console/tests/fixtures/ap-rig.ts
new file mode 100644
index 0000000000..a0c5cf762e
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/ap-rig.ts
@@ -0,0 +1,114 @@
+/**
+ * The in-memory disk, fake host and state the autopilot's live specs share (ap-live.spec.ts, ap-review.spec.ts): no engine, no clock.
+ */
+import { mcOf, type MissionRecord } from '../../hooks/mission-control'
+import { seal, type Envelope } from '../../hooks/data/ap-envelope'
+import { encodeLine, JOURNAL_FILE, parseJournal, type JournalEvent } from '../../hooks/data/ap-journal'
+import type { TaskRecord } from '../../hooks/data/parse'
+import type { Host } from '../../hooks/host'
+import { newState, type State } from '../../hooks/state'
+import type { Ctx, Kit } from '../../hooks/views/common'
+import type { SlotEnv } from '../../hooks/views/wf-slots'
+
+export const CWD = '/w'
+export const T0 = Date.parse('2026-10-06T00:00:00.000Z')
+export const J = `${CWD}/${JOURNAL_FILE}`
+export const E = `${CWD}/.claude-flow/console/autopilot/envelope.json`
+export const KILL = `${CWD}/.claude-flow/console/autopilot/KILL`
+
+export const ENV: Envelope = { name: 'night', toolClasses: ['edit', 'read', 'test'], paths: [CWD], repos: [], network: [], secretEnv: [], spend: { hourUsd: 2, dayUsd: 10, totalUsd: 40 }, concurrency: 1, maxDurationMs: 7 * 86_400_000, verify: [['true']], acceptWithoutAnatole: true }
+
+export type Rig = { files: Map<string, string>; runs: string[][]; prompts: string[]; toasts: string[]; host: Host; failVerify: { on: boolean } }
+
+export function rig(): Rig {
+ const files = new Map<string, string>()
+ const runs: string[][] = []
+ const prompts: string[] = []
+ const toasts: string[] = []
+ const failVerify = { on: false }
+
+ const host = {
+ fs: {
+ read: async (p: string) => files.get(p) ?? Promise.reject(new Error('ENOENT')),
+ stat: async (p: string) => (files.has(p) ? { mtimeMs: 1, size: (files.get(p) as string).length, kind: 'file', isLink: false } : [...files.keys()].some(k => k.startsWith(`${p}/`)) ? { kind: 'dir', isLink: false } : Promise.reject(new Error('ENOENT'))),
+ list: async () => [],
+ },
+ run: async (argv: readonly string[], _t: number, stdin?: string) => {
+ runs.push([...argv])
+
+ if (argv[0] === 'dd') {
+ const path = (argv.find(a => a.startsWith('of=')) as string).slice(3)
+
+ files.set(path, argv.includes('oflag=append') ? `${files.get(path) ?? ''}${stdin ?? ''}` : (stdin ?? ''))
+ } else if (argv[0] === 'install') {
+ const path = argv.at(-1) as string
+
+ files.set(path, argv.includes('/dev/null') ? '' : (stdin ?? ''))
+ } else if (argv[0] === 'rm') files.delete(argv.at(-1) as string)
+ else if (argv[0] === 'cp') files.set(argv.at(-1) as string, files.get(argv.at(-2) as string) ?? '')
+ else if (argv[0] === 'true' || argv[0] === 'false') return { exitCode: failVerify.on ? 1 : 0, stdout: '', stderr: '' }
+
+ return { exitCode: 0, stdout: '', stderr: '' }
+ },
+ invalidate: () => undefined,
+ toast: (t: string) => void toasts.push(t),
+ every: () => ({ cancel: () => undefined }),
+ after: () => ({ cancel: () => undefined }),
+ storeSet: async () => undefined,
+ submitPrompt: async (t: string) => void prompts.push(t),
+ } as unknown as Host
+
+ return { files, runs, prompts, toasts, host, failVerify }
+}
+
+export const task = (id: string, status: string): TaskRecord => ({ id, type: 'feature', description: '', status, assignedTo: [], tags: [] })
+
+export const mission = (): MissionRecord => ({
+ id: 'msn_0123456789abcdef01234567', objective: 'tidy the parser', profile: 'feature', rigor: 'standard',
+ tasks: [
+ { id: 't1', title: 'Fix the parser bug', phase: 'S', agent: 'coder', requirement: 'tests pass', dependsOn: [], rufloTaskId: 'r1' },
+ { id: 't2', title: 'Publish the package to npm', phase: 'A', agent: 'coder', requirement: 'it is published', dependsOn: [], rufloTaskId: 'r2' },
+ { id: 't3', title: 'Review the module', phase: 'P', agent: 'coder', requirement: 'a summary', dependsOn: [], rufloTaskId: 'r3' },
+ ],
+ acceptance: [], events: [], paused: false, cancelled: false, auto: false, createdAtMs: 1,
+})
+
+export function stateWith(tasks: TaskRecord[], anatole: 'on' | 'off' | 'absent' = 'on'): State {
+ const state = newState({})
+
+ state.cwd = CWD
+ state.snapshot = { tasks, agents: [], claims: [], swarm: null, plugins: { missingFromClone: [], installed: [] }, alerts: [], anatole: anatole === 'absent' ? undefined : { present: true, status: { mode: anatole === 'on' ? 'notify' : 'off' }, modeOverride: null, overrides: {}, alerts: [], refused: [], badAlerts: 0 } } as never
+ mcOf(state).missions.set('msn_0123456789abcdef01234567', mission())
+ mcOf(state).active = 'msn_0123456789abcdef01234567'
+
+ return state
+}
+
+/** Seeds an approved, started autopilot on the rig's disk. */
+export function started(r: Rig, extra: JournalEvent[] = []): void {
+ const sealed = seal(ENV, 1, T0)
+
+ r.files.set(E, JSON.stringify(sealed))
+ r.files.set(J, [{ t: 'start', at: T0, envHash: sealed.hash, revision: 1, anatole: 'on' } as JournalEvent, ...extra].map(encodeLine).join(''))
+}
+
+export const kit = { Box: (props: Record<string, unknown>) => ({ kind: 'Box', props }), Text: (props: Record<string, unknown>) => ({ kind: 'Text', props }), Button: (props: Record<string, unknown>) => ({ kind: 'Button', props }) } as unknown as Kit
+export const ctxOf = (state: State, nowMs: number): Ctx => ({ kit, state, nowMs, columns: 120, pictures: new Map(), act: {} as never })
+
+export type El = { kind: string; props: Record<string, unknown> }
+
+export const flat = (node: unknown, out: El[] = []): El[] => {
+ if (Array.isArray(node)) node.forEach(child => flat(child, out))
+ else if (typeof node === 'object' && node !== null) {
+ out.push(node as El)
+ flat((node as El).props?.children, out)
+ }
+
+ return out
+}
+
+export const words = (tree: unknown): string => flat(tree).filter(el => el.kind === 'Text' && typeof el.props.children === 'string').map(el => el.props.children as string).join('\n')
+export const buttons = (tree: unknown): string[] => flat(tree).filter(el => el.kind === 'Button').map(el => String(el.props.label))
+export const envOf = (state: State, nowMs: number): SlotEnv => ({ ctx: ctxOf(state, nowMs), runs: [], run: null, phase: null, agent: null, ui: {} as never, nowMs })
+export const journal = (r: Rig): JournalEvent[] => parseJournal(r.files.get(J) ?? '').events
+
diff --git a/v3/docs/adr/ADR-463-workflows-worktrees-templates-anatole.md b/v3/docs/adr/ADR-463-workflows-worktrees-templates-anatole.md
index 71985b8236..14f22f78d8 100644
--- a/v3/docs/adr/ADR-463-workflows-worktrees-templates-anatole.md
+++ b/v3/docs/adr/ADR-463-workflows-worktrees-templates-anatole.md
@@ -55,7 +55,7 @@ start never matches. The board shows per agent the blocked and notified counts,
override, else the default), and an inspector tab lists one agent's alerts, masked and stripped. Everything is labelled as reported by the
mod and unauthenticated.
-**The console cannot stop or message a running workflow.** None of the three adds such a button; the page's own line saying so (ADR-464)
+**The console cannot stop or message a running workflow.** (Amended by ADR-465: the control tab can, through the engine's own TaskStop and SendMessage.) None of the three adds such a button; the page's own line saying so (ADR-464)
stays, and a worktree whose agent is running is kept with that reason instead of a disabled button.
## 3. Consequences
diff --git a/v3/docs/adr/ADR-464-workflows-page-wiring-and-slots.md b/v3/docs/adr/ADR-464-workflows-page-wiring-and-slots.md
index e9486c4755..f56ed926cc 100644
--- a/v3/docs/adr/ADR-464-workflows-page-wiring-and-slots.md
+++ b/v3/docs/adr/ADR-464-workflows-page-wiring-and-slots.md
@@ -42,7 +42,7 @@ View-local keys shadow tab keys while the page is open, as Claims' do. ADR-458's
**Notices.** A workflow run that changed to finished or failed between two reads raises one band notice (deduped by the notice ring).
Reads happen only while the page is open, so this is not a background watcher; it says what changed while the person looked.
-**What the console cannot do.** It cannot stop or message a running Claude Code workflow. Where those buttons would be, the page says so
+**What the console cannot do.** (Amended by ADR-465: it now can, through the engine's own TaskStop and SendMessage, behind the engine's permission check and the confirm card.) It could not stop or message a running Claude Code workflow when this was written. Where those buttons would be, the page says so
and where to do it (Claude Code's Workflows panel, TaskStop). The only writes are ADR-458's: stop and spawn a ruflo agent behind the confirm card.
**Seams.** `views/wf-slots.ts` is a registry; features call `registerSlot` from their own module and edit no shared file. Kinds:
diff --git a/v3/docs/adr/ADR-466-mission-autopilot.md b/v3/docs/adr/ADR-466-mission-autopilot.md
index 07698b2269..c4390514d8 100644
--- a/v3/docs/adr/ADR-466-mission-autopilot.md
+++ b/v3/docs/adr/ADR-466-mission-autopilot.md
@@ -88,9 +88,11 @@ Adaptation cannot widen the envelope, spend, tools, network, concurrency or rele
### 2.4 Parking (`views/ap-parked.ts`)
A task the envelope does not allow, that names a hard deny, that cannot be classified (`cls: null`: the classifier never
-defaults), that touches a path outside the folders, or that the permission preflight says would ask or deny, is **parked** with
-a question and a notice; the loop carries on with other work. The person answers approve once (that task, one step, then the
-envelope applies again) or deny (final). Retries past the policy also park.
+defaults), that names a path outside the folders, a URL host not on the network list or a GitHub repository not on the repo
+list, or that the permission preflight says would ask or deny, is **parked** with a question and a notice; the loop carries on
+with other work. The person answers approve once (that task, one step, then the envelope applies again) or deny (final). A
+class the person's own settings **deny** has no approve button and an old approval is ignored for it: the console does not lift
+a deny. A class the settings only *ask* about can be approved once (the engine still asks). Retries past the policy also park.
### 2.5 Safety
@@ -119,9 +121,28 @@ network, verify) are loaded from `.claude-flow/console/autopilot/envelope.draft.
- Every step that reached `done` without a verify command is flagged unverified; with none configured nothing is learned.
- Parallelism above 1 is bounded in practice by the mission's own one-task-at-a-time dispatch.
+### Honest limits (found in the adversarial review, 2026-10-06)
+
+- **The envelope gates what a task SAYS, not what a session does.** Class, paths, URL hosts and GitHub repositories are read from
+ the task text by keyword and pattern (`data/ap-guard.ts`); a relative path, a `~` path or a task that does not name its target is
+ not caught. Spend, concurrency, duration and the verify commands are enforced; **secret names are a record only** (nothing reads
+ them). The real boundary is the engine's permission check on every tool call, which autopilot never bypasses. The panel says so.
+- **Verify commands run through this console**, not the engine, so they are shown in full on the Start confirm card and are not run
+ where the person's settings deny the `test` class (the step is then done-unverified).
+- **A sleeping machine** is credited to steps in flight (a gap of three ticks or more between passes), so a step is not failed as
+ timed out for time nobody could have worked. **A clock set back** does not hold a backoff for the size of the jump. Day counts and
+ the digest use UTC, so DST changes nothing. The maximum duration is wall-clock: sleep counts toward it.
+- **A full disk**: a pass whose journal write fails starts nothing and says so; a Stop that reaches neither the journal nor the KILL
+ file is held in memory (and said to be "this session only") so a re-read cannot resume the loop, and is written when the disk answers.
+- **Stop wins a race**: a pass re-checks the flag and the phase just before it journals a step, because gathering facts (a verify
+ command, up to 10 minutes) happens after the first check.
+- **Adaptation** does not learn from a hand-over the mission refused, and does not re-propose a setting a trial was reverted away
+ from (without that, a clean old history re-proposed it every ten minutes).
+- Fixed: the Stop key `9` existed as a key slot and again as a board button (two buttons on one key ran it twice); the board button now carries no hotkey.
+
## 4. Test and benchmark plan
-`tests/ap-core.spec.ts` (40) and `tests/ap-live.spec.ts` (17), pure and fast: SHA-256 vectors; envelope validation, sealing,
+`tests/ap-core.spec.ts` (30), `tests/ap-adapt.spec.ts` (10), `tests/ap-live.spec.ts` (17) and, from the review, `tests/ap-review.spec.ts` (16, each a defect the review found), pure and fast: SHA-256 vectors; envelope validation, sealing,
tamper, widening; journal round trip, washing and the fixed argv; every ordering rule of the machine; **kill-switch property**
(60 seeded random walks: once the flag is seen no tick ever acts and nothing restarts the loop); **no double start** (60 walks:
no task has two live steps, no id repeats); **crash-resume** (30 walks, a fresh fold at every third prefix, each orphan