🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(ruflo-console): Self-Evolution view (🧬): the governed loop, ledger, lineage, policy gate and witness
ruve8f8f3bfc01c
diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.tsindex 5fb683024c..5521e8603e 100644--- a/plugins/ruflo-console/hooks/actions.ts+++ b/plugins/ruflo-console/hooks/actions.ts@@ -23,6 +23,8 @@ export type ActionSpec = {note?: string/** How long the CLI may take; 90 s when unset. */timeoutMs?: number+ /** Reads what a lab run printed into its result lines (and may keep what it parsed); the lab's reader when unset. */+ lines?: (stdout: string, stderr: string) => string[]}export const exec = (tool: string, params: Record<string, string>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as constdiff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.tsindex a52ccfc673..ffc5e14471 100644--- a/plugins/ruflo-console/hooks/bindings.ts+++ b/plugins/ruflo-console/hooks/bindings.ts@@ -4,6 +4,7 @@*/import { claimTask, handoffClaim, releaseClaim, stealClaim, whyNot } from './actions'import { EVENT_KINDS } from './data/events'+import { evolveActions } from './evolve'import { HARNESSES, harnessSpec, isLive, newSession, send, whyNotRun } from './harness'import { plain } from './data/parse'import type { Host } from './host'@@ -54,6 +55,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Stepsvoid freshRead().then(() => probe(true))// The skills lists come from `npx skills`, not the disk read: r asks for them again on that view.if (state.view === 'skills') actions.skills.list()+ if (state.view === 'evolve') actions.evolve.reread()},help: () => {state.isHelp = !state.isHelp@@ -250,6 +252,8 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps},// ▸ edit hands the skill to the AI terminal, as x.ruv.io's ▸ open does: typed, not run.skills: skillActions(state, host, runner, text => actions.term.load('claude', text)),+ // ▸ ask on the Self-Evolution view types a repo prompt into the AI terminal, as ▸ edit does: typed, not run.+ evolve: evolveActions(state, host, text => actions.term.load('claude', text)),}return actionsdiff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.tsindex 3a53a91496..54527f026a 100644--- a/plugins/ruflo-console/hooks/controller.ts+++ b/plugins/ruflo-console/hooks/controller.ts@@ -13,6 +13,7 @@ import { markPicture } from './gfx/pictures'import type { Host } from './host'import { agentLogs } from './ops'import { createRunner, type Runner } from './runner'+import { loadEvolve } from './evolve'import { listSkills } from './skills'import { CLI_PREFIXES, isBooting, PANE_ID, push, rowsOf, storeKeyOf, type State } from './state'import type { Actions } from './views/common'@@ -400,6 +401,8 @@ export function createController(state: State, host: Host): Controller {void listSkills(state, host)focusField('skills-search')}+ // Opening Self-Evolution reads ruflo's own flywheel files (local, no CLI run); its checks wait for a click.+ if (view === 'evolve') void loadEvolve(state, host)}/**diff --git a/plugins/ruflo-console/hooks/data/evolve.ts b/plugins/ruflo-console/hooks/data/evolve.tsnew file mode 100644index 0000000000..b517ff29dd--- /dev/null+++ b/plugins/ruflo-console/hooks/data/evolve.ts@@ -0,0 +1,325 @@+/**+ * The self-evolution view's facts: what ruflo's governed-evolution stack wrote to disk, and readers for what its CLI+ * prints. Read against @claude-flow/cli 3.51.1's source:+ *+ * - `.claude-flow/flywheel-v1/transaction-state.json` (services/flywheel-transaction.ts): the ADR-322 flywheel's state,+ * `{activeChampionRef, servingEpoch, ledgerHead, receiptStates{id: {status}}, commits[]}`; each commit links its+ * `baselineRef` to the `candidateId` it promoted, so the commits are the champion's ancestry.+ * - `.claude-flow/flywheel-v1/receipts/<hex>.json` (services/flywheel-receipt.ts): `{payload, signature?}`, the payload+ * naming `receiptId, candidateId, baselineRef, decision, issuedAt` and its `statistics`.+ * - `.claude-flow/flywheel/generation-N.json` and `served.json` (services/harness-flywheel-generations.ts): the older+ * generations loop, each bundle naming its `parent` and, on a pass, `promotion.candidateManifestHash`.+ * - `.claude-flow/harness-active-policy.json` (config/harness-feedback-applier.ts): the champion served, with the+ * `previous` pointer a rollback returns to and `rolledBack` once it has.+ * - `verification/<os>/manifest.md.json` (ADR-103): the signed witness manifest; only its header is read here.+ *+ * Same rules as ./parse: any shape tolerated, nothing guessed, every string cleaned. `.claude-flow/policy/state.json` is+ * never read (it reaches tens of MB); the policy ledger is asked of `ruflo policy status` when the person clicks.+ */+import { jsonAfter } from './cli'+import { readBounded, under, type ReadCache, type ReaderFs } from './files'+import { jsonObject, msOf, numberOf, plain, recordOf, stringOf } from './parse'++export const EVOLVE_FILES = {+ flywheel: '.claude-flow/flywheel-v1/transaction-state.json',+ receipts: '.claude-flow/flywheel-v1/receipts',+ generations: '.claude-flow/flywheel',+ served: '.claude-flow/flywheel/served.json',+ policy: '.claude-flow/harness-active-policy.json',+ rgi: '.rgi/runtime.db',+} as const++export const OSES = ['linux', 'macos', 'windows'] as const+export type Os = (typeof OSES)[number]++/** Each signed witness manifest by the OS it was generated on: a fixed path, never one the person types. */+export const MANIFEST_PATHS: Record<Os, string> = { linux: 'verification/linux/manifest.md.json', macos: 'verification/macos/manifest.md.json', windows: 'verification/windows/manifest.md.json' }++/** At most this many receipt files and generation bundles are read, newest first. */+export const MAX_RECEIPTS = 20+export const MAX_GENERATIONS = 12++export type Commit = { candidate: string; baseline?: string; receipt?: string; epoch?: number; atMs?: number; proposer?: string }+export type FlywheelFile = { champion?: string; served?: string; epoch?: number; head?: string; statuses: Record<string, string>; commits: Commit[] }+export type Receipt = { id: string; decision?: string; candidate?: string; baseline?: string; isSigned: boolean; atMs?: number; lift?: number; status?: string }+export type Generation = { generation: number; parent: string | null; candidate?: string; isPromoted: boolean; branch?: string; mutation?: string; cause?: string; atMs?: number }+export type Served = { champion?: string; fromGeneration?: number; atMs?: number }+export type ActivePolicy = { champion: string; previous?: string; isRolledBack: boolean; tier?: string; layer?: string; appliedAtMs?: number }+export type Manifest = { os: Os; path: string; issuedAtMs?: number; gitCommit?: string; branch?: string; fixes?: number; isSigned: boolean }++/** What the disk held when the view last read it; null fields are files that are not there (or not readable). */+export type EvolveFiles = {+ flywheel: FlywheelFile | null+ receipts: Receipt[] | null+ generations: Generation[] | null+ served: Served | null+ policy: ActivePolicy | null+ manifests: Manifest[]+ hasRgiDb: boolean+ readAtMs: number+}++export type Ledger = { isValid: boolean; commits: number; head?: string; errors: string[]; atMs: number }+export type Witness = { os: Os; isOk: boolean; isSignatureValid: boolean; pass: number; drift: number; regressed: number; missing: number; atMs: number }+export type PolicyLedger = { mode: string; rules: number; approvals: number; receipts: number; isValid: boolean; atMs: number }+export type GateDecision = { outcome: string; enforced: string; mode: string; reason: string; atMs: number }++/** The evolve view between renders: the files as read, and what the CLI answered when the person asked. */+export type EvolveState = {+ files: EvolveFiles | null+ isReading: boolean+ ledger: Ledger | null+ witness: Partial<Record<Os, Witness>>+ policyLedger: PolicyLedger | null+ gate: GateDecision | null+}++export const emptyEvolve = (): EvolveState => ({ files: null, isReading: false, ledger: null, witness: {}, policyLedger: null, gate: null })++const REF = /^(sha256:)?[0-9a-f]{8,64}$/++/** A content ref (`sha256:<hex>` or bare hex) as written, or undefined: only such strings are drawn as lineage nodes. */+export const refOf = (value: unknown): string | undefined => (typeof value === 'string' && REF.test(value) ? value : undefined)++/** A ref as a person reads it: the first eight hex digits. The genesis head reads as such. */+export function shortRef(ref: string | undefined): string {+ if (ref === undefined) return 'n/a'++ const hex = ref.replace(/^sha256:/, '')++ return /^0+$/.test(hex) ? 'genesis' : hex.slice(0, 8)+}++export function parseFlywheel(text: string | null): FlywheelFile | null {+ const value = jsonObject(text)++ if (value === null) return null++ const statuses: Record<string, string> = {}++ for (const [id, entry] of Object.entries(recordOf(value.receiptStates) ?? {}).slice(0, 500)) {+ const status = stringOf(recordOf(entry)?.status, 16)++ if (refOf(id) !== undefined && status !== undefined) statuses[id] = status+ }++ const commits = (Array.isArray(value.commits) ? value.commits : []).slice(-200).flatMap(entry => {+ const commit = recordOf(entry)+ const candidate = refOf(commit?.candidateId)++ if (commit === null || candidate === undefined) return []++ const baseline = refOf(commit.baselineRef)+ const receipt = refOf(commit.receiptId)+ const epoch = numberOf(commit.servingEpoch)+ const atMs = msOf(commit.promotedAt)+ const proposer = stringOf(commit.proposer, 20)++ return [{ candidate, ...(baseline !== undefined && { baseline }), ...(receipt !== undefined && { receipt }), ...(epoch !== undefined && { epoch }), ...(atMs !== undefined && { atMs }), ...(proposer !== undefined && { proposer }) }]+ })+ const champion = refOf(value.activeChampionRef)+ const served = refOf(value.servedChampionRef)+ const epoch = numberOf(value.servingEpoch)+ const head = refOf(value.ledgerHead)++ return { statuses, commits, ...(champion !== undefined && { champion }), ...(served !== undefined && { served }), ...(epoch !== undefined && { epoch }), ...(head !== undefined && { head }) }+}++/** One receipt file: its payload's identity and decision, and whether a signature is attached (not whether it holds). */+export function parseReceipt(text: string | null): Receipt | null {+ const value = jsonObject(text)+ const payload = recordOf(value?.payload)+ const id = refOf(payload?.receiptId)++ if (value === null || payload === null || id === undefined) return null++ const decision = stringOf(payload.decision, 16)+ const candidate = refOf(payload.candidateId)+ const baseline = refOf(payload.baselineRef)+ const atMs = msOf(payload.issuedAt)+ const lift = numberOf(recordOf(payload.statistics)?.relativeLift)+ const signature = recordOf(value.signature)++ return {+ id,+ isSigned: typeof signature?.signatureBase64 === 'string' && signature.signatureBase64.length > 20,+ ...(decision !== undefined && { decision }),+ ...(candidate !== undefined && { candidate }),+ ...(baseline !== undefined && { baseline }),+ ...(atMs !== undefined && { atMs }),+ ...(lift !== undefined && { lift }),+ }+}++export function parseGeneration(text: string | null): Generation | null {+ const value = jsonObject(text)+ const generation = numberOf(value?.generation)++ if (value === null || generation === undefined) return null++ const promotion = recordOf(value.promotion)+ const regression = recordOf(value.regression)+ const candidate = refOf(promotion?.candidateManifestHash ?? regression?.candidateManifestHash)+ const branch = stringOf(value.branch, 24)+ const mutation = stringOf(promotion?.mutationClass ?? regression?.mutationClass ?? value.mutationClass, 40)+ const cause = stringOf(regression?.failureCause, 16)+ const atMs = msOf(value.createdAt)++ return {+ generation,+ parent: refOf(value.parent) ?? null,+ isPromoted: promotion !== null,+ ...(candidate !== undefined && { candidate }),+ ...(branch !== undefined && { branch }),+ ...(mutation !== undefined && { mutation }),+ ...(cause !== undefined && { cause }),+ ...(atMs !== undefined && { atMs }),+ }+}++export function parseServed(text: string | null): Served | null {+ const value = jsonObject(text)++ if (value === null) return null++ const champion = refOf(value.championHash)+ const fromGeneration = numberOf(value.fromGeneration)+ const atMs = msOf(value.servedAt)++ return { ...(champion !== undefined && { champion }), ...(fromGeneration !== undefined && { fromGeneration }), ...(atMs !== undefined && { atMs }) }+}++/** The active policy with the rollback pointer facts.ts leaves out: `previous`, and `rolledBack` once it was used. */+export function parseActivePolicy(text: string | null): ActivePolicy | null {+ const value = jsonObject(text)+ const champion = stringOf(value?.championId, 90)++ if (value === null || champion === undefined) return null++ const previous = stringOf(value.previous, 90)+ const tier = stringOf(value.provenanceTier, 40)+ const layer = stringOf(value.layer, 40)+ const appliedAtMs = msOf(value.appliedAt)++ return { champion, isRolledBack: value.rolledBack === true, ...(previous !== undefined && { previous }), ...(tier !== undefined && { tier }), ...(layer !== undefined && { layer }), ...(appliedAtMs !== undefined && { appliedAtMs }) }+}++/** A witness manifest's header: when, from which commit, how many fixes, and whether it carries a signature. */+export function parseManifest(text: string | null, os: Os): Manifest | null {+ const value = jsonObject(text)+ const manifest = recordOf(value?.manifest)++ if (value === null || manifest === null) return null++ const integrity = recordOf(value.integrity)+ const issuedAtMs = msOf(manifest.issuedAt)+ const gitCommit = stringOf(manifest.gitCommit, 12)+ const branch = stringOf(manifest.branch, 40)+ const fixes = numberOf(recordOf(manifest.summary)?.totalFixes) ?? (Array.isArray(manifest.fixes) ? manifest.fixes.length : undefined)++ return {+ os,+ path: MANIFEST_PATHS[os],+ isSigned: typeof integrity?.signature === 'string' && integrity.signature.length > 20,+ ...(issuedAtMs !== undefined && { issuedAtMs }),+ ...(gitCommit !== undefined && { gitCommit }),+ ...(branch !== undefined && { branch }),+ ...(fixes !== undefined && { fixes }),+ }+}++/** Reads every evolution file under `cwd`; nothing here rejects, and a file that is not there reads as null. */+export async function readEvolve(fs: ReaderFs, cache: ReadCache, cwd: string, nowMs: number): Promise<EvolveFiles> {+ const read = async (path: string) => {+ const result = await readBounded(fs, cache, under(cwd, path))++ return result.text+ }+ const newest = async (dir: string, pattern: RegExp, max: number, order: (name: string) => number) => {+ const entries = await fs.list(under(cwd, dir)).catch(() => null)++ if (entries === null) return null++ return entries+ .filter(entry => pattern.test(entry.name))+ .sort((a, b) => order(b.name) - order(a.name) || (b.mtimeMs ?? 0) - (a.mtimeMs ?? 0))+ .slice(0, max)+ .map(entry => `${dir}/${entry.name}`)+ }+ const [flywheelText, receiptPaths, generationPaths, servedText, policyText, manifestTexts, hasRgiDb] = await Promise.all([+ read(EVOLVE_FILES.flywheel),+ newest(EVOLVE_FILES.receipts, /^[0-9a-f]{64}\.json$/, MAX_RECEIPTS, () => 0),+ newest(EVOLVE_FILES.generations, /^generation-\d{1,6}\.json$/, MAX_GENERATIONS, name => Number(/\d+/.exec(name)?.[0] ?? 0)),+ read(EVOLVE_FILES.served),+ read(EVOLVE_FILES.policy),+ Promise.all(OSES.map(os => read(MANIFEST_PATHS[os]))),+ fs.stat(under(cwd, EVOLVE_FILES.rgi)).then(() => true, () => false),+ ])+ const flywheel = parseFlywheel(flywheelText)+ const receipts = receiptPaths === null ? null : (await Promise.all(receiptPaths.map(path => read(path).then(parseReceipt)))).flatMap(receipt => (receipt === null ? [] : [{ ...receipt, ...(flywheel?.statuses[receipt.id] !== undefined && { status: flywheel.statuses[receipt.id] }) }]))+ const generations = generationPaths === null ? null : (await Promise.all(generationPaths.map(path => read(path).then(parseGeneration)))).flatMap(generation => (generation === null ? [] : [generation]))++ return {+ flywheel,+ receipts,+ generations: generations?.sort((a, b) => a.generation - b.generation) ?? null,+ served: parseServed(servedText),+ policy: parseActivePolicy(policyText),+ manifests: OSES.flatMap((os, i) => parseManifest(manifestTexts[i] ?? null, os) ?? []),+ hasRgiDb,+ readAtMs: nowMs,+ }+}++const count = (value: unknown): number => numberOf(value) ?? 0++/** `metaharness flywheel status`: `{state, ledger: {valid, errors, commits, head}}`, its ledger as checked. */+export function parseLedger(stdout: string, atMs: number): Ledger | null {+ const ledger = recordOf(recordOf(jsonAfter(stdout))?.ledger)++ if (ledger === null || typeof ledger.valid !== 'boolean') return null++ const head = refOf(ledger.head)++ return { isValid: ledger.valid, commits: count(ledger.commits), errors: (Array.isArray(ledger.errors) ? ledger.errors : []).slice(0, 5).map(error => plain(error, 140)), atMs, ...(head !== undefined && { head }) }+}++/** `verify --manifest <path> --json`: the signature checks and the per-fix tally against the installed CLI. */+export function parseWitness(stdout: string, os: Os, atMs: number): Witness | null {+ const value = recordOf(jsonAfter(stdout))+ const summary = recordOf(value?.summary)+ const signature = recordOf(value?.signature)++ if (value === null || summary === null) return null++ return {+ os,+ isOk: value.ok === true,+ isSignatureValid: signature?.manifestHashOk === true && signature.publicKeyReproducible === true && signature.signatureValid === true,+ pass: count(summary.pass),+ drift: count(summary.drift),+ regressed: count(summary.regressed),+ missing: count(summary.missing),+ atMs,+ }+}++/** `policy status`: the ADR-324 engine's mode, its counts, and whether its decision ledger verifies. */+export function parsePolicyLedger(stdout: string, atMs: number): PolicyLedger | null {+ const value = recordOf(jsonAfter(stdout))+ const ledger = recordOf(value?.ledger)++ if (value === null || ledger === null) return null++ return { mode: stringOf(value.mode, 12) ?? 'n/a', rules: count(value.rules), approvals: count(value.approvals), receipts: count(value.receipts), isValid: ledger.valid === true, atMs }+}++/** `policy evaluate`: the decision the gate reached, as enforced in the current mode. */+export function parseGate(stdout: string, atMs: number): GateDecision | null {+ const value = recordOf(jsonAfter(stdout))+ const outcome = stringOf(value?.outcome, 24)++ if (value === null || outcome === undefined) return null++ return { outcome, enforced: stringOf(value.enforcedOutcome, 24) ?? outcome, mode: stringOf(value.mode, 12) ?? 'n/a', reason: stringOf(value.reason, 160) ?? '', atMs }+}diff --git a/plugins/ruflo-console/hooks/evolve.ts b/plugins/ruflo-console/hooks/evolve.tsnew file mode 100644index 0000000000..5533b0f2c5--- /dev/null+++ b/plugins/ruflo-console/hooks/evolve.ts@@ -0,0 +1,232 @@+/**+ * The Self-Evolution view's work: the governed-evolution loop as ruflo records it, and the checks a person can run on+ * it. Every entry is a fixed argv checked against the CLI's dispatchers (commands/metaharness.ts dispatchFlywheel,+ * commands/policy.ts, commands/verify.ts). The reads are $0 and local and run at once; the one write (asking the policy+ * gate about a promotion) asks first and says what it appends. CLI verbs are used, never `mcp exec`, which appends a+ * receipt to the policy ledger on every call.+ *+ * Authority (ADR-322): the flywheel, Darwin and MetaHarness propose and evaluate; they cannot promote themselves. There+ * is no promote, evidence-reset or rollback entry here: the view shows the promotion command and the person runs it.+ * Candidate runs (`flywheel run`) live in the MetaHarness lab, which this view links to rather than repeats.+ */+import type { ActionSpec } from './actions'+import { MANIFEST_PATHS, OSES, parseGate, parseLedger, parsePolicyLedger, parseWitness, readEvolve, shortRef, type EvolveFiles, type Os } from './data/evolve'+import { jsonAfter } from './data/cli'+import { plain, recordOf } from './data/parse'+import type { Host } from './host'+import { labLines, LAB_MAX_LINES, PROMOTE_COMMAND } from './mh-lab'+import type { State } from './state'++export type EvolveCost = 'read' | 'writes'++export type EvolveEntry = {+ id: string+ name: string+ about: string+ label: string+ cost: EvolveCost+ args: (state: State) => readonly string[] | null+ why?: string+ note?: string+ timeoutMs?: number+}++const FLY = ['metaharness', 'flywheel'] as const++/** The request `policy evaluate` is asked: the promote action the CLI's promote would put to the gate, as this console. */+export function gateRequest(receiptId?: string): Record<string, unknown> {+ return { identity: { id: 'ruflo-console', type: 'plugin' }, action: { type: 'metaharness.candidate.promote', ...(receiptId !== undefined && { resource: receiptId }), environment: 'production', destructive: true } }+}++/** The newest accepted receipt still waiting to be promoted: what a promotion would be asked about. */+export function candidateReceipt(files: EvolveFiles | null): string | undefined {+ return files?.receipts?.find(receipt => receipt.decision === 'accepted' && (receipt.status === undefined || receipt.status === 'evaluated'))?.id+}++const manifestOf = (state: State, os: Os) => state.evolve.files?.manifests.find(manifest => manifest.os === os)++const witnessEntry = (os: Os): EvolveEntry => ({+ id: `evolve-witness-${os}`,+ name: `WITNESS ${os.toUpperCase()}`,+ about: `check the signed ${os} manifest against the installed CLI`,+ label: `verify the signed ${os} witness manifest (ruflo verify --manifest, local)`,+ cost: 'read',+ args: state => (manifestOf(state, os) === undefined ? null : ['verify', '--manifest', MANIFEST_PATHS[os], '--json']),+ why: `no ${MANIFEST_PATHS[os]} in this project (without --manifest, ruflo verify fetches from GitHub: not offered)`,+ timeoutMs: 180_000,+})++export const EVOLVE: readonly EvolveEntry[] = [+ { id: 'evolve-ledger', name: 'LEDGER', about: 'verify the flywheel ledger: hash chain, parents, champion pointer', label: 'verify the flywheel ledger (metaharness flywheel status)', cost: 'read', args: () => [...FLY, 'status'] },+ { id: 'evolve-receipts', name: 'RECEIPTS', about: 'every evaluation receipt: decision, signed, state', label: 'list flywheel receipts and their verdicts', cost: 'read', args: () => [...FLY, 'receipts'] },+ { id: 'evolve-history', name: 'PROMOTIONS', about: 'every promotion commit: baseline → candidate, epoch', label: 'list flywheel promotion commits (the champion lineage)', cost: 'read', args: () => [...FLY, 'history'] },+ { id: 'evolve-policy', name: 'POLICY', about: 'the ADR-324 engine: mode, rules, receipts, ledger valid', label: 'policy status: mode, rules and whether its ledger verifies', cost: 'read', args: () => ['policy', 'status'], note: '$0, local: a read; a first run may record the ledger trust anchor (.claude-flow/policy, ~/.config/ruflo/policy-trust)' },+ ...OSES.map(witnessEntry),+ {+ id: 'evolve-gate',+ name: 'GATE CHECK',+ about: 'would the policy gate allow a promotion now? decides nothing',+ label: 'ask the policy gate about a promotion (policy evaluate, promotes nothing)',+ cost: 'writes',+ args: state => ['policy', 'evaluate', JSON.stringify(gateRequest(candidateReceipt(state.evolve.files)))],+ note: '$0, local: appends one decision receipt to .claude-flow/policy/state.json; promotes nothing',+ },+]++/** The promotion command, shown and never run (ADR-322: a policy act, a person's): the lab's, so both say the same. */+export { PROMOTE_COMMAND }++export const REPOS = {+ autogenous: 'https://github.com/ruvnet/autogenous',+ rgi: 'https://github.com/ruvnet/rGi',+} as const++/** What ▸ ask types into the AI terminal for a repo: read-only research, the person adds the question and sends it. */+export const repoPrompt = (repo: keyof typeof REPOS): string =>+ `Read ${REPOS[repo]} with gh (README, docs, ADRs), read-only: do not clone, build or run anything. How does it relate to this project's ruflo flywheel (ADR-322 receipts in .claude-flow/flywheel-v1)? `++const count = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`++/** What one entry printed, as lines worth reading, keeping the parsed answer where the board draws it. */+export function evolveLines(state: State, id: string, stdout: string, stderr: string, atMs: number): string[] {+ const evolve = state.evolve+ const value = jsonAfter(stdout)+ const lines = ((): string[] => {+ if (id === 'evolve-ledger') {+ const ledger = parseLedger(stdout, atMs)+ const flywheel = recordOf(recordOf(value)?.state)++ if (ledger === null) return []+ evolve.ledger = ledger++ return [+ `ledger ${ledger.isValid ? 'VALID' : 'INVALID'} · ${count(ledger.commits, 'commit')} · head ${shortRef(ledger.head)}`,+ ...ledger.errors.map(error => `✗ ${error}`),+ `champion ${shortRef(typeof flywheel?.activeChampionRef === 'string' ? flywheel.activeChampionRef : undefined)} · serving epoch ${String(flywheel?.servingEpoch ?? 'n/a')} · ${count(Object.keys(recordOf(flywheel?.receiptStates) ?? {}).length, 'receipt')} registered`,+ ]+ }++ if (id === 'evolve-receipts' && Array.isArray(value)) {+ if (value.length === 0) return ['no receipts yet: ▸ FLYWHEEL RUN in the MetaHarness lab evaluates candidates into receipts']++ return value.slice(0, 30).flatMap(entry => {+ const row = recordOf(entry)+ const state = recordOf(row?.state)++ return row === null ? [] : [`${shortRef(String(row.receiptId ?? ''))} · ${plain(String(row.decision ?? 'n/a'), 12)} · ${row.signed === true ? 'signed' : 'UNSIGNED'} · ${plain(String(state?.status ?? 'unregistered'), 12)} · candidate ${shortRef(String(row.candidateId ?? ''))}`]+ })+ }++ if (id === 'evolve-history') {+ const commits = recordOf(value)?.commits++ if (!Array.isArray(commits)) return []+ if (commits.length === 0) return ['no promotions yet: the ledger is at genesis']++ return commits.slice(-30).flatMap(entry => {+ const commit = recordOf(entry)++ return commit === null ? [] : [`epoch ${String(commit.servingEpoch ?? '?')} · ${shortRef(String(commit.baselineRef ?? ''))} → ${shortRef(String(commit.candidateId ?? ''))} · receipt ${shortRef(String(commit.receiptId ?? ''))} · ${plain(String(commit.proposer ?? ''), 16)}`]+ })+ }++ if (id === 'evolve-policy') {+ const policy = parsePolicyLedger(stdout, atMs)++ if (policy === null) return []+ evolve.policyLedger = policy++ return [`mode ${policy.mode} · ${count(policy.rules, 'rule')} · ${count(policy.approvals, 'approval')} · ${count(policy.receipts, 'receipt')}`, `decision ledger ${policy.isValid ? 'verifies' : 'DOES NOT VERIFY'}`]+ }++ if (id === 'evolve-gate') {+ const gate = parseGate(stdout, atMs)++ if (gate === null) return []+ evolve.gate = gate++ return [`outcome ${gate.outcome} · enforced ${gate.enforced} · mode ${gate.mode}`, ...(gate.reason !== '' ? [`reason: ${gate.reason}`] : []), 'nothing was promoted: this asked the gate only']+ }++ const os = OSES.find(candidate => id === `evolve-witness-${candidate}`)++ if (os !== undefined) {+ const witness = parseWitness(stdout, os, atMs)++ if (witness === null) return []+ evolve.witness[os] = witness++ const failing = (Array.isArray(recordOf(value)?.results) ? (recordOf(value)?.results as unknown[]) : []).map(recordOf).filter(row => row !== null && row.status !== 'pass')++ return [+ `signature ${witness.isSignatureValid ? 'valid (hash, key and signature check)' : 'DOES NOT VERIFY'} · overall ${witness.isOk ? 'ok' : 'NOT OK'}`,+ `${witness.pass} pass · ${witness.drift} drift · ${witness.regressed} regressed · ${witness.missing} missing, against the installed CLI`,+ ...failing.slice(0, 20).map(row => `[${plain(String(row?.status ?? ''), 10)}] ${plain(String(row?.id ?? ''), 8)} ${plain(String(row?.desc ?? ''), 60)} · ${plain(String(row?.file ?? ''), 80)}`),+ ]+ }++ return []+ })()++ return lines.length > 0 ? lines.slice(0, LAB_MAX_LINES).map(line => plain(line, 160)) : labLines(id, stdout, stderr)+}++/** The spec for an entry: a read runs at once, the write asks; null when it cannot run now. */+export function evolveSpec(entry: EvolveEntry, state: State): ActionSpec | null {+ const args = entry.args(state)++ if (args === null) return null++ return {+ label: entry.label,+ args,+ expect: entry.cost === 'read' ? 'its output on the Self-Evolution board' : `its decision on the board; ${entry.note ?? ''}`,+ lab: entry.id,+ lines: (stdout, stderr) => evolveLines(state, entry.id, stdout, stderr, Date.now()),+ ...(entry.cost === 'read' && { isReadOnly: true }),+ ...(entry.note !== undefined && { note: entry.note }),+ ...(entry.timeoutMs !== undefined && { timeoutMs: entry.timeoutMs }),+ }+}++export const evolveWhy = (entry: EvolveEntry): string => entry.why ?? 'it cannot run now'++const reading = new WeakMap<State, Promise<void>>()++/** Reads the evolution files again (opening the view, r, ▸ reread); a read already running is joined. */+export function loadEvolve(state: State, host: Host): Promise<void> {+ const held = reading.get(state)++ if (held !== undefined) return held++ state.evolve.isReading = true+ host.invalidate()++ const run = readEvolve(host.fs, state.cache, state.cwd, Date.now())+ .then(files => {+ state.evolve.files = files+ })+ .catch(() => undefined)+ .finally(() => {+ state.evolve.isReading = false+ reading.delete(state)+ host.invalidate()+ })++ reading.set(state, run)++ return run+}++export type EvolveActions = {+ reread: () => void+ /** Types a read-only research prompt about the repo into the AI terminal (claude): nothing runs until it is sent. */+ ask: (repo: keyof typeof REPOS) => void+}++export function evolveActions(state: State, host: Host, load: (text: string) => void): EvolveActions {+ return {+ reread: () => void loadEvolve(state, host),+ ask: repo => load(repoPrompt(repo)),+ }+}diff --git a/plugins/ruflo-console/hooks/gfx/evolve.ts b/plugins/ruflo-console/hooks/gfx/evolve.tsnew file mode 100644index 0000000000..7333fe0f4d--- /dev/null+++ b/plugins/ruflo-console/hooks/gfx/evolve.ts@@ -0,0 +1,158 @@+/**+ * The governed-evolution loop as a picture, and the champion's ancestry as a tree. Pure: `loopStagesOf` and+ * `lineageOf` read what the evolve view holds, `loopPicture` draws the stages for an instant on the real clock. A stage+ * lights only from data: a file ruflo wrote, or what its CLI answered when the person asked. What nothing measures+ * reads n/a, dimmed, never dark. The dot that runs along the arrows is decoration over lit stages only.+ */+import { shortRef, type EvolveFiles, type EvolveState } from '../data/evolve'+import { COLOR, Grid, mix } from './raster'++export type StageMark = 'lit' | 'dark' | 'bad' | 'na'+export type LoopStage = { name: string; value: string; mark: StageMark; source: string }++const na = (name: string, source: string): LoopStage => ({ name, value: 'n/a', mark: 'na', source })++/**+ * OBSERVE → PROPOSE → EVALUATE → VERIFY → PROMOTE → REVERSE. The counts come from the flywheel files (receipts, commits,+ * generations), VERIFY from the last `flywheel status` the person ran, REVERSE from the active policy's rollback pointer.+ */+export function loopStagesOf(evolve: EvolveState): LoopStage[] {+ const files = evolve.files++ if (files === null) return ['OBSERVE', 'PROPOSE', 'EVALUATE', 'VERIFY', 'PROMOTE', 'REVERSE'].map(name => na(name, 'not read yet'))++ const receipts = files.receipts ?? []+ const generations = files.generations ?? []+ const hasStore = files.flywheel !== null || files.receipts !== null || files.generations !== null+ const runs = receipts.length + generations.length+ const candidates = new Set([...receipts.flatMap(receipt => receipt.candidate ?? []), ...generations.flatMap(generation => generation.candidate ?? [])]).size+ const decided = receipts.filter(receipt => receipt.decision !== undefined)+ const accepted = decided.filter(receipt => receipt.decision === 'accepted').length + generations.filter(generation => generation.isPromoted).length+ const promoted = (files.flywheel?.commits.length ?? 0) + generations.filter(generation => generation.isPromoted).length+ const mark = (n: number): StageMark => (n > 0 ? 'lit' : 'dark')+ const ledger = evolve.ledger+ const policy = files.policy++ return [+ hasStore ? { name: 'OBSERVE', value: `${runs} runs`, mark: mark(runs), source: 'receipts + generations on disk' } : na('OBSERVE', 'no flywheel files'),+ hasStore ? { name: 'PROPOSE', value: `${candidates} cand`, mark: mark(candidates), source: 'distinct candidate refs' } : na('PROPOSE', 'no flywheel files'),+ hasStore ? { name: 'EVALUATE', value: `${decided.length + generations.length} · ${accepted}✓`, mark: mark(decided.length + generations.length), source: 'receipt decisions' } : na('EVALUATE', 'no flywheel files'),+ ledger === null ? na('VERIFY', '▸ LEDGER checks the hash chain') : { name: 'VERIFY', value: ledger.isValid ? 'valid' : 'INVALID', mark: ledger.isValid ? 'lit' : 'bad', source: 'metaharness flywheel status' },+ hasStore ? { name: 'PROMOTE', value: `${promoted} · ep ${files.flywheel?.epoch ?? 'n/a'}`, mark: mark(promoted), source: 'promotion commits + promoted generations' } : na('PROMOTE', 'no flywheel files'),+ policy === null+ ? na('REVERSE', 'no harness-active-policy.json')+ : { name: 'REVERSE', value: policy.isRolledBack ? 'rolled back' : policy.previous !== undefined ? 'armed' : 'no ptr', mark: policy.isRolledBack ? 'lit' : 'dark', source: 'the active policy’s previous pointer' },+ ]+}++const BORDER: Record<StageMark, number> = { lit: COLOR.ok, dark: COLOR.line, bad: COLOR.bad, na: COLOR.dim }++/** Rows the loop picture takes: the six boxes and the return path under them. */+export const LOOP_ROWS = 5++/** Six boxes left to right with their values, and the way back from REVERSE to OBSERVE underneath. */+export function loopPicture(stages: readonly LoopStage[], columns: number, t: number): Grid {+ const grid = new Grid(columns, LOOP_ROWS)+ const n = Math.max(1, stages.length)+ const box = Math.max(7, Math.floor((columns - (n - 1) * 3) / n))+ const centre = (i: number) => i * (box + 3) + Math.floor(box / 2)++ stages.forEach((stage, i) => {+ const x0 = i * (box + 3)+ const color = BORDER[stage.mark]+ const inner = box - 2++ grid.text(x0, 0, `╭${'─'.repeat(inner)}╮`, color)+ grid.text(x0, 1, `│${stage.name.padEnd(inner).slice(0, inner)}│`, stage.mark === 'na' ? COLOR.dim : COLOR.accent)+ grid.text(x0, 2, `│${stage.value.padStart(inner).slice(0, inner)}│`, stage.mark === 'lit' ? COLOR.ok : stage.mark === 'bad' ? COLOR.bad : COLOR.dim)+ grid.text(x0, 3, `╰${'─'.repeat(inner)}╯`, color)++ if (i > 0) {+ const ax = x0 - 3+ const isFlowing = stage.mark === 'lit' && stages[i - 1]?.mark === 'lit'++ grid.text(ax, 1, '──▶', isFlowing ? COLOR.ok : COLOR.line)+ if (isFlowing) grid.set(ax + (Math.floor(t / 400) % 3), 1, '●', mix(COLOR.ok, COLOR.warn, 0.5))+ }+ })++ // The loop closes: REVERSE (or a new run) feeds the next OBSERVE.+ const from = centre(n - 1)+ const to = centre(0)++ grid.set(to, 4, '╰', COLOR.line)+ grid.text(to + 1, 4, '─'.repeat(Math.max(0, from - to - 1)), COLOR.line)+ grid.set(from, 4, '╯', COLOR.line)+ grid.set(to, 3, '▲', stages[0]?.mark === 'lit' ? COLOR.ok : COLOR.line)+ grid.text(to + 2, 4, ' next run ', COLOR.dim)++ return grid+}++export type LineageKind = 'root' | 'promoted' | 'champion' | 'rejected' | 'pending'+export type LineageRow = { prefix: string; ref: string; kind: LineageKind; note: string }+type Edge = { parent: string; child: string; kind: Exclude<LineageKind, 'root' | 'champion'>; note: string; atMs: number }++export const MAX_LINEAGE_ROWS = 18+const ROOT = 'root'++/** A forest of edges as rows, roots first, each child under its parent with ├─ / └─ and the champion marked. */+function treeRows(edges: readonly Edge[], champion: string | undefined): LineageRow[] {+ const children = new Map<string, Edge[]>()++ for (const edge of edges) children.set(edge.parent, [...(children.get(edge.parent) ?? []), edge])++ const isChild = new Set(edges.map(edge => edge.child))+ const roots = [...children.keys()].filter(ref => !isChild.has(ref))+ const rows: LineageRow[] = []+ const seen = new Set<string>()+ const walk = (ref: string, prefix: string, depth: number) => {+ const kids = (children.get(ref) ?? []).slice().sort((a, b) => a.atMs - b.atMs)++ kids.forEach((edge, i) => {+ if (rows.length >= MAX_LINEAGE_ROWS || seen.has(edge.child) || depth > 24) return++ const isLast = i === kids.length - 1++ seen.add(edge.child)+ rows.push({ prefix: `${prefix}${isLast ? '└─' : '├─'}`, ref: edge.child, kind: edge.child === champion && edge.kind === 'promoted' ? 'champion' : edge.kind, note: edge.note })+ walk(edge.child, `${prefix}${isLast ? ' ' : '│ '}`, depth + 1)+ })+ }++ for (const root of roots) {+ if (rows.length >= MAX_LINEAGE_ROWS) break+ rows.push({ prefix: '', ref: root, kind: 'root', note: root === ROOT ? 'the first generation' : 'baseline' })+ walk(root, '', 1)+ }++ return rows+}++const when = (atMs: number | undefined) => (atMs === undefined ? '' : ` · ${new Date(atMs).toISOString().slice(0, 10)}`)++/**+ * The champion's ancestry, per store. The flywheel's: each promotion commit links its baseline to the candidate, and+ * each receipt not promoted hangs off its baseline as rejected or waiting. The generations loop's: each bundle's parent.+ */+export function lineageOf(files: EvolveFiles | null): { flywheel: LineageRow[]; generations: LineageRow[] } {+ if (files === null) return { flywheel: [], generations: [] }++ const commits = files.flywheel?.commits ?? []+ const promoted = new Set(commits.map(commit => commit.candidate))+ const flywheel: Edge[] = [+ ...commits.map(commit => ({ parent: commit.baseline ?? ROOT, child: commit.candidate, kind: 'promoted' as const, note: `epoch ${commit.epoch ?? '?'}${commit.receipt !== undefined ? ` · receipt ${shortRef(commit.receipt)}` : ''}${when(commit.atMs)}`, atMs: commit.atMs ?? 0 })),+ ...(files.receipts ?? []).flatMap(receipt =>+ receipt.candidate === undefined || promoted.has(receipt.candidate)+ ? []+ : [{ parent: receipt.baseline ?? ROOT, child: receipt.candidate, kind: receipt.decision === 'accepted' ? ('pending' as const) : ('rejected' as const), note: `${receipt.decision ?? 'undecided'} · ${receipt.status ?? 'unregistered'} · receipt ${shortRef(receipt.id)}${when(receipt.atMs)}`, atMs: receipt.atMs ?? 0 }],+ ),+ ]+ const generations: Edge[] = (files.generations ?? []).flatMap(generation =>+ generation.candidate === undefined+ ? []+ : [{ parent: generation.parent ?? ROOT, child: generation.candidate, kind: generation.isPromoted ? ('promoted' as const) : ('rejected' as const), note: `gen ${generation.generation}${generation.mutation !== undefined ? ` · ${generation.mutation}` : ''}${generation.cause !== undefined ? ` · failed ${generation.cause}` : ''}${when(generation.atMs)}`, atMs: generation.atMs ?? generation.generation }],+ )++ return { flywheel: treeRows(flywheel, files.flywheel?.champion), generations: treeRows(generations, files.served?.champion) }+}diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.tsindex 320a67f328..fdefb610ad 100644--- a/plugins/ruflo-console/hooks/palette.ts+++ b/plugins/ruflo-console/hooks/palette.ts@@ -6,6 +6,7 @@import { HIVE_ROLES, pickedProposal } from './data/hive'import { hiveBroadcast, hivePropose, hiveSpawn, hiveVote } from './hive'import { claimTask, handoffClaim, releaseClaim, stealClaim, type ActionSpec } from './actions'+import { EVOLVE, evolveSpec, evolveWhy } from './evolve'import { LAB, labSpec, labWhy } from './mh-lab'import { AGENT_TYPES, agentLogs, dispatchWorker, memorySearch, memoryStore, reroute, setClaimStatus, spawnAgent, stopAgent, swarmInit, swarmStop, vote, WORKERS } from './ops'import { VIEWS, type State, type ViewId } from './state'@@ -115,6 +116,8 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {// The MetaHarness lab: reads run at once, the rest ask first; promotion is never an entry (see mh-lab.ts).for (const entry of LAB) add(entry.id, 'metaharness', entry.label, { kind: 'spec', spec: labSpec(entry, state), why: labWhy(entry) })+ // The Self-Evolution checks: reads at once, the gate check asks; promotion is never an entry (see evolve.ts).+ for (const entry of EVOLVE) add(entry.id, 'evolve', entry.label, { kind: 'spec', spec: evolveSpec(entry, state), why: evolveWhy(entry) })for (const worker of WORKERS) add(`worker-${worker}`, 'workers', `dispatch the ${worker} background worker`, { kind: 'spec', spec: dispatchWorker(worker), why: 'unknown worker' })diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.tsindex 6a61fe2313..c17b9aaa68 100644--- a/plugins/ruflo-console/hooks/runner.ts+++ b/plugins/ruflo-console/hooks/runner.ts@@ -60,7 +60,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner// A lab run's output goes to the lab's result panel, scrolled from its top; the footer keeps the one-line outcome.if (spec.lab !== undefined) {- state.lab.result = { id: spec.lab, label: spec.label, ok, exitCode: result.exitCode, ...(spec.note !== undefined && { note: spec.note }), lines: labLines(spec.lab, result.stdout, result.stderr), atMs: Date.now() }+ state.lab.result = { id: spec.lab, label: spec.label, ok, exitCode: result.exitCode, ...(spec.note !== undefined && { note: spec.note }), lines: spec.lines?.(result.stdout, result.stderr) ?? labLines(spec.lab, result.stdout, result.stderr), atMs: Date.now() }state.select.item = 0}diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.tsindex 4270e97672..d0a17b105a 100644--- a/plugins/ruflo-console/hooks/state.ts+++ b/plugins/ruflo-console/hooks/state.ts@@ -3,6 +3,7 @@ import type { PluginOptions, Timer } from 'claude-code'import type { ProbeResult } from './data/cli'import type { ConsoleEvent } from './data/events'import type { ReadCache } from './data/files'+import { emptyEvolve, type EvolveState } from './data/evolve'import { emptySkills, type SkillsState } from './data/skills'import type { Snapshot } from './data/snapshot'import type { RufloRoute, RufloSnapshot } from '../types'@@ -10,7 +11,7 @@ import type { RufloRoute, RufloSnapshot } from '../types'export const PLUGIN_NAME = 'ruflo-console'export const PANE_ID = 'ruflo-console'-export type ViewId = 'menu' | 'overview' | 'swarm' | 'hive' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory' | 'cost' | 'timeline' | 'approvals' | 'events' | 'missions' | 'xruv' | 'terminal' | 'skills' | 'agent'+export type ViewId = 'menu' | 'overview' | 'swarm' | 'hive' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory' | 'cost' | 'timeline' | 'approvals' | 'events' | 'missions' | 'xruv' | 'terminal' | 'skills' | 'evolve' | 'agent'/*** The views in tab order, each with its hotkey and the inline height it asks for. Digits are the first nine; the three@@ -42,6 +43,8 @@ export const VIEWS: readonly { id: ViewId; key: string; label: string; short: st{ id: 'terminal', key: 'i', label: 'Terminal', short: 'Trm', icon: '💻', blurb: 'an AI terminal: codex, claude or both, each a session that remembers the conversation, streamed live', rows: 32 },// No hotkey: every digit and letter is taken. The tab, the menu prompt and /ruflo skills reach it by name.{ id: 'skills', key: '', label: 'Skills', short: 'Skl', icon: '🧰', blurb: 'agent skills (npx skills, skills.sh): what is installed here and globally, search, add, update, remove, create', rows: 34 },+ // No hotkey either: the tab, the menu prompt, the palette and /ruflo evolve reach it by name.+ { id: 'evolve', key: '', label: 'Self-Evolution', short: 'Evo', icon: '🧬', blurb: 'the governed loop: flywheel receipts, ledger, lineage, the policy gate, the witness; Autogenous and rGi', rows: 44 },]export const AGENT_VIEW = { id: 'agent' as const, rows: 28 }@@ -217,6 +220,8 @@ export type State = {}/** The skills view: installed skills, the last search, and the change running now. */skills: SkillsState+ /** The Self-Evolution view: the flywheel files as last read, and what its checks answered. */+ evolve: EvolveStatetimers: Map<string, Timer>stats: { renders: number[]; refreshes: number[]; frames: number[] }}@@ -261,6 +266,7 @@ export function newState(raw: PluginOptions | undefined): State {barDrawnAtMs: 0,terminal: { harness: 'codex', draft: '', lines: [], runs: new Map(), sessions: {}, isLive: { codex: false, claude: false }, turns: { codex: 0, claude: 0 }, costUsd: 0, scroll: 0, unseen: 0, asked: null },skills: emptySkills(),+ evolve: emptyEvolve(),timers: new Map(),stats: { renders: [], refreshes: [], frames: [] },}diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.tsindex 482d9f5b70..f7dd42d0cc 100644--- a/plugins/ruflo-console/hooks/views/common.ts+++ b/plugins/ruflo-console/hooks/views/common.ts@@ -6,6 +6,7 @@import type { Elements, RenderChildren, RenderElement } from 'claude-code'import type { ProbeResult } from '../data/cli'+import type { EvolveActions } from '../evolve'import type { Grid } from '../gfx/raster'import type { SkillActions } from '../skills'import type { HarnessId, State, ViewId } from '../state'@@ -44,6 +45,8 @@ export type Actions = {term: { harness: (id: HarnessId) => void; draft: (text: string) => void; submit: (text: string) => void; stop: () => void; fresh: () => void; clear: () => void; load: (id: HarnessId, text: string) => void; /** Moves the window up (positive) or down by screen rows. */ scroll: (by: number) => void; /** Puts an earlier question back in the field. */ reuse: (text: string) => void }/** The skills view: list, search, and the confirm-gated add, remove, update and create; edit loads the terminal. */skills: SkillActions+ /** The Self-Evolution view: read its files again; ▸ ask types a repo prompt into the AI terminal. */+ evolve: EvolveActions}export type Ctx = {diff --git a/plugins/ruflo-console/hooks/views/evolve.ts b/plugins/ruflo-console/hooks/views/evolve.tsnew file mode 100644index 0000000000..10e79324c0--- /dev/null+++ b/plugins/ruflo-console/hooks/views/evolve.ts@@ -0,0 +1,226 @@+import type { RenderElement } from 'claude-code'++import { shortRef, type Manifest, type Receipt } from '../data/evolve'+import { candidateReceipt, EVOLVE, evolveSpec, PROMOTE_COMMAND, REPOS, type EvolveEntry } from '../evolve'+import { lineageOf, loopStagesOf, type LineageRow } from '../gfx/evolve'+import { ago, button, clip, col, kv, picture, row, rule, text, THEME, type Ctx } from './common'++/** Result lines in view at once; j/k scroll the rest. */+const RESULT_ROWS = 12+const RECEIPTS_SHOWN = 8++const entryOf = (id: string): EvolveEntry | undefined => EVOLVE.find(entry => entry.id === id)++/** One check as a dotted row: its cost tag, its name, what it does, and its ▸ button (dim when it cannot run now). */+function entryRow(ctx: Ctx, id: string): RenderElement | null {+ const entry = entryOf(id)++ if (entry === undefined) return null++ const lead = Math.max(14, Math.min(18, ctx.columns - 40))+ const isBlocked = evolveSpec(entry, ctx.state) === null++ return row(+ ctx,+ [+ ctx.kit.Text({ bold: true, color: entry.cost === 'read' ? THEME.ok : THEME.info, children: entry.cost === 'read' ? ' $0 ' : ' wr ' }),+ ctx.kit.Text({ bold: true, color: THEME.head, children: ` ${entry.name} `.padEnd(lead, '.') }),+ ctx.kit.Text({ color: THEME.info, dimColor: isBlocked, wrap: 'truncate-end', children: clip(` ${isBlocked ? (entry.why ?? entry.about) : entry.about}`, Math.max(4, ctx.columns - lead - 16)) }),+ ctx.kit.Button({ key: `evolve-${entry.id}`, label: entry.cost === 'read' ? ' ▸ run' : ' ▸ ask', plain: true, dimColor: true, onPress: () => void ctx.act.run(entry.id) }),+ ],+ `evolve-row-${entry.id}`,+ )+}++const rows = (ctx: Ctx, ids: readonly string[]): RenderElement[] => ids.flatMap(id => entryRow(ctx, id) ?? [])++function loopRows(ctx: Ctx): RenderElement[] {+ const stages = loopStagesOf(ctx.state.evolve)+ const words = stages.map(stage => `${stage.mark === 'lit' ? '●' : stage.mark === 'bad' ? '✗' : '○'} ${stage.name} ${stage.value}`).join(' → ')+ const unknown = stages.filter(stage => stage.mark === 'na')++ return [+ rule(ctx, 'Loop', 'observe → propose → evaluate → verify → promote → reverse'),+ picture(ctx, 'evolve-loop', ` ${words}`),+ ...(unknown.length > 0 ? [text(ctx, ` n/a: ${unknown.map(stage => `${stage.name.toLowerCase()} (${stage.source})`).join(' · ')}`, { dimColor: true })] : []),+ ]+}++function receiptLine(ctx: Ctx, receipt: Receipt): RenderElement {+ const verdict = receipt.decision ?? 'undecided'+ const color = receipt.decision === 'accepted' ? THEME.ok : receipt.decision === 'rejected' ? THEME.bad : THEME.warn+ const lift = receipt.lift === undefined ? '' : ` · lift ${receipt.lift >= 0 ? '+' : ''}${(receipt.lift * 100).toFixed(1)}%`++ return row(ctx, [+ ctx.kit.Text({ bold: true, color, children: ` ${receipt.decision === 'accepted' ? '✓' : receipt.decision === 'rejected' ? '✗' : '?'} ${shortRef(receipt.id)} ` }),+ ctx.kit.Text({ color, children: verdict.padEnd(9) }),+ ctx.kit.Text({ dimColor: true, wrap: 'truncate-end', children: clip(` ${receipt.isSigned ? 'signed' : 'UNSIGNED'} · ${receipt.status ?? 'unregistered'} · ${shortRef(receipt.baseline)} → ${shortRef(receipt.candidate)}${lift} · ${ago(receipt.atMs, ctx.nowMs)}`, Math.max(4, ctx.columns - 24)) }),+ ])+}++function ledgerRows(ctx: Ctx): RenderElement[] {+ const { evolve } = ctx.state+ const files = evolve.files+ const flywheel = files?.flywheel ?? null+ const ledger = evolve.ledger+ const out: RenderElement[] = [rule(ctx, 'Ledger & receipts', '.claude-flow/flywheel-v1 · ADR-322')]++ out.push(+ kv(ctx, 'ledger', ledger === null ? 'n/a: not verified yet (▸ LEDGER checks it)' : `${ledger.isValid ? 'VALID' : 'INVALID'} · ${ledger.commits} commits · head ${shortRef(ledger.head)} · ${ago(ledger.atMs, ctx.nowMs)}`, ledger === null ? undefined : ledger.isValid ? THEME.ok : THEME.bad),+ )+ for (const error of ledger?.errors ?? []) out.push(text(ctx, ` ✗ ${error}`, { color: THEME.bad }))+ out.push(kv(ctx, 'champion', flywheel === null ? 'n/a: no transaction-state.json' : `${shortRef(flywheel.champion)} · serving epoch ${flywheel.epoch ?? 'n/a'} · served ${shortRef(flywheel.served)}`))++ const receipts = files?.receipts ?? null++ if (receipts === null) out.push(text(ctx, ' receipts: n/a (no receipts folder): ▸ FLYWHEEL RUN in the MetaHarness lab evaluates candidates into receipts', { dimColor: true }))+ else if (receipts.length === 0) out.push(text(ctx, ' receipts: none yet', { dimColor: true }))+ else out.push(text(ctx, ` receipts: ${receipts.length} newest${receipts.length >= 20 ? ' (of more)' : ''} · ${receipts.filter(receipt => receipt.decision === 'accepted').length} accepted · ${receipts.filter(receipt => !receipt.isSigned).length} unsigned`, { color: THEME.info }))++ for (const receipt of (receipts ?? []).slice(0, RECEIPTS_SHOWN)) out.push(receiptLine(ctx, receipt))++ out.push(...rows(ctx, ['evolve-ledger', 'evolve-receipts', 'evolve-history']))+ out.push(text(ctx, ' per-receipt signature check: n/a here, ruflo runs it only inside promote · autogenous verifier: n/a (a library, nothing built)', { dimColor: true }))++ return out+}++function treeLine(ctx: Ctx, line: LineageRow): RenderElement {+ const color = line.kind === 'champion' ? THEME.ok : line.kind === 'rejected' ? THEME.bad : line.kind === 'pending' ? THEME.warn : line.kind === 'root' ? THEME.head : THEME.info+ const glyph = line.kind === 'champion' ? '★' : line.kind === 'rejected' ? '✗' : line.kind === 'pending' ? '◌' : line.kind === 'root' ? '◇' : '●'++ return row(ctx, [+ ctx.kit.Text({ dimColor: true, children: ` ${line.prefix}` }),+ ctx.kit.Text({ bold: line.kind === 'champion', color, children: `${glyph} ${line.ref === 'root' ? 'root' : shortRef(line.ref)}${line.kind === 'champion' ? ' champion' : ''} ` }),+ ctx.kit.Text({ dimColor: true, wrap: 'truncate-end', children: clip(line.note, Math.max(4, ctx.columns - line.prefix.length - 24)) }),+ ])+}++function lineageRows(ctx: Ctx): RenderElement[] {+ const files = ctx.state.evolve.files+ const lineage = lineageOf(files)+ const out: RenderElement[] = [rule(ctx, 'Lineage', '★ champion · ● promoted · ◌ accepted, waiting · ✗ rejected')]++ out.push(text(ctx, ' flywheel-v1 (promotion commits and receipts):', { color: THEME.info }))+ if (lineage.flywheel.length === 0) out.push(text(ctx, ` n/a: ${files?.flywheel === null && files?.receipts === null ? 'no flywheel-v1 files' : 'no promotions or receipts yet (the ledger is at genesis)'}`, { dimColor: true }))+ for (const line of lineage.flywheel) out.push(treeLine(ctx, line))++ out.push(text(ctx, ' generations (.claude-flow/flywheel, each bundle’s parent):', { color: THEME.info }))+ if (lineage.generations.length === 0) out.push(text(ctx, ' n/a: no generation-N.json bundles', { dimColor: true }))+ for (const line of lineage.generations) out.push(treeLine(ctx, line))++ return out+}++function policyRows(ctx: Ctx): RenderElement[] {+ const { evolve } = ctx.state+ const policy = evolve.files?.policy ?? null+ const ledger = evolve.policyLedger+ const gate = evolve.gate+ const out: RenderElement[] = [rule(ctx, 'Policies', 'harness-active-policy.json · ADR-324 gate')]++ out.push(kv(ctx, 'active policy', policy === null ? 'n/a: no .claude-flow/harness-active-policy.json' : `${shortRef(policy.champion)} · ${policy.tier ?? 'tier n/a'} · ${policy.layer ?? 'layer n/a'} · applied ${ago(policy.appliedAtMs, ctx.nowMs)}`))+ if (policy !== null) out.push(kv(ctx, 'rollback', policy.isRolledBack ? `rolled back to ${shortRef(policy.previous)}` : policy.previous !== undefined ? `armed: previous ${shortRef(policy.previous)} (the generations loop rolls back on a regression; no CLI verb)` : 'no previous pointer'))+ out.push(kv(ctx, 'policy engine', ledger === null ? 'n/a: not asked yet (▸ POLICY)' : `mode ${ledger.mode} · ${ledger.rules} rules · ${ledger.approvals} approvals · ${ledger.receipts} receipts · ledger ${ledger.isValid ? 'verifies' : 'DOES NOT VERIFY'}`, ledger === null ? undefined : ledger.isValid ? THEME.ok : THEME.bad))+ out.push(kv(ctx, 'promote gate', gate === null ? `n/a: not asked yet (▸ GATE CHECK${candidateReceipt(evolve.files) !== undefined ? ` about receipt ${shortRef(candidateReceipt(evolve.files))}` : ''})` : `${gate.enforced} in ${gate.mode} mode · ${gate.reason || 'no reason given'} · ${ago(gate.atMs, ctx.nowMs)}`, gate === null ? undefined : gate.enforced === 'allowed' ? THEME.ok : THEME.warn))+ out.push(...rows(ctx, ['evolve-policy', 'evolve-gate']))+ out.push(text(ctx, ' policy_status / policy_evaluate are the same engine; the CLI verbs are used because mcp exec adds a ledger receipt per call', { dimColor: true }))++ return out+}++function manifestLine(ctx: Ctx, manifest: Manifest): RenderElement {+ const witness = ctx.state.evolve.witness[manifest.os]+ const result = witness === undefined ? 'not verified yet' : `${witness.isSignatureValid ? 'signature valid' : 'SIGNATURE FAILS'} · ${witness.pass} pass · ${witness.drift} drift · ${witness.regressed} regressed · ${witness.missing} missing · ${ago(witness.atMs, ctx.nowMs)}`+ const color = witness === undefined ? THEME.info : witness.isSignatureValid && witness.regressed === 0 ? THEME.ok : THEME.bad++ return kv(ctx, `${manifest.os}`, `${manifest.isSigned ? 'signed' : 'UNSIGNED'} · ${manifest.fixes ?? 'n/a'} fixes · ${manifest.branch ?? 'n/a'} @ ${manifest.gitCommit ?? 'n/a'} · issued ${ago(manifest.issuedAtMs, ctx.nowMs)} · ${result}`, color)+}++function witnessRows(ctx: Ctx): RenderElement[] {+ const manifests = ctx.state.evolve.files?.manifests ?? []+ const out: RenderElement[] = [rule(ctx, 'Witness', 'verification/<os>/manifest.md.json · ADR-103 · read-only')]++ if (manifests.length === 0) out.push(text(ctx, ' n/a: no signed witness manifest in this project (verification/<os>/manifest.md.json)', { dimColor: true }))++ for (const manifest of manifests) out.push(manifestLine(ctx, manifest))++ out.push(...rows(ctx, manifests.map(manifest => `evolve-witness-${manifest.os}`)))+ if (manifests.length > 0) out.push(text(ctx, ' each fix is checked against the installed @claude-flow/cli; a manifest from another OS may drift here', { dimColor: true }))++ return out+}++function whereRows(ctx: Ctx): RenderElement[] {+ const hasRgiDb = ctx.state.evolve.files?.hasRgiDb ?? false+ const ask = (repo: keyof typeof REPOS) => button(ctx, `evolve-ask-${repo}`, `▸ ask about ${repo === 'rgi' ? 'rGi' : 'Autogenous'}`, () => ctx.act.evolve.ask(repo))++ return [+ rule(ctx, 'What runs where', 'integrated here · only linked'),+ text(ctx, ` Autogenous · ${REPOS.autogenous}`, { bold: true, color: THEME.head }),+ text(ctx, ' integrated: the receipt format. ruflo writes ruflo.flywheel-receipt/v1, the schema autogenous’s radio-moe exports and verifies;', { color: THEME.ok }),+ text(ctx, ' fractional policy values are decimal strings so its stricter verifier accepts them (ruvnet/autogenous#15).', { color: THEME.ok }),+ text(ctx, ' linked only: its verifier (crates/verifier, verifyExportedReceipt) is a library with no binary or build here: n/a;', { dimColor: true }),+ text(ctx, ' autogenous-service (HTTP :8080, /v1/agl/admit, /v1/promote) is not built or running here; AGL/AAP are its protocols.', { dimColor: true }),+ row(ctx, [ask('autogenous')]),+ text(ctx, ` rGi · ${REPOS.rgi}`, { bold: true, color: THEME.head }),+ text(ctx, ' linked only: a perpetual runtime (observe → plan → admit → execute → record) holding the enduring cognitive policies;', { dimColor: true }),+ text(ctx, ` its state is SQLite .rgi/runtime.db: ${hasRgiDb ? 'present here (never opened)' : 'not in this project'}; its CLI needs a checkout: none here, so n/a.`, { dimColor: true }),+ text(ctx, ' ruflo stays the execution authority (manifesto §6): neither repo can promote here.', { dimColor: true }),+ row(ctx, [ask('rgi')]),+ text(ctx, ' ▸ ask types a read-only research prompt into the AI terminal (claude); Enter twice sends it, nothing opens a browser', { dimColor: true }),+ ]+}++function resultRows(ctx: Ctx): RenderElement[] {+ const { state, nowMs } = ctx+ const running = state.lab.running?.id.startsWith('evolve-') === true ? state.lab.running : null+ const result = state.lab.result?.id.startsWith('evolve-') === true ? state.lab.result : null+ const out: RenderElement[] = [rule(ctx, 'Result', running !== null ? `running ${Math.round((nowMs - running.startedAtMs) / 1000)}s` : result === null ? 'nothing run yet' : `${result.ok ? '✓' : '✗'} exit ${result.exitCode ?? 'n/a'} · ${ago(result.atMs, nowMs)}`)]++ if (running !== null) out.push(text(ctx, ` ▸ ${running.label} …`, { color: THEME.warn }))+ if (result === null) {+ if (running === null) out.push(text(ctx, ' ▸ run a check: a $0 read answers here at once; ▸ ask shows its command and runs after you confirm (y)', { dimColor: true }))++ return out+ }++ out.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad }))+ if (result.note !== undefined) out.push(text(ctx, ` ${result.note}`, { color: THEME.warn }))++ const top = Math.max(0, Math.min(state.select.item, result.lines.length - RESULT_ROWS))++ for (const line of result.lines.slice(top, top + RESULT_ROWS)) out.push(text(ctx, ` ${line}`))+ if (result.lines.length > RESULT_ROWS) out.push(row(ctx, [text(ctx, ` lines ${top + 1}-${Math.min(result.lines.length, top + RESULT_ROWS)} of ${result.lines.length} `, { dimColor: true }), button(ctx, 'evolve-up', 'up', () => ctx.act.select(-1), { hotkey: 'k' }), button(ctx, 'evolve-down', 'down', () => ctx.act.select(1), { hotkey: 'j' })]))++ return out+}++/**+ * Self-Evolution: the governed loop as ruflo recorded it (flywheel receipts, ledger, champion, promotions, rollback+ * pointer), its lineage, the policy gate and the witness manifest, each check a button; Autogenous and rGi as what is+ * integrated and what is only linked. Promotion is a command the person runs, never a button.+ */+export function evolveView(ctx: Ctx): RenderElement {+ const { evolve } = ctx.state+ const status = evolve.isReading ? 'reading the flywheel files…' : evolve.files === null ? 'not read yet' : `files read ${ago(evolve.files.readAtMs, ctx.nowMs)}`++ return col(+ ctx,+ [+ row(ctx, [text(ctx, ` ${status} `, { dimColor: true }), button(ctx, 'evolve-reread', 'Reread', () => ctx.act.evolve.reread()), button(ctx, 'evolve-lab', 'MetaHarness lab: run candidates', () => ctx.act.view('metaharness'))]),+ ...loopRows(ctx),+ ...ledgerRows(ctx),+ ...lineageRows(ctx),+ ...policyRows(ctx),+ ...witnessRows(ctx),+ ...whereRows(ctx),+ ...resultRows(ctx),+ rule(ctx, 'Promote', 'a person’s act · never from this pane'),+ text(ctx, ' The flywheel, Darwin and MetaHarness propose and evaluate; none may promote itself (ADR-322). Review the receipt, then run:', { color: THEME.info }),+ text(ctx, ` ${PROMOTE_COMMAND}`, { bold: true, color: THEME.warn }),+ text(ctx, ' It needs an approved Ed25519 public key and --confirm, and it passes the policy gate (▸ GATE CHECK asks that gate first).', { dimColor: true }),+ ],+ 'evolve',+ )+}diff --git a/plugins/ruflo-console/hooks/views/frames.ts b/plugins/ruflo-console/hooks/views/frames.tsindex b3efe40cc9..29bbe086f8 100644--- a/plugins/ruflo-console/hooks/views/frames.ts+++ b/plugins/ruflo-console/hooks/views/frames.ts@@ -11,6 +11,7 @@ import { agentLabels } from '../data/parse'import type { Snapshot } from '../data/snapshot'import type { Channels, Peers, Roster } from '../data/cli'import { pipelinePicture, radarPicture, samplesPicture, trendPicture, gaugePicture, type Stage } from '../gfx/charts'+import { loopPicture, loopStagesOf } from '../gfx/evolve'import { flowModelOf, flowPicture, flowRows } from '../gfx/flow'import { federationPicture, ganttPicture, heatmapPicture, type FedNode, type HealthRow, type Lane } from '../gfx/maps'import { activityPicture, bannerPicture, bootPicture, titlePicture, curvePicture, headerPicture, PULSE_MS, topologyPicture, type TopoModel } from '../gfx/pictures'@@ -212,6 +213,9 @@ export function picturesOf(state: State, columns: number, nowMs: number, t: numbpictures.set('burn', samplesPicture('spend since load', state.history.spend, width))break}+ case 'evolve':+ pictures.set('evolve-loop', loopPicture(loopStagesOf(state.evolve), width, t))+ breakcase 'timeline': {const lanes = lanesOf(state, nowMs)diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.tsindex 585f47c21c..598629192c 100644--- a/plugins/ruflo-console/hooks/views/pane.ts+++ b/plugins/ruflo-console/hooks/views/pane.ts@@ -11,6 +11,7 @@ import { agentView } from './agent'import { claimsView } from './claims'import { ago, button, clip, col, isBbs, row, setLook, text, THEME, type Ctx } from './common'import { costView } from './cost'+import { evolveView } from './evolve'import { federationView } from './federation'import { hiveView } from './hive'import { learningView } from './learning'@@ -53,6 +54,7 @@ const BODIES: Record<ViewId, (ctx: Ctx) => RenderElement> = {xruv: xruvView,terminal: terminalView,skills: skillsView,+ evolve: evolveView,agent: agentView,}@@ -134,7 +136,8 @@ function confirmRow(ctx: Ctx): RenderElement | null {ctx,[text(ctx, `Confirm: ${pending.label.replace(/\?+$/, '')}?`, { bold: true, color: THEME.warn }),- text(ctx, `runs: ${pending.shows ?? `ruflo ${pending.args.join(' ')}`}`, { dimColor: true }),+ // Wrapped, not clipped: the person says yes to the whole argv, so all of it shows (a JSON argument runs long).+ ctx.kit.Text({ dimColor: true, wrap: 'wrap', children: `runs: ${pending.shows ?? `ruflo ${pending.args.join(' ')}`}` }),...(pending.note !== undefined ? [text(ctx, pending.note, { bold: /money|models/i.test(pending.note), color: /money|models/i.test(pending.note) ? THEME.bad : THEME.warn })] : []),row(ctx, [button(ctx, 'confirm', 'Yes, run it (y)', ctx.act.confirm, { hotkey: 'y', primary: true }), button(ctx, 'cancel', 'Cancel (n)', ctx.act.cancel, { hotkey: 'n' })]),],diff --git a/plugins/ruflo-console/tests/evolve.spec.ts b/plugins/ruflo-console/tests/evolve.spec.tsnew file mode 100644index 0000000000..bcc1004560--- /dev/null+++ b/plugins/ruflo-console/tests/evolve.spec.ts@@ -0,0 +1,213 @@+/**+ * The Self-Evolution view's pure parts under vitest: the catalog's invariants (fixed argv, no promotion, the witness+ * only ever with --manifest), the file readers against an in-memory disk, the CLI readers against what the checks+ * print, the loop stages lighting from data only, and the lineage tree. Run with+ * npx vitest run plugins/ruflo-console/tests/evolve.spec.ts+ */+import { describe, expect, it } from 'vitest'++import type { ReaderFs } from '../hooks/data/files'+import { parseActivePolicy, parseLedger, parseManifest, parsePolicyLedger, parseWitness, readEvolve, refOf, shortRef } from '../hooks/data/evolve'+import { candidateReceipt, EVOLVE, evolveLines, evolveSpec, evolveWhy, gateRequest, repoPrompt } from '../hooks/evolve'+import { lineageOf, LOOP_ROWS, loopPicture, loopStagesOf } from '../hooks/gfx/evolve'+import { PROMOTE_COMMAND } from '../hooks/mh-lab'+import { newState } from '../hooks/state'+import { C1, C2, EVOLVE_FILES, EVOLVE_OUT, R4, WARN } from './fixtures/evolve'++/** An in-memory disk under /work, as the engine's fs calls answer it. */+function fsOf(files: Readonly<Record<string, string>>): ReaderFs {+ const all = new Map(Object.entries(files).map(([path, text]) => [`/work/${path}`, text]))++ return {+ read: async path => {+ const text = all.get(path)++ if (text === undefined) throw new Error('ENOENT')++ return text+ },+ stat: async path => {+ const text = all.get(path)++ if (text === undefined) throw new Error('ENOENT')++ return { mtimeMs: 1, size: text.length }+ },+ list: async dir => {+ const names = [...all.keys()].filter(path => path.startsWith(`${dir}/`) && !path.slice(dir.length + 1).includes('/')).map(path => path.slice(dir.length + 1))++ if (names.length === 0) throw new Error('ENOENT')++ return names.map(name => ({ name, kind: 'file', mtimeMs: 1 }))+ },+ }+}++async function worldState(files: Readonly<Record<string, string>> = EVOLVE_FILES) {+ const state = newState({})++ state.cwd = '/work'+ state.evolve.files = await readEvolve(fsOf(files), state.cache, '/work', 1_000)++ return state+}++describe('the evolve catalog', () => {+ it('every id is evolve-*, unique; no argv promotes, resets, runs a candidate, rolls back or reaches a shell', async () => {+ const state = await worldState()+ const ids = EVOLVE.map(entry => entry.id)++ expect(new Set(ids).size).toBe(ids.length)+ expect(ids.every(id => id.startsWith('evolve-'))).toBe(true)++ for (const entry of EVOLVE) {+ const argv = evolveSpec(entry, state)?.args ?? []++ expect(argv, entry.id).not.toContain('promote')+ expect(argv, entry.id).not.toContain('evidence-reset')+ expect(argv, entry.id).not.toContain('run')+ expect(argv, entry.id).not.toContain('--confirm')+ expect(argv.some(word => /^(sh|bash|mcp)$/.test(word)), entry.id).toBe(false)+ // `verify` without --manifest fetches from GitHub: never offered.+ if (argv[0] === 'verify') expect(argv.slice(1, 3), entry.id).toEqual(['--manifest', `verification/${entry.id.slice('evolve-witness-'.length)}/manifest.md.json`])+ }++ expect(PROMOTE_COMMAND).toContain('flywheel promote <receipt-id>')+ })++ it('reads run at once with one fixed argv; the gate check asks first and says what it appends', async () => {+ const state = await worldState()+ const spec = (id: string) => evolveSpec(EVOLVE.find(entry => entry.id === id)!, state)++ expect(spec('evolve-ledger')).toMatchObject({ args: ['metaharness', 'flywheel', 'status'], isReadOnly: true, lab: 'evolve-ledger' })+ expect(spec('evolve-receipts')?.args).toEqual(['metaharness', 'flywheel', 'receipts'])+ expect(spec('evolve-history')?.args).toEqual(['metaharness', 'flywheel', 'history'])+ expect(spec('evolve-policy')?.args).toEqual(['policy', 'status'])+ expect(spec('evolve-witness-linux')?.args).toEqual(['verify', '--manifest', 'verification/linux/manifest.md.json', '--json'])++ const gate = spec('evolve-gate')++ expect(gate?.isReadOnly).toBeUndefined()+ expect(gate?.note).toMatch(/appends one decision receipt .* promotes nothing/)+ expect(gate?.args.slice(0, 2)).toEqual(['policy', 'evaluate'])+ expect(JSON.parse(gate?.args[2] ?? '{}')).toEqual(gateRequest(R4))+ expect(gateRequest(R4)).toMatchObject({ identity: { id: 'ruflo-console', type: 'plugin' }, action: { type: 'metaharness.candidate.promote', resource: R4 } })+ })++ it('a witness entry with no manifest on disk cannot run and says why; the gate asks about no receipt when none waits', async () => {+ const state = await worldState({})+ const macos = EVOLVE.find(entry => entry.id === 'evolve-witness-macos')!++ expect(evolveSpec(macos, state)).toBeNull()+ expect(evolveWhy(macos)).toContain('without --manifest, ruflo verify fetches from GitHub')+ expect(candidateReceipt(state.evolve.files)).toBeUndefined()+ expect(JSON.parse(evolveSpec(EVOLVE.find(entry => entry.id === 'evolve-gate')!, state)?.args[2] ?? '{}').action.resource).toBeUndefined()+ })++ it('the repo prompt is read-only research, typed and never run', () => {+ expect(repoPrompt('autogenous')).toMatch(/^Read https:\/\/github\.com\/ruvnet\/autogenous with gh .* do not clone, build or run anything/)+ expect(repoPrompt('rgi')).toContain('https://github.com/ruvnet/rGi')+ })+})++describe('the file readers', () => {+ it('reads the flywheel state, receipts newest first with their status, generations, served, policy and manifest', async () => {+ const files = (await worldState()).evolve.files!++ expect(files.flywheel).toMatchObject({ champion: C2, epoch: 2, commits: [{ candidate: C1, epoch: 1 }, { candidate: C2, epoch: 2, proposer: 'darwin' }] })+ expect(files.receipts).toHaveLength(4)+ expect(files.receipts?.find(receipt => receipt.id === R4)).toMatchObject({ decision: 'accepted', status: 'evaluated', isSigned: true, lift: 0.042 })+ expect(files.receipts?.filter(receipt => !receipt.isSigned)).toHaveLength(1)+ expect(files.generations?.map(generation => generation.generation)).toEqual([1, 2])+ expect(files.generations?.[1]).toMatchObject({ isPromoted: false, cause: 'holdout', parent: 'a'.repeat(64) })+ expect(files.served).toMatchObject({ champion: 'a'.repeat(64), fromGeneration: 1 })+ expect(files.policy).toMatchObject({ isRolledBack: false, previous: expect.stringMatching(/^sha256:5555/) })+ expect(files.manifests).toEqual([expect.objectContaining({ os: 'linux', isSigned: true, fixes: 117, gitCommit: '77a77a4527d…' })])+ expect(files.hasRgiDb).toBe(false)+ })++ it('a project with none of the files reads null everywhere, nothing invented', async () => {+ const files = (await worldState({})).evolve.files!++ expect(files).toMatchObject({ flywheel: null, receipts: null, generations: null, served: null, policy: null, manifests: [], hasRgiDb: false })+ })++ it('refs: only hex content refs pass; genesis reads as such', () => {+ expect(refOf('sha256:../../etc')).toBeUndefined()+ expect(refOf(`sha256:${'a'.repeat(64)}`)).toBeDefined()+ expect(shortRef(`sha256:${'0'.repeat(64)}`)).toBe('genesis')+ expect(shortRef(C1)).toBe('cccccccc')+ expect(parseActivePolicy('{"championId":"x","rolledBack":true}')?.isRolledBack).toBe(true)+ expect(parseManifest('{"manifest":{}}', 'linux')?.isSigned).toBe(false)+ })+})++describe('the CLI readers', () => {+ it('flywheel status: valid at genesis, and an invalid ledger with its errors', () => {+ expect(parseLedger(EVOLVE_OUT.statusEmpty, 5)).toEqual({ isValid: true, commits: 0, head: `sha256:${'0'.repeat(64)}`, errors: [], atMs: 5 })+ expect(parseLedger(EVOLVE_OUT.statusBroken, 5)).toMatchObject({ isValid: false, commits: 2, errors: ['commit 2: parent mismatch'] })+ expect(parseLedger(WARN, 5)).toBeNull()+ })++ it('verify --json, policy status: the signature checks and tallies; mode, counts, ledger', () => {+ expect(parseWitness(EVOLVE_OUT.verify, 'linux', 5)).toEqual({ os: 'linux', isOk: true, isSignatureValid: true, pass: 116, drift: 0, regressed: 0, missing: 1, atMs: 5 })+ expect(parsePolicyLedger(EVOLVE_OUT.policy, 5)).toEqual({ mode: 'legacy', rules: 0, approvals: 0, receipts: 8, isValid: true, atMs: 5 })+ })++ it('result lines: each check reads as a sentence and keeps its answer for the board', () => {+ const state = newState({})++ expect(evolveLines(state, 'evolve-ledger', EVOLVE_OUT.statusEmpty, WARN, 9)).toEqual(['ledger VALID · 0 commits · head genesis', 'champion n/a · serving epoch 0 · 0 receipts registered'])+ expect(state.evolve.ledger?.isValid).toBe(true)+ expect(evolveLines(state, 'evolve-receipts', '[]\n', '', 9)[0]).toMatch(/^no receipts yet/)+ expect(evolveLines(state, 'evolve-receipts', EVOLVE_OUT.receipts, '', 9)).toEqual(['11111111 · accepted · signed · consumed · candidate cccccccc', '33333333 · rejected · UNSIGNED · unregistered · candidate eeeeeeee'])+ expect(evolveLines(state, 'evolve-history', EVOLVE_OUT.historyEmpty, '', 9)).toEqual(['no promotions yet: the ledger is at genesis'])+ expect(evolveLines(state, 'evolve-history', EVOLVE_OUT.history, '', 9)[0]).toBe('epoch 1 · bbbbbbbb → cccccccc · receipt 11111111 · local')+ expect(evolveLines(state, 'evolve-witness-linux', EVOLVE_OUT.verify, '', 9)).toEqual([+ 'signature valid (hash, key and signature check) · overall ok',+ '116 pass · 0 drift · 0 regressed · 1 missing, against the installed CLI',+ '[missing] F9 session_list dual-shape · v3/y.js',+ ])+ expect(evolveLines(state, 'evolve-gate', EVOLVE_OUT.gate, '', 9)[0]).toBe('outcome allowed · enforced allowed · mode legacy')+ expect(state.evolve.gate?.enforced).toBe('allowed')+ expect(evolveLines(state, 'evolve-policy', '', 'error: unknown command\n', 9)).toEqual(['error: unknown command'])+ })+})++describe('the loop and the lineage', () => {+ it('stages read n/a until there is data; VERIFY lights only after the ledger check ran', async () => {+ const blank = newState({})++ expect(loopStagesOf(blank.evolve).every(stage => stage.mark === 'na')).toBe(true)++ const state = await worldState()+ const before = loopStagesOf(state.evolve)++ expect(before.map(stage => stage.mark)).toEqual(['lit', 'lit', 'lit', 'na', 'lit', 'dark'])+ expect(before.find(stage => stage.name === 'PROMOTE')?.value).toBe('3 · ep 2')+ expect(before.find(stage => stage.name === 'REVERSE')?.value).toBe('armed')++ state.evolve.ledger = { isValid: false, commits: 2, errors: ['x'], atMs: 1 }+ expect(loopStagesOf(state.evolve).find(stage => stage.name === 'VERIFY')).toMatchObject({ mark: 'bad', value: 'INVALID' })++ const empty = await worldState({})++ expect(loopStagesOf(empty.evolve).map(stage => stage.mark)).toEqual(['na', 'na', 'na', 'na', 'na', 'na'])+ })++ it('the picture is the size asked for, and names each stage', async () => {+ const grid = loopPicture(loopStagesOf((await worldState()).evolve), 96, 0)+ const row = (y: number) => Array.from({ length: grid.columns }, (_, x) => String.fromCodePoint(grid.glyph(x, y))).join('')++ expect([grid.columns, grid.rows]).toEqual([96, LOOP_ROWS])+ expect(row(1)).toMatch(/OBSERVE.*PROPOSE.*EVALUATE.*VERIFY.*PROMOTE.*REVERSE/)+ })++ it('the flywheel lineage: baseline → C1 → C2 champion, a rejected branch off C1, a waiting one off C2; generations mark the served one', async () => {+ const { flywheel, generations } = lineageOf((await worldState()).evolve.files)++ expect(flywheel.map(row => `${row.prefix}${row.kind}:${shortRef(row.ref)}`)).toEqual(['root:bbbbbbbb', '└─promoted:cccccccc', ' ├─rejected:eeeeeeee', ' └─champion:dddddddd', ' └─pending:ffffffff'])+ expect(generations.map(row => `${row.prefix}${row.kind}`)).toEqual(['root', '└─champion', ' └─rejected'])+ expect(lineageOf(null)).toEqual({ flywheel: [], generations: [] })+ })+})diff --git a/plugins/ruflo-console/tests/fixtures/evolve.ts b/plugins/ruflo-console/tests/fixtures/evolve.tsnew file mode 100644index 0000000000..548f40a7ac--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/evolve.ts@@ -0,0 +1,80 @@+/**+ * A governed-evolution world in the shapes @claude-flow/cli 3.51.1 writes and prints: the flywheel-v1 state with two+ * promotions, three receipts (two promoted, one rejected) and one accepted receipt waiting, two generation bundles, the+ * active policy with its rollback pointer, a signed witness manifest, and what each CLI check printed. The empty-ledger+ * and policy outputs are as captured from a real run; the rest follow the source's field names.+ */+const ref = (c: string) => `sha256:${c.repeat(64)}`++export const GENESIS = `sha256:${'0'.repeat(64)}`+export const BASE = ref('b')+export const C1 = ref('c')+export const C2 = ref('d')+export const REJ = ref('e')+export const WAIT = ref('f')+export const R1 = ref('1')+export const R2 = ref('2')+export const R3 = ref('3')+export const R4 = ref('4')++const receipt = (receiptId: string, candidateId: string, baselineRef: string, decision: string, issuedAt: string, isSigned = true) =>+ JSON.stringify({+ payload: { schemaVersion: 'ruflo.flywheel-receipt/v1', receiptId, lineageId: 'lin-1', candidateId, baselineRef, decision, issuedAt, statistics: { relativeLift: decision === 'accepted' ? 0.042 : -0.01, significant: decision === 'accepted' } },+ ...(isSigned && { signature: { algorithm: 'ed25519', domain: 'ruflo/flywheel-receipt/v1', publicKeyPem: '-----BEGIN PUBLIC KEY-----', signatureBase64: 'c2lnbmF0dXJlLWJ5dGVzLWZvci10ZXN0aW5nLW9ubHk=' } }),+ })++export const EVOLVE_FILES: Record<string, string> = {+ '.claude-flow/flywheel-v1/transaction-state.json': JSON.stringify({+ version: 1,+ activeChampionRef: C2,+ ledgerHead: ref('9'),+ servingEpoch: 2,+ servedChampionRef: C2,+ receiptStates: { [R1]: { receiptId: R1, status: 'consumed' }, [R2]: { receiptId: R2, status: 'consumed' }, [R3]: { receiptId: R3, status: 'evaluated' }, [R4]: { receiptId: R4, status: 'evaluated' } },+ commits: [+ { commitId: 'c-1', receiptId: R1, sequence: 1, previousLedgerHead: GENESIS, baselineRef: BASE, candidateId: C1, servingEpoch: 1, proposer: 'local', promotedAt: '2026-09-30T10:00:00.000Z' },+ { commitId: 'c-2', receiptId: R2, sequence: 2, previousLedgerHead: ref('8'), baselineRef: C1, candidateId: C2, servingEpoch: 2, proposer: 'darwin', promotedAt: '2026-10-01T10:00:00.000Z' },+ ],+ }),+ [`.claude-flow/flywheel-v1/receipts/${'1'.repeat(64)}.json`]: receipt(R1, C1, BASE, 'accepted', '2026-09-30T09:00:00.000Z'),+ [`.claude-flow/flywheel-v1/receipts/${'2'.repeat(64)}.json`]: receipt(R2, C2, C1, 'accepted', '2026-10-01T09:00:00.000Z'),+ [`.claude-flow/flywheel-v1/receipts/${'3'.repeat(64)}.json`]: receipt(R3, REJ, C1, 'rejected', '2026-10-01T08:00:00.000Z', false),+ [`.claude-flow/flywheel-v1/receipts/${'4'.repeat(64)}.json`]: receipt(R4, WAIT, C2, 'accepted', '2026-10-02T08:00:00.000Z'),+ '.claude-flow/flywheel/generation-1.json': JSON.stringify({ generation: 1, parent: null, branch: 'main', kind: 'synthetic', createdAt: 1790000000000, promotion: { parentManifestHash: null, candidateManifestHash: 'a'.repeat(64), mutationClass: 'retrieval:alpha' }, regression: null }),+ '.claude-flow/flywheel/generation-2.json': JSON.stringify({ generation: 2, parent: 'a'.repeat(64), branch: 'main', kind: 'synthetic', createdAt: 1790100000000, promotion: null, regression: { candidateManifestHash: '7'.repeat(64), ancestor: 'a'.repeat(64), mutationClass: 'retrieval:multi', failureCause: 'holdout' } }),+ '.claude-flow/flywheel/served.json': JSON.stringify({ championHash: 'a'.repeat(64), config: { alpha: 0.3 }, servedAt: 1790050000000, fromGeneration: 1 }),+ '.claude-flow/harness-active-policy.json': JSON.stringify({ championId: 'sha256:6141a8ea990c5063b77e090ae8f37f9c539d8aa8f58dcceb30f3a82f97e57319', provenanceTier: 'oracle:test-exec', layer: 'framework/node-cli', appliedAt: 1783689629580, previous: 'sha256:5555aaaa990c5063b77e090ae8f37f9c539d8aa8f58dcceb30f3a82f97e57319', params: { alpha: 0.3 } }),+ 'verification/linux/manifest.md.json': JSON.stringify({+ manifest: { schema: 'ruflo-witness/v1', issuedAt: '2026-10-02T15:54:52.530Z', gitCommit: '77a77a4527d543d19ed3f2af77f509b742326256', branch: 'release/3.51.1', os: 'linux', summary: { totalFixes: 117, verified: 117, missing: 0 }, fixes: [{ id: 'F1', desc: 'hooks_metrics persistence', file: 'v3/x.js', sha256: 'ab', marker: 'm', markerVerified: true }] },+ integrity: { manifestHashAlgo: 'sha256', manifestHash: 'ab', signatureAlgo: 'ed25519', publicKey: 'pk', signature: 'c2lnbmF0dXJlLWJ5dGVzLWZvci10ZXN0aW5nLW9ubHk=', seedDerivation: 'sha256(gitCommit:ruflo-witness/v1)' },+ }),+}++/** What each check printed (stdout); the CLI writes its [WARN] banner to stderr. */+export const EVOLVE_OUT = {+ /** `metaharness flywheel status` on a fresh project, as captured. */+ statusEmpty: `{\n "state": {\n "version": 1,\n "activeChampionRef": null,\n "ledgerHead": "${GENESIS}",\n "servingEpoch": 0,\n "receiptStates": {},\n "commits": []\n },\n "ledger": {\n "valid": true,\n "errors": [],\n "commits": 0,\n "head": "${GENESIS}"\n }\n}\n`,+ statusBroken: JSON.stringify({ state: { activeChampionRef: C2, servingEpoch: 2, receiptStates: {} }, ledger: { valid: false, errors: ['commit 2: parent mismatch'], commits: 2, head: ref('9') } }, null, 2),+ receipts: JSON.stringify([{ receiptId: R1, anchorRef: null, candidateId: C1, baselineRef: BASE, decision: 'accepted', signed: true, issuedAt: '2026-09-30T09:00:00.000Z', state: { receiptId: R1, status: 'consumed' } }, { receiptId: R3, candidateId: REJ, baselineRef: C1, decision: 'rejected', signed: false, state: null }], null, 2),+ history: JSON.stringify({ ledgerHead: ref('9'), commits: [{ receiptId: R1, baselineRef: BASE, candidateId: C1, servingEpoch: 1, proposer: 'local' }] }, null, 2),+ historyEmpty: `{\n "ledgerHead": "${GENESIS}",\n "commits": []\n}\n`,+ /** `policy status`, as captured. */+ policy: '{\n "version": 1,\n "mode": "legacy",\n "migratedFrom": "pre-ADR-324; capabilities=agentdb.rvf",\n "rules": 0,\n "budgets": 0,\n "approvals": 0,\n "receipts": 8,\n "ledger": {\n "valid": true,\n "length": 8\n }\n}\n',+ gate: JSON.stringify({ requestId: 'req-1', outcome: 'allowed', enforcedOutcome: 'allowed', mode: 'legacy', reason: 'legacy-default-allow', matchedRules: [], obligations: [], receiptId: 'pr-1' }, null, 2),+ verify: JSON.stringify(+ {+ ok: true,+ manifest: { schema: 'ruflo-witness/v1' },+ signature: { manifestHashOk: true, publicKeyReproducible: true, signatureValid: true },+ results: [+ { id: 'F1', desc: 'hooks_metrics persistence', file: 'v3/x.js', status: 'pass', sha256Match: true, markerPresent: true },+ { id: 'F9', desc: 'session_list dual-shape', file: 'v3/y.js', status: 'missing', sha256Match: false, markerPresent: false },+ ],+ summary: { pass: 116, drift: 0, regressed: 0, missing: 1 },+ },+ null,+ 2,+ ),+}++export const WARN = '\u001b[33m\u001b[1m[WARN]\u001b[0m Skipped helper auto-refresh — .LOCKED marker present\n'diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.tsindex 39a1187e2b..77919dd4f8 100644--- a/plugins/ruflo-console/tests/views.test.ts+++ b/plugins/ruflo-console/tests/views.test.ts@@ -1,6 +1,7 @@import type { TestBody } from 'claude-code/testing'import { describe, expect, mock, test } from 'claude-code/testing'+import { EVOLVE_FILES, EVOLVE_OUT, R4 } from './fixtures/evolve'import { HIVE_FILES, RAFT_ID, WORKERS } from './fixtures/hive'import { MISSION_OBSERVATION } from './fixtures/missions'import { HIVE_TOKEN, RUFLO_FILES } from './fixtures/ruflo-run'@@ -369,4 +370,55 @@ describe('views', () => {expect(textOf(await pane.drawn())).toContain('no area "nope"')await pane.unmount()})++ test('self-evolution: every section from the flywheel files; opening runs nothing; a read runs at once; the gate asks first', { options: { boot: false } }, async ($, on) => {+ const world = worldOf(on, { ...RUFLO_FILES, ...EVOLVE_FILES })+ const evolveRuns = () => world.runs.filter(argv => /flywheel|policy|verify/.test(argv.join(' ')) && !argv.includes('mcp'))++ world.respond = argv => {+ const line = argv.join(' ')++ if (line.endsWith('metaharness flywheel status')) return { exitCode: 0, stdout: EVOLVE_OUT.statusEmpty, stderr: '[WARN] Skipped helper auto-refresh' }+ if (line.includes('policy evaluate')) return { exitCode: 0, stdout: EVOLVE_OUT.gate, stderr: '' }++ return cliAnswer(argv)+ }+ mock.clock(on)+ await $.session.start(SESSION)++ const { text, tree, rasters } = await drawn($, 'evolve')+ const buttons = elementsOf(tree, 'Button').map(keyOf)++ expect(rasters).toEqual(['header', 'title', 'evolve-loop'])+ for (const section of ['LOOP', 'LEDGER & RECEIPTS', 'LINEAGE', 'POLICIES', 'WITNESS', 'WHAT RUNS WHERE', 'PROMOTE']) expect(text).toContain(`▓▒░ ${section} ░▒▓`)+ expect(text).toContain('dddddddd champion')+ expect(text).toContain('✗ 33333333 \nrejected \n UNSIGNED · evaluated · cccccccc → eeeeeeee')+ expect(text).toContain('✗ eeeeeeee \nrejected · evaluated · receipt 33333333')+ expect(text).toContain('armed: previous 5555aaaa')+ expect(text).toContain('signed · 117 fixes · release/3.51.1 @ 77a77a4527d… ')+ expect(text).toContain('https://github.com/ruvnet/autogenous')+ expect(text).toContain('ruflo metaharness flywheel promote <receipt-id> --public-key <approved-ed25519.pem> --confirm')+ expect(buttons).toEqual(expect.arrayContaining(['evolve-evolve-ledger', 'evolve-evolve-gate', 'evolve-evolve-witness-linux', 'evolve-ask-autogenous', 'evolve-ask-rgi', 'evolve-lab']))+ expect(buttons.some(key => /promote/.test(key))).toBe(false)+ // Opening the view read the files only: no flywheel, policy or verify run.+ expect(evolveRuns()).toEqual([])++ expect((await $.command.run(command('run evolve-ledger'))).text).toBe('✓ verify the flywheel ledger (metaharness flywheel status) · exit 0\n ledger VALID · 0 commits · head genesis\n champion n/a · serving epoch 0 · 0 receipts registered')+ expect(evolveRuns().map(argv => argv.join(' '))).toEqual(['npx --offline -y @claude-flow/cli@latest metaharness flywheel status'])++ const gate = JSON.stringify({ identity: { id: 'ruflo-console', type: 'plugin' }, action: { type: 'metaharness.candidate.promote', resource: R4, environment: 'production', destructive: true } })++ expect((await $.command.run(command('run evolve-gate'))).text).toMatch(/^Asked: ask the policy gate about a promotion/)++ const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })+ const asked = textOf(await pane.drawn())++ await pane.unmount()+ expect(asked).toContain(`runs: ruflo policy evaluate ${gate}`)+ expect(asked).toContain('appends one decision receipt to .claude-flow/policy/state.json; promotes nothing')+ expect(evolveRuns()).toHaveLength(1)++ expect((await $.command.run(command('yes'))).text).toContain('outcome allowed · enforced allowed · mode legacy')+ expect(evolveRuns().map(argv => argv.slice(4))).toEqual([['metaharness', 'flywheel', 'status'], ['policy', 'evaluate', gate]])+ })})