Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

feat(ruflo-console): Project Anatole section in Security & Doctor (0.33.23)

ruvf80c1584a2f3
diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json
index 23c7ee1464..3893ab70f5 100644
--- a/plugins/ruflo-console/.claude-plugin/plugin.json
+++ b/plugins/ruflo-console/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-console",
"description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings → Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.",
- "version": "0.33.20",
+ "version": "0.33.23",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-console/README.md b/plugins/ruflo-console/README.md
index 82b85907c6..ad0ddc7ec7 100644
--- a/plugins/ruflo-console/README.md
+++ b/plugins/ruflo-console/README.md
@@ -44,3 +44,12 @@ Open it with `/ruflo room` (menu: Safety → The Room).
- **Mods**: one line per plugin mod that has written `.claude-flow/<name>-mod/status.json`. Press a line for its detail: what it guards (the file's own `summary`), guard, calls, blocked, the *class* of its last refusal (`secret`, `destructive`, `path`, `network`, `policy`, `other`; the refused text is never kept), `modVersion`, session start, last write, file age, and a stale marker when the last write was an earlier session.
A status file is data, not instructions: it is size-capped, shape-checked (`version: 1` only), and every string is stripped of control and bidi characters and cut to length before it is drawn. `summary`, `modVersion` and `lastDenied` are optional; a mod that does not write them shows "not reported".
+
+## Project Anatole in Security & Doctor
+
+An optional **Project Anatole** section on the Security & Doctor page (key `u`) lists, runs and edits the `ruflo-protector` mod (ADR-453). Without the plugin it is one line: `claude plugin install ruflo-protector@ruflo`.
+
+- **Reads** `.claude-flow/protector-mod/status.json`, `rules.json` and the last 200 lines of `alerts.jsonl` through the bounded, regular-file-only reader (a file over 64 KB is refused; every field is whitelisted and cleaned). It is labelled *reported by the mod, unauthenticated*: any process can write those files.
+- **Shows** the mode, the baseline's maturity ("learning 62%"), open alerts by severity, blocked and `degraded`; one row per rule (OWASP refs, severity, an off · notify · block chip, hits and acked share over the last 200 alerts, "changed from default"); the open alerts with `ack` and `allow`. The Findings meter counts open alerts, labelled as Anatole's.
+- **Runs** `/protector run` and `/protector replay` into the page's Result panel.
+- **Edits** the mode (off, learn, notify, enforce) and per-rule modes through `/protector`; every change asks first and its confirm row starts with `Effect:`. `enforce` is declared an install-class action and `reset-baseline` a delete-class one, so Claude's console tools always wait for you on both (palette ids `anatole-mode`, `anatole-rule`, `anatole-ack`, `anatole-allow`, `anatole-reset`, `anatole-run`, `anatole-replay`).
diff --git a/plugins/ruflo-console/hooks/anatole.ts b/plugins/ruflo-console/hooks/anatole.ts
new file mode 100644
index 0000000000..c13cf36a79
--- /dev/null
+++ b/plugins/ruflo-console/hooks/anatole.ts
@@ -0,0 +1,150 @@
+/**
+ * Project Anatole in the console (ADR-453 §9): the shipped rule table as static metadata, the slash strings every button sends, and the
+ * palette entries behind them. A change goes to the mod as `host.runSlash('protector', '<verb args>')` after the console's confirm; the mod
+ * answers locally. Pure: no `$`. Every value that reaches a command passes a fixed pattern first (data/anatole.ts).
+ */
+import type { ActionSpec } from './actions'
+import { ALERT_ID, FINGERPRINT, MODES, RULE_ID, RULE_MODES, type AnatoleAlert, type AnatoleMode, type RuleMode } from './data/anatole'
+import { plain } from './data/parse'
+import type { Host } from './host'
+import { textLines } from './secure'
+import type { State } from './state'
+import type { PaletteEntry } from './palette'
+
+export type RuleMeta = { id: string; title: string; owasp: readonly string[]; severity: 'critical' | 'high' | 'medium'; fallback: RuleMode }
+
+/** The 13 rules of version 1 (ADR-453 §5): what the page lists. The mod's own list is not reachable from here, so it is kept in step with the ADR by a test. */
+export const ANATOLE_RULES: readonly RuleMeta[] = [
+ { id: 'PR-001', title: 'secret leaves the machine', owasp: ['LLM02', 'T2'], severity: 'critical', fallback: 'block' },
+ { id: 'PR-002', title: 'remote code piped into an interpreter', owasp: ['T11', 'LLM06'], severity: 'critical', fallback: 'block' },
+ { id: 'PR-003', title: 'persistence or self-modification', owasp: ['T3', 'T11', 'LLM06'], severity: 'high', fallback: 'block' },
+ { id: 'PR-004', title: 'credential store read, then egress', owasp: ['LLM02', 'T3'], severity: 'high', fallback: 'notify' },
+ { id: 'PR-005', title: 'risky action in a tainted turn', owasp: ['LLM01', 'T6'], severity: 'high', fallback: 'notify' },
+ { id: 'PR-006', title: 'destructive operation', owasp: ['LLM06', 'T2'], severity: 'critical', fallback: 'block' },
+ { id: 'PR-007', title: 'unbounded consumption', owasp: ['LLM10', 'T4'], severity: 'medium', fallback: 'notify' },
+ { id: 'PR-008', title: 'unseen host carrying a body', owasp: ['LLM02'], severity: 'medium', fallback: 'notify' },
+ { id: 'PR-009', title: 'files outside the known areas', owasp: ['LLM06', 'T3'], severity: 'medium', fallback: 'notify' },
+ { id: 'PR-010', title: 'instruction override in an agent message', owasp: ['T12', 'LLM01'], severity: 'high', fallback: 'notify' },
+ { id: 'PR-011', title: 'agent spawn that escalates', owasp: ['T13', 'T3'], severity: 'medium', fallback: 'notify' },
+ { id: 'PR-012', title: 'unfamiliar dependency source', owasp: ['LLM03'], severity: 'medium', fallback: 'notify' },
+ { id: 'PR-013', title: 'system prompt sent to a network sink', owasp: ['LLM07'], severity: 'high', fallback: 'notify' },
+]
+
+/** The slash strings, one place: the buttons, the palette and the tests all read these. */
+export const slashOf = {
+ run: () => 'run',
+ replay: () => 'replay',
+ mode: (mode: AnatoleMode) => `mode ${mode}`,
+ rule: (id: string, mode: RuleMode) => `rule ${id} ${mode}`,
+ ack: (id: string) => `ack ${id}`,
+ allow: (fp: string) => `allow ${fp}`,
+ reset: () => 'reset-baseline',
+}
+
+export const INSTALL_LINE = 'Project Anatole is not installed: claude plugin install ruflo-protector@ruflo'
+export const UNAUTH = 'reported by the mod, unauthenticated: any process can write these files'
+
+/** Result-panel ids of the two reads; the Security page shows them in its Result block. */
+export const ANATOLE_RESULTS = ['anatole-run', 'anatole-replay'] as const
+export const isAnatoleResult = (id: string): boolean => (ANATOLE_RESULTS as readonly string[]).includes(id)
+
+const wired = new WeakMap<State, Host>()
+
+/** The host the palette needs to send a slash command; set once with the other actions. */
+export const wireAnatole = (state: State, host: Host): void => void wired.set(state, host)
+
+const NOT_WIRED = 'open the console first'
+
+type Make = { label: string; verb: string; note: string; expect: string; declared?: 'write' | 'delete' | 'install'; read?: boolean }
+
+/** A spec that sends `/protector <verb>`. A read runs at once and its answer fills the Result panel; a change asks first and says its effect. */
+function slashSpec(state: State, make: Make): ActionSpec | null {
+ const host = wired.get(state)
+
+ if (host === undefined) return null
+
+ const id = make.read === true ? `anatole-${make.verb}` : null
+
+ return {
+ label: make.label,
+ args: [],
+ expect: make.expect,
+ shows: `/protector ${make.verb}`,
+ note: make.note,
+ ...(make.declared !== undefined && { declared: make.declared }),
+ ...(make.read === true && { isReadOnly: true }),
+ run: async () => {
+ if (id !== null) state.lab.running = { id, label: make.label, startedAtMs: Date.now() }
+
+ host.invalidate()
+
+ try {
+ const answer = await host.runSlash('protector', make.verb)
+ const text = typeof answer === 'object' && answer !== null && typeof answer.text === 'string' ? answer.text : ''
+ const lines = text === '' ? ['the mod returned no text: its answer is in the conversation; this page reads the files it wrote'] : textLines(text)
+
+ if (id !== null) state.lab.result = { id, label: make.label, ok: true, exitCode: null, note: UNAUTH, lines, atMs: Date.now() }
+ else state.outcome = { label: make.label, ok: true, verified: 'n/a', detail: `sent /protector ${make.verb}; the page reads the result from the mod's files`, atMs: Date.now() }
+ } catch (error) {
+ const why = plain(error instanceof Error ? error.message : String(error), 160) || 'refused'
+
+ if (id !== null) state.lab.result = { id, label: make.label, ok: false, exitCode: null, lines: [`/protector ${make.verb} did not run: ${why}`, 'is the ruflo-protector plugin loaded? /reload-plugins'], atMs: Date.now() }
+ else state.outcome = { label: make.label, ok: false, verified: 'n/a', detail: `/protector ${make.verb} did not run: ${why}`, atMs: Date.now() }
+ } finally {
+ state.lab.running = null
+ host.invalidate()
+ }
+ },
+ }
+}
+
+const EFFECT = 'Effect: the mod changes only its own settings under .claude-flow/protector-mod/; tool calls are not touched until enforce'
+
+export const runSpec = (state: State): ActionSpec | null => slashSpec(state, { label: 'Anatole run: scan the Claude configuration', verb: slashOf.run(), read: true, expect: 'findings in the Result panel', note: 'Effect: reads the event ring and this project’s Claude configuration; changes nothing' })
+export const replaySpec = (state: State): ActionSpec | null => slashSpec(state, { label: 'Anatole replay: what would have fired', verb: slashOf.replay(), read: true, expect: 'alerts that would have fired, in the Result panel', note: 'Effect: re-scores the recorded events against the current rules; changes nothing' })
+
+export function modeSpec(state: State, mode: AnatoleMode): ActionSpec | null {
+ const enforce = mode === 'enforce'
+
+ return slashSpec(state, {
+ label: enforce ? 'Anatole mode enforce: rules marked block will deny tool calls' : `Anatole mode ${mode}`,
+ verb: slashOf.mode(mode),
+ expect: `mode ${mode} in status.json`,
+ // Enforce changes how Claude behaves for every unattended run: it is the class that always asks Claude's tools too.
+ ...(enforce && { declared: 'install' as const }),
+ note: enforce ? 'Effect: a tool call that matches a rule set to block is denied; replay first to check for false positives' : EFFECT,
+ })
+}
+
+export const ruleSpec = (state: State, id: string, mode: RuleMode): ActionSpec | null => (RULE_ID.test(id) ? slashSpec(state, { label: `Anatole rule ${id} ${mode}`, verb: slashOf.rule(id, mode), expect: `${id} ${mode} in rules.json`, note: EFFECT }) : null)
+export const ackSpec = (state: State, id: string): ActionSpec | null => (ALERT_ID.test(id) ? slashSpec(state, { label: `Anatole ack ${id}: mark it a false positive`, verb: slashOf.ack(id), expect: 'the alert acked', note: 'Effect: marks the alert a false positive and teaches the baseline; the rule’s acked share rises' }) : null)
+export const allowSpec = (state: State, fp: string): ActionSpec | null => (FINGERPRINT.test(fp) ? slashSpec(state, { label: `Anatole allow ${fp}`, verb: slashOf.allow(fp), expect: 'the fingerprint in allow.json', note: 'Effect: this shape no longer raises an alert; a hard rule class is never allowed by it' }) : null)
+export const resetSpec = (state: State): ActionSpec | null => slashSpec(state, { label: 'Anatole reset-baseline: forget what is normal', verb: slashOf.reset(), declared: 'delete', expect: 'baseline back to learning', note: 'Effect: deletes the learned baseline; anomaly alerts stop until it matures again' })
+
+/** `PR-002 off` → its parts, or null. */
+const ruleArgs = (text: string): [string, RuleMode] | null => {
+ const [id, mode, ...rest] = text.trim().split(/\s+/)
+ const found = RULE_MODES.find(candidate => candidate === mode)
+
+ return rest.length === 0 && id !== undefined && RULE_ID.test(id) && found !== undefined ? [id, found] : null
+}
+
+/** The palette's Anatole entries: `/ruflo run anatole-rule PR-002 off`, so Claude's console tools and the buttons share one path. */
+export function anatolePalette(state: State): PaletteEntry[] {
+ const g = 'security'
+ const alerts: readonly AnatoleAlert[] = state.snapshot?.anatole?.alerts ?? []
+ const spec = (id: string, label: string, made: ActionSpec | null, why = NOT_WIRED): PaletteEntry => ({ id, group: g, label, run: { kind: 'spec', spec: made, why } })
+ const text = (id: string, label: string, make: (value: string) => ActionSpec | null, why: string): PaletteEntry => ({ id, group: g, label, run: { kind: 'text', keyword: id, make, why: () => why } })
+
+ return [
+ spec('anatole-run', 'Project Anatole: run (scan the Claude configuration)', runSpec(state)),
+ spec('anatole-replay', 'Project Anatole: replay (what would have fired)', replaySpec(state)),
+ text('anatole-mode', 'anatole-mode off|learn|notify|enforce: set the Project Anatole mode (asks first)', value => MODES.find(mode => mode === value.trim()) === undefined ? null : modeSpec(state, value.trim() as AnatoleMode), 'type anatole-mode off, learn, notify or enforce'),
+ text('anatole-rule', 'anatole-rule PR-### off|notify|block: set one rule’s mode (asks first)', value => { const parts = ruleArgs(value); return parts === null ? null : ruleSpec(state, parts[0], parts[1]) }, 'type anatole-rule PR-002 off, notify or block'),
+ text('anatole-ack', 'anatole-ack <alert id>: mark an alert a false positive (asks first)', value => ackSpec(state, value.trim()), 'type anatole-ack and an alert id'),
+ text('anatole-allow', 'anatole-allow <12-hex fingerprint>: allow a shape without an alert (asks first)', value => allowSpec(state, value.trim()), 'type anatole-allow and a 12-character fingerprint'),
+ spec('anatole-reset', 'Project Anatole: reset the baseline (asks first; deletes what it learned)', resetSpec(state)),
+ // One entry per open alert, so a model can address it by its id exactly (ADR-450 T13).
+ ...alerts.filter(alert => alert.state === 'open').slice(0, 20).flatMap(alert => [spec(`anatole-ack-${alert.id}`, `ack alert ${alert.id} (${alert.rule})`, ackSpec(state, alert.id)), ...(alert.fp === null ? [] : [spec(`anatole-allow-${alert.fp}`, `allow fingerprint ${alert.fp} (${alert.rule})`, allowSpec(state, alert.fp))])]),
+ ]
+}
diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.ts
index 6a2186dbfb..9d3b15f26b 100644
--- a/plugins/ruflo-console/hooks/bindings.ts
+++ b/plugins/ruflo-console/hooks/bindings.ts
@@ -17,6 +17,7 @@ import { catalogActions } from './plugin-catalog'
import { saveAllowed } from './remember'
import { pluginNames, settingsActions } from './settings'
import { catalogOf } from './plugin-catalog'
+import { wireAnatole } from './anatole'
import { devtoolsActions } from './devtools'
import { HARNESSES, harnessSpec, isAutoAccept, isLive, newSession, send, whyNotRun } from './harness'
import { helpActions } from './help-actions'
@@ -73,6 +74,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
host.invalidate()
}
+ wireAnatole(state, host)
const actions: Actions = {
view: setView,
remember: () => {
diff --git a/plugins/ruflo-console/hooks/data/anatole.ts b/plugins/ruflo-console/hooks/data/anatole.ts
new file mode 100644
index 0000000000..064f053f57
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/anatole.ts
@@ -0,0 +1,176 @@
+import { readBounded, under, type ReadCache, type ReaderFs } from './files'
+import { jsonObject, plain, recordOf } from './parse'
+
+/**
+ * Project Anatole's files (ADR-453 §8) under `.claude-flow/protector-mod/`, read through the bounded, regular-file-only reader (ADR-450 T2).
+ * Everything here is what the mod REPORTED: any process can write these files, so the page labels it unauthenticated and never lets a
+ * value from a file reach a command except through the tight patterns below (`RULE_ID`, `FINGERPRINT`, `ALERT_ID`).
+ */
+export const ANATOLE_DIR = '.claude-flow/protector-mod'
+/** A file over this is refused, not trimmed (status and rules); the alert log is read whole under ALERTS_MAX and cut to its last lines. */
+export const ANATOLE_MAX_BYTES = 65_536
+export const ALERTS_MAX_BYTES = 512 * 1024
+export const ALERTS_TAIL = 200
+/** A status file older than this was written by a session that has ended. */
+export const ANATOLE_STALE_MS = 6 * 3_600_000
+
+export const RULE_ID = /^PR-\d{3}$/
+export const FINGERPRINT = /^[0-9a-f]{12}$/
+export const ALERT_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,39}$/
+const OWASP = /^(LLM\d{2}|T\d{1,2})$/
+
+export const MODES = ['off', 'learn', 'notify', 'enforce'] as const
+export type AnatoleMode = (typeof MODES)[number]
+export const RULE_MODES = ['off', 'notify', 'block'] as const
+export type RuleMode = (typeof RULE_MODES)[number]
+export const ALERT_SEVERITIES = ['critical', 'high', 'medium', 'low'] as const
+export type AlertSeverity = (typeof ALERT_SEVERITIES)[number]
+export type AlertState = 'open' | 'acked' | 'allowed'
+
+export type AnatoleStatus = {
+ mode: AnatoleMode | null
+ modVersion: string | null
+ calls: number
+ blocked: number
+ updatedMs: number | null
+ summary: string
+ open: Record<AlertSeverity, number> & { total: number }
+ baseline: { state: 'learning' | 'mature'; maturity: number; events: number; sessions: number } | null
+ /** `false`, or the short reason the mod gave (ADR-453 §2.3: the protector failed open). */
+ degraded: false | string
+}
+
+export type RuleOverride = { mode: RuleMode; demoted: boolean }
+export type AnatoleAlert = { id: string; atMs: number | null; rule: string; owasp: string[]; severity: AlertSeverity; action: 'blocked' | 'notified'; tool: string; summary: string; fp: string | null; state: AlertState }
+
+/** What the folder held. `present` is false when no file of the three exists (the plugin was never loaded here). */
+export type AnatoleFacts = {
+ present: boolean
+ status: AnatoleStatus | null
+ /** The person's own mode override from rules.json, when it set one. */
+ modeOverride: AnatoleMode | null
+ overrides: Record<string, RuleOverride>
+ alerts: AnatoleAlert[]
+ /** Names of files that existed but were refused (too large, not regular, unknown shape). */
+ refused: string[]
+ /** How many alert lines were not usable (malformed, hostile). */
+ badAlerts: number
+}
+
+export const NO_ANATOLE: AnatoleFacts = { present: false, status: null, modeOverride: null, overrides: {}, alerts: [], refused: [], badAlerts: 0 }
+
+const whole = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.min(Math.floor(v), Number.MAX_SAFE_INTEGER) : 0)
+const oneOf = <T extends string>(list: readonly T[], v: unknown): T | null => list.find(item => item === v) ?? null
+const isV1 = (value: Record<string, unknown>): boolean => value.schemaVersion === 1
+const stamp = (v: unknown): number | null => {
+ if (typeof v === 'number' && Number.isFinite(v) && v >= 0) return Math.floor(v)
+
+ const parsed = typeof v === 'string' && v.length <= 40 ? Date.parse(v) : Number.NaN
+
+ return Number.isFinite(parsed) ? parsed : null
+}
+
+/** status.json, or null when it is not version 1 of an object. Counts are whole numbers, maturity is clamped to 0-100, text is cleaned and short. */
+export function parseAnatoleStatus(text: string | null): AnatoleStatus | null {
+ const value = jsonObject(text)
+
+ if (value === null || !isV1(value)) return null
+
+ const alerts = recordOf(value.alerts) ?? {}
+ const base = recordOf(value.baseline)
+ const open = { critical: whole(alerts.critical), high: whole(alerts.high), medium: whole(alerts.medium), low: whole(alerts.low), total: 0 }
+
+ open.total = Math.max(whole(alerts.open), open.critical + open.high + open.medium + open.low)
+
+ const state = base?.state === 'mature' ? 'mature' : 'learning'
+ const version = typeof value.modVersion === 'string' && /^[0-9][0-9A-Za-z.+-]{0,15}$/.test(value.modVersion) ? value.modVersion : null
+
+ return {
+ mode: oneOf(MODES, value.mode),
+ modVersion: version,
+ calls: whole(value.calls),
+ blocked: whole(value.blocked),
+ updatedMs: stamp(value.updatedAt) ?? stamp(value.updatedMs),
+ summary: plain(value.summary, 120),
+ open,
+ baseline: base === null ? null : { state, maturity: Math.min(100, whole(base.maturity)), events: whole(base.events), sessions: whole(base.sessions) },
+ degraded: value.degraded === false || value.degraded === undefined || value.degraded === null ? false : plain(typeof value.degraded === 'string' ? value.degraded : 'degraded', 80) || 'degraded',
+ }
+}
+
+/** rules.json: only the person's overrides. A rule id that is not `PR-###` or a mode that is not off|notify|block is dropped. `demoted` is read only if the mod set it (the schema does not define it). */
+export function parseAnatoleRules(text: string | null): { mode: AnatoleMode | null; overrides: Record<string, RuleOverride> } | null {
+ const value = jsonObject(text)
+
+ if (value === null || !isV1(value)) return null
+
+ const overrides: Record<string, RuleOverride> = {}
+
+ for (const [id, entry] of Object.entries(recordOf(value.rules) ?? {}).slice(0, 64)) {
+ const mode = oneOf(RULE_MODES, recordOf(entry)?.mode)
+
+ if (RULE_ID.test(id) && mode !== null) overrides[id] = { mode, demoted: recordOf(entry)?.demoted === true }
+ }
+
+ return { mode: oneOf(MODES, value.mode), overrides }
+}
+
+/** One alert line: every enum whitelisted, every token that can reach a command matched against its pattern, a hostile line is null. */
+export function parseAlertLine(line: string): AnatoleAlert | null {
+ const value = line.length <= 4096 ? jsonObject(line) : null
+
+ if (value === null) return null
+
+ const severity = oneOf(ALERT_SEVERITIES, value.severity)
+ const rule = typeof value.rule === 'string' && RULE_ID.test(value.rule) ? value.rule : null
+ const id = typeof value.id === 'string' && ALERT_ID.test(value.id) ? value.id : null
+ const state = oneOf(['open', 'acked', 'allowed'] as const, value.state)
+
+ if (severity === null || rule === null || id === null || state === null) return null
+
+ return {
+ id,
+ atMs: stamp(value.at),
+ rule,
+ owasp: (Array.isArray(value.owasp) ? value.owasp : []).filter((tag): tag is string => typeof tag === 'string' && OWASP.test(tag)).slice(0, 6),
+ severity,
+ action: value.action === 'blocked' ? 'blocked' : 'notified',
+ tool: plain(value.tool, 40),
+ summary: plain(value.summary, 160),
+ fp: typeof value.fp === 'string' && FINGERPRINT.test(value.fp) ? value.fp : null,
+ state,
+ }
+}
+
+/** The last ALERTS_TAIL lines of the log, newest last; returns the usable alerts and how many lines were not. */
+export function parseAlerts(text: string | null): { alerts: AnatoleAlert[]; bad: number } {
+ if (text === null) return { alerts: [], bad: 0 }
+
+ const lines = text.split('\n').filter(line => line.trim() !== '').slice(-ALERTS_TAIL)
+ const alerts = lines.flatMap(line => parseAlertLine(line) ?? [])
+
+ return { alerts, bad: lines.length - alerts.length }
+}
+
+/** Reads the folder; never rejects. A missing file is absence, not an error; a file that exists and is refused is named in `refused`. */
+export async function readAnatole(fs: ReaderFs, cache: ReadCache, cwd: string): Promise<AnatoleFacts> {
+ const at = (name: string) => under(cwd, `${ANATOLE_DIR}/${name}`)
+ const [status, rules, log] = await Promise.all([readBounded(fs, cache, at('status.json'), ANATOLE_MAX_BYTES, true), readBounded(fs, cache, at('rules.json'), ANATOLE_MAX_BYTES, true), readBounded(fs, cache, at('alerts.jsonl'), ALERTS_MAX_BYTES, true)])
+ const present = [status, rules, log].some(read => read.text !== null || read.reason !== 'missing')
+
+ if (!present) return NO_ANATOLE
+
+ const refused: string[] = []
+ const check = (name: string, read: typeof status, parsed: unknown) => {
+ if (read.text === null ? read.reason !== 'missing' : parsed === null) refused.push(name)
+ }
+ const parsedStatus = parseAnatoleStatus(status.text)
+ const parsedRules = parseAnatoleRules(rules.text)
+ const tail = parseAlerts(log.text)
+
+ check('status.json', status, parsedStatus)
+ check('rules.json', rules, parsedRules)
+ check('alerts.jsonl', log, log.text === null ? null : {})
+
+ return { present: true, status: parsedStatus, modeOverride: parsedRules?.mode ?? null, overrides: parsedRules?.overrides ?? {}, alerts: tail.alerts, refused, badAlerts: tail.bad }
+}
diff --git a/plugins/ruflo-console/hooks/data/snapshot.ts b/plugins/ruflo-console/hooks/data/snapshot.ts
index 783c5fc261..c498aec248 100644
--- a/plugins/ruflo-console/hooks/data/snapshot.ts
+++ b/plugins/ruflo-console/hooks/data/snapshot.ts
@@ -3,6 +3,7 @@
* ruflo marketplace clone's manifest. A fact a file does not hold is null and its read's reason says why; the views
* draw that as n/a, missing or too large, never as zero.
*/
+import { readAnatole, type AnatoleFacts } from './anatole'
import {
enabledOf,
parseActivity,
@@ -82,6 +83,8 @@ export type Snapshot = {
missions: MissionObservation | null
/** The ruflo-agentdb mod's own status file (ADR-445); null while the mod has not written one. */
agentdbMod: AgentdbMod | null
+ /** Project Anatole's reported files (ADR-453): unauthenticated, bounded, shape-checked. */
+ anatole?: AnatoleFacts
/** Every `.claude-flow/<short>-mod/status.json` the per-plugin mods wrote (ADR-446), bounded and shape-checked. */
mods: ModsFacts
changed: number
@@ -135,6 +138,7 @@ export async function readSnapshot(fs: ReaderFs, cache: ReadCache, cwd: string,
missions: parseMissions(text('missions')),
agentdbMod: parseAgentdbMod(text('agentdbMod')),
mods: await readMods(fs, cache, cwd),
+ anatole: await readAnatole(fs, cache, cwd),
changed: disk.changed,
readAtMs: nowMs,
}
diff --git a/plugins/ruflo-console/hooks/help-topics-more.ts b/plugins/ruflo-console/hooks/help-topics-more.ts
index 5b1ffc77de..8f89ce86f8 100644
--- a/plugins/ruflo-console/hooks/help-topics-more.ts
+++ b/plugins/ruflo-console/hooks/help-topics-more.ts
@@ -11,6 +11,7 @@ export const MORE_TOPICS: readonly HelpTopic[] = [
{ text: 'Run a quick scan of the code. It is local and read-only.', go: { run: 'sec-scan-quick' } },
{ text: 'Look for secrets in the tree. Only the file and type show, never the value.', go: { run: 'sec-secrets' } },
{ text: 'Open Security & Doctor (key u). Paste any text to have AIDefence check it for injection and PII.', go: { view: 'secure' } },
+ { text: 'Project Anatole (optional, ruflo-protector) lists its rules, alerts and mode on the same page; changes ask first, and enforce and reset-baseline ask hardest.', go: { view: 'secure' } },
{ text: 'Send the findings to Claude with one button, and ask it what to fix first.' },
{ text: 'Add a sentry to scan again on a schedule, or when files change. The fix sentry works in its own branch and never pushes.' },
],
diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.ts
index c599cfc2d6..0e3514f1ea 100644
--- a/plugins/ruflo-console/hooks/palette.ts
+++ b/plugins/ruflo-console/hooks/palette.ts
@@ -17,6 +17,7 @@ import { settingsPalette } from './settings-palette'
import { devPalette } from './devtools'
import { LAB, labSpec, labWhy } from './mh-lab'
import { PERF } from './perf'
+import { anatolePalette } from './anatole'
import { SECURE, SECURE_KEYWORDS, SECURE_TEXT, secSpec, secTextSpec } from './secure'
import { skillPaletteEntries } from './skills-lab'
import { automateEntries } from './automate'
@@ -176,6 +177,7 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
// Dev Tools: local reads run at once, the rest ask first; an entry with a field takes its text (see devtools.ts).
out.push(...devPalette(state))
out.push(...catalogPalette(state))
+ out.push(...anatolePalette(state))
out.push(...missionPalette(state))
out.push(...askPalette(state))
out.push(...settingsPalette(state))
diff --git a/plugins/ruflo-console/hooks/secure.ts b/plugins/ruflo-console/hooks/secure.ts
index d611fc762e..eeee66feaf 100644
--- a/plugins/ruflo-console/hooks/secure.ts
+++ b/plugins/ruflo-console/hooks/secure.ts
@@ -288,4 +288,4 @@ export function secTextSpec(entry: SecText, text: string, state: State): ActionS
}
/** Is a lab result one of this view's? */
-export const isSecureResult = (id: string): boolean => SECURE.some(entry => entry.id === id) || SECURE_TEXT.some(entry => entry.id === id)
+export const isSecureResult = (id: string): boolean => id.startsWith('anatole-') || SECURE.some(entry => entry.id === id) || SECURE_TEXT.some(entry => entry.id === id)
diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts
index a2b7983d6b..aff8018138 100644
--- a/plugins/ruflo-console/hooks/version.ts
+++ b/plugins/ruflo-console/hooks/version.ts
@@ -2,4 +2,4 @@
* The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest
* (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift.
*/
-export const CONSOLE_VERSION = '0.33.20'
+export const CONSOLE_VERSION = '0.33.23'
diff --git a/plugins/ruflo-console/hooks/views/anatole.ts b/plugins/ruflo-console/hooks/views/anatole.ts
new file mode 100644
index 0000000000..3773b1d793
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/anatole.ts
@@ -0,0 +1,163 @@
+import type { RenderElement } from 'claude-code'
+
+import { ALERT_SEVERITIES, ANATOLE_STALE_MS, MODES, RULE_MODES, type AnatoleAlert, type AnatoleFacts, type AnatoleMode, type RuleMode } from '../data/anatole'
+import { ANATOLE_RULES, INSTALL_LINE, UNAUTH, type RuleMeta } from '../anatole'
+import { ago, button, clip, type Ctx, row, section, text, THEME } from './common'
+
+const SEV_COLOR = { critical: () => THEME.bad, high: () => THEME.bad, medium: () => THEME.warn, low: () => THEME.info }
+
+/** What each mode does, in one sentence: shown under the chooser so the choice is never a guess. */
+const MODE_NOTE: Record<string, string> = {
+ off: 'Anatole does nothing: it records nothing and raises nothing.',
+ learn: 'Learning only (the default): it records the baseline of what is normal here and says nothing.',
+ notify: 'Raises alerts and never blocks anything. Run replay first to see what it would say.',
+ enforce: 'Rules set to block deny the tool call, and the reason names the rule and how to allow it. Switching to enforce asks first.',
+}
+
+/** A sub-heading inside the card: the title, a rule, and what it summarises at the right, so the block reads on its own. */
+function subhead(ctx: Ctx, title: string, right = ''): RenderElement {
+ const head = ` ${title} `
+ const tail = right === '' ? '' : ` ${right} `
+ const fill = Math.max(2, ctx.columns - 12 - head.length - tail.length)
+
+ return row(ctx, [ctx.kit.Text({ bold: true, color: THEME.head, children: head }), ctx.kit.Text({ dimColor: true, children: '─'.repeat(fill) }), ...(tail === '' ? [] : [ctx.kit.Text({ dimColor: true, children: tail })])])
+}
+
+/** An explanation under a block: dim, wrapped (never clipped), indented one column. */
+const note = (ctx: Ctx, words: string): RenderElement => ctx.kit.Text({ dimColor: true, wrap: 'wrap', children: ` ${words}` })
+
+/** What the page knows of one rule: its mode now, whether the person changed it, and its record in the alert tail. */
+export type RuleRow = { meta: RuleMeta; mode: RuleMode; changed: boolean; demoted: boolean; hits: number; ackedShare: number | null }
+
+/** The 13 shipped rules merged with rules.json's overrides and counted over the last alerts read (the status file carries no per-rule counts). */
+export function ruleRows(facts: AnatoleFacts): RuleRow[] {
+ return ANATOLE_RULES.map(meta => {
+ const mine = facts.alerts.filter(alert => alert.rule === meta.id)
+ const over = facts.overrides[meta.id]
+ const mode = over?.mode ?? meta.fallback
+
+ return { meta, mode, changed: over !== undefined && over.mode !== meta.fallback, demoted: over?.demoted === true, hits: mine.length, ackedShare: mine.length === 0 ? null : Math.round((mine.filter(alert => alert.state === 'acked').length / mine.length) * 100) }
+ })
+}
+
+/** The open alerts by severity as one labelled line for the Findings meter, or null when the plugin has not reported. */
+export function anatoleMeterLine(facts: AnatoleFacts | undefined): string | null {
+ const open = facts?.status?.open
+
+ return open === undefined ? null : `Project Anatole open alerts: ${ALERT_SEVERITIES.map(level => `${open[level]} ${level}`).join(' · ')} (${UNAUTH})`
+}
+
+const chipRow = <T extends string>(ctx: Ctx, label: string, keyOf: string, options: readonly T[], current: T | null, press: (value: T) => void): RenderElement =>
+ row(ctx, [text(ctx, ` ${label} `, { bold: true, color: THEME.head }), ...options.map(option => ctx.kit.Button({ key: `${keyOf}-${option}`, label: ` ${option} `, ...(option === current ? { variant: 'primary' as const } : { plain: true, dimColor: true }), onPress: () => press(option) }))], `${keyOf}-row`)
+
+function statusRows(ctx: Ctx, facts: AnatoleFacts): RenderElement[] {
+ const status = facts.status
+ const rows: RenderElement[] = []
+
+ if (status === null) {
+ rows.push(text(ctx, ` no readable status.json yet${facts.refused.includes('status.json') ? ' (refused: too large, not a regular file, or an unknown shape)' : ': start a session with the plugin loaded'}`, { color: THEME.warn }))
+
+ return rows
+ }
+
+ const base = status.baseline
+ const width = Math.max(8, Math.min(24, ctx.columns - 60))
+ const filled = base === null ? 0 : Math.round((base.maturity / 100) * width)
+ const stale = status.updatedMs !== null && ctx.nowMs - status.updatedMs > ANATOLE_STALE_MS
+
+ rows.push(
+ row(ctx, [
+ text(ctx, ` mode ${status.mode ?? 'unknown'}${facts.modeOverride !== null && facts.modeOverride !== status.mode ? ` (rules.json asks for ${facts.modeOverride})` : ''}`, { bold: true, color: status.mode === 'enforce' ? THEME.warn : THEME.ok }),
+ text(ctx, ` · baseline ${base === null ? 'n/a' : `${base.state} ${base.maturity}% `}`, { color: THEME.info }),
+ ...(base === null ? [] : [text(ctx, `${'â–ˆ'.repeat(filled)}${'â–‘'.repeat(width - filled)}`, { color: base.state === 'mature' ? THEME.ok : THEME.warn })]),
+ text(ctx, base === null ? '' : ` ${base.events} events · ${base.sessions} sessions`, { dimColor: true }),
+ ], 'anatole-status-a'),
+ )
+ rows.push(
+ row(ctx, [
+ text(ctx, ` open ${status.open.total}:`, { bold: status.open.total > 0, color: status.open.total > 0 ? THEME.warn : THEME.ok }),
+ ...ALERT_SEVERITIES.map(level => text(ctx, ` ${status.open[level]} ${level}`, status.open[level] > 0 ? { color: SEV_COLOR[level]() } : { dimColor: true })),
+ text(ctx, ` · blocked ${status.blocked} · calls ${status.calls}`, { dimColor: true }),
+ ...(status.degraded !== false ? [text(ctx, ` · degraded: ${status.degraded}`, { bold: true, color: THEME.bad })] : []),
+ ], 'anatole-status-b'),
+ )
+ rows.push(text(ctx, ` ${UNAUTH} · written ${ago(status.updatedMs, ctx.nowMs)}${stale ? ' (an earlier session)' : ''}`, { dimColor: true }))
+
+ return rows
+}
+
+function ruleList(ctx: Ctx, facts: AnatoleFacts): RenderElement[] {
+ const rows = ruleRows(facts)
+ const lead = Math.max(12, Math.min(30, ctx.columns - 70))
+ const count = (mode: RuleMode): number => rows.filter(item => item.mode === mode).length
+
+ return [
+ subhead(ctx, 'Rules', `${rows.length} · ${count('block')} block · ${count('notify')} notify · ${count('off')} off`),
+ row(ctx, [text(ctx, ' ID ', { dimColor: true }), text(ctx, 'SEVERITY '.padEnd(9), { dimColor: true }), text(ctx, 'RULE'.padEnd(lead), { dimColor: true }), text(ctx, ' OWASP'.padEnd(20), { dimColor: true }), text(ctx, ' MODE · RECORD', { dimColor: true })], 'anatole-rules-head'),
+ ...rows.map(item =>
+ row(ctx, [
+ text(ctx, ` ${item.meta.id} `, { bold: true, color: THEME.head }),
+ text(ctx, `${item.meta.severity.padEnd(8)} `, { color: SEV_COLOR[item.meta.severity]() }),
+ ctx.kit.Text({ color: THEME.info, wrap: 'truncate-end', children: clip(`${item.meta.title}`, lead).padEnd(lead) }),
+ text(ctx, ` ${item.meta.owasp.join(',')}`.padEnd(20), { dimColor: true }),
+ ...RULE_MODES.map(mode => ctx.kit.Button({ key: `anatole-rule-${item.meta.id}-${mode}`, label: ` ${mode} `, ...(mode === item.mode ? { variant: 'primary' as const } : { plain: true, dimColor: true }), onPress: () => void ctx.act.run('anatole-rule', `${item.meta.id} ${mode}`) })),
+ text(ctx, ` ${item.hits} hits${item.ackedShare === null ? '' : ` · ${item.ackedShare}% acked`}${item.demoted ? ' · auto-demoted to notify' : item.changed ? ' · changed from default' : ''}`, item.demoted || item.changed ? { color: THEME.warn } : { dimColor: true }),
+ ], `anatole-rule-${item.meta.id}`),
+ ),
+ note(ctx, 'Hits and acked share count the last 200 alerts the mod logged. A rule set to block takes effect only in mode enforce.'),
+ ]
+}
+
+function alertRows(ctx: Ctx, alerts: readonly AnatoleAlert[]): RenderElement[] {
+ const all = alerts.filter(alert => alert.state === 'open')
+ const open = all.slice(-10).reverse()
+ const head = subhead(ctx, 'Open alerts', all.length === 0 ? 'none' : all.length > open.length ? `${open.length} of ${all.length}` : String(all.length))
+
+ if (open.length === 0) return [head, text(ctx, ' ✓ no open alerts', { color: THEME.ok })]
+
+ return [
+ head,
+ ...open.flatMap(alert => [
+ row(ctx, [
+ text(ctx, ` ${alert.severity.padEnd(9)}`, { bold: true, color: SEV_COLOR[alert.severity]() }),
+ text(ctx, `${alert.rule} ${alert.action === 'blocked' ? 'blocked' : 'notified'} `, { bold: true }),
+ text(ctx, ` ${ago(alert.atMs, ctx.nowMs)} `, { dimColor: true }),
+ button(ctx, `anatole-ack-${alert.id}`, 'ack', () => void ctx.act.run('anatole-ack', alert.id)),
+ ...(alert.fp === null ? [] : [button(ctx, `anatole-allow-${alert.fp}`, 'allow', () => void ctx.act.run('anatole-allow', alert.fp ?? ''))]),
+ ], `anatole-alert-${alert.id}`),
+ ctx.kit.Text({ dimColor: true, wrap: 'wrap', children: ` ${alert.tool}: ${alert.summary}` }),
+ ]),
+ ]
+}
+
+/**
+ * The Project Anatole section of Security & Doctor (ADR-453 §9): status, the rule list with its mode chips, run and replay, the mode chooser
+ * and the open alerts. Every change asks first (the confirm row names its Effect); reset-baseline is a delete-class action.
+ */
+export function anatoleSection(ctx: Ctx): RenderElement[] {
+ const facts = ctx.state.snapshot?.anatole
+
+ if (facts === undefined || !facts.present) return section(ctx, 'sec-anatole', 'Project Anatole', 'not installed', [text(ctx, ` ${INSTALL_LINE}`, { dimColor: true })], false)
+
+ const status = facts.status
+ const open = status?.open.total ?? facts.alerts.filter(alert => alert.state === 'open').length
+ const right = `${status?.mode ?? 'no status'} · ${open} open${status?.degraded !== false && status !== null ? ' · degraded' : ''}`
+ const mode = status?.mode ?? null
+ const children: RenderElement[] = [
+ subhead(ctx, 'Status', status === null ? 'not reported yet' : ''),
+ ...statusRows(ctx, facts),
+ ...ruleList(ctx, facts),
+ subhead(ctx, 'Actions'),
+ row(ctx, [button(ctx, 'anatole-run', 'â–¶ run', () => void ctx.act.run('anatole-run'), { primary: true }), button(ctx, 'anatole-replay', 'â–¶ replay', () => void ctx.act.run('anatole-replay'))], 'anatole-actions'),
+ note(ctx, 'â–¶ run scans the Claude configuration (settings, hooks, helpers) for exposure. The result opens in the Result panel.'),
+ note(ctx, 'â–¶ replay shows what the recorded events would have fired under the current rules and baseline.'),
+ subhead(ctx, 'Mode', mode ?? 'unknown'),
+ chipRow(ctx, 'mode', 'anatole-mode', MODES, mode, (next: AnatoleMode) => void ctx.act.run('anatole-mode', next)),
+ ...(mode !== null && MODE_NOTE[mode] !== undefined ? [note(ctx, MODE_NOTE[mode] ?? '')] : []),
+ row(ctx, [button(ctx, 'anatole-reset', '⌫ reset baseline', () => void ctx.act.run('anatole-reset'))], 'anatole-reset-row'),
+ note(ctx, 'Reset baseline forgets everything learned and starts again. It asks first.'),
+ ...alertRows(ctx, facts.alerts),
+ ]
+
+ return section(ctx, 'sec-anatole', 'Project Anatole', right, [ctx.kit.Box({ key: 'anatole-card', flexDirection: 'column', borderStyle: 'round', borderColor: THEME.info, paddingX: 1, children })], open > 0)
+}
diff --git a/plugins/ruflo-console/hooks/views/secure.ts b/plugins/ruflo-console/hooks/views/secure.ts
index d1456f9ef0..21dd4b5e45 100644
--- a/plugins/ruflo-console/hooks/views/secure.ts
+++ b/plugins/ruflo-console/hooks/views/secure.ts
@@ -4,6 +4,7 @@ import { DOCTOR_COMPONENTS, isSecureResult, SECURE, SECURE_TEXT, secMemo, SEVERI
import { slot } from './attention'
import { spinAt } from '../spinner'
import { sentryRows } from './sentries'
+import { anatoleMeterLine, anatoleSection } from './anatole'
import { ago, button, clip, col, type Ctx, row, rule, section, tagChip, text, THEME } from './common'
/** Result lines in view at once; j/k scroll the rest. */
@@ -260,9 +261,10 @@ export function secureView(ctx: Ctx): RenderElement {
'sec-findings',
'Findings',
findings === null ? 'none measured yet' : `${SEVERITIES.map(level => `${findings.counts[level]} ${level}`).join(' · ')} · ${ago(findings.atMs, nowMs)}`,
- findings === null ? meterRows(ctx) : [...meterRows(ctx), sendFindingsRow(ctx)],
+ [...meterRows(ctx), ...anatoleMeterRows(ctx), ...(findings === null ? [] : [sendFindingsRow(ctx)])],
true,
),
+ ...anatoleSection(ctx),
...sentryRows(ctx),
// Open: the text field lives here, and the checks below it read what is typed; folded, the field would be out of reach.
...section(ctx, 'sec-check', 'Check text', memo.draft === '' ? 'type or paste text, then run a check' : `${memo.draft.length} characters ready`, pasteRows(ctx), true),
@@ -283,3 +285,10 @@ export function secureView(ctx: Ctx): RenderElement {
/** This view's result block alone: the pane asks for it to place under the row that was clicked. */
export const secureResult = (ctx: Ctx): RenderElement[] => resultRows(ctx, isSecureResult)
+
+/** Open Project Anatole alerts by severity, labelled as the mod's report and kept apart from the scan's own counts. */
+function anatoleMeterRows(ctx: Ctx): RenderElement[] {
+ const line = anatoleMeterLine(ctx.state.snapshot?.anatole)
+
+ return line === null ? [] : [text(ctx, ` ${line}`, { color: THEME.warn })]
+}
diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh
index 4940f0d5ba..51cb1bea9f 100755
--- a/plugins/ruflo-console/scripts/smoke.sh
+++ b/plugins/ruflo-console/scripts/smoke.sh
@@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
-step "1. plugin.json declares ruflo-console 0.33.20"
+step "1. plugin.json declares ruflo-console 0.33.23"
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
- && grep -q '"version": "0.33.20"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
+ && grep -q '"version": "0.33.23"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
step "2. hooks.json names exactly one module and no classic hook commands"
grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \
diff --git a/plugins/ruflo-console/tests/anatole.spec.ts b/plugins/ruflo-console/tests/anatole.spec.ts
new file mode 100644
index 0000000000..250ded2432
--- /dev/null
+++ b/plugins/ruflo-console/tests/anatole.spec.ts
@@ -0,0 +1,243 @@
+/**
+ * Project Anatole in the console (ADR-453 §8, §9): the bounded reader with hostile files, the Security page section, the slash each button
+ * sends, and the class each action has for Claude's console tools.
+ * npx vitest run plugins/ruflo-console/tests/anatole.spec.ts
+ */
+import { describe, expect, it } from 'vitest'
+
+import { ALERTS_TAIL, parseAlertLine, parseAlerts, parseAnatoleRules, parseAnatoleStatus, readAnatole } from '../hooks/data/anatole'
+import { readSnapshot } from '../hooks/data/snapshot'
+import type { ReaderFs } from '../hooks/data/files'
+import { ANATOLE_RULES, anatolePalette, INSTALL_LINE, slashOf, wireAnatole } from '../hooks/anatole'
+import { classOf } from '../hooks/model-tools'
+import { newState } from '../hooks/state'
+import { ruleRows } from '../hooks/views/anatole'
+import type { Actions } from '../hooks/views/common'
+import { viewText } from '../hooks/views/pane'
+
+const STATUS = { schemaVersion: 1, name: 'protector', modVersion: '0.1.0', mode: 'notify', calls: 40, blocked: 2, updatedAt: '2026-10-05T10:00:00Z', summary: 'ok', alerts: { open: 3, critical: 1, high: 1, medium: 1, low: 0, total: 5 }, baseline: { state: 'learning', maturity: 62, events: 120, sessions: 2 }, rules: { total: 13, block: 4, notify: 8, off: 1 }, degraded: false }
+const alert = (extra: Record<string, unknown> = {}) => JSON.stringify({ id: 'a1', at: '2026-10-05T09:00:00Z', rule: 'PR-002', owasp: ['T11', 'LLM06'], severity: 'critical', action: 'blocked', tool: 'Bash', summary: 'curl piped into sh', fp: 'abcdef012345', state: 'open', session: 's', ...extra })
+const files = (map: Record<string, string>): ReaderFs => ({
+ read: async path => map[path.split('/').at(-1) ?? ''] ?? '',
+ stat: async path => {
+ const text = map[path.split('/').at(-1) ?? '']
+
+ if (text === undefined) throw new Error('ENOENT')
+
+ return { mtimeMs: 1, size: text.length, kind: 'file' }
+ },
+ list: async () => [],
+})
+const act = new Proxy(() => undefined, { get: () => act, apply: () => undefined }) as unknown as Actions
+
+describe('the reader', () => {
+ it('reads schema 1 status and clamps what a hostile file claims', () => {
+ expect(parseAnatoleStatus(JSON.stringify(STATUS))).toMatchObject({ mode: 'notify', blocked: 2, open: { critical: 1, total: 3 }, baseline: { state: 'learning', maturity: 62 }, degraded: false })
+ const evil = parseAnatoleStatus(JSON.stringify({ ...STATUS, mode: 'rm -rf', blocked: -5, summary: 'x\u001b[31m‮ok', baseline: { maturity: 1e9, state: 'weird' }, degraded: 'boom\u0007' }))
+
+ expect(evil).toMatchObject({ mode: null, blocked: 0, baseline: { maturity: 100, state: 'learning' }, degraded: 'boom' })
+ expect(evil?.summary).not.toMatch(/[\u0000-\u001f‮]/)
+ })
+
+ it('refuses other schema versions and junk', () => {
+ for (const text of [JSON.stringify({ ...STATUS, schemaVersion: 2 }), '[]', 'nope', '', null]) expect(parseAnatoleStatus(text)).toBeNull()
+ })
+
+ it('keeps only valid rule ids and modes from rules.json', () => {
+ expect(parseAnatoleRules(JSON.stringify({ schemaVersion: 1, mode: 'enforce', rules: { 'PR-002': { mode: 'off' }, 'PR-9': { mode: 'off' }, 'PR-003': { mode: 'wild' }, '../x': { mode: 'off' } } }))).toEqual({ mode: 'enforce', overrides: { 'PR-002': { mode: 'off', demoted: false } } })
+ })
+
+ it('drops alert lines whose ids could reach a command, and cleans their text', () => {
+ expect(parseAlertLine(alert())).toMatchObject({ id: 'a1', rule: 'PR-002', fp: 'abcdef012345', owasp: ['T11', 'LLM06'] })
+
+ for (const bad of [{ id: 'a; rm -rf /' }, { id: '' }, { rule: 'PR-2' }, { severity: 'doom' }, { state: 'x' }]) expect(parseAlertLine(alert(bad))).toBeNull()
+
+ expect(parseAlertLine(alert({ fp: 'abc; id' }))?.fp).toBeNull()
+ expect(parseAlertLine(alert({ owasp: ['T11', '$(x)'], summary: 'a\u001b[2Jb‮' }))?.owasp).toEqual(['T11'])
+ expect(parseAlertLine(alert({ summary: 'a\u001b[2Jb‮' }))?.summary).toBe('ab')
+ })
+
+ it('takes the last 200 lines and counts the bad ones', () => {
+ const lines = Array.from({ length: 250 }, (_, i) => alert({ id: `a${i}` }))
+
+ lines[249] = '{not json'
+
+ const { alerts, bad } = parseAlerts(lines.join('\n'))
+
+ expect(alerts).toHaveLength(ALERTS_TAIL - 1)
+ expect(bad).toBe(1)
+ expect(alerts.at(-1)?.id).toBe('a248')
+ })
+
+ it('is absent when no file exists, refuses a link or an oversize file, and never throws', async () => {
+ expect((await readAnatole(files({}), new Map(), '/p')).present).toBe(false)
+
+ const big = await readAnatole(files({ 'status.json': JSON.stringify({ ...STATUS, pad: 'x'.repeat(70_000) }) }), new Map(), '/p')
+
+ expect(big).toMatchObject({ present: true, status: null, refused: ['status.json'] })
+
+ const link: ReaderFs = { ...files({ 'status.json': JSON.stringify(STATUS) }), stat: async () => ({ mtimeMs: 1, size: 10, kind: 'file', isLink: true }) }
+
+ expect(await readAnatole(link, new Map(), '/p')).toMatchObject({ status: null, refused: expect.arrayContaining(['status.json']) })
+ })
+})
+
+describe('the section', () => {
+ const draw = async (map: Record<string, string>, columns = 130) => {
+ const state = newState({})
+
+ state.snapshot = await readSnapshot(files({}), new Map(), '/w', '/h', {}, 0)
+ state.snapshot = { ...state.snapshot, anatole: await readAnatole(files(map), new Map(), '/w') }
+ state.view = 'secure'
+
+ return { state, text: viewText({ state, nowMs: Date.parse('2026-10-05T10:05:00Z'), columns, act }, 'secure') }
+ }
+
+ it('says how to install it, and nothing else, when the plugin never reported', async () => {
+ const { text } = await draw({})
+
+ expect(text).toContain('Project Anatole')
+ expect(text).toContain('not installed')
+ expect(text).not.toContain('PR-001')
+ })
+
+ it('shows status, the 13 rules, mode chips and the open alerts, labelled unauthenticated', async () => {
+ const { text } = await draw({ 'status.json': JSON.stringify({ ...STATUS, degraded: 'timeout' }), 'rules.json': JSON.stringify({ schemaVersion: 1, rules: { 'PR-002': { mode: 'off' }, 'PR-004': { mode: 'notify', demoted: true } } }), 'alerts.jsonl': `${alert()}\n${alert({ id: 'a2', state: 'acked' })}\n` })
+
+ for (const id of ANATOLE_RULES.map(rule => rule.id)) expect(text).toContain(id)
+ expect(text).toMatch(/mode notify/)
+ expect(text).toContain('learning 62%')
+ expect(text).toContain('degraded: timeout')
+ expect(text).toContain('unauthenticated')
+ expect(text).toContain('changed from default')
+ expect(text).toContain('auto-demoted')
+ expect(text).toContain('2 hits · 50% acked')
+ expect(text).toMatch(/Project Anatole open alerts: 1 critical · 1 high · 1 medium · 0 low/)
+ expect(text).toContain('curl piped into sh')
+ })
+
+ it('is laid out in labelled blocks, each explanation on its own wrapped line (not squeezed beside a button)', async () => {
+ const { text } = await draw({ 'status.json': JSON.stringify(STATUS), 'alerts.jsonl': alert({ summary: 'curl piped into sh (Bash)' }) })
+ const at = (word: string): number => text.indexOf(word)
+
+ // The blocks come in order, each under its own heading.
+ expect(text).toMatch(/Status ─+/)
+ expect(text).toMatch(/Rules ─+ 13 · \d+ block · \d+ notify · \d+ off/)
+ expect(text).toMatch(/Actions ─+/)
+ expect(text).toMatch(/Mode ─+ notify/)
+ expect(text).toMatch(/Open alerts ─+ 1/)
+ expect(at('Status')).toBeLessThan(at('Rules'))
+ expect(at('Rules')).toBeLessThan(at('Actions'))
+ expect(at('Actions')).toBeLessThan(at('Mode'))
+ expect(at('Mode')).toBeLessThan(at('Open alerts'))
+ // The explanations are separate lines, one per thing explained, and the current mode is described.
+ expect(text).toContain('â–¶ run scans the Claude configuration')
+ expect(text).toContain('â–¶ replay shows what the recorded events would have fired')
+ expect(text).toContain('Raises alerts and never blocks anything.')
+ expect(text).toContain('Reset baseline forgets everything learned and starts again. It asks first.')
+ expect(text).not.toMatch(/\[ â–¶ replay \][^\n]*scan the Claude configuration/)
+ // Nothing runs into its neighbour: the severity word, the rule id, and the mode label and its first chip.
+ expect(text).toMatch(/(critical|high) +PR-00\d blocked/)
+ expect(text).toMatch(/ mode \[ off \]/)
+ // An alert is two lines: what happened, then its detail.
+ expect(text).toMatch(/PR-002 blocked[^\n]*\n[^\n]*Bash: curl piped into sh/)
+ })
+
+ it('describes whichever mode is current, and says plainly when there is nothing to act on', async () => {
+ const enforce = await draw({ 'status.json': JSON.stringify({ ...STATUS, mode: 'enforce' }) })
+
+ expect(enforce.text).toContain('Rules set to block deny the tool call')
+ expect(enforce.text).toContain('✓ no open alerts')
+ expect(enforce.text).toMatch(/Open alerts ─+ none/)
+ expect((await draw({ 'status.json': JSON.stringify({ ...STATUS, mode: 'learn' }) })).text).toContain('Learning only (the default)')
+ })
+
+ it('computes a rule row from the shipped table, its override and the alert tail', async () => {
+ const { state } = await draw({ 'rules.json': JSON.stringify({ schemaVersion: 1, rules: { 'PR-001': { mode: 'notify' } } }), 'alerts.jsonl': alert({ rule: 'PR-001' }) })
+ const rows = ruleRows(state.snapshot!.anatole)
+
+ expect(rows).toHaveLength(13)
+ expect(rows[0]).toMatchObject({ mode: 'notify', changed: true, hits: 1, ackedShare: 0 })
+ expect(rows[1]).toMatchObject({ mode: 'block', changed: false, hits: 0, ackedShare: null })
+ })
+
+ it('keeps the shipped rule table in step with ADR-453 section 5', () => {
+ expect(ANATOLE_RULES.map(rule => `${rule.id}:${rule.severity}:${rule.fallback}`)).toEqual(['PR-001:critical:block', 'PR-002:critical:block', 'PR-003:high:block', 'PR-004:high:notify', 'PR-005:high:notify', 'PR-006:critical:block', 'PR-007:medium:notify', 'PR-008:medium:notify', 'PR-009:medium:notify', 'PR-010:high:notify', 'PR-011:medium:notify', 'PR-012:medium:notify', 'PR-013:high:notify'])
+ })
+})
+
+describe('the actions', () => {
+ const sent: string[] = []
+ const host = { invalidate: () => undefined, runSlash: async (command: string, args: string) => { sent.push(`${command} ${args}`); return { text: 'one\ntwo' } } }
+ const state = newState({})
+
+ wireAnatole(state, host as never)
+
+ const specOf = (id: string, text = '') => {
+ const entry = anatolePalette(state).find(candidate => candidate.id === id)
+
+ if (entry?.run.kind === 'spec') return entry.run.spec
+
+ return entry?.run.kind === 'text' ? entry.run.make(text) : null
+ }
+
+ it('sends exactly the slash string for each button, through host.runSlash', async () => {
+ for (const [id, text, slash] of [['anatole-mode', 'learn', 'mode learn'], ['anatole-rule', 'PR-002 block', 'rule PR-002 block'], ['anatole-ack', 'a1', 'ack a1'], ['anatole-allow', 'abcdef012345', 'allow abcdef012345'], ['anatole-reset', '', 'reset-baseline'], ['anatole-run', '', 'run'], ['anatole-replay', '', 'replay']] as const) {
+ const spec = specOf(id, text)
+
+ expect(spec?.shows).toBe(`/protector ${slash}`)
+ await spec?.run?.()
+ expect(sent.at(-1)).toBe(`protector ${slash}`)
+ }
+
+ expect(slashOf.rule('PR-001', 'off')).toBe('rule PR-001 off')
+ })
+
+ it('refuses anything that is not a rule id, a mode or a fingerprint', () => {
+ expect(specOf('anatole-mode', 'enforce; ls')).toBeNull()
+ expect(specOf('anatole-rule', 'PR-002 explode')).toBeNull()
+ expect(specOf('anatole-rule', 'PR-002 off extra')).toBeNull()
+ expect(specOf('anatole-ack', 'a; b')).toBeNull()
+ expect(specOf('anatole-allow', 'XYZ')).toBeNull()
+ })
+
+ it('puts run and replay answers in the Result panel, and a failure there too', async () => {
+ await specOf('anatole-run')?.run?.()
+ expect(state.lab.result).toMatchObject({ id: 'anatole-run', ok: true, lines: ['one', 'two'] })
+
+ const broken = newState({})
+
+ wireAnatole(broken, { invalidate: () => undefined, runSlash: async () => Promise.reject(new Error('no such command')) } as never)
+
+ const entry = anatolePalette(broken).find(candidate => candidate.id === 'anatole-replay')
+
+ await (entry?.run.kind === 'spec' ? entry.run.spec?.run?.() : undefined)
+ expect(broken.lab.result).toMatchObject({ id: 'anatole-replay', ok: false })
+ })
+
+ it('classes them for Claude: reads at read, edits at write, enforce asks as install, reset is delete', () => {
+ const cls = (id: string, text = '') => {
+ const spec = specOf(id, text)
+
+ return spec === null ? null : spec.isReadOnly === true ? 'read' : classOf({ label: spec.label, args: spec.args, ...(spec.note !== undefined && { note: spec.note }), ...(spec.shows !== undefined && { shows: spec.shows }), expect: spec.expect, ...(spec.declared !== undefined && { declared: spec.declared }) })
+ }
+
+ expect(cls('anatole-run')).toBe('read')
+ expect(cls('anatole-replay')).toBe('read')
+
+ for (const [id, text] of [['anatole-mode', 'off'], ['anatole-mode', 'learn'], ['anatole-mode', 'notify'], ['anatole-rule', 'PR-002 off'], ['anatole-rule', 'PR-002 block'], ['anatole-ack', 'a1'], ['anatole-allow', 'abcdef012345']] as const) expect(cls(id, text)).toBe('write')
+
+ expect(cls('anatole-mode', 'enforce')).toBe('install')
+ expect(cls('anatole-reset')).toBe('delete')
+ })
+
+ it('addresses each open alert by its own id', async () => {
+ const own = newState({})
+
+ wireAnatole(own, host as never)
+ own.snapshot = { ...(await readSnapshot(files({}), new Map(), '/w', '/h', {}, 0)), anatole: await readAnatole(files({ 'alerts.jsonl': alert() }), new Map(), '/w') }
+
+ expect(anatolePalette(own).map(entry => entry.id)).toEqual(expect.arrayContaining(['anatole-ack-a1', 'anatole-allow-abcdef012345']))
+ expect(INSTALL_LINE).toContain('claude plugin install ruflo-protector@ruflo')
+ })
+})