🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(ruflo-mods): agentTrim option hooks agent.offer (default off), ADR-451 item 2; 0.3.1
ruv33a60c715f9a
diff --git a/plugins/ruflo-mods/.claude-plugin/plugin.json b/plugins/ruflo-mods/.claude-plugin/plugin.jsonindex f094ec9613..a250616cdc 100644--- a/plugins/ruflo-mods/.claude-plugin/plugin.json+++ b/plugins/ruflo-mods/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-mods","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.3.0",+ "version": "0.3.1","author": {"name": "ruvnet","url": "https://github.com/ruvnet"@@ -54,6 +54,20 @@"required": false,"default": false},+ "agentTrim": {+ "type": "boolean",+ "title": "Hide unused agent types",+ "description": "Keep agent types the project does not use out of the model's agent listing and dispatch, to save prompt tokens. Always kept: built-in agents, coder, reviewer, tester, planner, researcher, any type used in the last 30 days, any named in the prompt or in agentTrimKeep. Off by default.",+ "required": false,+ "default": false+ },+ "agentTrimKeep": {+ "type": "string",+ "title": "Agent types to never hide",+ "description": "Comma-separated agent type names that agentTrim must keep offered.",+ "required": false,+ "default": ""+ },"modTrust": {"type": "string","title": "Mod trust gate",diff --git a/plugins/ruflo-mods/hooks/agents/index.ts b/plugins/ruflo-mods/hooks/agents/index.tsnew file mode 100644index 0000000000..7f15ff020b--- /dev/null+++ b/plugins/ruflo-mods/hooks/agents/index.ts@@ -0,0 +1,52 @@+import type { EngineInterface, On } from 'claude-code'++import type { ModOptions } from '../options'+import type { ModState } from '../state'+import { isKept, readUsage, type Usage } from './trim'++const LEDGER = 'agentUse'++/**+ * `agent.offer` (ADR-451 item 2): keeps agent types the project does not use+ * out of the model's listing and out of dispatch. Off unless `agentTrim` is+ * on. A type stays when it is built in, a pinned core role, named in+ * `agentTrimKeep`, used in the last 30 days (the `$.store` ledger, fed by+ * `agent.spawn`), or named in the current prompt. Tighten-only on what the+ * model sees; any failure offers the type (the hook is skipped).+ */+export function registerAgents(on: On, state: ModState, options: ModOptions) {+ state.agentTrim.enabled = true++ on('agent.spawn', { subagentType: /^.+$/ }, async ($, e, next) => {+ try {+ const usage = await loadLedger($, state)+ usage[e.subagentType] = await $.clock.now()+ await $.store.set(LEDGER, usage)+ } catch {+ // an unwritable ledger only means the type may be hidden next session+ }+ return next(e)+ })++ on('agent.offer', async ($, e, next) => {+ const result = await next(e)+ if (!result.isOffered) return result+ const kept = isKept(e, { keep: options.agentTrimKeep, usage: await loadLedger($, state), prompt: state.agentTrim.prompt, now: await $.clock.now() })+ if (kept) return result+ const first = state.agentTrim.hidden.size === 0+ state.agentTrim.hidden.add(e.agent)+ if (first) {+ try {+ $.ui.toast('ruflo agentTrim: unused agent types are hidden from the model (see /ruflo-mods)')+ } catch {+ // a refused toast never changes the answer+ }+ }+ return { ...result, isOffered: false }+ }).catch(($, e, next) => next(e)) // fail open: a broken trim offers the type+}++/** The usage ledger, read once per process; a failed read is an empty ledger. */+function loadLedger($: EngineInterface, state: ModState): Promise<Usage> {+ return (state.agentTrim.ledger ??= $.store.get(LEDGER).then(readUsage, () => readUsage(undefined)))+}diff --git a/plugins/ruflo-mods/hooks/agents/trim.ts b/plugins/ruflo-mods/hooks/agents/trim.tsnew file mode 100644index 0000000000..d75aa9b28c--- /dev/null+++ b/plugins/ruflo-mods/hooks/agents/trim.ts@@ -0,0 +1,41 @@+/** Agent types never hidden: the core roles ADR-451 pins, plus the engine's own. */+export const PINNED: ReadonlySet<string> = new Set([+ 'coder', 'reviewer', 'tester', 'planner', 'researcher', 'general-purpose', 'explore', 'plan', 'claude', 'fork',+])++export const USED_WINDOW_MS = 30 * 24 * 60 * 60 * 1000++/** Last-used time (ms) by agent type: the `$.store` ledger. */+export type Usage = Record<string, number>++export type Offer = { agent: string; source: string }++export type TrimContext = {+ /** Types the person named in `agentTrimKeep`, lower case. */+ keep: ReadonlySet<string>+ usage: Usage+ /** The latest prompt, lower case; a type it names is kept. */+ prompt: string+ now: number+}++/** `plugin:role` and `role` are the same role for pinning and naming. */+const bare = (agent: string) => agent.slice(agent.lastIndexOf(':') + 1).toLowerCase()++/** The usage ledger as stored: only finite, non-negative times under plain names survive. */+export function readUsage(value: unknown): Usage {+ const out: Usage = Object.create(null)+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return out+ for (const [name, at] of Object.entries(value)) if (typeof at === 'number' && Number.isFinite(at) && at >= 0) out[name] = at+ return out+}++/** Whether the type stays offered. Fail-open by construction: anything unclear is kept. */+export function isKept(offer: Offer, ctx: TrimContext): boolean {+ if (offer.source === 'built-in') return true+ const name = bare(offer.agent)+ if (!name || PINNED.has(name) || ctx.keep.has(name) || ctx.keep.has(offer.agent.toLowerCase())) return true+ const at = ctx.usage[offer.agent]+ if (typeof at === 'number' && ctx.now - at < USED_WINDOW_MS) return true+ return ctx.prompt.includes(offer.agent.toLowerCase()) || ctx.prompt.includes(name)+}diff --git a/plugins/ruflo-mods/hooks/options.ts b/plugins/ruflo-mods/hooks/options.tsindex 71dac24110..04799bec9c 100644--- a/plugins/ruflo-mods/hooks/options.ts+++ b/plugins/ruflo-mods/hooks/options.ts@@ -12,6 +12,8 @@ export type ModOptions = {readonly costBudgetUsd?: numberreadonly costHardStop: booleanreadonly toolHints: boolean+ readonly agentTrim: boolean+ readonly agentTrimKeep: ReadonlySet<string>readonly modTrust: TrustPolicyreadonly modTrustAllow: ReadonlySet<string>}@@ -37,7 +39,15 @@ export function readOptions(options: PluginOptions | undefined): ModOptions {costBudgetUsd: budgetOf(o.costBudgetUsd),costHardStop: bool(o.costHardStop, false),toolHints: bool(o.toolHints, false),+ agentTrim: bool(o.agentTrim, false),+ agentTrimKeep: keepNames(o.agentTrimKeep),modTrust: TRUST.includes(o.modTrust as TrustPolicy) ? (o.modTrust as TrustPolicy) : 'observe',modTrustAllow: names(o.modTrustAllow),}}++/** Agent type names to never hide, from a comma list or a string array; lower case, plain names only. */+function keepNames(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().toLowerCase()).filter(v => /^[a-z0-9._:-]{1,64}$/.test(v)))+}diff --git a/plugins/ruflo-mods/hooks/register.ts b/plugins/ruflo-mods/hooks/register.tsindex 6c5a89e539..f83dedcb1a 100644--- a/plugins/ruflo-mods/hooks/register.ts+++ b/plugins/ruflo-mods/hooks/register.ts@@ -1,5 +1,6 @@import type { Register } from 'claude-code'+import { registerAgents } from './agents'import { registerCost } from './cost'import { registerDescribe } from './describe'import { registerGuard } from './guard'@@ -37,4 +38,5 @@ export const register: Register = (on, options) => {registerLearn(on, state, guidance)registerCost(on, state, opts)if (opts.toolHints) registerDescribe(on, state)+ if (opts.agentTrim) registerAgents(on, state, opts)}diff --git a/plugins/ruflo-mods/hooks/route/index.ts b/plugins/ruflo-mods/hooks/route/index.tsindex 42000f3652..6552ac4ecc 100644--- a/plugins/ruflo-mods/hooks/route/index.ts+++ b/plugins/ruflo-mods/hooks/route/index.ts@@ -22,6 +22,7 @@ export function registerRoute(on: On, state: ModState, options: ModOptions, guidon('prompt.submit', async ($, e, next) => {const text = typeof e.text === 'string' ? e.text : ''+ if (state.agentTrim.enabled) state.agentTrim.prompt = text.slice(0, 4000).toLowerCase() // agent.offer keeps a type the prompt namesconst advisory = guidance ? await guidance.prompt(text, { stat: path => $.fs.stat(path), read: path => $.fs.read(path) }) : undefinedconst context = [...(e.context ?? []), ...(advisory ? [advisory] : [])]if (!state.owned.has('route')) return next(advisory ? { ...e, context } : e)diff --git a/plugins/ruflo-mods/hooks/state.ts b/plugins/ruflo-mods/hooks/state.tsindex c97c8aa6e9..939250c697 100644--- a/plugins/ruflo-mods/hooks/state.ts+++ b/plugins/ruflo-mods/hooks/state.ts@@ -30,6 +30,8 @@ export type ModState = {budget: { level: BudgetLevel; usd?: number; limit?: number }/** `tool.describe` hints (ADR-451): whether the feature is on and which tools it described. */toolHints: { enabled: boolean; described: Set<string> }+ /** `agent.offer` trim (ADR-451): whether it is on, the types it hid, and the latest prompt (lower case). */+ agentTrim: { enabled: boolean; hidden: Set<string>; prompt: string; ledger?: Promise<Record<string, number>> }/** Other mods' status segments, by id (`$.ruflo.segment`). */segments: Map<string, string>/**@@ -53,6 +55,7 @@ export function createState(): ModState {policy: 'none',budget: { level: 'OK' },toolHints: { enabled: false, described: new Set() },+ agentTrim: { enabled: false, hidden: new Set(), prompt: '' },segments: new Map(),draw: () => undefined,}@@ -136,6 +139,7 @@ export function report(s: ModState): string {` policy: ${s.policy}; ${s.tightened} call(s) tightened, ${s.observed} observed`,` budget: ${budget}`,` tool hints: ${s.toolHints.enabled ? `${s.toolHints.described.size} tool(s) described` : 'off (set the toolHints option)'}`,+ ` agent trim: ${s.agentTrim.enabled ? `${s.agentTrim.hidden.size} type(s) hidden` : 'off (set the agentTrim option)'}`,` segments: ${segments.join(', ') || 'none'}`,` guidance: ${s.guidance.status}; ${s.guidance.saved} unverified observation(s), ${s.guidance.pending.length} pending, ${s.guidance.dropped} dropped`,].join('\n')diff --git a/plugins/ruflo-mods/scripts/smoke.sh b/plugins/ruflo-mods/scripts/smoke.shindex 3b1e7b99e3..8091204ef2 100755--- a/plugins/ruflo-mods/scripts/smoke.sh+++ b/plugins/ruflo-mods/scripts/smoke.sh@@ -1,5 +1,5 @@#!/usr/bin/env bash-# Structural + security smoke for ruflo-mods v0.3.0 (ADR-404, ADR-447).+# Structural + security smoke for ruflo-mods v0.3.1 (ADR-404, ADR-447).# Static only: CI has no Claude Code, so the hooks module's behaviour is held# by v3/@claude-flow/cli/__tests__/mods/*.test.ts and, where function hooks are# on, by `claude plugin test plugins/ruflo-mods`.@@ -12,9 +12,9 @@ ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }HOOKS="$ROOT/hooks"-step "1. plugin.json declares ruflo-mods 0.3.0"+step "1. plugin.json declares ruflo-mods 0.3.1"grep -q '"name": "ruflo-mods"' "$ROOT/.claude-plugin/plugin.json" \- && grep -q '"version": "0.3.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"+ && grep -q '"version": "0.3.1"' "$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" \@@ -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('engine.create' on('plugin.register' on('prompt.submit' on('session.end' on('session.measure' on('session.start' on('tool.call' on('tool.check' on('tool.describe' on('turn.complete' "+expected="on('agent.offer' 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('tool.describe' on('turn.complete' "[[ "$events" == "$expected" ]] && ok || bad "got: $events"step "6. tool.check merges with stricter() (tighten-only)"diff --git a/plugins/ruflo-mods/tests/agents.test.ts b/plugins/ruflo-mods/tests/agents.test.tsnew file mode 100644index 0000000000..b9b3df2a39--- /dev/null+++ b/plugins/ruflo-mods/tests/agents.test.ts@@ -0,0 +1,88 @@+import { describe, expect, test, tier } from 'claude-code/testing'++import { isKept, readUsage, USED_WINDOW_MS } from '../hooks/agents/trim'+import { consumer, run } from './fixtures/consumer'+import { START, world } from './fixtures/world'++tier('user')++const ENGINE = { plugin: 'engine', tier: 'core' } as never+const offer = (agent: string, source = 'plugin') => ({ agent, description: 'x', source, provider: ENGINE })+const NOW = 1_000_000_000_000+const ctx = (over: Partial<Parameters<typeof isKept>[1]> = {}) => ({ keep: new Set<string>(), usage: {}, prompt: '', now: NOW, ...over })++describe('agent.offer trim (ADR-451)', () => {+ test('off by default: every type stays offered', { plugins: [consumer] }, async ($, on) => {+ world(on)+ memory(on)+ on('agent.offer', () => ({ isOffered: true }))+ on('command.run', () => ({ text: 'core' }))+ await $.session.start(START)++ expect((await $.agent.offer(offer('lab:runner'))).isOffered).toBe(true)+ expect((await $.command.run(run('ruflo-mods'))).text).toContain('agent trim: off')+ })++ test('on: unused plugin types are hidden, pinned, built-in and named ones are kept', { options: { agentTrim: true, agentTrimKeep: 'Lab:Keeper' } }, async ($, on) => {+ world(on)+ memory(on)+ on('agent.offer', () => ({ isOffered: true }))+ on('prompt.submit', ($, e) => ({ text: e.text }))+ await $.session.start(START)+ await $.prompt.submit({ text: 'please use the Specialist agent' } as never)++ expect((await $.agent.offer(offer('lab:runner'))).isOffered).toBe(false)+ expect((await $.agent.offer(offer('coder'))).isOffered).toBe(true)+ expect((await $.agent.offer(offer('ruflo-core:reviewer'))).isOffered).toBe(true)+ expect((await $.agent.offer(offer('Explore', 'built-in'))).isOffered).toBe(true)+ expect((await $.agent.offer(offer('lab:keeper'))).isOffered).toBe(true)+ expect((await $.agent.offer(offer('Specialist'))).isOffered).toBe(true)+ })++ test('a type that was already hidden by another hook stays hidden', { options: { agentTrim: true } }, async ($, on) => {+ world(on)+ memory(on)+ on('agent.offer', () => ({ isOffered: false }))+ await $.session.start(START)+ expect((await $.agent.offer(offer('coder'))).isOffered).toBe(false)+ })++ test('a spawned type is kept afterwards (the ledger), and /ruflo-mods counts the hidden', { options: { agentTrim: true }, plugins: [consumer] }, async ($, on) => {+ world(on)+ memory(on)+ on('agent.offer', () => ({ isOffered: true }))+ on('agent.spawn', () => ({ deny: 'test: no real spawn' }))+ on('command.run', () => ({ text: 'core' }))+ await $.session.start(START)++ expect((await $.agent.offer(offer('lab:runner'))).isOffered).toBe(false)+ await $.agent.spawn({ tool_use_id: 't', prompt: 'p', description: 'd', subagentType: 'lab:runner' } as never).catch(() => undefined)+ expect((await $.agent.offer(offer('lab:runner'))).isOffered).toBe(true)+ expect((await $.command.run(run('ruflo-mods'))).text).toContain('agent trim: 1 type(s) hidden')+ })+})++describe('isKept', () => {+ test('the 30-day window is exclusive at the edge', () => {+ expect(isKept(offer('lab:a'), ctx({ usage: { 'lab:a': NOW - USED_WINDOW_MS + 1 } }))).toBe(true)+ expect(isKept(offer('lab:a'), ctx({ usage: { 'lab:a': NOW - USED_WINDOW_MS } }))).toBe(false)+ })+ test('a hostile ledger cannot keep or crash anything', () => {+ expect(readUsage(null)).toEqual({})+ expect(readUsage([1])).toEqual({})+ expect(Object.keys(readUsage({ a: 'x', b: -1, c: Infinity, d: 5 }))).toEqual(['d'])+ expect(isKept(offer('constructor'), ctx({ usage: readUsage({}) }))).toBe(false)+ })+})++/** The clock and the plugin store, answered from memory. */+function memory(on: Parameters<typeof world>[0]) {+ const store = new Map<string, unknown>()+ on('clock.now', () => ({ value: NOW }))+ on('store.get', ($, e) => ({ value: store.get(e.key) }))+ on('store.set', ($, e) => {+ store.set(e.key, JSON.parse(JSON.stringify(e.value)))+ return { value: undefined }+ })+ return store+}