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(mods): $.ruflo noun, status segments, mod trust gate, refusal-tolerant $ (ADR-404)

ruv8a1e11f3bde0
diff --git a/plugins/ruflo-mods/.claude-plugin/plugin.json b/plugins/ruflo-mods/.claude-plugin/plugin.json
index 653a927cbd..4149fb64bf 100644
--- a/plugins/ruflo-mods/.claude-plugin/plugin.json
+++ b/plugins/ruflo-mods/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "ruflo-mods",
- "description": "ruflo as a Claude Code mod (function hooks, early access, ADR-404): in-process prompt routing, edit learning signals, tighten-only tool checks from ruflo policy, and the cost-tracker budget ladder on live session cost. Opt-in and removable: the classic hook-handler hooks stay the default and take every event back whenever the mod is not loaded.",
+ "description": "ruflo as a Claude Code mod (function hooks, ADR-404): in-process prompt routing, edit learning signals, tighten-only tool checks from ruflo policy, the cost-tracker budget ladder, a mod trust gate for newly installed mods, and the $.ruflo noun other mods compose their status with. Opt-in and removable: the classic hook-handler hooks stay the default and take every event back whenever the mod is not loaded.",
"version": "0.1.0",
"author": {
"name": "ruvnet",
@@ -14,8 +14,10 @@
"function-hooks",
"routing",
"policy",
- "cost"
+ "cost",
+ "trust"
],
+ "types": "./types/index.d.ts",
"userConfig": {
"routeContext": {
"type": "boolean",
@@ -44,6 +46,25 @@
"description": "At 100% of the session budget, refuse new subagent spawns.",
"required": false,
"default": false
+ },
+ "modTrust": {
+ "type": "string",
+ "title": "Mod trust gate",
+ "description": "How ruflo treats a hooks module installed or hot-reloaded after it (a mod Claude wrote, say). \"observe\" (default): name what it can do (host commands, network, environment, tool verdicts) in the transcript. \"refuse-risky\": refuse user-tier mods that can do any of those, unless named in modTrustAllow. \"off\": do not watch.",
+ "required": false,
+ "default": "observe",
+ "options": [
+ "observe",
+ "refuse-risky",
+ "off"
+ ]
+ },
+ "modTrustAllow": {
+ "type": "string",
+ "title": "Trusted mods",
+ "description": "Comma-separated plugin names the trust gate never refuses.",
+ "required": false,
+ "default": ""
}
}
}
diff --git a/plugins/ruflo-mods/hooks/cost/index.ts b/plugins/ruflo-mods/hooks/cost/index.ts
index 7f09ce9f77..2d4ef61309 100644
--- a/plugins/ruflo-mods/hooks/cost/index.ts
+++ b/plugins/ruflo-mods/hooks/cost/index.ts
@@ -1,7 +1,7 @@
import type { On } from 'claude-code'
import type { ModOptions } from '../options'
-import { statusText, type ModState } from '../state'
+import { redraw, type ModState } from '../state'
import { alertLevel, isRaised } from './budget'
/**
@@ -25,8 +25,12 @@ export function registerCost(on: On, state: ModState, options: ModOptions) {
const raised = isRaised(state.budget.level, level)
state.budget = { level, usd, limit }
if (raised) {
- $.ui.toast(`ruflo budget ${level}: $${usd.toFixed(2)} of $${limit.toFixed(2)} this session`)
- if (state.statusLine) $.ui.status(statusText(state))
+ try {
+ $.ui.toast(`ruflo budget ${level}: $${usd.toFixed(2)} of $${limit.toFixed(2)} this session`)
+ } catch {
+ // a refused toast never fails the hook
+ }
+ redraw(state)
}
return result
})
diff --git a/plugins/ruflo-mods/hooks/guard/index.ts b/plugins/ruflo-mods/hooks/guard/index.ts
index 1cf8794b7f..e9853bf1e9 100644
--- a/plugins/ruflo-mods/hooks/guard/index.ts
+++ b/plugins/ruflo-mods/hooks/guard/index.ts
@@ -1,7 +1,7 @@
import type { On } from 'claude-code'
import { cachedFile, type Read } from '../files'
-import { statusText, under, type ModState } from '../state'
+import { redraw, under, type ModState } from '../state'
import { dangerousCommandVerdict } from './dangerous-command'
import { parseProjection, policyOpinion, PROJECTION_PATH, type Projection } from './policy'
import { stricter, type Verdict } from './verdict'
@@ -57,12 +57,16 @@ export function registerGuard(on: On, state: ModState) {
const { verdict, observed } = opinionOf(state, read, tool, e.input)
if (observed) {
state.observed++
- $.ui.log(`ruflo policy (observe): ${tool} ${observed}`, { to: 'debug' })
+ try {
+ $.ui.log(`ruflo policy (observe): ${tool} ${observed}`, { to: 'debug' })
+ } catch {
+ // a refused log never turns an observation into a failure
+ }
}
const merged = stricter(chain, verdict)
if (merged !== chain) {
state.tightened++
- if (state.statusLine) $.ui.status(statusText(state))
+ redraw(state)
}
return merged
}).catch(async ($, e, next) => {
diff --git a/plugins/ruflo-mods/hooks/learn/index.ts b/plugins/ruflo-mods/hooks/learn/index.ts
index 39e77ff267..23b86145cf 100644
--- a/plugins/ruflo-mods/hooks/learn/index.ts
+++ b/plugins/ruflo-mods/hooks/learn/index.ts
@@ -1,7 +1,7 @@
import type { EngineInterface, On } from 'claude-code'
import { isMissing } from '../files'
-import { statusText, under, type ModState } from '../state'
+import { redraw, under, type ModState } from '../state'
import { appendRecords, EDIT_TOOLS, editedFile, MAX_LINES, PENDING_PATH, rufloSessionId, SESSION_PATH } from './insights'
/** Written early once this many edits wait, so a long turn holds little. */
@@ -26,7 +26,11 @@ export async function flushEdits($: EngineInterface, state: ModState): Promise<v
} catch (error) {
state.edits.unshift(...records)
state.edits.splice(0, Math.max(0, state.edits.length - MAX_LINES))
- $.ui.log(`ruflo mods: edit records not written yet (${String((error as Error)?.message ?? error)})`, { to: 'debug' })
+ try {
+ $.ui.log(`ruflo mods: edit records not written yet (${String((error as Error)?.message ?? error)})`, { to: 'debug' })
+ } catch {
+ // nothing more to do: the records wait for the next turn
+ }
}
}
@@ -49,7 +53,7 @@ export function registerLearn(on: On, state: ModState) {
sessionId: null,
})
state.editCount++
- if (state.statusLine) $.ui.status(statusText(state))
+ redraw(state)
if (state.edits.length >= FLUSH_AT) await flushEdits($, state)
return result
})
diff --git a/plugins/ruflo-mods/hooks/noun.ts b/plugins/ruflo-mods/hooks/noun.ts
new file mode 100644
index 0000000000..0223976b32
--- /dev/null
+++ b/plugins/ruflo-mods/hooks/noun.ts
@@ -0,0 +1,57 @@
+import type { EngineInterface, On } from 'claude-code'
+
+import type { RufloSnapshot } from '../types'
+import { redraw, setSegment, sortedSegments, type ModState } from './state'
+
+/** The snapshot `$.ruflo.snapshot()` answers: copies, never live state. */
+export function snapshotOf(s: ModState): RufloSnapshot {
+ return {
+ owned: [...s.owned],
+ routed: s.routed,
+ lastRoute: s.lastRoute ? { ...s.lastRoute } : null,
+ policy: s.policy,
+ tightened: s.tightened,
+ observed: s.observed,
+ edits: s.editCount,
+ ...(s.budget.limit !== undefined
+ ? { budget: { level: s.budget.level, ...(s.budget.usd !== undefined ? { usd: s.budget.usd } : {}), limit: s.budget.limit } }
+ : {}),
+ segments: sortedSegments(s).map(([id, text]) => ({ id, text })),
+ }
+}
+
+/**
+ * `engine.create`: adds `$.ruflo` (contract: ../types/index.d.ts) and takes
+ * the status line drawer from the `$` built beneath, so every redraw goes
+ * through one place and a refused `ui.status` never fails a hook.
+ *
+ * Another plugin's `$.ruflo.<method>(input)` runs as an event through the
+ * chain, these methods its core; where this mod is not seated the noun is
+ * absent and such a call rejects, which its callers catch.
+ */
+export function registerNoun(on: On, state: ModState) {
+ on('engine.create', async ($, e, next) => {
+ const beneath = await next(e)
+
+ state.draw = text => {
+ try {
+ beneath.ui.status(text)
+ } catch {
+ // an admin may withhold ui.status: the line simply is not drawn
+ }
+ }
+
+ const ruflo: EngineInterface['ruflo'] = {
+ segment: async input => {
+ setSegment(state, input)
+ redraw(state)
+ },
+ lastRoute: async () => (state.lastRoute ? { ...state.lastRoute } : null),
+ snapshot: async () => snapshotOf(state),
+ }
+
+ // Beneath wins: if another step already added `ruflo`, ours never replaces it.
+ const added = { ruflo }
+ return { ...added, ...beneath }
+ })
+}
diff --git a/plugins/ruflo-mods/hooks/options.ts b/plugins/ruflo-mods/hooks/options.ts
index 9c65f51a88..11adb7a3d6 100644
--- a/plugins/ruflo-mods/hooks/options.ts
+++ b/plugins/ruflo-mods/hooks/options.ts
@@ -1,6 +1,7 @@
import type { PluginOptions } from 'claude-code'
import { budgetOf } from './cost/budget'
+import type { TrustPolicy } from './trust'
/** The plugin's `userConfig` options, validated: a bad value is the default. */
export type ModOptions = {
@@ -8,11 +9,21 @@ export type ModOptions = {
readonly statusLine: boolean
readonly costBudgetUsd?: number
readonly costHardStop: boolean
+ readonly modTrust: TrustPolicy
+ readonly modTrustAllow: ReadonlySet<string>
}
const bool = (value: unknown, fallback: boolean) =>
value === true || value === 'true' ? true : value === false || value === 'false' ? false : fallback
+const TRUST: readonly TrustPolicy[] = ['observe', 'refuse-risky', 'off']
+
+/** Plugin names, from a comma list or a string array; anything else is none. */
+function names(value: unknown): ReadonlySet<string> {
+ const list = typeof value === 'string' ? value.split(',') : Array.isArray(value) ? value : []
+ return new Set(list.filter((v): v is string => typeof v === 'string').map(v => v.trim()).filter(v => /^[A-Za-z0-9._-]{1,64}$/.test(v)))
+}
+
export function readOptions(options: PluginOptions | undefined): ModOptions {
const o = options ?? {}
return {
@@ -20,5 +31,7 @@ export function readOptions(options: PluginOptions | undefined): ModOptions {
statusLine: bool(o.statusLine, true),
costBudgetUsd: budgetOf(o.costBudgetUsd),
costHardStop: bool(o.costHardStop, false),
+ modTrust: TRUST.includes(o.modTrust as TrustPolicy) ? (o.modTrust as TrustPolicy) : 'observe',
+ modTrustAllow: names(o.modTrustAllow),
}
}
diff --git a/plugins/ruflo-mods/hooks/register.ts b/plugins/ruflo-mods/hooks/register.ts
index 9a676dbce5..bc593291ee 100644
--- a/plugins/ruflo-mods/hooks/register.ts
+++ b/plugins/ruflo-mods/hooks/register.ts
@@ -3,24 +3,31 @@ import type { Register } from 'claude-code'
import { registerCost } from './cost'
import { registerGuard } from './guard'
import { registerLearn } from './learn'
+import { registerNoun } from './noun'
import { readOptions } from './options'
import { registerRoute } from './route'
import { registerSession } from './session'
import { createState } from './state'
+import { registerTrust } from './trust'
/**
- * ruflo as a Claude Code mod (ADR-404, early access).
+ * ruflo as a Claude Code mod (ADR-404).
*
* In-process equivalents of the classic hook-handler.cjs events that fire on
- * every prompt and every edit, plus tighten-only tool checks and the cost
- * ladder. Additive and opt-in: the classic hooks stay the default, keep every
- * event the mod does not own, and take everything back whenever the mod is not
- * loaded (function hooks off, `allowManagedModsOnly`, a failed start).
+ * every prompt and every edit, tighten-only tool checks, the cost ladder, the
+ * `$.ruflo` noun other mods compose with, and the mod trust gate. Additive
+ * and opt-in: the classic hooks stay the default, keep every event the mod
+ * does not own, and take everything back whenever the mod is not loaded.
+ *
+ * Registration order is nesting order (the first registered wraps the rest):
+ * the trust gate first, so it judges modules before anything else of ours runs.
*/
export const register: Register = (on, options) => {
const state = createState()
const opts = readOptions(options)
+ registerTrust(on, opts.modTrust, opts.modTrustAllow)
+ registerNoun(on, state)
registerSession(on, state, opts)
registerRoute(on, state, opts)
registerGuard(on, state)
diff --git a/plugins/ruflo-mods/hooks/route/index.ts b/plugins/ruflo-mods/hooks/route/index.ts
index 2e99edaf08..eaf44d5b75 100644
--- a/plugins/ruflo-mods/hooks/route/index.ts
+++ b/plugins/ruflo-mods/hooks/route/index.ts
@@ -2,7 +2,7 @@ import type { On } from 'claude-code'
import { cachedFile } from '../files'
import type { ModOptions } from '../options'
-import { statusText, under, type ModState } from '../state'
+import { redraw, under, type ModState } from '../state'
import { formatRoute } from './format'
import { parseRanked, rankedContext } from './ranked-context'
import { routeTask } from './route-task'
@@ -34,7 +34,7 @@ export function registerRoute(on: On, state: ModState, options: ModOptions) {
if (context) blocks.push(context)
}
blocks.push(formatRoute(text, result))
- if (state.statusLine) $.ui.status(statusText(state))
+ redraw(state)
return next({ ...e, context: [...(e.context ?? []), blocks.join('\n')] })
}).catch(($, e, next) => next(e)) // a broken plugin never blocks a prompt
diff --git a/plugins/ruflo-mods/hooks/session.ts b/plugins/ruflo-mods/hooks/session.ts
index 94235bd63f..41559b95eb 100644
--- a/plugins/ruflo-mods/hooks/session.ts
+++ b/plugins/ruflo-mods/hooks/session.ts
@@ -2,7 +2,7 @@ import type { EngineInterface, On } from 'claude-code'
import { HANDSHAKE_MARKER, ownedEvents } from './ownership'
import type { ModOptions } from './options'
-import { report, under, type ModState } from './state'
+import { redraw, report, under, type ModState } from './state'
const HELPER = '.claude/helpers/hook-handler.cjs'
@@ -50,6 +50,7 @@ export function registerSession(on: On, state: ModState, options: ModOptions) {
state.owned = new Set(ownedEvents(settings, await helperHonours($)))
await $.env.set('RUFLO_MODS_OWNS', state.owned.size ? [...state.owned].join(',') : undefined)
state.statusLine = options.statusLine && !hasClassicStatusLine(settings)
+ redraw(state)
await $.command
.register({ name: 'ruflo-mods', description: 'ruflo mods: what this session routed, recorded and tightened' })
.catch(() => undefined)
@@ -59,9 +60,13 @@ export function registerSession(on: On, state: ModState, options: ModOptions) {
}).catch(async ($, e, next) => {
state.owned = new Set()
await $.env.set('RUFLO_MODS_OWNS', undefined).catch(() => undefined)
- $.ui.log(`ruflo mods: session start failed (${next.error.message ?? next.error.kind}); classic hooks keep every event`, {
- to: 'debug',
- })
+ try {
+ $.ui.log(`ruflo mods: session start failed (${next.error.message ?? next.error.kind}); classic hooks keep every event`, {
+ to: 'debug',
+ })
+ } catch {
+ // a withheld ui.log changes nothing: the classic hooks already have every event
+ }
// Replay-safe: resolves to what the hook's own call settled to, or runs
// the hooks beneath once when it never called.
return next(e)
diff --git a/plugins/ruflo-mods/hooks/state.ts b/plugins/ruflo-mods/hooks/state.ts
index 3ec32bc698..1dafcd3ef7 100644
--- a/plugins/ruflo-mods/hooks/state.ts
+++ b/plugins/ruflo-mods/hooks/state.ts
@@ -5,12 +5,16 @@ import type { RouteResult } from './route/route-task'
/**
* What the mod knows during one process, shared by its features. In memory
- * only: it dies with the process, as the classic handshake variable does.
+ * only: it dies with the process, as the classic handshake variable does. A
+ * hot reload re-runs `register` and `session.start`, which rebuild it; the
+ * only state that would matter across a reload (pending edit records) is
+ * written at every turn end, so a reload loses at most one turn's records.
*/
export type ModState = {
/** The session's project root, where the classic helpers keep their files. */
root: string
owned: ReadonlySet<Ownable>
+ /** Whether ruflo's own parts are shown (off where the ruflo statusLine helper runs). */
statusLine: boolean
lastRoute?: RouteResult
routed: number
@@ -20,6 +24,13 @@ export type ModState = {
editCount: number
policy: 'none' | 'legacy' | 'observe' | 'enforce' | 'unreadable'
budget: { level: BudgetLevel; usd?: number; limit?: number }
+ /** Other mods' status segments, by id (`$.ruflo.segment`). */
+ segments: Map<string, string>
+ /**
+ * Draws the status line. Installed by the `engine.create` step from the `$`
+ * beneath; a refused `ui.status` is swallowed, never failing a hook.
+ */
+ draw: (text: string | undefined) => void
}
export function createState(): ModState {
@@ -34,26 +45,70 @@ export function createState(): ModState {
editCount: 0,
policy: 'none',
budget: { level: 'OK' },
+ segments: new Map(),
+ draw: () => undefined,
}
}
/** A path under the session's project root. */
export const under = (s: ModState, relative: string) => `${s.root}/${relative}`
-/** The one status line under the prompt. */
-export function statusText(s: ModState): string {
- const parts = ['ruflo']
- if (s.lastRoute) {
- const pct = Math.round(s.lastRoute.confidence * 100)
- parts.push(s.lastRoute.matched ? `${s.lastRoute.agent} ${pct}%` : `no route (${pct}%)`)
+export const MAX_SEGMENTS = 8
+export const MAX_SEGMENT_CHARS = 48
+const SEGMENT_ID = /^[A-Za-z0-9_-]{1,32}$/
+
+/**
+ * Sets or clears one segment. Untrusted input: the id must be a short token,
+ * the text loses control and bidi-override characters, collapses whitespace
+ * and is cut to 48 characters. Throws (the caller's call rejects) on a bad id
+ * or a new id past the cap.
+ */
+export function setSegment(s: ModState, input: unknown): void {
+ const { id, text } = (input ?? {}) as { id?: unknown; text?: unknown }
+ if (typeof id !== 'string' || !SEGMENT_ID.test(id)) throw new Error('ruflo.segment: id must be 1-32 of [A-Za-z0-9_-]')
+ if (text !== null && typeof text !== 'string') throw new Error('ruflo.segment: text must be a string or null')
+ const clean =
+ text === null
+ ? ''
+ : text
+ .replace(/[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁠-⁩]/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+ if (!clean) {
+ s.segments.delete(id)
+ return
+ }
+ if (!s.segments.has(id) && s.segments.size >= MAX_SEGMENTS) throw new Error(`ruflo.segment: at most ${MAX_SEGMENTS} segments`)
+ s.segments.set(id, clean.length > MAX_SEGMENT_CHARS ? `${clean.slice(0, MAX_SEGMENT_CHARS - 1)}…` : clean)
+}
+
+/** Segments as shown: sorted by id. */
+export const sortedSegments = (s: ModState) => [...s.segments].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+
+/**
+ * The one status line: ruflo's own parts (when shown), then segments; or
+ * undefined (clears the line) when there is nothing to show. Only measured
+ * facts: a route that did not match says so, nothing is estimated.
+ */
+export function statusText(s: ModState): string | undefined {
+ const parts: string[] = []
+ if (s.statusLine) {
+ if (s.lastRoute) {
+ const pct = Math.round(s.lastRoute.confidence * 100)
+ parts.push(s.lastRoute.matched ? `${s.lastRoute.agent} ${pct}%` : `no route (${pct}%)`)
+ }
+ if (s.editCount) parts.push(`${s.editCount} edit${s.editCount === 1 ? '' : 's'}`)
+ if (s.policy !== 'none' && s.policy !== 'legacy') parts.push(`policy ${s.policy}`)
+ if (s.tightened) parts.push(`${s.tightened} tightened`)
+ if (s.budget.limit !== undefined && s.budget.level !== 'OK') parts.push(`budget ${s.budget.level}`)
}
- if (s.editCount) parts.push(`${s.editCount} edit${s.editCount === 1 ? '' : 's'}`)
- if (s.policy !== 'none' && s.policy !== 'legacy') parts.push(`policy ${s.policy}`)
- if (s.tightened) parts.push(`${s.tightened} tightened`)
- if (s.budget.limit !== undefined && s.budget.level !== 'OK') parts.push(`budget ${s.budget.level}`)
- return parts.join(' · ')
+ for (const [, text] of sortedSegments(s)) parts.push(text)
+ return parts.length ? ['ruflo', ...parts].join(' · ') : undefined
}
+/** Redraws the status line from the state. */
+export const redraw = (s: ModState) => s.draw(statusText(s))
+
/** What `/ruflo-mods` prints. */
export function report(s: ModState): string {
const route = s.lastRoute
@@ -63,12 +118,14 @@ export function report(s: ModState): string {
s.budget.limit === undefined
? 'off (set the costBudgetUsd option)'
: `${s.budget.level}: $${(s.budget.usd ?? 0).toFixed(2)} of $${s.budget.limit.toFixed(2)}`
+ const segments = sortedSegments(s).map(([id]) => id)
return [
- 'ruflo mods (ADR-404, early access)',
+ 'ruflo mods (ADR-404)',
` owns: ${[...s.owned].join(', ') || 'nothing (classic hooks keep every event)'}`,
` routed: ${s.routed} prompt(s); last ${route}`,
` edits: ${s.editCount} recorded, ${s.edits.length} pending write`,
` policy: ${s.policy}; ${s.tightened} call(s) tightened, ${s.observed} observed`,
` budget: ${budget}`,
+ ` segments: ${segments.join(', ') || 'none'}`,
].join('\n')
}
diff --git a/plugins/ruflo-mods/hooks/trust.ts b/plugins/ruflo-mods/hooks/trust.ts
new file mode 100644
index 0000000000..26ca4e7419
--- /dev/null
+++ b/plugins/ruflo-mods/hooks/trust.ts
@@ -0,0 +1,103 @@
+import type { On } from 'claude-code'
+
+/**
+ * The mod trust gate (ADR-404). Claude Code can now write, install and
+ * hot-reload a mod mid-session, and a mod runs with Claude Code's own access.
+ * A user-tier hook on `plugin.register` judges every hooks module admitted
+ * after it (and every reload), reading what the host scanned the module to
+ * use; it may answer `{ refuse }`. This gate names what a module could do and,
+ * only when the person opts in, refuses user-tier modules that can do the
+ * risky things below. It reads the scan, never the module's own claims.
+ *
+ * What it cannot do: judge modules admitted before it (the host orders
+ * admission), or any prepend/append/builtin module (the organization's and
+ * Claude Code's own, out of a person's reach by design).
+ */
+
+export type TrustPolicy = 'observe' | 'refuse-risky' | 'off'
+
+export type ModuleScan = {
+ readonly name: string
+ readonly tier: string
+ readonly provenance: string
+ readonly uses: { readonly events?: readonly string[]; readonly calls?: readonly string[]; readonly env?: unknown }
+}
+
+/** Calls that reach outside the session: commands, network, the environment. */
+const RISKY_CALLS: Record<string, string> = {
+ 'process.run': 'runs host commands',
+ 'http.fetch': 'makes network requests',
+ 'env.set': 'changes the environment of later hooks and tools',
+}
+
+/** Hooks that decide for, or over, everything else. */
+const RISKY_EVENTS: Record<string, string> = {
+ 'tool.check': 'can answer tool permission verdicts',
+ 'tool.call': 'can rewrite or answer tool calls',
+ '*': 'sees every event',
+ 'classic.*': 'can answer every settings hook',
+ 'plugin.register': 'can refuse other mods',
+ 'prompt.compose': 'can rewrite the system prompt',
+}
+
+const isStrings = (v: unknown): v is readonly string[] => Array.isArray(v) && v.every(s => typeof s === 'string')
+
+/** What a module's scan says it could do that matters, as readable reasons. */
+export function riskOf(scan: ModuleScan): string[] {
+ const calls = isStrings(scan.uses?.calls) ? scan.uses.calls : []
+ const events = isStrings(scan.uses?.events) ? scan.uses.events : []
+ return [
+ ...calls.filter(c => c in RISKY_CALLS).map(c => `${c} (${RISKY_CALLS[c]})`),
+ ...events.filter(ev => ev in RISKY_EVENTS).map(ev => `on ${ev} (${RISKY_EVENTS[ev]})`),
+ ]
+}
+
+export type TrustDecision = { readonly judged: boolean; readonly risk: readonly string[]; readonly refuse?: string }
+
+/**
+ * Judges one registering module. Only user-tier modules other than this one
+ * and the allow-listed are judged; refusal only under `refuse-risky`.
+ */
+export function judge(scan: ModuleScan, policy: TrustPolicy, allow: ReadonlySet<string>): TrustDecision {
+ if (policy === 'off' || scan.tier !== 'user' || scan.name === 'ruflo-mods' || allow.has(scan.name)) {
+ return { judged: false, risk: [] }
+ }
+ const risk = riskOf(scan)
+ return policy === 'refuse-risky' && risk.length > 0
+ ? {
+ judged: true,
+ risk,
+ refuse: `ruflo mod trust (modTrust=refuse-risky): ${scan.name} ${risk.join('; ')}; allow it by name in modTrustAllow`,
+ }
+ : { judged: true, risk }
+}
+
+/** The one line a person reads about a judged module. */
+export const trustLine = (scan: ModuleScan, d: TrustDecision) =>
+ `ruflo mod trust: ${scan.name} (${scan.provenance}) ${d.refuse ? 'REFUSED' : 'loaded'}${d.risk.length ? `; ${d.risk.join('; ')}` : '; no risky calls or hooks'}`
+
+export function registerTrust(on: On, policy: TrustPolicy, allow: ReadonlySet<string>) {
+ if (policy === 'off') return
+ const told = new Set<string>()
+
+ on('plugin.register', async ($, e, next) => {
+ const decision = judge(e, policy, allow)
+ if (!decision.judged) return next(e)
+ const key = `${e.provenance}:${decision.refuse ? 'refused' : 'loaded'}`
+ if (!told.has(key)) {
+ told.add(key)
+ try {
+ $.ui.log(trustLine(e, decision), decision.risk.length ? undefined : { to: 'debug' })
+ } catch {
+ // a withheld ui.log never decides admission
+ }
+ }
+ return decision.refuse ? { refuse: decision.refuse } : next(e)
+ }).catch(($, e, next) =>
+ // Observing, a failure admits as Claude Code would without ruflo; set to
+ // refuse, the gate guards something, so a module it could not judge stays out.
+ policy === 'refuse-risky' && e.tier === 'user' && e.name !== 'ruflo-mods' && !allow.has(e.name)
+ ? { refuse: `ruflo mod trust could not judge ${e.name} (${next.error.message ?? next.error.kind}); refused (modTrust=refuse-risky)` }
+ : next(e),
+ )
+}
diff --git a/plugins/ruflo-mods/scripts/smoke.sh b/plugins/ruflo-mods/scripts/smoke.sh
index e6135c64ca..6f5cabed9f 100755
--- a/plugins/ruflo-mods/scripts/smoke.sh
+++ b/plugins/ruflo-mods/scripts/smoke.sh
@@ -32,7 +32,7 @@ hits=$(grep -rnE '\$\.(http|process|model|mcp)\.' "$HOOKS" || true)
step "5. only the documented events are hooked"
events=$(grep -rhoE "on\('[a-z.*]+'" "$HOOKS" | sort -u | tr '\n' ' ')
-expected="on('agent.spawn' on('command.run' on('prompt.submit' on('session.end' on('session.measure' on('session.start' on('tool.call' on('tool.check' on('turn.complete' "
+expected="on('agent.spawn' on('command.run' on('engine.create' on('plugin.register' on('prompt.submit' on('session.end' on('session.measure' on('session.start' on('tool.call' on('tool.check' on('turn.complete' "
[[ "$events" == "$expected" ]] && ok || bad "got: $events"
step "6. tool.check merges with stricter() (tighten-only)"
@@ -51,5 +51,10 @@ step "9. every hooks file is under 500 lines"
long=$(find "$HOOKS" -name '*.ts' -exec awk 'END { if (NR > 500) print FILENAME }' {} \;)
[[ -z "$long" ]] && ok || bad "$long"
+step "10. the \$.ruflo contract is declared and flat (one input per method)"
+grep -q '"types": "./types/index.d.ts"' "$ROOT/.claude-plugin/plugin.json" \
+ && grep -q "ruflo: Ruflo" "$ROOT/types/index.d.ts" \
+ && ! grep -qE "^\s+[a-z]+: \{" "$ROOT/types/index.d.ts" && ok || bad "types/index.d.ts must declare a flat Ruflo noun"
+
printf "\n%d passed, %d failed\n" "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]]
diff --git a/plugins/ruflo-mods/tests/cost.test.ts b/plugins/ruflo-mods/tests/cost.test.ts
new file mode 100644
index 0000000000..36094fb276
--- /dev/null
+++ b/plugins/ruflo-mods/tests/cost.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import { consumer, run } from './fixtures/consumer'
+import { START, world } from './fixtures/world'
+
+tier('user')
+
+const measure = (usd: number) => ({ context: { window: 200_000 }, rateLimits: [], cost: { usd }, changed: ['cost' as const] })
+
+describe('cost', () => {
+ test('the budget ladder says each rung once on the way up; HARD_STOP halts new agents', { plugins: [consumer], options: { costBudgetUsd: 2, costHardStop: true } }, async ($, on) => {
+ world(on)
+ const toasts: string[] = []
+ on('ui.toast', ($, e) => (toasts.push(e.text), { value: undefined }))
+ on('session.measure', ($, e) => ({ changed: e.changed }))
+ on('agent.spawn', () => ({ model: 'sonnet' }))
+ on('command.run', () => ({ text: 'core' }))
+ await $.session.start(START)
+
+ const spawn = () =>
+ $.agent.spawn({ prompt: 'p', description: 'd', subagentType: 'coder' } as Parameters<typeof $.agent.spawn>[0])
+ expect(await spawn()).toEqual({ model: 'sonnet' })
+ for (const usd of [0.5, 1.1, 1.2, 1.6, 1.85, 2.4]) await $.session.measure(measure(usd))
+
+ expect(toasts.map(t => t.split(':')[0])).toEqual(['ruflo budget INFO', 'ruflo budget WARNING', 'ruflo budget CRITICAL', 'ruflo budget HARD_STOP'])
+ expect((await spawn()).deny).toMatch(/halted \(costHardStop\)/)
+ expect(JSON.parse((await $.command.run(run('consumer-snapshot'))).text ?? 'null').budget).toEqual({ level: 'HARD_STOP', usd: 2.4, limit: 2 })
+ })
+})
diff --git a/plugins/ruflo-mods/tests/fixtures/consumer.ts b/plugins/ruflo-mods/tests/fixtures/consumer.ts
new file mode 100644
index 0000000000..a5486c5037
--- /dev/null
+++ b/plugins/ruflo-mods/tests/fixtures/consumer.ts
@@ -0,0 +1,27 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * Another mod using `$.ruflo` the way ruOS and ruflo-ruos do: from its own
+ * hooks. `/consumer <json>` calls the method named in the JSON and answers
+ * what it resolved to, or `error: <message>` when the call rejected.
+ */
+export const consumer: Plugin = {
+ name: 'consumer',
+ tier: 'user',
+ register: on => {
+ on('command.run', { command: 'consumer-segment' }, async ($, e) => {
+ const input = JSON.parse(e.args) as { id: string; text: string | null }
+ try {
+ await $.ruflo.segment(input)
+ return { text: 'ok' }
+ } catch (error) {
+ return { text: `error: ${String((error as Error)?.message ?? error)}` }
+ }
+ })
+ on('command.run', { command: 'consumer-last-route' }, async $ => ({ text: JSON.stringify(await $.ruflo.lastRoute()) }))
+ on('command.run', { command: 'consumer-snapshot' }, async $ => ({ text: JSON.stringify(await $.ruflo.snapshot()) }))
+ },
+}
+
+const PRESENTATION = { isFullscreen: false, columns: 100 }
+export const run = (command: string, args = '') => ({ command, args, origin: { kind: 'composer' as const }, presentation: PRESENTATION })
diff --git a/plugins/ruflo-mods/tests/noun.test.ts b/plugins/ruflo-mods/tests/noun.test.ts
new file mode 100644
index 0000000000..948be04f40
--- /dev/null
+++ b/plugins/ruflo-mods/tests/noun.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import { consumer, run } from './fixtures/consumer'
+import { prompt, START, world } from './fixtures/world'
+
+tier('user')
+
+const segment = (id: string, text: string | null) => run('consumer-segment', JSON.stringify({ id, text }))
+
+describe('noun', () => {
+ test('$.ruflo.segment composes other mods into the one bar: sanitised, bounded, sorted, cleared by null', { plugins: [consumer] }, async ($, on) => {
+ const w = world(on)
+ on('prompt.submit', ($, e) => ({ text: e.text }))
+ on('command.run', () => ({ text: 'core' }))
+ await $.session.start(START)
+ await $.prompt.submit(prompt('write tests'))
+
+ expect((await $.command.run(segment('ruos', 'ruOS 1/2 agents\u001b[31m · Work‮Desktop'))).text).toBe('ok')
+ expect((await $.command.run(segment('aaa', 'x'.repeat(200)))).text).toBe('ok')
+ expect(w.statuses.at(-1)).toBe(`ruflo · tester 60% · ${'x'.repeat(47)}… · ruOS 1/2 agents [31m · Work Desktop`)
+
+ await $.command.run(segment('aaa', null))
+ expect(w.statuses.at(-1)).toBe('ruflo · tester 60% · ruOS 1/2 agents [31m · Work Desktop')
+
+ expect((await $.command.run(segment('bad id!', 'x'))).text).toMatch(/^error: /)
+ for (let i = 0; i < 7; i++) await $.command.run(segment(`s${i}`, 'y'))
+ expect((await $.command.run(segment('one-too-many', 'z'))).text).toMatch(/at most 8/)
+ })
+
+ test('lastRoute and snapshot answer copies of what the mod measured, nothing invented', { plugins: [consumer] }, async ($, on) => {
+ world(on)
+ on('prompt.submit', ($, e) => ({ text: e.text }))
+ on('command.run', () => ({ text: 'core' }))
+ await $.session.start(START)
+ expect((await $.command.run(run('consumer-last-route'))).text).toBe('null')
+
+ await $.prompt.submit(prompt('hello'))
+ expect(JSON.parse((await $.command.run(run('consumer-last-route'))).text ?? 'null')).toEqual({
+ agent: 'coder',
+ confidence: 0.3,
+ matched: false,
+ reason: 'no-match-default',
+ })
+ const snap = JSON.parse((await $.command.run(run('consumer-snapshot'))).text ?? 'null')
+ expect(snap).toMatchObject({ owned: ['route', 'post-edit'], routed: 1, policy: 'none', tightened: 0, edits: 0, segments: [] })
+ expect(snap.budget).toBeUndefined()
+ })
+})
diff --git a/plugins/ruflo-mods/tests/register.test.ts b/plugins/ruflo-mods/tests/register.test.ts
index 2870aec623..ef7c0c46b4 100644
--- a/plugins/ruflo-mods/tests/register.test.ts
+++ b/plugins/ruflo-mods/tests/register.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, test, tier } from 'claude-code/testing'
+import type { Plugin } from 'claude-code/testing'
import { HELPER, prompt, ROOT, START, world } from './fixtures/world'
@@ -8,7 +9,30 @@ const CLASSIC_ROUTE = {
hooks: { UserPromptSubmit: [{ hooks: [{ command: 'node "$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs" route' }] }] },
}
+/** A second tighten-only guard, as ruOS ships one: deny destructive ruOS tools. */
+const ruosGuard: Plugin = {
+ name: 'ruos-guard',
+ tier: 'user',
+ register: on => {
+ on('tool.check', async ($, e, next) => {
+ const verdict = await next(e)
+ return /^mcp__ruos__(desktop|secret)_delete$/.test(e.tool) ? { decision: 'deny', reason: 'ruos: confirm first' } : verdict
+ })
+ },
+}
+
describe('register', () => {
+ test('two tighten-only tool.check mods compose: a deny from either holds, nothing loosens', { plugins: [ruosGuard] }, async ($, on) => {
+ world(on)
+ on('tool.check', ($, e) => (e.tool === 'Read' ? { decision: 'deny', reason: 'rule', rule: 'Read(.env)' } : { decision: 'allow' }))
+ await $.session.start(START)
+
+ expect(await $.tool.check({ tool: 'mcp__ruos__desktop_delete', input: {} })).toMatchObject({ decision: 'deny', reason: 'ruos: confirm first' })
+ expect((await $.tool.check({ tool: 'Bash', input: { command: 'rm -rf /' } })).decision).toBe('deny')
+ expect(await $.tool.check({ tool: 'Read', input: { file_path: '.env' } })).toMatchObject({ decision: 'deny', rule: 'Read(.env)' })
+ expect((await $.tool.check({ tool: 'Bash', input: { command: 'ls' } })).decision).toBe('allow')
+ })
+
test('owns route and post-edit where no classic hook runs them, and says so to the classic hooks', async ($, on) => {
const w = world(on)
await $.session.start(START)
diff --git a/plugins/ruflo-mods/tests/trust.test.ts b/plugins/ruflo-mods/tests/trust.test.ts
new file mode 100644
index 0000000000..7813114bf9
--- /dev/null
+++ b/plugins/ruflo-mods/tests/trust.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+import type { Plugin } from 'claude-code/testing'
+
+import { START, world } from './fixtures/world'
+
+tier('user')
+
+const autoAllow: Plugin = {
+ name: 'auto-allow',
+ tier: 'user',
+ register: on => {
+ on('tool.check', () => ({ decision: 'allow' }))
+ },
+}
+const quiet: Plugin = {
+ name: 'quiet',
+ tier: 'user',
+ register: on => {
+ on('turn.complete', ($, e, next) => next(e))
+ },
+}
+
+describe('trust', () => {
+ test('observe (default): names what a later mod can do, and loads it', { plugins: [autoAllow, quiet] }, async ($, on) => {
+ const w = world(on)
+ on('tool.check', () => ({ decision: 'ask' }))
+ await $.session.start(START)
+
+ expect(w.logs.join('\n')).toContain('ruflo mod trust: auto-allow')
+ expect(w.logs.join('\n')).toContain('on tool.check (can answer tool permission verdicts)')
+ })
+
+ test(
+ 'refuse-risky: a later user-tier mod that can answer tool verdicts is refused at load',
+ { plugins: [autoAllow], options: { modTrust: 'refuse-risky' } },
+ async ($, on) => {
+ world(on)
+ on('tool.check', () => ({ decision: 'ask' }))
+ // The host refuses the module at load and the test engine reports it,
+ // naming who refused and why.
+ await expect($.session.start(START)).rejects.toThrow(/auto-allow: refused by ruflo-mods: .*can answer tool permission verdicts/)
+ },
+ )
+
+ test('refuse-risky loads a mod that does nothing risky', { plugins: [quiet], options: { modTrust: 'refuse-risky' } }, async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ expect(w.logs.join('\n')).not.toContain('REFUSED')
+ })
+
+ test(
+ 'refuse-risky honours the allow-list',
+ { plugins: [autoAllow], options: { modTrust: 'refuse-risky', modTrustAllow: 'auto-allow' } },
+ async ($, on) => {
+ world(on)
+ on('tool.check', () => ({ decision: 'ask' }))
+ await $.session.start(START)
+
+ expect((await $.tool.check({ tool: 'Read', input: { file_path: 'a' } })).decision).toBe('allow')
+ },
+ )
+})
diff --git a/plugins/ruflo-mods/tsconfig.json b/plugins/ruflo-mods/tsconfig.json
index 54f8e34062..0890edd166 100644
--- a/plugins/ruflo-mods/tsconfig.json
+++ b/plugins/ruflo-mods/tsconfig.json
@@ -1,17 +1,4 @@
{
- "compilerOptions": {
- "target": "es2023",
- "lib": ["es2023"],
- "types": [],
- "module": "esnext",
- "moduleResolution": "bundler",
- "strict": true,
- "noUncheckedIndexedAccess": true,
- "noEmit": true,
- "skipLibCheck": true,
- "jsx": "react",
- "jsxFactory": "h",
- "jsxFragmentFactory": "Fragment"
- },
- "include": [".claude/types", "hooks", "tests"]
+ "//": "Claude Code (>= 2.1.287) writes its authoritative declarations and this base config into .claude-plugin/types/ when it loads the plugin (gitignored there). Load it once, or run `claude plugin validate .`, then `tsc -p .`",
+ "extends": "./.claude-plugin/types/tsconfig.json"
}
diff --git a/plugins/ruflo-mods/types/index.d.ts b/plugins/ruflo-mods/types/index.d.ts
new file mode 100644
index 0000000000..fbb3164494
--- /dev/null
+++ b/plugins/ruflo-mods/types/index.d.ts
@@ -0,0 +1,67 @@
+/**
+ * The `$.ruflo` noun (ADR-404): the one contract for it, exported here and
+ * declared on `EngineInterface`, as the telemetry mod keeps `$.telemetry`'s.
+ *
+ * The ruflo mod adds it in the `engine.create` fold. Every method is flat,
+ * `$.ruflo.<method>(input)`, the only shape `claude plugin validate` accepts.
+ * Where the ruflo mod is not seated there is no `$.ruflo`, and a call rejects:
+ * a consumer (ruOS, ruflo-ruos, ruflo-swarm) catches and degrades.
+ *
+ * Stable: other mods vendor this file with a parity test. A change here is a
+ * breaking change for them; add, never rename.
+ */
+
+/**
+ * One segment of the ruflo status bar, contributed by another mod.
+ *
+ * `id`: 1-32 characters of letters, digits, `_` or `-`, the contributor's
+ * own name (`ruos`). `text`: what to show; `null` (or text that sanitises to
+ * nothing) removes the segment. Text is untrusted: control and bidi-override
+ * characters are stripped, whitespace collapsed, and it is cut to 48
+ * characters. At most 8 segments; a new id past that rejects. Segments are
+ * shown sorted by id, after ruflo's own parts.
+ */
+export type RufloSegment = { id: string; text: string | null }
+
+/** The last prompt route the mod made, as the model was told it. */
+export type RufloRoute = {
+ agent: string
+ /** A heuristic prior, not a calibrated probability: 0.6 on a keyword match, 0.3 on none (#3567). */
+ confidence: number
+ matched: boolean
+ reason: string
+}
+
+/** What the mod knows this process: nothing estimated, nothing invented. */
+export type RufloSnapshot = {
+ /** Classic events the mod runs in-process; empty when classic hooks keep them. */
+ owned: readonly ('route' | 'post-edit')[]
+ routed: number
+ lastRoute: RufloRoute | null
+ /** `none`: no ruflo policy for Claude Code tools. `unreadable`: present, failing closed. */
+ policy: 'none' | 'legacy' | 'observe' | 'enforce' | 'unreadable'
+ /** Tool calls ruflo tightened (allow to ask or deny, ask to deny). */
+ tightened: number
+ /** Calls observe-mode policy would have tightened. */
+ observed: number
+ edits: number
+ /** Absent when no budget is set. */
+ budget?: { level: 'OK' | 'INFO' | 'WARNING' | 'CRITICAL' | 'HARD_STOP'; usd?: number; limit: number }
+ segments: readonly { id: string; text: string }[]
+}
+
+export type Ruflo = {
+ /** Sets (or with `text: null` removes) one status bar segment. */
+ segment: (input: RufloSegment) => Promise<void>
+ /** The last route, or null before the first owned prompt. */
+ lastRoute: () => Promise<RufloRoute | null>
+ /** Everything above at once. */
+ snapshot: () => Promise<RufloSnapshot>
+}
+
+declare module 'claude-code' {
+ interface EngineInterface {
+ /** ruflo's routing, policy and status state; present where the ruflo mod is seated. */
+ ruflo: Ruflo
+ }
+}
diff --git a/scripts/ci-test-baseline.txt b/scripts/ci-test-baseline.txt
index 6393e076c1..a2f1eb3c2b 100644
--- a/scripts/ci-test-baseline.txt
+++ b/scripts/ci-test-baseline.txt
@@ -11,6 +11,10 @@ plugins/ruflo-adr/scripts/__tests__/verify-read-safety-3147.test.mjs
plugins/ruflo-business-pods/scripts/pod-tick.test.mjs
plugins/ruflo-core/scripts/escape-cmd-arg.test.cjs
plugins/ruflo-core/scripts/mcp-launch.test.cjs
+plugins/ruflo-mods/tests/cost.test.ts
+plugins/ruflo-mods/tests/noun.test.ts
+plugins/ruflo-mods/tests/register.test.ts
+plugins/ruflo-mods/tests/trust.test.ts
plugins/ruflo-workflows/scripts/gaia-audit.test.mjs
ruflo/src/ruvocal/src/lib/components/chat/MarkdownRenderer.svelte.test.ts
ruflo/src/ruvocal/src/lib/migrations/migrations.spec.ts
diff --git a/v3/@claude-flow/cli/__tests__/mods/harness.ts b/v3/@claude-flow/cli/__tests__/mods/harness.ts
index de3326462f..406bb24f13 100644
--- a/v3/@claude-flow/cli/__tests__/mods/harness.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/harness.ts
@@ -180,5 +180,10 @@ export function loadMod(register: (on: any, options: any) => unknown, world: Wor
return run(0, e);
}
- return { $, dispatch, regs, events: () => [...new Set(regs.map((r) => r.event))] };
+ /** Runs the engine.create fold over `$` (core answers `$` as built so far). */
+ async function create(): Promise<any> {
+ return dispatch('engine.create', { plugins: ['ruflo-mods'] }, () => $);
+ }
+
+ return { $, dispatch, create, regs, events: () => [...new Set(regs.map((r) => r.event))] };
}
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts
index 9f278373c9..be2b48cea1 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts
@@ -135,14 +135,21 @@ describe('ADR-404 ruflo verdicts', () => {
}
});
- it('a hook failure is caught: allow becomes ask, nothing loosens', async () => {
+ it('a refused ui.log is swallowed: observe still changes nothing', async () => {
const world = memoryWorld();
withProjection(world, 'observe', [DENY_BASH_RULE]);
- world.failLog = true; // observe logs, the log throws, the hook fails
+ world.failLog = true;
const mod = await started(world);
- expect(await check(mod, 'Bash', { command: 'git push' }, { decision: 'allow' })).toMatchObject({ decision: 'ask' });
- const deny = { decision: 'deny' as D, rule: 'x' };
- expect(await check(mod, 'Bash', { command: 'git push' }, deny)).toBe(deny);
+ const chain = { decision: 'allow' as D };
+ expect(await check(mod, 'Bash', { command: 'git push' }, chain)).toBe(chain);
+ });
+
+ it('when the world beneath fails, the catch answers ask: ruflo could not judge', async () => {
+ const mod = await started(memoryWorld());
+ const out = await mod.dispatch('tool.check', { tool: 'Read', input: {}, tool_use_id: 'x' }, () => {
+ throw new Error('engine verdict failed');
+ });
+ expect(out).toMatchObject({ decision: 'ask' });
});
it('an absent projection is no policy, not a failure', async () => {
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-noun-trust.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-noun-trust.test.ts
new file mode 100644
index 0000000000..377dd04189
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-noun-trust.test.ts
@@ -0,0 +1,87 @@
+/**
+ * ADR-404 — the $.ruflo noun (segments) and the mod trust gate, through the
+ * harness (CI). The same behaviour runs on the real engine in
+ * plugins/ruflo-mods/tests/{noun,trust}.test.ts.
+ */
+import { describe, it, expect } from 'vitest';
+
+import { register } from '../../../../../plugins/ruflo-mods/hooks/register';
+import { judge, riskOf } from '../../../../../plugins/ruflo-mods/hooks/trust';
+import { MAX_SEGMENTS, createState, setSegment, statusText } from '../../../../../plugins/ruflo-mods/hooks/state';
+import { loadMod, memoryWorld } from './harness';
+
+describe('ADR-404 $.ruflo noun', () => {
+ it('engine.create adds ruflo and keeps everything beneath', async () => {
+ const mod = loadMod(register, memoryWorld());
+ const built = await mod.create();
+ expect(typeof built.ruflo.segment).toBe('function');
+ expect(typeof built.fs.read).toBe('function');
+ });
+
+ it('segments: untrusted text sanitised, bounded, sorted; null clears; bad ids and overflow reject', async () => {
+ const world = memoryWorld();
+ const mod = loadMod(register, world);
+ const built = await mod.create();
+ await mod.dispatch('session.start', { cwd: '/work', surface: null, isInteractive: false }, (e) => ({ cwd: e.cwd }));
+ await built.ruflo.segment({ id: 'ruos', text: 'a\u0007b‮\n\tc' });
+ await built.ruflo.segment({ id: 'aa', text: 'z'.repeat(100) });
+ expect(world.statuses.at(-1)).toBe(`ruflo · ${'z'.repeat(47)}… · a b c`);
+ await built.ruflo.segment({ id: 'aa', text: null });
+ expect(world.statuses.at(-1)).toBe('ruflo · a b c');
+ await expect(built.ruflo.segment({ id: '../x', text: 'y' })).rejects.toThrow();
+ await expect(built.ruflo.segment({ id: 'ok', text: 42 })).rejects.toThrow();
+ });
+
+ it('caps at MAX_SEGMENTS and an empty bar clears the line', () => {
+ const s = createState();
+ for (let i = 0; i < MAX_SEGMENTS; i++) setSegment(s, { id: `s${i}`, text: 'x' });
+ expect(() => setSegment(s, { id: 'more', text: 'x' })).toThrow(/at most/);
+ setSegment(s, { id: 's0', text: 'updated' }); // an existing id may change
+ const empty = createState();
+ expect(statusText(empty)).toBeUndefined();
+ });
+
+ it('snapshot answers measured facts only, as copies', async () => {
+ const mod = loadMod(register, memoryWorld());
+ const built = await mod.create();
+ await mod.dispatch('session.start', { cwd: '/work', surface: null, isInteractive: false }, (e) => ({ cwd: e.cwd }));
+ await mod.dispatch('prompt.submit', { text: 'design the architecture', wait: false, origin: { kind: 'composer' } }, (e) => e);
+ const snap = await built.ruflo.snapshot();
+ expect(snap).toMatchObject({ routed: 1, lastRoute: { agent: 'architect', matched: true, confidence: 0.6 }, policy: 'none' });
+ snap.lastRoute.agent = 'mutated';
+ expect((await built.ruflo.lastRoute()).agent).toBe('architect');
+ });
+});
+
+describe('ADR-404 mod trust gate', () => {
+ const scan = (over: object) => ({ name: 'm', tier: 'user', provenance: 'm@inline', uses: { events: [], calls: [] }, ...over });
+
+ it('names risky calls and hooks from the host scan', () => {
+ expect(riskOf(scan({ uses: { events: ['tool.check', 'turn.complete'], calls: ['process.run', 'fs.read', 'http.fetch'] } }))).toEqual([
+ 'process.run (runs host commands)', 'http.fetch (makes network requests)', 'on tool.check (can answer tool permission verdicts)',
+ ]);
+ expect(riskOf(scan({ uses: { events: 'nope', calls: [1] } as never }))).toEqual([]);
+ });
+
+ it('judges only other user-tier modules; refuses only under refuse-risky', () => {
+ const risky = scan({ uses: { events: ['*'], calls: [] } });
+ expect(judge(risky, 'observe', new Set()).refuse).toBeUndefined();
+ expect(judge(risky, 'refuse-risky', new Set()).refuse).toMatch(/sees every event/);
+ expect(judge(risky, 'refuse-risky', new Set(['m'])).judged).toBe(false);
+ expect(judge({ ...risky, tier: 'prepend' }, 'refuse-risky', new Set()).judged).toBe(false);
+ expect(judge({ ...risky, name: 'ruflo-mods' }, 'refuse-risky', new Set()).judged).toBe(false);
+ expect(judge(risky, 'off', new Set()).judged).toBe(false);
+ });
+
+ it('through the hook: refuse-risky refuses, a failing gate refuses rather than admits', async () => {
+ const world = memoryWorld();
+ const mod = loadMod(register, world, { modTrust: 'refuse-risky' });
+ const e = { name: 'evil', tier: 'user', root: '/x', provenance: 'evil@inline', uses: { events: ['tool.check'], calls: [] } };
+ expect((await mod.dispatch('plugin.register', e, () => ({ allow: true }))).refuse).toMatch(/refuse-risky/);
+ expect(await mod.dispatch('plugin.register', { ...e, uses: { events: ['turn.complete'], calls: [] } }, () => ({ allow: true }))).toEqual({ allow: true });
+ expect(world.logs.join('\n')).toContain('REFUSED');
+ const observing = loadMod(register, memoryWorld());
+ expect(await observing.dispatch('plugin.register', e, () => ({ allow: true }))).toEqual({ allow: true });
+ expect(loadMod(register, memoryWorld(), { modTrust: 'off' }).events()).not.toContain('plugin.register');
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
index ca8e11d9bc..2873769a14 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
@@ -29,6 +29,7 @@ const CLASSIC = {
async function start(world: World, options: Record<string, unknown> = {}) {
const mod = loadMod(register, world, options);
+ await mod.create(); // the engine runs the engine.create fold before any other hook
const next = await mod.dispatch('session.start', { cwd: world.root, surface: 'terminal', isInteractive: true }, (e) => ({ cwd: e.cwd }));
return { mod, next };
}
@@ -106,11 +107,11 @@ describe('ADR-404 session start', () => {
const world = memoryWorld('/work', { statusLine: { type: 'command', command: 'node .claude/helpers/statusline.cjs' } });
const { mod } = await start(world);
await mod.dispatch('prompt.submit', { text: 'build', wait: false, origin: { kind: 'composer' } }, (e) => e);
- expect(world.statuses).toEqual([]);
+ expect(world.statuses.filter(Boolean)).toEqual([]); // cleared, never drawn
const plain = memoryWorld('/work', {});
const started = await start(plain);
await started.mod.dispatch('prompt.submit', { text: 'build', wait: false, origin: { kind: 'composer' } }, (e) => e);
- expect(plain.statuses).toEqual(['ruflo · coder 60%']);
+ expect(plain.statuses.filter(Boolean)).toEqual(['ruflo · coder 60%']);
});
});