🌊 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(console): autopilot pure core - envelope, journal, step machine, adapt gate, guards (ADR-466)
ruva65692eb1cbb
diff --git a/plugins/ruflo-console/hooks/data/ap-adapt.ts b/plugins/ruflo-console/hooks/data/ap-adapt.tsnew file mode 100644index 0000000000..a4d24dfccc--- /dev/null+++ b/plugins/ruflo-console/hooks/data/ap-adapt.ts@@ -0,0 +1,218 @@+/**+ * What the autopilot may tune about its OWN way of working (ADR-466 §3), and the gate it must pass. Pure.+ *+ * Learning proposes and evaluates; it never decides and never widens. The tunables are step size, parallelism (never above the+ * envelope's cap), the model tier per class of step, the retry count and the ordering, each with a hard range. A change goes+ * propose -> evaluate (replay over the settled steps in the journal) -> promote, and only promote writes: it re-checks the result+ * against the envelope, and returns an immutable receipt whose hash chains to the one before. The current tunables are the fold of the+ * receipts over the defaults, so they survive a restart and every one can be reverted from its own receipt.+ *+ * Two kinds of change. A CONSERVATIVE one (lower parallelism, a higher tier, one more retry) is supported by evidence about the setting+ * being left: it is failing. An AGGRESSIVE one (higher parallelism, a lower tier) can only be supported by evidence about the setting+ * being left too (it is clean), so it enters a TRIAL and `reviewTrials` reverts it as soon as the new setting does worse. Steps that+ * 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 type { StepRec } from './ap-loop'++export const TIERS = ['low', 'mid', 'high'] as const+export type Tier = (typeof TIERS)[number]+export const ORDERINGS = ['fifo', 'smallest-first'] as const+export type Ordering = (typeof ORDERINGS)[number]++export type Tunables = { stepSize: number; parallelism: number; retries: number; ordering: Ordering; tiers: Record<string, Tier>; defaultTier: Tier }++export const RANGE = { stepSize: [1, 5], parallelism: [1, 8], retries: [0, 3] } as const+export const MIN_SAMPLES = 6+export const TRIAL_SAMPLES = 6+export const FAIL_HIGH = 0.4+export const CLEAN = 0.1++export const DEFAULTS: Tunables = { stepSize: 1, parallelism: 1, retries: 1, ordering: 'fifo', tiers: {}, defaultTier: 'mid' }++const clampInt = (value: number, [lo, hi]: readonly [number, number], cap = hi): number => Math.max(lo, Math.min(Math.min(hi, cap), Math.round(Number.isFinite(value) ? value : lo)))++/** The tunables forced into every range and under the envelope's concurrency. The envelope is only read. */+export function clampToEnvelope(t: Tunables, env: Envelope): Tunables {+ const tiers: Record<string, Tier> = {}++ for (const [cls, tier] of Object.entries(t.tiers)) if ((TIERS as readonly string[]).includes(tier)) tiers[cls] = tier++ return {+ stepSize: clampInt(t.stepSize, RANGE.stepSize),+ parallelism: clampInt(t.parallelism, RANGE.parallelism, env.concurrency),+ retries: clampInt(t.retries, RANGE.retries),+ ordering: (ORDERINGS as readonly string[]).includes(t.ordering) ? t.ordering : 'fifo',+ tiers,+ defaultTier: (TIERS as readonly string[]).includes(t.defaultTier) ? t.defaultTier : 'mid',+ }+}++export const tierOf = (t: Tunables, cls: string): Tier => t.tiers[cls] ?? t.defaultTier++export type Change = { path: string; from: string; to: string }++const PATH = /^(parallelism|retries|stepSize|ordering|tier\.[a-z][a-z-]{1,23})$/++/** One change applied, or null when the path is not a tunable or the value is out of range. Nothing outside the tunables can be reached. */+export function applyChange(t: Tunables, change: Change): Tunables | null {+ if (!PATH.test(change.path)) return null++ const next: Tunables = { ...t, tiers: { ...t.tiers } }++ if (change.path.startsWith('tier.')) {+ if (!(TIERS as readonly string[]).includes(change.to)) return null+ next.tiers[change.path.slice(5)] = change.to as Tier++ return next+ }++ if (change.path === 'ordering') {+ if (!(ORDERINGS as readonly string[]).includes(change.to)) return null+ next.ordering = change.to as Ordering++ return next+ }++ const n = Number(change.to)+ const key = change.path as 'parallelism' | 'retries' | 'stepSize'++ if (!Number.isInteger(n) || n < RANGE[key][0] || n > RANGE[key][1]) return null+ next[key] = n++ return next+}++export type Outcome = { at: number; cls: string; tier: string; par: number; attempt: number; ok: boolean; durationMs: number }++/** Settled, verified steps only: a verified done is a success, a failed step a failure, everything else is dropped. */+export function outcomesOf(steps: readonly StepRec[]): Outcome[] {+ return steps.flatMap(step => {+ const ok = step.status === 'done' && step.verified === true++ if (!ok && step.status !== 'failed') 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) }]+ })+}++export type Proposal = { id: string; change: Change; direction: 'conservative' | 'aggressive'; reason: string }+export type Verdict = { verdict: 'supported' | 'insufficient' | 'rejected'; evidence: string }++const rate = (list: readonly Outcome[]): number => (list.length === 0 ? 0 : list.filter(o => !o.ok).length / list.length)+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[] {+ const out: Proposal[] = []+ const classes = [...new Set(outcomes.map(o => o.cls))]++ for (const cls of classes) {+ const tier = tierOf(t, cls)+ const arm = outcomes.filter(o => o.cls === cls && o.tier === tier)++ if (arm.length < MIN_SAMPLES) continue++ const up = nextTier(tier, 1)+ const down = nextTier(tier, -1)++ if (rate(arm) >= FAIL_HIGH && up !== null) out.push({ id: `tier-${cls}-${up}`, change: { path: `tier.${cls}`, from: tier, to: up }, direction: 'conservative', reason: `${cls} steps fail ${pct(rate(arm))} at ${tier}` })+ else if (rate(arm) <= CLEAN && arm.length >= 2 * MIN_SAMPLES && down !== null) out.push({ id: `tier-${cls}-${down}`, change: { path: `tier.${cls}`, from: tier, to: down }, direction: 'aggressive', reason: `${cls} steps are clean at ${tier} (${arm.length} of them)` })+ }++ const here = outcomes.filter(o => o.par === t.parallelism)++ if (here.length >= MIN_SAMPLES && rate(here) >= FAIL_HIGH - 0.1 && t.parallelism > RANGE.parallelism[0]) out.push({ id: `par-${t.parallelism - 1}`, change: { path: 'parallelism', from: String(t.parallelism), to: String(t.parallelism - 1) }, direction: 'conservative', reason: `${pct(rate(here))} of steps fail at parallelism ${t.parallelism}` })+ else if (here.length >= 2 * MIN_SAMPLES && rate(here) <= CLEAN && t.parallelism < Math.min(RANGE.parallelism[1], env.concurrency)) out.push({ id: `par-${t.parallelism + 1}`, change: { path: 'parallelism', from: String(t.parallelism), to: String(t.parallelism + 1) }, direction: 'aggressive', reason: `steps are clean at parallelism ${t.parallelism} (${here.length} of them)` })++ const retried = outcomes.filter(o => o.attempt > 1)++ 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)+}++/** Replays the proposal over what the journal holds: does the evidence about the setting being left support leaving it? */+export function evaluate(p: Proposal, outcomes: readonly Outcome[], t: Tunables): Verdict {+ const key = p.change.path+ const arm = key.startsWith('tier.') ? outcomes.filter(o => o.cls === key.slice(5) && o.tier === p.change.from) : key === 'parallelism' ? outcomes.filter(o => o.par === Number(p.change.from)) : key === 'retries' ? outcomes.filter(o => o.attempt > 1) : []++ if (arm.length < MIN_SAMPLES) return { verdict: 'insufficient', evidence: `${arm.length} settled steps on the current setting, ${MIN_SAMPLES} needed` }++ const failing = rate(arm)++ if (p.direction === 'conservative') {+ const good = key === 'retries' ? 1 - failing >= 0.6 : failing >= FAIL_HIGH - 0.1++ return good ? { verdict: 'supported', evidence: `${arm.length} steps replayed: ${key === 'retries' ? `${pct(1 - failing)} of retries succeed` : `${pct(failing)} fail`}` } : { verdict: 'rejected', evidence: `${arm.length} steps replayed: not enough of a problem (${pct(failing)} fail)` }+ }++ return arm.length >= 2 * MIN_SAMPLES && failing <= CLEAN ? { verdict: 'supported', evidence: `${arm.length} steps replayed: ${pct(failing)} fail on the current setting; enters a trial and is reverted if the new setting does worse` } : { verdict: 'rejected', evidence: `${arm.length} steps replayed: ${pct(failing)} fail, not clean enough to try less caution` }+}++export type Promoted = { ok: true; tunables: Tunables; receipt: Receipt } | { ok: false; why: string }++export const GENESIS = 'genesis'+const receiptHash = (r: Omit<Receipt, 'hash'>): string => sha256(canonical(r))++/** The governed gate. Only a `supported` verdict passes; the result must stay inside the ranges and the envelope's concurrency; the receipt chains to `prev`. */+export function promote(p: Proposal, verdict: Verdict, t: Tunables, env: Envelope, prev: string, nowMs: number): Promoted {+ if (verdict.verdict !== 'supported') return { ok: false, why: `not promoted: ${verdict.verdict} (${verdict.evidence})` }++ const applied = applyChange(t, p.change)++ if (applied === null) return { ok: false, why: 'not promoted: that is not a tunable or the value is out of range' }++ const clamped = clampToEnvelope(applied, env)++ if (canonical(clamped) !== canonical(applied)) return { ok: false, why: 'not promoted: the result would sit outside the envelope or a range' }++ const body = { id: p.id, at: nowMs, path: p.change.path, from: p.change.from, to: p.change.to, direction: p.direction, evidence: verdict.evidence.slice(0, 300), prev }++ return { ok: true, tunables: clamped, receipt: { ...body, hash: receiptHash(body) } }+}++/** The receipts in order, each hashing its own body and naming the one before. A broken link is where the chain was edited. */+export function verifyReceipts(receipts: readonly Receipt[]): { ok: boolean; badAt: number | null } {+ let prev = GENESIS++ for (const [index, r] of receipts.entries()) {+ const { hash, ...body } = r++ if (r.prev !== prev || receiptHash(body) !== hash) return { ok: false, badAt: index }+ prev = hash+ }++ return { ok: true, badAt: null }+}++export const lastHash = (receipts: readonly Receipt[]): string => receipts.at(-1)?.hash ?? GENESIS++/** The tunables now: the defaults with each receipt applied in order, clamped to the envelope. A receipt that no longer applies is skipped (and is visible in the list). */+export function tunablesFrom(receipts: readonly Receipt[], env: Envelope, base: Tunables = DEFAULTS): Tunables {+ let t = clampToEnvelope(base, env)++ for (const r of receipts) t = clampToEnvelope(applyChange(t, { path: r.path, from: r.from, to: r.to }) ?? t, env)++ return t+}++/** Reverses a receipt: the proposal that puts `from` back. A reversal is always conservative-by-construction (it restores what ran before). */+export const reversal = (r: Receipt): Proposal => ({ id: `revert-${r.id}`.slice(0, 60), change: { path: r.path, from: r.to, to: r.from }, direction: 'conservative', reason: `revert ${r.id}` })++/** Aggressive receipts still on trial that the outcomes since then say did worse: returns the reversals to apply. */+export function reviewTrials(receipts: readonly Receipt[], outcomes: readonly Outcome[]): Proposal[] {+ const out: Proposal[] = []++ for (const [index, r] of receipts.entries()) {+ if (r.direction !== 'aggressive' || receipts.slice(index + 1).some(later => later.path === r.path)) continue++ const since = outcomes.filter(o => o.at >= r.at && (r.path.startsWith('tier.') ? o.cls === r.path.slice(5) && o.tier === r.to : r.path === 'parallelism' ? o.par === Number(r.to) : false))++ if (since.length >= TRIAL_SAMPLES && rate(since) > CLEAN + 0.1) out.push(reversal(r))+ }++ return out+}diff --git a/plugins/ruflo-console/hooks/data/ap-envelope.ts b/plugins/ruflo-console/hooks/data/ap-envelope.tsnew file mode 100644index 0000000000..0ff3c830b8--- /dev/null+++ b/plugins/ruflo-console/hooks/data/ap-envelope.ts@@ -0,0 +1,276 @@+/**+ * The autopilot's scope contract (ADR-466 §1): the ONE thing the person approves. Pure. An envelope is validated field by field (an+ * unknown field is an error, so nothing can smuggle in a grant), canonicalised, hashed and sealed with a revision. A sealed file whose+ * hash does not match its body is treated as tampered and the loop refuses to run on it. Hard denies are not part of the envelope: they+ * are a constant of this file, and an envelope that names one as allowed is rejected, never trimmed.+ */++/** Classes of action an envelope can allow. Each task is classified (data/ap-guard.ts) into exactly one, or is parked. */+export const TOOL_CLASSES = ['read', 'edit', 'test', 'git-local', 'git-branch', 'network', 'spawn', 'mcp'] as const+export type ToolClass = (typeof TOOL_CLASSES)[number]++/** What autopilot can never be granted, however the envelope is written. */+export const HARD_DENIES = ['publish', 'release', 'deploy', 'force-push', 'secret-access', 'delete-outside-worktree', 'envelope-edit'] as const+export type HardDeny = (typeof HARD_DENIES)[number]++export const ENVELOPE_VERSION = 1+export const MIN_DURATION_MS = 3_600_000+export const MAX_DURATION_MS = 90 * 86_400_000+export const MAX_CONCURRENCY = 8++export type Spend = { hourUsd: number; dayUsd: number; totalUsd: number }++export type Envelope = {+ name: string+ toolClasses: ToolClass[]+ /** Absolute folders the work may touch (a path is inside when it is the folder or below it). */+ paths: string[]+ /** `owner/name` repositories it may use. */+ repos: string[]+ /** Hostnames it may reach. */+ network: string[]+ /** Names of environment variables it may read; never their values. */+ secretEnv: string[]+ spend: Spend+ concurrency: number+ maxDurationMs: number+ /** Fixed argv lists run after a step to check its effect (tests, gates). A step with none is recorded as unverified. */+ verify: string[][]+ /** Recorded consent to run with Project Anatole absent or off. */+ acceptWithoutAnatole: boolean+}++const KEYS = ['name', 'toolClasses', 'paths', 'repos', 'network', 'secretEnv', 'spend', 'concurrency', 'maxDurationMs', 'verify', 'acceptWithoutAnatole'] as const+// eslint-disable-next-line no-control-regex+const BAD_CHARS = /[\u0000-\u001f\u007f-\u009f---]|[\u{e0000}-\u{e0fff}]/u+const REPO = /^[A-Za-z0-9_.-]{1,60}\/[A-Za-z0-9_.-]{1,100}$/+const HOST = /^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$/+const ENV = /^[A-Z][A-Z0-9_]{1,63}$/++export type Checked = { ok: true; envelope: Envelope } | { ok: false; errors: string[] }++const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)+const strings = (value: unknown, max: number): string[] | null => (Array.isArray(value) && value.length <= max && value.every(item => typeof item === 'string') ? (value as string[]) : null)+const money = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= 1_000_000++/** True for a name that is, or says it is, a hard deny. */+export const isHardDeny = (name: string): boolean => (HARD_DENIES as readonly string[]).includes(name.trim().toLowerCase())++/** Validates a candidate envelope. Every problem is listed; nothing is repaired or clamped. */+export function validateEnvelope(raw: unknown): Checked {+ const errors: string[] = []++ if (!isRecord(raw)) return { ok: false, errors: ['an envelope is an object'] }++ for (const key of Object.keys(raw)) if (!(KEYS as readonly string[]).includes(key)) errors.push(`unknown field "${key.slice(0, 30)}": nothing is granted by a field this console does not define`)++ const name = typeof raw.name === 'string' && raw.name.trim() !== '' && raw.name.length <= 60 && !BAD_CHARS.test(raw.name) ? raw.name.trim() : null++ if (name === null) errors.push('name: 1 to 60 printable characters')++ const classes = strings(raw.toolClasses, 12)++ if (classes === null) errors.push('toolClasses: a list of tool classes')++ for (const entry of classes ?? []) {+ if (isHardDeny(entry)) errors.push(`toolClasses: "${entry}" is a hard deny and can never be granted to autopilot`)+ else if (!(TOOL_CLASSES as readonly string[]).includes(entry)) errors.push(`toolClasses: unknown class "${entry.slice(0, 20)}"`)+ }++ const paths = strings(raw.paths, 20)++ if (paths === null || paths.length === 0) errors.push('paths: at least one absolute folder')++ for (const path of paths ?? []) if (!path.startsWith('/') || path === '/' || path.length > 300 || BAD_CHARS.test(path) || path.split('/').includes('..') || path.includes('\\')) errors.push(`paths: "${path.slice(0, 40)}" is not an absolute folder below the root with no ..`)++ const repos = strings(raw.repos, 20)++ if (repos === null) errors.push('repos: a list of owner/name')++ for (const repo of repos ?? []) if (!REPO.test(repo)) errors.push(`repos: "${repo.slice(0, 40)}" is not owner/name`)++ const network = strings(raw.network, 30)++ if (network === null) errors.push('network: a list of hostnames (empty means none)')++ for (const host of network ?? []) if (!HOST.test(host) || host.includes('..')) errors.push(`network: "${host.slice(0, 40)}" is not a lowercase hostname (no wildcard, no port)`)++ const secretEnv = strings(raw.secretEnv, 8)++ if (secretEnv === null) errors.push('secretEnv: a list of up to 8 variable names (empty means none)')++ for (const variable of secretEnv ?? []) if (!ENV.test(variable)) errors.push(`secretEnv: "${variable.slice(0, 30)}" is not a variable name; give names only, never values`)++ const spend = isRecord(raw.spend) ? raw.spend : null+ const spendOk = spend !== null && money(spend.hourUsd) && money(spend.dayUsd) && money(spend.totalUsd)++ if (!spendOk) errors.push('spend: hourUsd, dayUsd and totalUsd, each above 0')+ else if (!((spend.hourUsd as number) <= (spend.dayUsd as number) && (spend.dayUsd as number) <= (spend.totalUsd as number))) errors.push('spend: hour must not exceed day, nor day the total')++ const concurrency = raw.concurrency++ if (typeof concurrency !== 'number' || !Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) errors.push(`concurrency: a whole number from 1 to ${MAX_CONCURRENCY}`)++ const duration = raw.maxDurationMs++ if (typeof duration !== 'number' || !Number.isFinite(duration) || duration < MIN_DURATION_MS || duration > MAX_DURATION_MS) errors.push('maxDurationMs: from 1 hour to 90 days')++ const verify = raw.verify++ if (!Array.isArray(verify) || verify.length > 6 || !verify.every(argv => Array.isArray(argv) && argv.length >= 1 && argv.length <= 24 && argv.every(part => typeof part === 'string' && part.length <= 300 && !BAD_CHARS.test(part)))) errors.push('verify: up to 6 argv lists of plain strings (a program and its arguments, never a shell line)')++ if (typeof raw.acceptWithoutAnatole !== 'boolean') errors.push('acceptWithoutAnatole: true or false')++ if (errors.length > 0) return { ok: false, errors }++ return {+ ok: true,+ envelope: {+ name: name as string,+ toolClasses: [...new Set(classes as ToolClass[])].sort(),+ paths: [...new Set(paths as string[])].map(path => path.replace(/\/+$/, '')).sort(),+ repos: [...new Set(repos as string[])].sort(),+ network: [...new Set(network as string[])].sort(),+ secretEnv: [...new Set(secretEnv as string[])].sort(),+ spend: { hourUsd: (spend as Spend).hourUsd, dayUsd: (spend as Spend).dayUsd, totalUsd: (spend as Spend).totalUsd },+ concurrency: concurrency as number,+ maxDurationMs: duration as number,+ verify: (verify as string[][]).map(argv => [...argv]),+ acceptWithoutAnatole: raw.acceptWithoutAnatole as boolean,+ },+ }+}++/** Stable JSON: keys sorted at every level, so the same envelope always hashes the same. */+export function canonical(value: unknown): string {+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`+ if (isRecord(value)) return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`++ return JSON.stringify(value) ?? 'null'+}++const K = Uint32Array.from([+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,+])++/** SHA-256 in plain TypeScript (the engine's module host is not promised `node:crypto`). Hex digest of the UTF-8 text. */+export function sha256(text: string): string {+ const bytes = new TextEncoder().encode(text)+ const total = Math.ceil((bytes.length + 9) / 64) * 64+ const data = new Uint8Array(total)++ data.set(bytes)+ data[bytes.length] = 0x80++ const view = new DataView(data.buffer)++ view.setUint32(total - 8, Math.floor((bytes.length * 8) / 0x100000000))+ view.setUint32(total - 4, (bytes.length * 8) >>> 0)++ const h = Uint32Array.from([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19])+ const w = new Uint32Array(64)+ const rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n))++ for (let offset = 0; offset < total; offset += 64) {+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4)++ for (let i = 16; i < 64; i++) {+ const a = w[i - 15] as number+ const b = w[i - 2] as number++ w[i] = ((w[i - 16] as number) + (rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3)) + (w[i - 7] as number) + (rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10))) >>> 0+ }++ let [a, b, c, d, e, f, g, hh] = h as unknown as number[] as [number, number, number, number, number, number, number, number]++ for (let i = 0; i < 64; i++) {+ const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + (K[i] as number) + (w[i] as number)) >>> 0+ const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0++ hh = g+ g = f+ f = e+ e = (d + t1) >>> 0+ d = c+ c = b+ b = a+ a = (t1 + t2) >>> 0+ }++ const next = [a, b, c, d, e, f, g, hh]++ for (let i = 0; i < 8; i++) h[i] = ((h[i] as number) + (next[i] as number)) >>> 0+ }++ return [...h].map(word => word.toString(16).padStart(8, '0')).join('')+}++export const hashOf = (envelope: Envelope): string => sha256(canonical(envelope))++/** What is written to disk: the envelope, which revision of it this is, when the person approved it, and its hash. */+export type Sealed = { version: number; revision: number; approvedAtMs: number; hash: string; envelope: Envelope }++export const seal = (envelope: Envelope, revision: number, approvedAtMs: number): Sealed => ({ version: ENVELOPE_VERSION, revision, approvedAtMs, hash: hashOf(envelope), envelope })++export type Opened = { ok: true; sealed: Sealed } | { ok: false; why: string }++/** Reads a sealed envelope back: it must parse, validate, and hash to what it says. A mismatch is "tampered", never repaired. */+export function open(text: string | null): Opened {+ if (text === null) return { ok: false, why: 'no envelope approved yet' }++ let value: unknown++ try {+ value = JSON.parse(text)+ } catch {+ return { ok: false, why: 'the envelope file is not JSON' }+ }++ if (!isRecord(value) || value.version !== ENVELOPE_VERSION || typeof value.hash !== 'string' || typeof value.revision !== 'number' || typeof value.approvedAtMs !== 'number') return { ok: false, why: 'the envelope file is not a version-1 sealed envelope' }++ const checked = validateEnvelope(value.envelope)++ if (!checked.ok) return { ok: false, why: `the envelope no longer validates: ${checked.errors[0]}` }+ if (hashOf(checked.envelope) !== value.hash) return { ok: false, why: 'the envelope does not match its hash: it was changed outside the console, so autopilot will not run on it' }++ return { ok: true, sealed: { version: ENVELOPE_VERSION, revision: value.revision, approvedAtMs: value.approvedAtMs, hash: value.hash, envelope: checked.envelope } }+}++/** Dimensions in which `next` grants more than `prev`. Empty means it only narrows or keeps. Any change at all needs a fresh confirm; this says what the confirm card should warn about. */+export function widened(prev: Envelope, next: Envelope): string[] {+ const out: string[] = []+ const grew = (label: string, before: readonly string[], after: readonly string[]): void => {+ const added = after.filter(item => !before.includes(item))++ if (added.length > 0) out.push(`${label}: adds ${added.slice(0, 4).join(', ')}${added.length > 4 ? '…' : ''}`)+ }++ grew('tool classes', prev.toolClasses, next.toolClasses)+ grew('paths', prev.paths, next.paths)+ grew('repos', prev.repos, next.repos)+ grew('network', prev.network, next.network)+ grew('secret env', prev.secretEnv, next.secretEnv)+ grew('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: longer')+ if (next.acceptWithoutAnatole && !prev.acceptWithoutAnatole) out.push('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('..') && envelope.paths.some(root => path === root || path.startsWith(`${root}/`))++export const hostAllowed = (envelope: Envelope, host: string): boolean => envelope.network.includes(host.toLowerCase())++export const classAllowed = (envelope: Envelope, toolClass: string): boolean => (envelope.toolClasses as readonly string[]).includes(toolClass)++/** The file the sealed envelope lives in, and its siblings. */+export const AUTOPILOT_DIR = '.claude-flow/console/autopilot'+export const ENVELOPE_FILE = `${AUTOPILOT_DIR}/envelope.json`+export const KILL_FILE = `${AUTOPILOT_DIR}/KILL`diff --git a/plugins/ruflo-console/hooks/data/ap-guard.ts b/plugins/ruflo-console/hooks/data/ap-guard.tsnew file mode 100644index 0000000000..85975644d4--- /dev/null+++ b/plugins/ruflo-console/hooks/data/ap-guard.ts@@ -0,0 +1,119 @@+/**+ * What the autopilot checks before it acts (ADR-466 §5): task classification, the Project Anatole gate, the kill flag, the spend+ * windows, the permission preflight and what counts as an effect. Pure apart from `killSeen` and `preflightAll`, which are given the+ * reader and the (optional) permission check. Nothing here widens anything: a task it cannot place is `cls: null` and is parked.+ */+import { missionCostArgv, parseMissionCost } from './mission-cost'+import { KILL_FILE, TOOL_CLASSES, type HardDeny, type ToolClass } from './ap-envelope'+import type { EffectFact, Preflight, TaskFact } from './ap-loop'+import type { AnatoleFacts } from './anatole'+import type { Spend } from './ap-envelope'+import type { ReaderFs } from './files'++/** Words that mean a hard deny. Matching is deliberately broad: a false match only parks a task for a question. */+const DENIES: readonly [HardDeny, RegExp][] = [+ ['publish', /\b(npm\s+publish|publish(es|ed|ing)?\b|pnpm\s+publish|cargo\s+publish|twine|docker\s+push)/i],+ ['release', /\b(gh\s+release|git\s+tag\b.*push|cut\s+a\s+release|create\s+(a\s+)?release|release\s+notes?\s+and\s+tag)/i],+ ['deploy', /\b(deploy(s|ed|ing)?\b|gcloud\s+run\s+deploy|firebase\s+deploy|kubectl\s+apply|terraform\s+apply)/i],+ ['force-push', /(push\s+(--force|-f\b|--force-with-lease)|force[- ]push)/i],+ ['secret-access', /\b(api[_ -]?key|secret|credential|password|private\s+key|\.env\b|gcloud\s+secrets|token)\b/i],+ ['delete-outside-worktree', /\b(rm\s+-rf?\s+(\/|~|\$HOME)|delete\s+(the\s+)?(home|root|\/)|drop\s+database|mkfs|dd\s+of=\/dev)/i],+ ['envelope-edit', /\b(autopilot\s+(envelope|scope|settings)|widen\s+(the\s+)?(envelope|scope)|raise\s+(the\s+)?(spend|budget)\s+(cap|ceiling)|grant\s+(itself|autopilot))/i],+]++/** From least to most privileged: a task that matches several is classified as the most privileged. */+const CLASS_WORDS: readonly [ToolClass, RegExp][] = [+ ['read', /\b(read|review|analy[sz]e|research|audit|inspect|summari[sz]e|investigate|survey|list|explain|document)/i],+ ['test', /\b(test|vitest|jest|lint|typecheck|benchmark|verify|validate|build)\b/i],+ ['edit', /\b(implement|write|fix|refactor|add|edit|update|create|rename|patch|optimi[sz]e|migrate|remove)\b/i],+ ['git-local', /\b(commit|stage|stash)\b/i],+ ['git-branch', /\b(branch|worktree|merge|rebase|cherry-pick)\b/i],+ ['spawn', /\b(spawn|swarm|sub-?agent|delegate)\b/i],+ ['mcp', /\b(mcp|ruflo\s+tool|agentdb|memory_)/i],+ ['network', /\b(fetch|download|curl|http|api\s+call|web\s+search|clone)\b/i],+]++// eslint-disable-next-line no-control-regex+const PATH = /(?:^|[\s"'`(])(\/(?:[A-Za-z0-9._@-]+\/)*[A-Za-z0-9._@-]+)/++/** 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 {+ const text = `${title}\n${requirement}`+ 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++ return { id, title: title.slice(0, 160), cls, hardDeny, path }+}++/** Anatole's state for the gate: `on` only when its status says a mode other than off, `off` when it says off, else `absent`. */+export function anatoleFact(facts: AnatoleFacts | undefined): 'on' | 'off' | 'absent' {+ const mode = facts?.status?.mode ?? facts?.modeOverride ?? null++ if (facts === undefined || !facts.present || mode === null) return 'absent'++ return mode === 'off' ? 'off' : 'on'+}++/** True when the kill flag exists. A stat that throws means no flag (a missing file is how stat says it). Checked on every tick. */+export async function killSeen(fs: Pick<ReaderFs, 'stat'>, cwd: string): Promise<boolean> {+ try {+ return (await fs.stat(`${cwd.replace(/\/+$/, '')}/${KILL_FILE}`)) !== undefined+ } catch {+ return false+ }+}++export type SpendWindows = { hour: readonly string[] | null; day: readonly string[] | null; total: readonly string[] | null }++/** The three ledger commands (last hour, last 24 hours, since the start) for the project; null where a path check refuses. */+export function spendArgvs(root: string, startMs: number, nowMs: number, project: string): SpendWindows {+ return { hour: missionCostArgv(root, nowMs - 3_600_000, null, project), day: missionCostArgv(root, nowMs - 86_400_000, null, project), total: missionCostArgv(root, startMs, null, project) }+}++/** The three ledger outputs as spend. Any window that did not parse, or whose total is unknown (unpriced rows), makes the whole reading null: unknown is not zero. */+export function spendOf(out: { hour: string; day: string; total: string }): Spend | null {+ const [hour, day, total] = [parseMissionCost(out.hour), parseMissionCost(out.day), parseMissionCost(out.total)]++ if (hour?.usd == null || day?.usd == null || total?.usd == null) return null++ return { hourUsd: hour.usd, dayUsd: day.usd, totalUsd: total.usd }+}++/** The engine's own permission check, when the host offers one (`$.tool.check`). Absent in this console today: said, never faked. */+export type ToolCheck = (tool: string) => Promise<{ decision?: string } | string | undefined>++/** 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__claude-flow__task_update', network: 'WebFetch' }++export async function preflightAll(check: ToolCheck | undefined): Promise<Record<string, Preflight>> {+ const out: Record<string, Preflight> = {}++ for (const cls of TOOL_CLASSES) {+ if (check === undefined) {+ out[cls] = 'unwired'+ continue+ }++ try {+ const answer = await check(PREFLIGHT_TOOL[cls])+ const decision = typeof answer === 'string' ? answer : answer?.decision++ out[cls] = decision === 'allow' ? 'allow' : decision === 'deny' ? 'deny' : decision === 'ask' ? 'ask' : 'unwired'+ } catch {+ out[cls] = 'unwired'+ }+ }++ return out+}++/** A step's effect. The ruflo task store's status is a CLAIM (its swarm execution is a known no-op): `done` needs the person's own verify commands to pass; with none the step is `done-unverified` and says so everywhere. */+export function effectOf(storeStatus: string | undefined, verify: { ran: number; failed: number }): EffectFact {+ if (storeStatus === 'failed' || storeStatus === 'cancelled') return 'failed'+ if (storeStatus !== 'completed') return 'unknown'+ if (verify.failed > 0) return 'failed'++ return verify.ran === 0 ? 'done-unverified' : 'done'+}diff --git a/plugins/ruflo-console/hooks/data/ap-journal.ts b/plugins/ruflo-console/hooks/data/ap-journal.tsnew file mode 100644index 0000000000..8a038ebca7--- /dev/null+++ b/plugins/ruflo-console/hooks/data/ap-journal.ts@@ -0,0 +1,176 @@+/**+ * The autopilot's journal (ADR-466 §2): an append-only JSONL file that is both the durable checkpoint (the loop's state is a fold of it)+ * and the audit log (every autonomous action is a line). Pure apart from nothing: reading is `parseJournal(text)`, writing is a line+ * from `encodeLine` appended through the fixed argv from `appendArgv` (the host's fs is read-only). Every free-text field is washed+ * (escapes, control/bidi/tag characters, credential mask) BEFORE it is encoded, so nothing hostile or secret is ever stored, drawn+ * or exported. A line that does not validate is counted and dropped, never thrown on.+ */+import { ESCAPES, HIDDEN } from './parse'+import { maskSecrets } from './workflows'+import { AUTOPILOT_DIR } from './ap-envelope'++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++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'++export type JournalEvent = { at: number } & (+ | { t: 'start'; envHash: string; revision: number; anatole: Anatole }+ | { t: 'step.started'; id: string; task: string; cls: string; attempt: number; deadline: number; tier: string; par?: number }+ | { t: 'step.done'; id: string; verified: boolean }+ | { t: 'step.failed'; id: string; why: string }+ | { t: 'parked'; id: string; task: string; question: string }+ | { t: 'answered'; id: string; answer: 'once' | 'deny' }+ | { t: 'pause'; reason: string }+ | { t: 'resume' }+ | { t: 'stop'; reason: string }+ | { t: 'beat' }+ | { t: 'adapt'; receipt: Receipt }+ | { t: 'digest'; day: string }+)++export type EventType = JournalEvent['t']++/** Free text for the journal: escapes dropped, hidden characters spaced, credentials masked, capped. */+export const wash = (value: string, max = 240): string => maskSecrets(value.replace(ESCAPES, '').replace(HIDDEN, ' ').replace(/\s+/g, ' ').trim()).slice(0, max)++const ID = /^[A-Za-z0-9][A-Za-z0-9_.:@-]{0,95}$/++const num = (value: unknown): number | null => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null)+const str = (value: unknown, max = 240): string | null => (typeof value === 'string' ? wash(value, max) : null)+const id = (value: unknown): string | null => (typeof value === 'string' && ID.test(value) ? value : null)++function receiptOf(value: unknown): Receipt | null {+ if (typeof value !== 'object' || value === null) return null++ const r = value as Record<string, unknown>+ const at = num(r.at)+ const hash = typeof r.hash === 'string' && /^[0-9a-f]{64}$/.test(r.hash) ? r.hash : null+ const prev = typeof r.prev === 'string' && /^([0-9a-f]{64}|genesis)$/.test(r.prev) ? r.prev : null+ const direction = r.direction === 'conservative' || r.direction === 'aggressive' ? r.direction : null+ const [rid, path, from, to, evidence] = [id(r.id), str(r.path, 60), str(r.from, 60), str(r.to, 60), str(r.evidence, 300)]++ return at === null || hash === null || prev === null || direction === null || rid === null || path === null || from === null || to === null || evidence === null ? null : { id: rid, at, path, from, to, direction, evidence, prev, hash }+}++/** One line to an event, or null when it is not a valid event of a known type. */+export function parseLine(line: string): JournalEvent | null {+ if (line.length < 2 || line.length > LINE_MAX * 2 || line[0] !== '{') return null++ let r: Record<string, unknown>++ try {+ const parsed: unknown = JSON.parse(line)++ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null+ r = parsed as Record<string, unknown>+ } catch {+ return null+ }++ const at = num(r.at)++ if (at === null) return null++ switch (r.t) {+ case 'start': {+ const [envHash, revision] = [typeof r.envHash === 'string' && /^[0-9a-f]{64}$/.test(r.envHash) ? r.envHash : null, num(r.revision)]++ return envHash === null || revision === null || (r.anatole !== 'on' && r.anatole !== 'accepted-without') ? null : { t: 'start', at, envHash, revision, anatole: r.anatole }+ }++ case 'step.started': {+ const [sid, task, cls, attempt, deadline, tier, par] = [id(r.id), id(r.task), str(r.cls, 24), num(r.attempt), num(r.deadline), str(r.tier, 12), num(r.par)]++ return sid === null || task === null || cls === null || attempt === null || deadline === null || tier === null ? null : { t: 'step.started', at, id: sid, task, cls, attempt, deadline, tier, ...(par !== null && { par }) }+ }++ case 'step.done': {+ const sid = id(r.id)++ return sid === null || typeof r.verified !== 'boolean' ? null : { t: 'step.done', at, id: sid, verified: r.verified }+ }++ case 'step.failed': {+ const [sid, why] = [id(r.id), str(r.why)]++ return sid === null || why === null ? null : { t: 'step.failed', at, id: sid, why }+ }++ case 'parked': {+ const [pid, task, question] = [id(r.id), id(r.task), str(r.question, 300)]++ return pid === null || task === null || question === null ? null : { t: 'parked', at, id: pid, task, question }+ }++ case 'answered': {+ const pid = id(r.id)++ return pid === null || (r.answer !== 'once' && r.answer !== 'deny') ? null : { t: 'answered', at, id: pid, answer: r.answer }+ }++ case 'pause':+ case 'stop': {+ const reason = str(r.reason)++ return reason === null ? null : { t: r.t, at, reason }+ }++ case 'resume':+ case 'beat':+ return { t: r.t, at }++ case 'adapt': {+ const receipt = receiptOf(r.receipt)++ return receipt === null ? null : { t: 'adapt', at, receipt }+ }++ case 'digest': {+ const day = typeof r.day === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(r.day) ? r.day : null++ return day === null ? null : { t: 'digest', at, day }+ }++ default:+ return null+ }+}++/** Keys that hold hashes and ids: they are not text, and a long hex string would read as a key to the mask. */+const KEEP = new Set(['t', 'envHash', 'hash', 'prev', 'id', 'task', 'day', 'anatole', 'answer', 'direction'])++/** The line to append (with its newline). Free text is washed again here, so an event built from raw text is safe to write. */+export function encodeLine(event: JournalEvent): string {+ const clean = JSON.parse(JSON.stringify(event, (key, value: unknown) => (typeof value === 'string' && !KEEP.has(key) ? wash(value, 300) : value))) as JournalEvent+ const line = JSON.stringify(clean)++ return `${line.length > LINE_MAX ? JSON.stringify({ t: 'pause', at: event.at, reason: 'an event was too long to journal' }) : line}\n`+}++export type ParsedJournal = { events: JournalEvent[]; bad: number; /** True when the text was cut at the first line because the file passed the cap. */ isCapped: boolean }++/** A journal as events, in file order. A half-written last line and any hostile line are counted in `bad`. */+export function parseJournal(text: string | null): ParsedJournal {+ if (text === null) return { events: [], bad: 0, isCapped: false }++ const lines = text.split('\n').filter(line => line.trim() !== '')+ const events: JournalEvent[] = []++ for (const line of lines) {+ const event = parseLine(line)++ if (event !== null) events.push(event)+ }++ return { events, bad: lines.length - events.length, isCapped: false }+}++/** Fixed argv that appends stdin to the journal: GNU dd with O_APPEND; no shell, the path is one element. */+export const appendArgv = (path: string): readonly string[] => ['dd', `of=${path}`, 'oflag=append', 'conv=notrunc', 'status=none']++/** Fixed argv that creates a flag file (the kill switch) and its folder: GNU install -D from an empty stdin. */+export const touchArgv = (path: string): readonly string[] => ['install', '-D', '-m', '600', '/dev/null', path]diff --git a/plugins/ruflo-console/hooks/data/ap-loop.ts b/plugins/ruflo-console/hooks/data/ap-loop.tsnew file mode 100644index 0000000000..bf75a73d8d--- /dev/null+++ b/plugins/ruflo-console/hooks/data/ap-loop.ts@@ -0,0 +1,327 @@+/**+ * The autopilot's step machine (ADR-466 §2, §4, §5). Pure: `foldJournal(events)` is the whole state, `tick(state, facts)` answers what+ * to journal and whether to start one step. No I/O, no clock (the time is in `facts`), so every rule is testable and a crash can only+ * lose what was not journaled yet.+ *+ * The order of the checks in `tick` IS the safety property: the kill switch is looked at before anything else and a stopped loop never+ * acts again without an explicit `start` event; an in-flight step is settled (finished, timed out, or found lost) before any new one+ * 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 type { Anatole, JournalEvent, Receipt } from './ap-journal'++export type Phase = 'idle' | 'running' | 'paused' | 'stopped'+export type StepRec = { id: string; task: string; cls: string; attempt: number; startedAt: number; deadline: number; status: 'started' | 'done' | 'failed'; verified?: boolean; why?: string; tier: string; par?: number; endedAt?: number }+export type ParkedRec = { id: string; task: string; question: string; at: number; answer?: 'once' | 'deny'; /** True once a step ran under an `once` answer. */ isUsed?: boolean }++export type LoopState = {+ phase: Phase+ startedAtMs: number | null+ envHash: string | null+ revision: number | null+ anatole: Anatole | null+ reason: string | null+ steps: StepRec[]+ parked: ParkedRec[]+ failures: number+ lastFailureAt: number | null+ lastBeatAt: number | null+ lastDigestDay: string | null+ receipts: Receipt[]+}++export const emptyLoop = (): LoopState => ({ phase: 'idle', startedAtMs: null, envHash: null, revision: null, anatole: null, reason: null, steps: [], parked: [], failures: 0, lastFailureAt: null, lastBeatAt: null, lastDigestDay: null, receipts: [] })++export const KEEP_STEPS = 400+/** Consecutive failures that pause the loop instead of letting it thrash. */+export const FAILURE_BUDGET = 5+export const BACKOFF_BASE_MS = 60_000+export const BACKOFF_MAX_MS = 3_600_000+export const BEAT_MS = 300_000+/** The share of the total spend ceiling at which the loop pauses (it stops at 100%). */+export const PAUSE_AT = 0.8++/** The loop's state as the journal says it. `base` is a checkpoint to continue from. */+export function foldJournal(events: readonly JournalEvent[], base: LoopState = emptyLoop()): LoopState {+ const s: LoopState = { ...base, steps: base.steps.map(step => ({ ...step })), parked: base.parked.map(p => ({ ...p })), receipts: [...base.receipts] }++ for (const e of events) {+ switch (e.t) {+ case 'start':+ Object.assign(s, { phase: 'running', startedAtMs: e.at, envHash: e.envHash, revision: e.revision, anatole: e.anatole, reason: null, failures: 0, lastFailureAt: null })+ break+ case 'step.started':+ // A repeated id (a replayed line) changes nothing: one step per id.+ if (!s.steps.some(step => step.id === e.id)) {+ s.steps.push({ id: e.id, task: e.task, cls: e.cls, attempt: e.attempt, startedAt: e.at, deadline: e.deadline, status: 'started', tier: e.tier, ...(e.par !== undefined && { par: e.par }) })++ const once = s.parked.find(p => p.task === e.task && p.answer === 'once' && p.isUsed !== true)++ if (once !== undefined) once.isUsed = true+ }+ break+ case 'step.done': {+ const step = s.steps.find(x => x.id === e.id && x.status === 'started')++ if (step !== undefined) {+ Object.assign(step, { status: 'done', verified: e.verified, endedAt: e.at })+ s.failures = 0+ }+ break+ }++ case 'step.failed': {+ const step = s.steps.find(x => x.id === e.id && x.status === 'started')++ if (step !== undefined) {+ Object.assign(step, { status: 'failed', why: e.why, endedAt: e.at })+ s.failures += 1+ s.lastFailureAt = e.at+ }+ break+ }++ case 'parked':+ if (!s.parked.some(p => p.id === e.id && p.answer === undefined)) s.parked.push({ id: e.id, task: e.task, question: e.question, at: e.at })+ break+ case 'answered': {+ const held = s.parked.find(p => p.id === e.id && p.answer === undefined)++ if (held !== undefined) held.answer = e.answer+ break+ }++ case 'pause':+ if (s.phase === 'running') Object.assign(s, { phase: 'paused', reason: e.reason })+ break+ case 'resume':+ if (s.phase === 'paused') Object.assign(s, { phase: 'running', reason: null, failures: 0 })+ break+ case 'stop':+ Object.assign(s, { phase: 'stopped', reason: e.reason })+ break+ case 'beat':+ s.lastBeatAt = e.at+ break+ case 'adapt':+ s.receipts.push(e.receipt)+ break+ case 'digest':+ s.lastDigestDay = e.day+ break+ }+ }++ return compactState(s)+}++/** Old finished steps are forgotten so weeks of running stay small; started steps and unanswered parks are never dropped. */+export function compactState(s: LoopState): LoopState {+ const live = s.steps.filter(step => step.status === 'started')+ const rest = s.steps.filter(step => step.status !== 'started').slice(-KEEP_STEPS)+ const keep = new Set([...live, ...rest])++ 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 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 }++export type Facts = {+ nowMs: number+ killSeen: boolean+ /** Null when the sealed envelope is missing, invalid or does not match its hash. */+ envelope: Envelope | null+ anatole: 'on' | 'off' | 'absent'+ /** Null when the cost ledger has not been read: unknown is never drawn or treated as $0. */+ spend: Spend | null+ /** The next ready task the picker chose, already excluding parked and denied tasks (`skipSet`). */+ task: TaskFact | null+ effects: Readonly<Record<string, EffectFact>>+ /** Started steps that no executor in this process is working on (they began before a restart). */+ orphans: ReadonlySet<string>+ tunables: Tunables+ preflight: Readonly<Record<string, Preflight>>+}++export type Decision = { events: JournalEvent[]; act: { id: string; task: TaskFact; cls: string; attempt: number; tier: string; deadline: number } | null; status: string }++const idle = (status: string, events: JournalEvent[] = []): Decision => ({ events, act: null, status })++/** The tasks the picker must skip: parked and waiting, denied, or already carrying a started or done step. */+export function skipSet(s: LoopState): Set<string> {+ return new Set([...s.parked.filter(p => p.answer === undefined || p.answer === 'deny' || p.isUsed === true).map(p => p.task), ...s.steps.filter(step => step.status !== 'failed').map(step => step.task)])+}++const parkId = (task: string, why: string): string => `p-${sha256(`${task}:${why}`).slice(0, 12)}`+export const stepId = (task: string, attempt: number): string => `s-${sha256(`${task}:${attempt}`).slice(0, 16)}`++export const backoffMs = (failures: number): number => Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.max(0, failures - 1))++/** Why a task cannot run inside the envelope, or null when it can. Ambiguous or out of scope means park with a question. */+export function whyParked(task: TaskFact, env: Envelope, preflight: Readonly<Record<string, Preflight>>): string | null {+ 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.`++ return null+}++/** One pass. See the file header for why the order matters. */+export function tick(s: LoopState, f: Facts): Decision {+ const now = f.nowMs++ if (s.phase === 'stopped') return idle(`stopped: ${s.reason ?? 'stopped'}`)+ if (f.killSeen) return idle('stopped: kill switch', [{ t: 'stop', at: now, reason: 'kill switch' }])+ if (s.phase === 'idle') return idle('not started')++ const events: JournalEvent[] = []++ // 1. Settle what is in flight: finished, timed out, or lost to a restart. Never rerun it here.+ const open = s.steps.filter(step => step.status === 'started')+ let failures = s.failures+ let lastFailure = s.lastFailureAt+ let stillOpen = 0++ for (const step of open) {+ const effect = f.effects[step.id] ?? 'unknown'++ if (effect === 'done' || effect === 'done-unverified') {+ events.push({ t: 'step.done', at: now, id: step.id, verified: effect === 'done' })+ failures = 0+ } else if (effect === 'failed') {+ events.push({ t: 'step.failed', at: now, id: step.id, why: 'the task reported failure' })+ failures += 1+ lastFailure = now+ } else if (now > step.deadline) {+ events.push({ t: 'step.failed', at: now, id: step.id, why: 'timed out' })+ failures += 1+ lastFailure = now+ } else if (f.orphans.has(step.id) && effect === 'absent') {+ events.push({ t: 'step.failed', at: now, id: step.id, why: 'lost on restart: no effect found' })+ failures += 1+ lastFailure = now+ } else stillOpen += 1+ }++ if (s.phase === 'paused') return idle(`paused: ${s.reason ?? 'paused'}`, events)++ const stopWith = (reason: string): Decision => ({ events: [...events, { t: 'stop', at: now, reason }], act: null, status: `stopped: ${reason}` })+ const pauseWith = (reason: string): Decision => ({ events: [...events, { t: 'pause', at: now, reason }], act: null, status: `paused: ${reason}` })++ // 2. The envelope, the clock, Anatole.+ if (f.envelope === null) return stopWith('the envelope is missing, invalid or was changed outside the console')+ if (s.startedAtMs !== null && now - s.startedAtMs > f.envelope.maxDurationMs) return stopWith('the envelope\'s maximum duration passed')+ if (f.anatole !== 'on' && !f.envelope.acceptWithoutAnatole) return pauseWith(f.anatole === 'off' ? 'Project Anatole is off' : 'Project Anatole is not installed')++ // 3. Spend. Total first: 100% stops, 80% pauses (nothing in flight is cut); an hour or day ceiling only holds the next step back.+ if (f.spend === null) return { events, act: null, status: 'waiting: spend not read yet' }+ if (f.spend.totalUsd >= f.envelope.spend.totalUsd) return stopWith('total spend ceiling reached')+ if (f.spend.totalUsd >= f.envelope.spend.totalUsd * PAUSE_AT) return pauseWith('80% of the total spend ceiling')+ if (f.spend.dayUsd >= f.envelope.spend.dayUsd) return { events, act: null, status: 'waiting: day spend ceiling' }+ if (f.spend.hourUsd >= f.envelope.spend.hourUsd) return { events, act: null, status: 'waiting: hour spend ceiling' }++ // 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'}` }++ // 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` }++ const task = f.task++ if (task === null) {+ if (s.lastBeatAt === null || now - s.lastBeatAt >= BEAT_MS) events.push({ t: 'beat', at: now })++ return { events, act: null, status: 'nothing ready' }+ }++ // 6. Never twice: a task with a started or done step, or that was denied, is not started.+ if (s.steps.some(step => step.task === task.id && step.status !== 'failed')) return { events, act: null, status: `task ${task.id} already has a step` }++ 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)++ 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.`++ return park(s, events, task, 'retries', why, now)+ }++ const why = answeredOnce ? null : whyParked(task, f.envelope, f.preflight)++ if (why !== null) return park(s, events, task, why, why, now)++ const cls = task.cls ?? 'read'+ const tier = f.tunables.tierOf(cls)++ return { events: [...events, { t: 'step.started', at: now, id: stepId(task.id, attempt), task: task.id, cls, attempt, deadline: now + f.tunables.stepTimeoutMs, tier, par: f.tunables.parallelism }], act: { id: stepId(task.id, attempt), task, cls, attempt, tier, deadline: now + f.tunables.stepTimeoutMs }, status: `started ${task.id}` }+}++function park(s: LoopState, events: JournalEvent[], task: TaskFact, key: string, question: string, now: number): Decision {+ const id = parkId(task.id, key)++ if (!s.parked.some(p => p.id === id && p.answer === undefined)) events.push({ t: 'parked', at: now, id, task: task.id, question })++ return { events, act: null, status: `parked ${task.id}` }+}++/** The facts the band and the panel draw from a state: nothing here is a placeholder. */+export type Summary = { phase: Phase; day: number | null; running: number; parked: number; done: number; failed: number; unverified: number; reason: string | null }++export function summarize(s: LoopState, nowMs: number): Summary {+ return {+ phase: s.phase,+ day: s.startedAtMs === null ? null : Math.floor(Math.max(0, nowMs - s.startedAtMs) / 86_400_000) + 1,+ running: s.steps.filter(step => step.status === 'started').length,+ parked: s.parked.filter(p => p.answer === undefined).length,+ done: s.steps.filter(step => step.status === 'done').length,+ failed: s.steps.filter(step => step.status === 'failed').length,+ unverified: s.steps.filter(step => step.status === 'done' && step.verified === false).length,+ reason: s.reason,+ }+}++/** The band text: `autopilot day 3 · $12/$40 · 2 parked`. A spend that was not read is `$n/a`, never `$0`. */+export function bandText(s: LoopState, nowMs: number, spendUsd: number | null, env: Envelope | null): string {+ const sum = summarize(s, nowMs)++ if (sum.phase === 'idle') return ''++ const money = (n: number): string => `$${Math.round(n * 100) / 100}`+ const cost = `${spendUsd === null ? '$n/a' : money(spendUsd)}/${env === null ? '$n/a' : money(env.spend.totalUsd)}`+ const state = sum.phase === 'running' ? '' : ` ${sum.phase}`++ return `autopilot${state} day ${sum.day ?? 'n/a'} · ${cost} · ${sum.parked} parked`+}++/** Events that fold back to this state's live parts, for compaction: a rotated journal starts from these and the old one is archived. */+export function snapshotEvents(s: LoopState): JournalEvent[] {+ if (s.startedAtMs === null || s.envHash === null || s.revision === null || s.anatole === null) return []++ const out: JournalEvent[] = [{ t: 'start', at: s.startedAtMs, envHash: s.envHash, revision: s.revision, anatole: s.anatole }]++ for (const p of s.parked) {+ out.push({ t: 'parked', at: p.at, id: p.id, task: p.task, question: p.question })+ if (p.answer !== undefined) out.push({ t: 'answered', at: p.at, id: p.id, answer: p.answer })+ }++ for (const step of s.steps.slice(-50)) {+ out.push({ t: 'step.started', at: step.startedAt, id: step.id, task: step.task, cls: step.cls, attempt: step.attempt, deadline: step.deadline, tier: step.tier, ...(step.par !== undefined && { par: step.par }) })+ if (step.status === 'done') out.push({ t: 'step.done', at: step.endedAt ?? step.startedAt, id: step.id, verified: step.verified === true })+ if (step.status === 'failed') out.push({ t: 'step.failed', at: step.endedAt ?? step.startedAt, id: step.id, why: step.why ?? 'failed' })+ }++ for (const receipt of s.receipts) out.push({ t: 'adapt', at: receipt.at, receipt })+ if (s.lastDigestDay !== null) out.push({ t: 'digest', at: s.startedAtMs, day: s.lastDigestDay })+ if (s.phase === 'paused') out.push({ t: 'pause', at: s.startedAtMs, reason: s.reason ?? 'paused' })+ if (s.phase === 'stopped') out.push({ t: 'stop', at: s.startedAtMs, reason: s.reason ?? 'stopped' })++ return out+}diff --git a/plugins/ruflo-console/tests/ap-core.spec.ts b/plugins/ruflo-console/tests/ap-core.spec.tsnew file mode 100644index 0000000000..affb8cdf33--- /dev/null+++ b/plugins/ruflo-console/tests/ap-core.spec.ts@@ -0,0 +1,540 @@+/**+ * The autopilot's pure core (ADR-466): envelope validation and sealing, the journal, the step machine (including the kill-switch and+ * crash-resume properties, run over a seeded random walk), the adaptation gate and the guards. Pure and fast. Run with+ * npx vitest run plugins/ruflo-console/tests/ap-core.spec.ts --testTimeout=30000+ */+import { describe, expect, it } from 'vitest'++import { applyChange, clampToEnvelope, DEFAULTS, evaluate, lastHash, outcomesOf, promote, propose, reviewTrials, tunablesFrom, verifyReceipts, type Tunables } from '../hooks/data/ap-adapt'+import { canonical, hashOf, HARD_DENIES, open, pathAllowed, seal, sha256, validateEnvelope, widened, type Envelope } from '../hooks/data/ap-envelope'+import { anatoleFact, classifyTask, effectOf, preflightAll } from '../hooks/data/ap-guard'+import { appendArgv, encodeLine, parseJournal, parseLine, type JournalEvent } from '../hooks/data/ap-journal'+import { bandText, emptyLoop, FAILURE_BUDGET, foldJournal, skipSet, snapshotEvents, stepId, summarize, tick, type Facts, type LoopState, type TaskFact } from '../hooks/data/ap-loop'++const T0 = Date.parse('2026-10-06T00:00:00.000Z')+const H = 3_600_000++const ENV: Envelope = { name: 'night shift', toolClasses: ['edit', 'read', 'test'], paths: ['/work/repo'], repos: ['ruvnet/ruflo'], network: [], secretEnv: [], spend: { hourUsd: 2, dayUsd: 10, totalUsd: 40 }, concurrency: 2, maxDurationMs: 7 * 24 * H, verify: [['true']], acceptWithoutAnatole: false }+const task = (id: string, over: Partial<TaskFact> = {}): TaskFact => ({ id, title: `do ${id}`, cls: 'edit', hardDeny: null, path: '/work/repo/src/a.ts', ...over })++const facts = (over: Partial<Facts> = {}): Facts => ({ nowMs: T0, killSeen: false, envelope: ENV, anatole: 'on', spend: { hourUsd: 0, dayUsd: 0, totalUsd: 0 }, task: task('t1'), effects: {}, orphans: new Set(), tunables: { parallelism: 1, retries: 1, stepTimeoutMs: 10 * 60_000, tierOf: () => 'mid' }, preflight: {}, ...over })++const started = (at = T0): JournalEvent => ({ t: 'start', at, envHash: hashOf(ENV), revision: 1, anatole: 'on' })+const running = (): LoopState => foldJournal([started()])++describe('sha256', () => {+ it('matches the published vectors', () => {+ expect(sha256('')).toBe('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')+ expect(sha256('abc')).toBe('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')+ expect(sha256('a'.repeat(1000))).toBe('41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3')+ })+})++describe('envelope', () => {+ it('accepts a good envelope and canonicalises it', () => {+ const ok = validateEnvelope({ ...ENV, toolClasses: ['test', 'read', 'edit', 'read'] })++ expect(ok.ok).toBe(true)+ expect(ok.ok && ok.envelope.toolClasses).toEqual(['edit', 'read', 'test'])+ expect(canonical({ b: 1, a: [2, { d: 1, c: 2 }] })).toBe('{"a":[2,{"c":2,"d":1}],"b":1}')+ })++ it('rejects every hard deny named as a class, never trims it', () => {+ for (const deny of HARD_DENIES) {+ const bad = validateEnvelope({ ...ENV, toolClasses: ['edit', deny] })++ expect(bad.ok).toBe(false)+ expect(!bad.ok && bad.errors.join(' ')).toContain('hard deny')+ }+ })++ it('rejects unknown fields, bad paths, secrets as values, bad spend and duration', () => {+ const errs = (patch: Record<string, unknown>): string => {+ const r = validateEnvelope({ ...ENV, ...patch })++ return r.ok ? '' : r.errors.join('|')+ }++ expect(errs({ grants: ['publish'] })).toContain('unknown field')+ expect(errs({ paths: ['/work/../etc'] })).toContain('paths')+ expect(errs({ paths: ['/'] })).toContain('paths')+ expect(errs({ paths: ['relative'] })).toContain('paths')+ expect(errs({ secretEnv: ['sk-live-abc123'] })).toContain('secretEnv')+ expect(errs({ spend: { hourUsd: 5, dayUsd: 2, totalUsd: 40 } })).toContain('hour must not exceed day')+ expect(errs({ spend: { hourUsd: 0, dayUsd: 2, totalUsd: 40 } })).toContain('spend')+ expect(errs({ maxDurationMs: 365 * 86_400_000 })).toContain('maxDurationMs')+ expect(errs({ concurrency: 99 })).toContain('concurrency')+ expect(errs({ network: ['*.evil.com'] })).toContain('network')+ expect(errs({ verify: ['rm -rf /'] })).toContain('verify')+ expect(errs({ repos: ['not a repo'] })).toContain('repos')+ })++ it('seals with a hash and opens only an untouched file', () => {+ const sealed = seal(ENV, 3, T0)+ const text = JSON.stringify(sealed)++ expect(open(text).ok).toBe(true)++ const edited = JSON.stringify({ ...sealed, envelope: { ...ENV, spend: { ...ENV.spend, totalUsd: 4000 } } })+ const result = open(edited)++ expect(result.ok).toBe(false)+ expect(!result.ok && result.why).toContain('does not match its hash')+ expect(open(null).ok).toBe(false)+ expect(open('{nope').ok).toBe(false)+ })++ it('says what widened and treats a pure narrowing as nothing', () => {+ expect(widened(ENV, { ...ENV, toolClasses: ['read'] })).toEqual([])+ expect(widened(ENV, { ...ENV, toolClasses: [...ENV.toolClasses, 'network'], concurrency: 4, acceptWithoutAnatole: true }).length).toBe(3)+ expect(widened(ENV, { ...ENV, spend: { ...ENV.spend, totalUsd: 80 } })[0]).toContain('totalUsd')+ })++ it('compares paths at a folder boundary and refuses ..', () => {+ expect(pathAllowed(ENV, '/work/repo')).toBe(true)+ expect(pathAllowed(ENV, '/work/repo/src/x.ts')).toBe(true)+ expect(pathAllowed(ENV, '/work/repository')).toBe(false)+ expect(pathAllowed(ENV, '/work/repo/../etc')).toBe(false)+ })+})++describe('journal', () => {+ it('round-trips events and drops what does not validate', () => {+ const events: JournalEvent[] = [started(), { t: 'step.started', at: T0 + 1, id: 's-1', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 99, tier: 'mid', par: 1 }, { t: 'step.done', at: T0 + 2, id: 's-1', verified: true }, { t: 'beat', at: T0 + 3 }]+ const text = events.map(encodeLine).join('')+ const parsed = parseJournal(`${text}{"t":"step.done","at":1\n{"t":"nope","at":1}\n[1]\n`)++ expect(parsed.events).toEqual(events)+ expect(parsed.bad).toBe(3)+ })++ it('washes escapes, control and tag characters and credentials before a line is written', () => {+ const line = encodeLine({ t: 'stop', at: T0, reason: `\u001b[31mred\u001b[0mevil\u{e0041} sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789` })++ expect(line).not.toMatch(/\u001b||[\u{e0000}-\u{e0fff}]u/u)+ expect(line).not.toContain('sk-ant-api03-abcdef')+ expect(line.endsWith('\n')).toBe(true)+ expect(parseLine(line.trim())?.t).toBe('stop')+ })++ it('appends with a fixed argv, the path as one element', () => {+ expect(appendArgv('/p/j; rm -rf /.jsonl')).toEqual(['dd', 'of=/p/j; rm -rf /.jsonl', 'oflag=append', 'conv=notrunc', 'status=none'])+ })+})++describe('loop: ordering of the safety checks', () => {+ it('does nothing before a start, and nothing after a stop without a new start', () => {+ expect(tick(emptyLoop(), facts()).act).toBeNull()++ const stopped = foldJournal([started(), { t: 'stop', at: T0 + 1, reason: 'x' }])++ expect(tick(stopped, facts()).act).toBeNull()+ expect(tick(foldJournal([started(), { t: 'stop', at: T0 + 1, reason: 'x' }, started(T0 + 5)]), facts()).act).not.toBeNull()+ })++ it('starts one step with a deterministic id and a deadline', () => {+ const d = tick(running(), facts())++ expect(d.act?.id).toBe(stepId('t1', 1))+ expect(d.act?.deadline).toBe(T0 + 10 * 60_000)+ expect(d.events[0]?.t).toBe('step.started')+ })++ it('the kill flag stops before anything else, even with a step in flight', () => {+ const s = foldJournal([started(), { t: 'step.started', at: T0, id: 's-a', task: 't0', cls: 'edit', attempt: 1, deadline: T0 + H, tier: 'mid' }])+ const d = tick(s, facts({ killSeen: true, effects: { 's-a': 'done' } }))++ expect(d.act).toBeNull()+ expect(d.events.map(e => e.t)).toEqual(['stop'])+ })++ it('stops on a missing or tampered envelope and when the duration passes', () => {+ expect(tick(running(), facts({ envelope: null })).events[0]).toMatchObject({ t: 'stop' })+ expect(tick(running(), facts({ nowMs: T0 + 8 * 24 * H })).events[0]).toMatchObject({ t: 'stop' })+ })++ it('refuses to run without Anatole unless that was accepted in the envelope', () => {+ expect(tick(running(), facts({ anatole: 'off' })).events[0]).toMatchObject({ t: 'pause', reason: 'Project Anatole is off' })+ expect(tick(running(), facts({ anatole: 'absent' })).events[0]).toMatchObject({ t: 'pause' })+ expect(tick(running(), facts({ anatole: 'absent', envelope: { ...ENV, acceptWithoutAnatole: true } })).act).not.toBeNull()+ })++ it('spend ladder: unread waits, 80% of total pauses, 100% stops, hour and day ceilings hold back', () => {+ expect(tick(running(), facts({ spend: null })).status).toContain('spend not read')+ expect(tick(running(), facts({ spend: null })).act).toBeNull()+ expect(tick(running(), facts({ spend: { hourUsd: 0, dayUsd: 0, totalUsd: 31.9 } })).act).not.toBeNull()+ expect(tick(running(), facts({ spend: { hourUsd: 0, dayUsd: 0, totalUsd: 32 } })).events[0]).toMatchObject({ t: 'pause' })+ expect(tick(running(), facts({ spend: { hourUsd: 0, dayUsd: 0, totalUsd: 40 } })).events[0]).toMatchObject({ t: 'stop' })+ expect(tick(running(), facts({ spend: { hourUsd: 2, dayUsd: 3, totalUsd: 5 } })).status).toContain('hour spend')+ expect(tick(running(), facts({ spend: { hourUsd: 0, dayUsd: 10, totalUsd: 20 } })).status).toContain('day spend')+ })++ it('an 80% pause never cuts a step in flight: it is still settled, not failed', () => {+ const s = foldJournal([started(), { t: 'step.started', at: T0, id: 's-a', task: 't0', cls: 'edit', attempt: 1, deadline: T0 + H, tier: 'mid' }])+ const d = tick(s, facts({ nowMs: T0 + 60_000, spend: { hourUsd: 0, dayUsd: 0, totalUsd: 33 }, effects: { 's-a': 'done' } }))++ expect(d.events.map(e => e.t)).toEqual(['step.done', 'pause'])+ })++ it('settles in-flight steps: done, failed report, timeout, and lost-on-restart only for orphans', () => {+ const s = foldJournal([started(), { t: 'step.started', at: T0, id: 's-a', task: 't0', cls: 'edit', attempt: 1, deadline: T0 + 1000, tier: 'mid' }])++ expect(tick(s, facts({ nowMs: T0 + 10, effects: { 's-a': 'done-unverified' } })).events[0]).toMatchObject({ t: 'step.done', verified: false })+ expect(tick(s, facts({ nowMs: T0 + 10, effects: { 's-a': 'failed' } })).events[0]).toMatchObject({ t: 'step.failed' })+ expect(tick(s, facts({ nowMs: T0 + 2000 })).events[0]).toMatchObject({ t: 'step.failed', why: 'timed out' })+ expect(tick(s, facts({ nowMs: T0 + 10, effects: { 's-a': 'absent' } })).events.length).toBe(0)+ expect(tick(s, facts({ nowMs: T0 + 10, effects: { 's-a': 'absent' }, orphans: new Set(['s-a']) })).events[0]).toMatchObject({ t: 'step.failed' })+ })++ it('waits at the concurrency cap and never starts a task twice', () => {+ const s = foldJournal([started(), { t: 'step.started', at: T0, id: 's-a', task: 't0', cls: 'edit', attempt: 1, deadline: T0 + H, tier: 'mid' }])++ expect(tick(s, facts({ nowMs: T0 + 5 })).act).toBeNull()+ expect(tick(s, facts({ nowMs: T0 + 5, tunables: { parallelism: 2, retries: 1, stepTimeoutMs: 1000, tierOf: () => 'mid' } })).act?.task.id).toBe('t1')+ expect(tick(s, facts({ nowMs: T0 + 5, task: task('t0'), tunables: { parallelism: 2, retries: 1, stepTimeoutMs: 1000, tierOf: () => 'mid' } })).act).toBeNull()+ })++ it('failure ladder: backoff after one, pause at the budget, resume clears it', () => {+ const fail = (n: number): JournalEvent[] => Array.from({ length: n }, (_v, i) => [{ t: 'step.started', at: T0 + i * 10, id: `s-${i}`, task: `f${i}`, cls: 'edit', attempt: 1, deadline: T0 + 1e9, tier: 'mid' }, { t: 'step.failed', at: T0 + i * 10 + 1, id: `s-${i}`, why: 'x' }] as JournalEvent[]).flat()+ const one = foldJournal([started(), ...fail(1)])++ expect(tick(one, facts({ nowMs: T0 + 5000 })).status).toContain('backing off')+ expect(tick(one, facts({ nowMs: T0 + 5000 + 61_000 })).act).not.toBeNull()++ const many = foldJournal([started(), ...fail(FAILURE_BUDGET)])++ expect(tick(many, facts({ nowMs: T0 + 1e7 })).events[0]).toMatchObject({ t: 'pause' })+ expect(foldJournal([started(), ...fail(FAILURE_BUDGET), { t: 'pause', at: T0 + 9e3, reason: 'r' }, { t: 'resume', at: T0 + 9e3 + 1 }]).failures).toBe(0)+ })++ it('parks what is outside the envelope or ambiguous, with a question, and does not repeat the park', () => {+ for (const t of [task('h', { hardDeny: 'publish' }), task('c', { cls: null }), task('n', { cls: 'network' }), task('p', { path: '/etc/passwd' })]) {+ const d = tick(running(), facts({ task: t }))++ expect(d.act).toBeNull()+ expect(d.events[0]).toMatchObject({ t: 'parked', task: t.id })++ const after = foldJournal([started(), ...d.events])++ expect(tick(after, facts({ task: t })).events).toEqual([])+ expect(skipSet(after).has(t.id)).toBe(true)+ }+ })++ it('parks when the permission preflight would deny or ask, and proceeds when it is not wired', () => {+ expect(tick(running(), facts({ preflight: { edit: 'deny' } })).events[0]).toMatchObject({ t: 'parked' })+ expect(tick(running(), facts({ preflight: { edit: 'ask' } })).events[0]).toMatchObject({ t: 'parked' })+ expect(tick(running(), facts({ preflight: { edit: 'unwired' } })).act).not.toBeNull()+ })++ it('approve-once lets exactly one step run; a hard deny can never be approved; deny is final', () => {+ const t = task('n', { cls: 'network' })+ const parked = tick(running(), facts({ task: t })).events++ const once = foldJournal([started(), ...parked, { t: 'answered', at: T0 + 1, id: (parked[0] as { id: string }).id, answer: 'once' }])+ const go = tick(once, facts({ task: t, nowMs: T0 + 2 }))++ expect(go.act?.task.id).toBe('n')++ const ran = foldJournal([started(), ...parked, { t: 'answered', at: T0 + 1, id: (parked[0] as { id: string }).id, answer: 'once' }, ...go.events, { t: 'step.failed', at: T0 + 3, id: go.act?.id ?? '', why: 'x' }])++ expect(ran.parked[0]?.isUsed).toBe(true)+ expect(tick(ran, facts({ task: t, nowMs: T0 + 3_600_000 })).act).toBeNull()++ const hard = task('h', { hardDeny: 'deploy' })+ const hp = tick(running(), facts({ task: hard })).events+ const approved = foldJournal([started(), ...hp, { t: 'answered', at: T0 + 1, id: (hp[0] as { id: string }).id, answer: 'once' }])++ expect(tick(approved, facts({ task: hard, nowMs: T0 + 2 })).act).toBeNull()++ const denied = foldJournal([started(), ...parked, { t: 'answered', at: T0 + 1, id: (parked[0] as { id: string }).id, answer: 'deny' }])++ expect(skipSet(denied).has('n')).toBe(true)+ })++ it('retries are bounded by the policy and then the task is parked', () => {+ let s = running()+ let at = T0++ for (let i = 0; i < 2; i++) {+ const d = tick(s, facts({ nowMs: at }))++ expect(d.act).not.toBeNull()+ s = foldJournal([...[started()], ...(s.steps.flatMap(step => [{ t: 'step.started', at: step.startedAt, id: step.id, task: step.task, cls: step.cls, attempt: step.attempt, deadline: step.deadline, tier: step.tier }, { t: 'step.failed', at: step.startedAt + 1, id: step.id, why: 'x' }] as JournalEvent[]) ), ...d.events, { t: 'step.failed', at: at + 1, id: d.act?.id ?? '', why: 'x' }])+ at += 2 * H+ }++ expect(tick(s, facts({ nowMs: at })).events[0]).toMatchObject({ t: 'parked' })+ })+})++describe('loop: properties over a seeded random walk', () => {+ const rng = (seed: number) => () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 0x100000000)++ const randomFacts = (r: () => number, now: number, s: LoopState, killAt: number, i: number): Facts => {+ const open = s.steps.filter(step => step.status === 'started')++ return facts({+ nowMs: now,+ killSeen: i >= killAt,+ anatole: r() < 0.9 ? 'on' : 'off',+ spend: r() < 0.9 ? { hourUsd: r() * 3, dayUsd: r() * 12, totalUsd: r() * 30 } : null,+ task: r() < 0.8 ? task(`t${Math.floor(r() * 12)}`, { cls: r() < 0.8 ? 'edit' : r() < 0.5 ? null : 'network' }) : null,+ effects: Object.fromEntries(open.map(step => [step.id, (['done', 'failed', 'unknown', 'absent', 'done-unverified'] as const)[Math.floor(r() * 5)] as never])),+ orphans: new Set(open.filter(() => r() < 0.3).map(step => step.id)),+ })+ }++ it('once the kill flag is seen no tick ever acts again, whatever else is true, and nothing restarts it', () => {+ for (let seed = 1; seed <= 60; seed++) {+ const r = rng(seed)+ const killAt = Math.floor(r() * 40)+ let s = running()+ let now = T0++ for (let i = 0; i < 80; i++) {+ now += Math.floor(r() * 5 * 60_000)++ const d = tick(s, randomFacts(r, now, s, killAt, i))++ if (i >= killAt) expect(d.act).toBeNull()++ s = foldJournal(d.events, s)+ if (i > killAt) expect(s.phase).toBe('stopped')+ }+ }+ })++ it('no task has two live steps, no step id repeats, and a step only starts while the loop is running', () => {+ for (let seed = 100; seed < 160; seed++) {+ const r = rng(seed)+ let s = running()+ let now = T0++ for (let i = 0; i < 120; i++) {+ now += Math.floor(r() * 10 * 60_000)++ const d = tick(s, randomFacts(r, now, s, 1e9, i))++ if (d.act !== null) {+ expect(s.phase).toBe('running')+ expect(s.steps.some(step => step.task === d.act?.task.id && step.status !== 'failed')).toBe(false)+ expect(s.steps.some(step => step.id === d.act?.id)).toBe(false)+ }++ s = foldJournal(d.events, s)+ if (s.phase === 'paused' && r() < 0.3) s = foldJournal([{ t: 'resume', at: now }], s)++ const live = s.steps.filter(step => step.status === 'started')++ expect(new Set(live.map(step => step.task)).size).toBe(live.length)+ expect(live.length).toBeLessThanOrEqual(1)+ }+ }+ })++ it('crash-resume: folding the journal from any prefix and ticking never starts an already-started or finished task', () => {+ for (let seed = 200; seed < 230; seed++) {+ const r = rng(seed)+ const journal: JournalEvent[] = [started()]+ let s = running()+ let now = T0++ for (let i = 0; i < 60; i++) {+ now += 90_000++ const d = tick(s, randomFacts(r, now, s, 1e9, i))++ journal.push(...d.events)+ s = foldJournal(d.events, s)+ if (s.phase !== 'running') s = foldJournal([{ t: 'resume', at: now }], s) && foldJournal([...journal, { t: 'resume', at: now }])+ if (s.phase === 'running' && journal.at(-1)?.t === 'pause') journal.push({ t: 'resume', at: now })+ }++ // Crash at every point: a fresh process folds the prefix text, every started step is an orphan, and nothing is double-started.+ for (let cut = 1; cut <= journal.length; cut += 3) {+ const text = journal.slice(0, cut).map(encodeLine).join('')+ const resumed = foldJournal(parseJournal(text).events)++ expect(resumed.steps.map(step => step.id)).toEqual(foldJournal(journal.slice(0, cut)).steps.map(step => step.id))++ const orphans = new Set(resumed.steps.filter(step => step.status === 'started').map(step => step.id))++ for (const orphan of resumed.steps.filter(step => step.status === 'started')) {+ const d = tick(resumed, facts({ nowMs: now + 5 * H, task: task(orphan.task), orphans, effects: { [orphan.id]: 'absent' } }))++ // Re-verified by effect: found lost, never restarted in the same pass.+ expect(d.act).toBeNull()+ }+ }+ }+ })++ it('a replayed journal line changes nothing (idempotent fold)', () => {+ const events: JournalEvent[] = [started(), { t: 'step.started', at: T0 + 1, id: 's-1', task: 't1', cls: 'edit', attempt: 1, deadline: T0 + 99, tier: 'mid' }]++ expect(foldJournal([...events, events[1] as JournalEvent]).steps.length).toBe(1)+ })++ it('a compacted snapshot folds back to the same live state', () => {+ const r = rng(7)+ let s = running()+ let now = T0++ for (let i = 0; i < 80; i++) {+ now += 120_000++ const d = tick(s, randomFacts(r, now, s, 1e9, i))++ s = foldJournal(d.events, s)+ if (s.phase === 'paused') s = foldJournal([{ t: 'resume', at: now }], s)+ }++ const back = foldJournal(snapshotEvents(s))++ expect(back.phase).toBe(s.phase)+ expect(back.steps.filter(step => step.status === 'started').map(step => step.id)).toEqual(s.steps.filter(step => step.status === 'started').map(step => step.id))+ expect(back.parked.filter(p => p.answer === undefined).length).toBe(s.parked.filter(p => p.answer === undefined).length)+ })+})++describe('band and summary', () => {+ it('draws day, spend and parked from what was read, and n/a where it was not', () => {+ const s = foldJournal([started(), { t: 'parked', at: T0 + 1, id: 'p-1', task: 't', question: 'q' }, { t: 'parked', at: T0 + 2, id: 'p-2', task: 'u', question: 'q' }])++ expect(bandText(s, T0 + 2 * 86_400_000 + 5, 12, ENV)).toBe('autopilot day 3 · $12/$40 · 2 parked')+ expect(bandText(s, T0, null, ENV)).toBe('autopilot day 1 · $n/a/$40 · 2 parked')+ expect(bandText(s, T0, 0, null)).toBe('autopilot day 1 · $0/$n/a · 2 parked')+ expect(bandText(emptyLoop(), T0, 5, ENV)).toBe('')+ expect(bandText(foldJournal([started(), { t: 'pause', at: T0, reason: 'x' }]), T0, 1, ENV)).toContain('paused')+ expect(summarize(s, T0).parked).toBe(2)+ })+})++describe('adaptation', () => {+ const step = (over: Partial<Parameters<typeof outcomesOf>[0][number]>) => ({ id: 's', task: 't', cls: 'edit', attempt: 1, startedAt: 0, deadline: 1, status: 'done' as const, verified: true, tier: 'mid', par: 1, endedAt: 10, ...over })+ const many = (n: number, over: Partial<Parameters<typeof outcomesOf>[0][number]>) => Array.from({ length: n }, (_v, i) => step({ ...over, id: `s${i}`, startedAt: i }))++ it('counts only verified successes and failures; an unverified step teaches nothing', () => {+ expect(outcomesOf([step({}), step({ verified: false }), step({ status: 'failed', verified: undefined }), step({ status: 'started' })]).length).toBe(2)+ })++ it('proposes a higher tier for failing steps and promotes it with a chained receipt', () => {+ const outcomes = outcomesOf(many(8, { status: 'failed', verified: undefined }))+ const [p] = propose(outcomes, DEFAULTS, ENV)++ expect(p?.change).toEqual({ path: 'tier.edit', from: 'mid', to: 'high' })++ const verdict = evaluate(p!, outcomes, DEFAULTS)++ expect(verdict.verdict).toBe('supported')++ const first = promote(p!, verdict, DEFAULTS, ENV, lastHash([]), T0)++ expect(first.ok).toBe(true)++ const t = first.ok ? first.tunables : DEFAULTS++ expect(t.tiers.edit).toBe('high')+ expect(tunablesFrom(first.ok ? [first.receipt] : [], ENV).tiers.edit).toBe('high')+ expect(verifyReceipts(first.ok ? [first.receipt] : []).ok).toBe(true)+ })++ it('refuses to promote without evidence, and a tampered receipt breaks the chain', () => {+ const few = outcomesOf(many(3, { status: 'failed', verified: undefined }))+ const p = { id: 'x', change: { path: 'tier.edit', from: 'mid', to: 'high' }, direction: 'conservative' as const, reason: '' }++ expect(promote(p, evaluate(p, few, DEFAULTS), DEFAULTS, ENV, 'genesis', T0).ok).toBe(false)++ const good = outcomesOf(many(8, { status: 'failed', verified: undefined }))+ const a = promote(p, evaluate(p, good, DEFAULTS), DEFAULTS, ENV, 'genesis', T0)++ if (!a.ok) throw new Error('setup')++ expect(verifyReceipts([{ ...a.receipt, to: 'low' }]).ok).toBe(false)+ expect(verifyReceipts([a.receipt, { ...a.receipt, prev: 'genesis' }]).ok).toBe(false)+ })++ it('aggressive changes need clean history and are reverted if the trial does worse', () => {+ const clean = outcomesOf(many(14, { tier: 'mid' }))+ const [p] = propose(clean, DEFAULTS, ENV)++ expect(p).toMatchObject({ direction: 'aggressive', change: { path: 'tier.edit', to: 'low' } })++ const ok = promote(p!, evaluate(p!, clean, DEFAULTS), DEFAULTS, ENV, 'genesis', 100)++ if (!ok.ok) throw new Error('setup')++ const worse = outcomesOf(many(8, { tier: 'low', status: 'failed', verified: undefined, startedAt: 200, endedAt: 210 }))++ expect(reviewTrials([ok.receipt], worse).map(r => r.change)).toEqual([{ path: 'tier.edit', from: 'low', to: 'mid' }])+ expect(reviewTrials([ok.receipt], outcomesOf(many(8, { tier: 'low', startedAt: 200, endedAt: 210 }))).length).toBe(0)+ })++ it('no sequence of proposals, valid or hostile, can take a tunable past the envelope or change the envelope', () => {+ const env = Object.freeze({ ...ENV, concurrency: 2 }) as Envelope+ const before = canonical(env)+ let t: Tunables = DEFAULTS++ for (const [path, to] of [['parallelism', '9'], ['parallelism', '2'], ['parallelism', '3'], ['parallelism', '-1'], ['retries', '99'], ['stepSize', '6'], ['ordering', 'chaos'], ['tier.edit', 'ultra'], ['__proto__.x', '1'], ['concurrency', '8'], ['tier.edit', 'low'], ['tier.A;B', 'low']] as const) {+ const applied = applyChange(t, { path, from: '', to })++ if (applied !== null) t = clampToEnvelope(applied, env)++ expect(t.parallelism).toBeLessThanOrEqual(env.concurrency)+ expect(t.retries).toBeLessThanOrEqual(3)+ expect(t.stepSize).toBeLessThanOrEqual(5)+ }++ const huge = promote({ id: 'p', change: { path: 'parallelism', from: '1', to: '3' }, direction: 'conservative', reason: '' }, { verdict: 'supported', evidence: 'forced' }, DEFAULTS, env, 'genesis', T0)++ expect(huge.ok).toBe(false)+ expect(canonical(env)).toBe(before)+ expect(clampToEnvelope({ ...DEFAULTS, parallelism: 8 }, env).parallelism).toBe(2)+ })+})++describe('guards', () => {+ it('classifies by the most privileged class the words suggest, and never defaults', () => {+ expect(classifyTask('a', 'Review the auth module').cls).toBe('read')+ expect(classifyTask('a', 'Fix the parser and run the tests').cls).toBe('edit')+ expect(classifyTask('a', 'Create a worktree and merge').cls).toBe('git-branch')+ expect(classifyTask('a', 'Completion: Learn: store the outcome').cls).toBeNull()+ expect(classifyTask('a', 'Edit /work/repo/src/x.ts').path).toBe('/work/repo/src/x.ts')+ })++ it('flags every hard deny family in a task', () => {+ const deny = (text: string): string | null => classifyTask('a', text).hardDeny++ expect(deny('npm publish the package')).toBe('publish')+ expect(deny('cut a release and tag')).toBe('release')+ expect(deny('deploy to production')).toBe('deploy')+ expect(deny('git push --force origin main')).toBe('force-push')+ expect(deny('read the API key from gcloud secrets')).toBe('secret-access')+ expect(deny('rm -rf / to clean up')).toBe('delete-outside-worktree')+ expect(deny('widen the envelope to allow network')).toBe('envelope-edit')+ expect(deny('refactor the parser')).toBeNull()+ })++ it('reads the Anatole gate from what the mod reported', () => {+ expect(anatoleFact(undefined)).toBe('absent')+ expect(anatoleFact({ present: false, status: null, modeOverride: null, overrides: {}, alerts: [], refused: [], badAlerts: 0 })).toBe('absent')+ expect(anatoleFact({ present: true, status: { mode: 'off' } as never, modeOverride: null, overrides: {}, alerts: [], refused: [], badAlerts: 0 })).toBe('off')+ expect(anatoleFact({ present: true, status: { mode: 'notify' } as never, modeOverride: null, overrides: {}, alerts: [], refused: [], badAlerts: 0 })).toBe('on')+ })++ it('preflight: absent check is unwired, a deny is deny, a throw is unwired', async () => {+ expect((await preflightAll(undefined)).edit).toBe('unwired')+ expect((await preflightAll(async tool => (tool === 'Edit' ? { decision: 'deny' } : 'allow'))).edit).toBe('deny')+ expect((await preflightAll(async () => 'allow')).read).toBe('allow')+ expect((await preflightAll(async () => Promise.reject(new Error('x')))).read).toBe('unwired')+ })++ it('an effect needs the store AND the verify commands; a store status alone is a claim', () => {+ expect(effectOf('completed', { ran: 0, failed: 0 })).toBe('done-unverified')+ expect(effectOf('completed', { ran: 2, failed: 0 })).toBe('done')+ expect(effectOf('completed', { ran: 2, failed: 1 })).toBe('failed')+ expect(effectOf('in_progress', { ran: 0, failed: 0 })).toBe('unknown')+ expect(effectOf('failed', { ran: 0, failed: 0 })).toBe('failed')+ })+})