🌊 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(mods): ruflo-mods plugin — ruflo as a Claude Code mod (ADR-404)
ruvd48897fb3464
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex f046371478..e230377412 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -215,6 +215,11 @@"name": "ruflo-music","source": "./plugins/ruflo-music","description": "AI music generation via Cognitum Music (cogmusic MCP) \u2014 compose lyrics/prompts, generate tracks, separate stems, extract MIDI, and master through your own music.cognitum.one account"+ },+ {+ "name": "ruflo-mods",+ "source": "./plugins/ruflo-mods",+ "description": "Early access (ADR-404): ruflo as a Claude Code mod (function hooks) \u2014 in-process routing, edit learning signals, tighten-only tool checks from ruflo policy, and the cost budget ladder. Opt-in via `ruflo mods install`; classic hooks stay the fallback"}]}diff --git a/plugins/ruflo-mods/.claude-plugin/plugin.json b/plugins/ruflo-mods/.claude-plugin/plugin.jsonnew file mode 100644index 0000000000..653a927cbd--- /dev/null+++ b/plugins/ruflo-mods/.claude-plugin/plugin.json@@ -0,0 +1,49 @@+{+ "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.",+ "version": "0.1.0",+ "author": {+ "name": "ruvnet",+ "url": "https://github.com/ruvnet"+ },+ "homepage": "https://github.com/ruvnet/ruflo",+ "license": "MIT",+ "keywords": [+ "ruflo",+ "mods",+ "function-hooks",+ "routing",+ "policy",+ "cost"+ ],+ "userConfig": {+ "routeContext": {+ "type": "boolean",+ "title": "Ranked memory with routes",+ "description": "Add the ranked-memory block (.claude-flow/data/ranked-context.json) to each prompt's routing context, as the classic route hook does.",+ "required": false,+ "default": true+ },+ "statusLine": {+ "type": "boolean",+ "title": "ruflo status line",+ "description": "Show a one-line ruflo status under the prompt. Never shown where the ruflo statusLine helper is already configured.",+ "required": false,+ "default": true+ },+ "costBudgetUsd": {+ "type": "number",+ "title": "Session budget (USD)",+ "description": "Apply the cost-tracker budget ladder (50/75/90/100%) to this session's live cost. 0 turns it off.",+ "required": false,+ "default": 0+ },+ "costHardStop": {+ "type": "boolean",+ "title": "Halt agents at 100% of budget",+ "description": "At 100% of the session budget, refuse new subagent spawns.",+ "required": false,+ "default": false+ }+ }+}diff --git a/plugins/ruflo-mods/.gitignore b/plugins/ruflo-mods/.gitignorenew file mode 100644index 0000000000..cde8bebf41--- /dev/null+++ b/plugins/ruflo-mods/.gitignore@@ -0,0 +1,2 @@+# /plugin-types output and local copies of the Claude Code declarations (early access, regenerate per release)+.claude/diff --git a/plugins/ruflo-mods/README.md b/plugins/ruflo-mods/README.mdnew file mode 100644index 0000000000..5af39e8b63--- /dev/null+++ b/plugins/ruflo-mods/README.md@@ -0,0 +1,41 @@+# ruflo-mods++ruflo as a Claude Code mod: function hooks, **early access**. Design and evidence: [ADR-404](../../v3/docs/adr/ADR-404-claude-code-mods-function-hooks.md).++```bash+ruflo mods install # opt in for this project (.claude/settings.local.json)+ruflo mods doctor # function hooks on? refused by policy? what does it own?+ruflo mods uninstall # remove only what install added+```++In a session, `/ruflo-mods` reports what the mod owns, routed, recorded and tightened.++## What it does++- **Routing:** `prompt.submit` routes each prompt in-process and hands the route, plus ranked memory, to the model as context. The text is the same as the classic `route` hook produces.+- **Edit learning:** `tool.call` records finished edits for the intelligence consolidator, once per turn.+- **Tool checks:** `tool.check` only tightens. It applies the dangerous-command list and ruflo policy rules that name `claude-code.*` actions (written by the CLI to `.claude-flow/policy/claude-code.json`). It never loosens a verdict.+- **Budget:** `session.measure` applies the cost-tracker budget ladder to live session cost (`costBudgetUsd`); `costHardStop` halts new subagents at 100%.++The classic `hook-handler.cjs` hooks stay installed and remain the fallback. The mod takes an event only where the classic helper hands it over (`RUFLO_MODS_OWNS`), so nothing fires twice. When the mod is not loaded, every classic hook runs as before.++## Options++Set these in the plugin's config:++| Option | Default | Effect |+|---|---|---|+| `routeContext` | `true` | Include ranked memory with routes |+| `statusLine` | `true` | One-line ruflo status. Skipped where the ruflo statusLine helper is configured |+| `costBudgetUsd` | `0` (off) | Session budget for the ladder |+| `costHardStop` | `false` | Refuse new subagents at 100% of budget |++## Tests++```bash+CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test plugins/ruflo-mods # real engine; needs the rollout switch on+cd v3/@claude-flow/cli && npx vitest run __tests__/mods/ # declaration-faithful harness, parity tests+bash plugins/ruflo-mods/scripts/smoke.sh # static security contract+```++To typecheck, copy the declarations `/plugin-types` writes into `plugins/ruflo-mods/.claude/types/`, then run `npx tsc -p plugins/ruflo-mods`.diff --git a/plugins/ruflo-mods/hooks/cost/budget.ts b/plugins/ruflo-mods/hooks/cost/budget.tsnew file mode 100644index 0000000000..e1ad21fb25--- /dev/null+++ b/plugins/ruflo-mods/hooks/cost/budget.ts@@ -0,0 +1,33 @@+/**+ * The ruflo-cost-tracker budget ladder (scripts/budget.mjs `alertLevel`),+ * applied to the session's live cost as `session.measure` pushes it, with no+ * jsonl parse and no node spawn. The parity test reads the thresholds out of+ * budget.mjs.+ */++export type BudgetLevel = 'OK' | 'INFO' | 'WARNING' | 'CRITICAL' | 'HARD_STOP'++export const LEVELS: ReadonlyArray<{ readonly level: BudgetLevel; readonly at: number }> = [+ { level: 'HARD_STOP', at: 1.0 },+ { level: 'CRITICAL', at: 0.9 },+ { level: 'WARNING', at: 0.75 },+ { level: 'INFO', at: 0.5 },+]++const ORDER: Record<BudgetLevel, number> = { OK: 0, INFO: 1, WARNING: 2, CRITICAL: 3, HARD_STOP: 4 }++export function alertLevel(utilization: number): BudgetLevel {+ return LEVELS.find(l => utilization >= l.at)?.level ?? 'OK'+}++/** Whether `next` is a higher rung than `previous`: the one moment to tell. */+export const isRaised = (previous: BudgetLevel, next: BudgetLevel) => ORDER[next] > ORDER[previous]++/**+ * The budget in USD from the plugin option, or undefined when off: anything+ * not a finite positive number is off, never a zero budget that halts at once.+ */+export function budgetOf(option: unknown): number | undefined {+ const n = typeof option === 'string' ? Number(option) : option+ return typeof n === 'number' && Number.isFinite(n) && n > 0 ? n : undefined+}diff --git a/plugins/ruflo-mods/hooks/cost/index.ts b/plugins/ruflo-mods/hooks/cost/index.tsnew file mode 100644index 0000000000..7f09ce9f77--- /dev/null+++ b/plugins/ruflo-mods/hooks/cost/index.ts@@ -0,0 +1,41 @@+import type { On } from 'claude-code'++import type { ModOptions } from '../options'+import { statusText, type ModState } from '../state'+import { alertLevel, isRaised } from './budget'++/**+ * ruflo-cost-tracker's budget ladder on the session's live cost:+ * `session.measure` pushes the figure after each turn, so no transcript parse+ * and no node spawn. Crossing a rung up says so once. With `costHardStop`,+ * the HARD_STOP rung does what budget.mjs recommends at 100%: new subagent+ * spawns are refused (a deny on `agent.spawn`; tightening only).+ */+export function registerCost(on: On, state: ModState, options: ModOptions) {+ const limit = options.costBudgetUsd+ if (limit === undefined) return+ state.budget = { level: 'OK', limit }++ on('session.measure', async ($, e, next) => {+ const result = await next(e)+ const usd = e.cost?.usd+ if (typeof usd !== 'number' || !Number.isFinite(usd) || usd < 0) return result++ const level = alertLevel(usd / limit)+ 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))+ }+ return result+ })++ if (options.costHardStop) {+ on('agent.spawn', ($, e, next) =>+ state.budget.level === 'HARD_STOP'+ ? { deny: `ruflo budget: $${(state.budget.usd ?? 0).toFixed(2)} of $${limit.toFixed(2)} spent; new agents are halted (costHardStop)` }+ : next(e),+ )+ }+}diff --git a/plugins/ruflo-mods/hooks/files.ts b/plugins/ruflo-mods/hooks/files.tsnew file mode 100644index 0000000000..58de3440b0--- /dev/null+++ b/plugins/ruflo-mods/hooks/files.ts@@ -0,0 +1,58 @@+import type { FsStat } from 'claude-code'++/**+ * The two `$.fs` calls a reader needs. The engine reads a module's `$` uses+ * off its source, so `$` itself never leaves a hook: the hook builds this+ * from `$.fs.stat` / `$.fs.read` spelled at the call site.+ */+export type FileHost = {+ readonly stat: (path: string) => Promise<FsStat>+ readonly read: (path: string) => Promise<string>+}++/** Under `$.fs.read`'s own 4 MiB bound, so an oversized file reads as too big. */+export const MAX_READ_BYTES = 4 * 1024 * 1024++export type Read<T> =+ | { readonly kind: 'absent' }+ | { readonly kind: 'ok'; readonly value: T }+ | { readonly kind: 'error'; readonly message: string }++export const isMissing = (error: unknown) => /ENOENT|no such file|not found/i.test(String((error as Error)?.message ?? error))++/**+ * A reader that parses a project file once per change: one `$.fs.stat` per+ * call, a `$.fs.read` and parse only when its size or mtime moved. Absent is+ * a value, not an error; anything else that fails is `error`, which a guard+ * fails closed on.+ *+ * @param pathOf the file's path, resolved per call (it follows the session root)+ * @param parse turns the text into the value; may throw+ */+export function cachedFile<T>(pathOf: () => string, parse: (text: string) => T) {+ let seen: { key: string; read: Read<T> } | undefined++ return async (fs: FileHost): Promise<Read<T>> => {+ const path = pathOf()+ let key: string+ try {+ const stat = await fs.stat(path)+ if (stat.kind !== 'file') return { kind: 'error', message: `${path} is not a file` }+ if (stat.size > MAX_READ_BYTES) return { kind: 'error', message: `${path} is over 4 MiB` }+ key = `${path}:${stat.size}:${stat.mtimeMs}`+ } catch (error) {+ seen = undefined+ return isMissing(error) ? { kind: 'absent' } : { kind: 'error', message: String(error) }+ }+ if (seen?.key === key) return seen.read++ let read: Read<T>+ try {+ read = { kind: 'ok', value: parse(await fs.read(path)) }+ } catch (error) {+ read = isMissing(error) ? { kind: 'absent' } : { kind: 'error', message: String((error as Error)?.message ?? error) }+ }+ seen = { key, read }+ return read+ }+}diff --git a/plugins/ruflo-mods/hooks/guard/dangerous-command.ts b/plugins/ruflo-mods/hooks/guard/dangerous-command.tsnew file mode 100644index 0000000000..3d17e29d34--- /dev/null+++ b/plugins/ruflo-mods/hooks/guard/dangerous-command.ts@@ -0,0 +1,26 @@+import type { Verdict } from './verdict'++/**+ * The commands hook-handler.cjs `pre-bash` refuses, matched the same way+ * (lowercased substring). The parity test reads the list out of+ * hook-handler.cjs and fails CI if the two drift.+ */+export const DANGEROUS_COMMANDS: readonly string[] = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:']++/**+ * A deny for a Bash call whose command is on the list, else undefined.+ *+ * @param tool the tool name as the model calls it+ * @param input the tool's arguments, unvalidated+ */+export function dangerousCommandVerdict(tool: string, input: unknown): Verdict | undefined {+ if (tool !== 'Bash') return undefined+ const raw = input !== null && typeof input === 'object' ? (input as { command?: unknown }).command : undefined+ // Same belt-and-braces as #2017: a non-string command is checked as text,+ // never skipped.+ const command = String(raw ?? '').toLowerCase()+ const hit = DANGEROUS_COMMANDS.find(d => command.includes(d))+ return hit === undefined+ ? undefined+ : { decision: 'deny', reason: `ruflo: dangerous command blocked (${hit})` }+}diff --git a/plugins/ruflo-mods/hooks/guard/index.ts b/plugins/ruflo-mods/hooks/guard/index.tsnew file mode 100644index 0000000000..1cf8794b7f--- /dev/null+++ b/plugins/ruflo-mods/hooks/guard/index.ts@@ -0,0 +1,74 @@+import type { On } from 'claude-code'++import { cachedFile, type Read } from '../files'+import { statusText, 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'++/** What `tool.check` answers when ruflo's own check could not run. */+export const CHECK_FAILED: Verdict = {+ decision: 'ask',+ reason: 'ruflo: its policy check could not run, so this call is put to you instead of allowed',+}++/**+ * Ruflo's opinion on one call, from the dangerous-command list and the read+ * policy projection; `observed` is set when observe mode would have acted.+ */+export function opinionOf(+ state: ModState,+ read: Read<Projection>,+ tool: string,+ input: unknown,+): { verdict?: Verdict; observed?: string } {+ const danger = dangerousCommandVerdict(tool, input)+ if (danger) return { verdict: danger }++ if (read.kind === 'absent') {+ state.policy = 'none'+ return {}+ }+ if (read.kind === 'error') {+ // The CLI writes a projection only where policy is in force: one that+ // exists and cannot be read fails closed, by one step.+ state.policy = 'unreadable'+ return { verdict: { ...CHECK_FAILED, reason: `ruflo: policy projection unreadable (${read.message}); asking instead of allowing` } }+ }+ state.policy = read.value.mode+ const { verdict, wouldBe } = policyOpinion(read.value, tool, input)+ return wouldBe ? { observed: wouldBe } : { verdict }+}++/**+ * `tool.check`: tighten only. The chain runs first (engine rules, mode, the+ * PreToolUse hooks, every plugin beneath); ruflo's opinion is merged with+ * `stricter`, so an allow may become an ask or a deny and nothing ever+ * becomes looser. The dangerous-command list always applies; ruflo policy+ * applies when the CLI projected rules for Claude Code tools.+ */+export function registerGuard(on: On, state: ModState) {+ const projection = cachedFile(() => under(state, PROJECTION_PATH), parseProjection)++ on('tool.check', async ($, e, next) => {+ const chain = await next(e)+ const tool = typeof e.tool === 'string' ? e.tool : ''+ const read = await projection({ stat: path => $.fs.stat(path), read: path => $.fs.read(path) })+ const { verdict, observed } = opinionOf(state, read, tool, e.input)+ if (observed) {+ state.observed+++ $.ui.log(`ruflo policy (observe): ${tool} ${observed}`, { to: 'debug' })+ }+ const merged = stricter(chain, verdict)+ if (merged !== chain) {+ state.tightened+++ if (state.statusLine) $.ui.status(statusText(state))+ }+ return merged+ }).catch(async ($, e, next) => {+ // ruflo could not judge. Fail closed by one step: the chain's verdict+ // stands where it is already ask or deny; an allow is put to the person.+ const chain = await next(e).catch(() => undefined)+ return chain ? stricter(chain, CHECK_FAILED) : CHECK_FAILED+ })+}diff --git a/plugins/ruflo-mods/hooks/guard/policy.ts b/plugins/ruflo-mods/hooks/guard/policy.tsnew file mode 100644index 0000000000..43e21c61f0--- /dev/null+++ b/plugins/ruflo-mods/hooks/guard/policy.ts@@ -0,0 +1,180 @@+import type { Verdict } from './verdict'++/**+ * Ruflo policy for Claude Code's own tool calls, read from the projection the+ * CLI writes beside the policy state (`.claude-flow/policy/claude-code.json`,+ * see cli/src/mods/policy-projection.ts) and never from state.json itself:+ * that file holds the receipt ledger (tens of MB) and is past the 4 MiB a hooks+ * module may read.+ *+ * Only rules whose `actions` name a `claude-code.` pattern explicitly take+ * part; a rule with no actions, or `*`, keeps meaning what it meant before+ * this mod existed (MCP calls only). Matching is engine.ts / evaluator.ts+ * `ruleMatches`, copied (a hooks module cannot import @claude-flow/security);+ * the parity test runs both over the same rules and requests. Only explicit+ * matches count: the engine's default-deny for an unmatched request does not+ * apply here, so turning the mod on never refuses a tool that no rule names.+ */++export const PROJECTION_PATH = '.claude-flow/policy/claude-code.json'+export const ACTION_PREFIX = 'claude-code.'++export type PolicyMode = 'legacy' | 'observe' | 'enforce'+type Effect = 'allow' | 'deny' | 'require_approval'++export type ProjectedRule = {+ readonly id: string+ readonly effect: Effect+ readonly actions: readonly string[]+ readonly enabled?: boolean+ readonly priority?: number+ readonly resources?: readonly string[]+ readonly principals?: readonly string[]+ readonly identityTypes?: readonly string[]+ readonly roles?: readonly string[]+ readonly environments?: readonly string[]+ readonly constraints?: Readonly<Record<string, unknown>>+}++export type Projection = { readonly mode: PolicyMode; readonly rules: readonly ProjectedRule[] }++export type ToolRequest = {+ readonly identity: { readonly id: string; readonly type: string; readonly roles?: readonly string[] }+ readonly action: {+ readonly type: string+ readonly resource?: string+ readonly environment?: string+ readonly network: boolean+ readonly destructive: boolean+ readonly namespace?: string+ readonly costUsd?: number+ readonly tokens?: number+ readonly concurrency?: number+ }+}++const MODES = new Set(['legacy', 'observe', 'enforce'])+const EFFECTS = new Set(['allow', 'deny', 'require_approval'])+const DESTRUCTIVE = new Set(['Bash', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit'])+const NETWORK = new Set(['Bash', 'WebFetch', 'WebSearch'])++const isStrings = (v: unknown): v is string[] => Array.isArray(v) && v.every(s => typeof s === 'string')+const optStrings = (v: unknown) => v === undefined || isStrings(v)++/** Whether a rule speaks to Claude Code tool calls by name. */+export const targetsClaudeCode = (actions: readonly string[]) =>+ actions.some(a => a.startsWith(ACTION_PREFIX))++/**+ * Validates the projection's text. Throws on anything malformed: the caller+ * fails closed on a projection that exists but cannot be read.+ */+export function parseProjection(text: string): Projection {+ const raw: unknown = JSON.parse(text)+ if (raw === null || typeof raw !== 'object') throw new Error('projection is not an object')+ const { version, mode, rules } = raw as Record<string, unknown>+ if (version !== 1) throw new Error(`unsupported projection version ${String(version)}`)+ if (typeof mode !== 'string' || !MODES.has(mode)) throw new Error('projection mode invalid')+ if (!Array.isArray(rules)) throw new Error('projection rules invalid')+ const valid = rules.map((r: unknown, i): ProjectedRule => {+ const rule = r as Record<string, unknown> | null+ const ok =+ rule !== null &&+ typeof rule === 'object' &&+ typeof rule.id === 'string' &&+ typeof rule.effect === 'string' &&+ EFFECTS.has(rule.effect) &&+ isStrings(rule.actions) &&+ optStrings(rule.resources) &&+ optStrings(rule.principals) &&+ optStrings(rule.identityTypes) &&+ optStrings(rule.roles) &&+ optStrings(rule.environments) &&+ (rule.priority === undefined || typeof rule.priority === 'number') &&+ (rule.constraints === undefined || (rule.constraints !== null && typeof rule.constraints === 'object'))+ if (!ok) throw new Error(`projection rule ${i} invalid`)+ return rule as unknown as ProjectedRule+ })+ return { mode: mode as PolicyMode, rules: valid.filter(r => targetsClaudeCode(r.actions)) }+}++/** The policy request for a Claude Code tool call. */+export function toolRequest(tool: string, input: unknown): ToolRequest {+ const args = input !== null && typeof input === 'object' ? (input as Record<string, unknown>) : {}+ const resource =+ typeof args.command === 'string' ? args.command+ : typeof args.file_path === 'string' ? args.file_path+ : typeof args.notebook_path === 'string' ? args.notebook_path+ : typeof args.url === 'string' ? args.url+ : tool+ return {+ identity: { id: 'claude-code', type: 'agent' },+ action: {+ type: `${ACTION_PREFIX}tool.${tool}`,+ resource,+ network: NETWORK.has(tool) || tool.startsWith('mcp__'),+ destructive: DESTRUCTIVE.has(tool),+ },+ }+}++function matches(patterns: readonly string[] | undefined, value: string | undefined): boolean {+ if (!patterns?.length) return true+ if (!value) return false+ return patterns.some(p => p === '*' || p === value || (p.endsWith('*') && value.startsWith(p.slice(0, -1))))+}++// evaluator.ts constraintsPass for a request that carries no evidence: a+// signed-evidence or provenance requirement can never be met here.+function constraintsPass(req: ToolRequest, c: Readonly<Record<string, unknown>> | undefined): boolean {+ if (!c) return true+ const a = req.action+ if (c.maxCostUsd !== undefined && (a.costUsd === undefined || a.costUsd > (c.maxCostUsd as number))) return false+ if (c.maxTokens !== undefined && (a.tokens === undefined || a.tokens > (c.maxTokens as number))) return false+ if (c.maxConcurrency !== undefined && (a.concurrency === undefined || a.concurrency > (c.maxConcurrency as number))) return false+ if (c.network === false && a.network === true) return false+ if (c.destructive === false && a.destructive === true) return false+ if (isStrings(c.allowedNamespaces) && c.allowedNamespaces.length && !matches(c.allowedNamespaces, a.namespace)) return false+ if (c.requireSignedEvidence) return false+ if (isStrings(c.requiredProvenance) && c.requiredProvenance.length) return false+ return true+}++/** evaluator.ts `ruleMatches`, over a projected rule. */+export function ruleMatches(rule: ProjectedRule, req: ToolRequest): boolean {+ if (rule.enabled === false) return false+ const { identity, action } = req+ return (+ matches(rule.actions, action.type) &&+ matches(rule.resources, action.resource) &&+ matches(rule.principals, identity.id) &&+ (!rule.identityTypes?.length || rule.identityTypes.includes(identity.type)) &&+ (!rule.roles?.length || rule.roles.some(role => identity.roles?.includes(role))) &&+ matches(rule.environments, action.environment) &&+ constraintsPass(req, rule.constraints)+ )+}++export type PolicyOpinion = { readonly verdict?: Verdict; readonly wouldBe?: string }++/**+ * Ruflo's opinion on a tool call: in `enforce`, a matched deny rule denies+ * and a matched approval rule asks; an allow rule says nothing (this mod+ * never loosens). In `observe`, `wouldBe` names what enforce would do.+ */+export function policyOpinion(projection: Projection, tool: string, input: unknown): PolicyOpinion {+ if (projection.mode === 'legacy' || projection.rules.length === 0) return {}+ const req = toolRequest(tool, input)+ const matched = projection.rules+ .filter(rule => ruleMatches(rule, req))+ .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id.localeCompare(b.id))+ const deny = matched.find(r => r.effect === 'deny')+ const approval = matched.find(r => r.effect === 'require_approval')+ const verdict: Verdict | undefined = deny+ ? { decision: 'deny', reason: `ruflo policy: denied-by:${deny.id}` }+ : approval+ ? { decision: 'ask', reason: `ruflo policy: approval-required-by:${approval.id}` }+ : undefined+ if (!verdict) return {}+ return projection.mode === 'enforce' ? { verdict } : { wouldBe: verdict.reason }+}diff --git a/plugins/ruflo-mods/hooks/guard/verdict.ts b/plugins/ruflo-mods/hooks/guard/verdict.tsnew file mode 100644index 0000000000..c05787ef10--- /dev/null+++ b/plugins/ruflo-mods/hooks/guard/verdict.ts@@ -0,0 +1,35 @@+/**+ * Verdict arithmetic for `tool.check`: this mod only ever tightens.+ *+ * `deny` > `ask` > `allow`. The merged verdict is the stricter of the chain's+ * and ruflo's; on a tie the chain's stands untouched, so its `rule` (what+ * sec-default reads to hold a deny) is never rewritten or erased.+ */++export type Decision = 'allow' | 'ask' | 'deny'++export type Verdict = {+ readonly decision: Decision+ readonly reason?: string+ readonly rule?: string+}++const RANK: Record<Decision, number> = { allow: 0, ask: 1, deny: 2 }++export function isDecision(value: unknown): value is Decision {+ return value === 'allow' || value === 'ask' || value === 'deny'+}++/**+ * The stricter of two verdicts; `ours` absent means ruflo has no opinion.+ *+ * @param chain what `next(e)` resolved to (the engine's verdict and beneath)+ * @param ours ruflo's tightening, if any+ */+export function stricter<V extends Verdict>(chain: V, ours: Verdict | undefined): V | Verdict {+ if (!ours) return chain+ // A chain answer of an unknown shape is treated as the loosest verdict, so+ // ruflo's opinion still holds; it never makes ruflo's verdict looser.+ const chainRank = isDecision(chain.decision) ? RANK[chain.decision] : -1+ return RANK[ours.decision] > chainRank ? ours : chain+}diff --git a/plugins/ruflo-mods/hooks/hooks.json b/plugins/ruflo-mods/hooks/hooks.jsonnew file mode 100644index 0000000000..280d2dd475--- /dev/null+++ b/plugins/ruflo-mods/hooks/hooks.json@@ -0,0 +1,4 @@+{+ "description": "ruflo as a mod (ADR-404, early access): routes each prompt in-process and hands the route to the model as prompt context; records edits for the intelligence consolidator; tightens tool.check with ruflo's dangerous-command list and the Claude Code rules of ruflo policy, never loosening a verdict; applies the cost-tracker budget ladder to live session cost. Owns an event only where the classic hook-handler hands it over, so nothing fires twice.",+ "modules": ["./register.ts"]+}diff --git a/plugins/ruflo-mods/hooks/learn/index.ts b/plugins/ruflo-mods/hooks/learn/index.tsnew file mode 100644index 0000000000..39e77ff267--- /dev/null+++ b/plugins/ruflo-mods/hooks/learn/index.ts@@ -0,0 +1,67 @@+import type { EngineInterface, On } from 'claude-code'++import { isMissing } from '../files'+import { statusText, 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. */+const FLUSH_AT = 50++/**+ * Writes the waiting edit records to pending-insights.jsonl. A file that+ * exists but cannot be read is never overwritten: the records wait (capped)+ * and the classic consolidator's file stays as it was.+ */+export async function flushEdits($: EngineInterface, state: ModState): Promise<void> {+ if (state.edits.length === 0) return+ const records = state.edits.splice(0)+ try {+ const session = await $.fs.read(under(state, SESSION_PATH)).catch(() => undefined)+ const sessionId = rufloSessionId(session)+ const existing = await $.fs.read(under(state, PENDING_PATH)).catch((error: unknown) => {+ if (isMissing(error)) return ''+ throw error+ })+ await $.fs.write(under(state, PENDING_PATH), appendRecords(existing, records.map(r => ({ ...r, sessionId }))))+ } 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' })+ }+}++/**+ * `tool.call` on the edit tools: hook-handler.cjs `post-edit` in-process,+ * recording each finished edit (a failed one with `success: false`, ADR-174;+ * a denied one never ran, as PostToolUse never fires for it). Written per+ * turn at `turn.complete`, and at `session.end`.+ */+export function registerLearn(on: On, state: ModState) {+ on('tool.call', async ($, e, next) => {+ const result = await next(e)+ if (!state.owned.has('post-edit') || !EDIT_TOOLS.has(e.tool) || result.deny !== undefined) return result++ state.edits.push({+ type: 'edit',+ file: editedFile(e),+ success: result.isError !== true,+ timestamp: Date.now(),+ sessionId: null,+ })+ state.editCount+++ if (state.statusLine) $.ui.status(statusText(state))+ if (state.edits.length >= FLUSH_AT) await flushEdits($, state)+ return result+ })++ on('turn.complete', async ($, e, next) => {+ const result = await next(e)+ await flushEdits($, state)+ return result+ })++ on('session.end', async ($, e, next) => {+ await flushEdits($, state)+ return next(e)+ })+}diff --git a/plugins/ruflo-mods/hooks/learn/insights.ts b/plugins/ruflo-mods/hooks/learn/insights.tsnew file mode 100644index 0000000000..c93ff2922b--- /dev/null+++ b/plugins/ruflo-mods/hooks/learn/insights.ts@@ -0,0 +1,58 @@+/**+ * Edit records for intelligence.cjs `consolidate()`, in the line format+ * `recordEdit` appends to `.claude-flow/data/pending-insights.jsonl`.+ *+ * `$.fs` has no append, so records are held in memory and written once per+ * turn (and at session end) by reading the file, adding the lines and writing+ * it back, with recordEdit's own cap (keep the last 2000 lines). A classic+ * writer appending in the same instant can lose a line; the window is one+ * read-write per turn instead of one per edit (ADR-404).+ */++export const PENDING_PATH = '.claude-flow/data/pending-insights.jsonl'+export const SESSION_PATH = '.claude-flow/sessions/current.json'+export const MAX_LINES = 2000+/** hook-handler.cjs `post-edit` matches these tools (settings-generator.ts). */+export const EDIT_TOOLS = new Set(['Write', 'Edit', 'MultiEdit'])++export type EditRecord = {+ readonly type: 'edit'+ readonly file: string+ readonly success: boolean+ readonly timestamp: number+ readonly sessionId: string | null+}++/** The file an edit tool's arguments name, or `unknown` as recordEdit says. */+export function editedFile(input: unknown): string {+ const path = input !== null && typeof input === 'object' ? (input as { file_path?: unknown }).file_path : undefined+ return typeof path === 'string' && path.length > 0 && path.length <= 4096 ? path : 'unknown'+}++/**+ * `context.sessionId` of `.claude-flow/sessions/current.json`, as+ * intelligence.cjs `sessionGet('sessionId')` reads it, or null.+ */+export function rufloSessionId(text: string | undefined): string | null {+ if (!text) return null+ try {+ const session = JSON.parse(text) as { context?: { sessionId?: unknown } } | null+ const value = session?.context?.sessionId+ return typeof value === 'string' ? value : null+ } catch {+ return null+ }+}++/**+ * The pending file's next text: what it held plus the new records, capped.+ *+ * @param existing the file's current text ('' when absent)+ * @param records the records to add+ */+export function appendRecords(existing: string, records: readonly EditRecord[]): string {+ const lines = existing.split('\n').filter(Boolean)+ for (const r of records) lines.push(JSON.stringify(r))+ const kept = lines.length > MAX_LINES ? lines.slice(-MAX_LINES) : lines+ return kept.length ? `${kept.join('\n')}\n` : ''+}diff --git a/plugins/ruflo-mods/hooks/options.ts b/plugins/ruflo-mods/hooks/options.tsnew file mode 100644index 0000000000..9c65f51a88--- /dev/null+++ b/plugins/ruflo-mods/hooks/options.ts@@ -0,0 +1,24 @@+import type { PluginOptions } from 'claude-code'++import { budgetOf } from './cost/budget'++/** The plugin's `userConfig` options, validated: a bad value is the default. */+export type ModOptions = {+ readonly routeContext: boolean+ readonly statusLine: boolean+ readonly costBudgetUsd?: number+ readonly costHardStop: boolean+}++const bool = (value: unknown, fallback: boolean) =>+ value === true || value === 'true' ? true : value === false || value === 'false' ? false : fallback++export function readOptions(options: PluginOptions | undefined): ModOptions {+ const o = options ?? {}+ return {+ routeContext: bool(o.routeContext, true),+ statusLine: bool(o.statusLine, true),+ costBudgetUsd: budgetOf(o.costBudgetUsd),+ costHardStop: bool(o.costHardStop, false),+ }+}diff --git a/plugins/ruflo-mods/hooks/ownership.ts b/plugins/ruflo-mods/hooks/ownership.tsnew file mode 100644index 0000000000..a88348e9c6--- /dev/null+++ b/plugins/ruflo-mods/hooks/ownership.ts@@ -0,0 +1,59 @@+/**+ * Which classic hook-handler events this mod takes over, so no event fires+ * twice (ADR-404, "One owner per event").+ *+ * The mod owns an event when no classic hook for it is configured, or when the+ * configured hook-handler.cjs honours the handshake: the mod sets+ * `RUFLO_MODS_OWNS` in the process environment, every settings hook started+ * after inherits it, and hook-handler.cjs returns early for an event named+ * there. A helper too old to know the handshake would run anyway, so the mod+ * stands down for that event and the classic hook keeps it.+ *+ * Only side-effect events are ever owned. `pre-bash` is a guard: the mod's+ * `tool.check` and the classic hook both refuse the same commands, a second+ * refusal changes nothing, and a forged handshake must never switch a guard+ * off. Session restore and end stay classic (intelligence init/consolidate+ * need Node).+ */++export const OWNABLE = ['route', 'post-edit'] as const+export type Ownable = (typeof OWNABLE)[number]++/** The marker hook-handler.cjs carries when it honours the handshake. */+export const HANDSHAKE_MARKER = 'RUFLO_MODS_OWNS'++type HookEntry = { readonly command?: unknown }+type HookGroup = { readonly hooks?: readonly HookEntry[] }++/** Which classic event and hook-handler subcommand carries each ownable. */+const CLASSIC: Record<Ownable, { readonly event: string; readonly subcommand: string }> = {+ route: { event: 'UserPromptSubmit', subcommand: 'route' },+ 'post-edit': { event: 'PostToolUse', subcommand: 'post-edit' },+}++function commandsOf(settings: unknown, event: string): string[] {+ const hooks = (settings as { hooks?: Record<string, unknown> } | null)?.hooks+ const groups = hooks?.[event]+ if (!Array.isArray(groups)) return []+ return (groups as HookGroup[]).flatMap(g =>+ Array.isArray(g?.hooks) ? g.hooks.map(h => h?.command).filter((c): c is string => typeof c === 'string') : [],+ )+}++/** Whether settings run hook-handler.cjs with this subcommand on this event. */+export function classicConfigured(settings: unknown, ownable: Ownable): boolean {+ const { event, subcommand } = CLASSIC[ownable]+ // `.cjs route`, `.cjs" route` (POSIX) and `.cjs\" route` (Windows cmd /c).+ const word = new RegExp(`hook-handler\\.c?js\\\\?["']?\\s+${subcommand}(?![\\w-])`)+ return commandsOf(settings, event).some(c => word.test(c))+}++/**+ * The events the mod owns this session.+ *+ * @param settings the merged settings (`$.settings.read()`)+ * @param helperHonours whether the hook-handler.cjs the hooks run carries the marker+ */+export function ownedEvents(settings: unknown, helperHonours: boolean): Ownable[] {+ return OWNABLE.filter(o => !classicConfigured(settings, o) || helperHonours)+}diff --git a/plugins/ruflo-mods/hooks/register.ts b/plugins/ruflo-mods/hooks/register.tsnew file mode 100644index 0000000000..9a676dbce5--- /dev/null+++ b/plugins/ruflo-mods/hooks/register.ts@@ -0,0 +1,29 @@+import type { Register } from 'claude-code'++import { registerCost } from './cost'+import { registerGuard } from './guard'+import { registerLearn } from './learn'+import { readOptions } from './options'+import { registerRoute } from './route'+import { registerSession } from './session'+import { createState } from './state'++/**+ * ruflo as a Claude Code mod (ADR-404, early access).+ *+ * 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).+ */+export const register: Register = (on, options) => {+ const state = createState()+ const opts = readOptions(options)++ registerSession(on, state, opts)+ registerRoute(on, state, opts)+ registerGuard(on, state)+ registerLearn(on, state)+ registerCost(on, state, opts)+}diff --git a/plugins/ruflo-mods/hooks/route/format.ts b/plugins/ruflo-mods/hooks/route/format.tsnew file mode 100644index 0000000000..0d3c369b64--- /dev/null+++ b/plugins/ruflo-mods/hooks/route/format.ts@@ -0,0 +1,23 @@+import type { RouteResult } from './route-task'++/**+ * The routing block as hook-handler.cjs `route` prints it, so the model reads+ * the same context whichever path produced it.+ *+ * @param prompt the prompt routed+ * @param result its route+ */+export function formatRoute(prompt: string, result: RouteResult): string {+ // The structured result says `no-match-default` (#3567); the box keeps the+ // classic wording, so the text the model reads is the same on both paths.+ const reason = result.matched ? result.reason : 'Default routing - no specific keyword matched'+ return [+ `[INFO] Routing task: ${prompt.substring(0, 80) || '(no prompt)'}`,+ '',+ '+------------------- Primary Recommendation -------------------+',+ `| Agent: ${result.agent.padEnd(53)}|`,+ `| Confidence: ${(result.confidence * 100).toFixed(1)}%${' '.repeat(44)}|`,+ `| Reason: ${reason.substring(0, 53).padEnd(53)}|`,+ '+--------------------------------------------------------------+',+ ].join('\n')+}diff --git a/plugins/ruflo-mods/hooks/route/index.ts b/plugins/ruflo-mods/hooks/route/index.tsnew file mode 100644index 0000000000..2e99edaf08--- /dev/null+++ b/plugins/ruflo-mods/hooks/route/index.ts@@ -0,0 +1,41 @@+import type { On } from 'claude-code'++import { cachedFile } from '../files'+import type { ModOptions } from '../options'+import { statusText, under, type ModState } from '../state'+import { formatRoute } from './format'+import { parseRanked, rankedContext } from './ranked-context'+import { routeTask } from './route-task'++export const RANKED_PATH = '.claude-flow/data/ranked-context.json'++/**+ * `prompt.submit`: hook-handler.cjs `route` in-process. The routing block+ * (and, with `routeContext`, the ranked-memory block) ride the prompt as+ * context the model reads and the user never sees: `prompt.submit` context is+ * the one injection point sec-default leaves to a person's plugins+ * (`prompt.context` is continued past the user tier).+ */+export function registerRoute(on: On, state: ModState, options: ModOptions) {+ const ranked = cachedFile(() => under(state, RANKED_PATH), parseRanked)++ on('prompt.submit', async ($, e, next) => {+ if (!state.owned.has('route')) return next(e)++ const text = typeof e.text === 'string' ? e.text : ''+ const result = routeTask(text)+ state.lastRoute = result+ state.routed++++ const blocks: string[] = []+ if (options.routeContext) {+ const read = await ranked({ stat: path => $.fs.stat(path), read: path => $.fs.read(path) })+ const context = read.kind === 'ok' ? rankedContext(text, read.value) : null+ if (context) blocks.push(context)+ }+ blocks.push(formatRoute(text, result))+ if (state.statusLine) $.ui.status(statusText(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/route/ranked-context.ts b/plugins/ruflo-mods/hooks/route/ranked-context.tsnew file mode 100644index 0000000000..8af24a873b--- /dev/null+++ b/plugins/ruflo-mods/hooks/route/ranked-context.ts@@ -0,0 +1,110 @@+/**+ * Ranked-memory context for a prompt: the scoring of intelligence.cjs+ * `getContext` (trigram Jaccard blended with PageRank, top 5 over 0.05),+ * read-only.+ *+ * Copied because a hooks module cannot import intelligence.cjs; the parity+ * test runs both over the same ranked-context.json and compares the text.+ * What this does not do: the classic path also writes `lastMatchedPatterns`+ * and boosts the previous match's confidence on every prompt. Those writes+ * stay with the classic helpers (ADR-404, "What the mod does not carry").+ */++const STOP_WORDS = new Set([+ 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being',+ 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',+ 'should', 'may', 'might', 'shall', 'can', 'to', 'of', 'in', 'for',+ 'on', 'with', 'at', 'by', 'from', 'as', 'into', 'through', 'during',+ 'before', 'after', 'and', 'but', 'or', 'nor', 'not', 'so', 'yet',+ 'both', 'either', 'neither', 'each', 'every', 'all', 'any', 'few',+ 'more', 'most', 'other', 'some', 'such', 'no', 'only', 'own', 'same',+ 'than', 'too', 'very', 'just', 'because', 'if', 'when', 'which',+ 'who', 'whom', 'this', 'that', 'these', 'those', 'it', 'its',+])++const ALPHA = 0.6+const MIN_THRESHOLD = 0.05+const TOP_K = 5++export type RankedEntry = {+ readonly id?: string+ readonly words?: readonly string[]+ readonly pageRank?: number+ readonly summary?: string+ readonly content?: string+ readonly accessCount?: number+}++export function tokenize(text: string): string[] {+ if (!text) return []+ return text+ .toLowerCase()+ .replace(/[^a-z0-9\s-]/g, ' ')+ .split(/\s+/)+ .filter(w => w.length > 2 && !STOP_WORDS.has(w))+}++export function trigrams(words: readonly string[]): Set<string> {+ const t = new Set<string>()+ for (const w of words) {+ for (let i = 0; i <= w.length - 3; i++) t.add(w.slice(i, i + 3))+ }+ return t+}++function jaccard(a: ReadonlySet<string>, b: ReadonlySet<string>): number {+ if (a.size === 0 && b.size === 0) return 0+ let shared = 0+ for (const item of a) if (b.has(item)) shared+++ return shared / (a.size + b.size - shared)+}++/** An entry with its trigrams worked out once, when the file is read. */+export type PreparedEntry = RankedEntry & { readonly tri: ReadonlySet<string> }++/**+ * Parses ranked-context.json text into its entries, each with its trigrams+ * (the file is re-read only when it changes, so this runs once per change,+ * not per prompt); anything not the expected shape reads as no entries.+ */+export function parseRanked(text: string): readonly PreparedEntry[] {+ try {+ const parsed: unknown = JSON.parse(text)+ const entries = (parsed as { entries?: unknown } | null)?.entries+ if (!Array.isArray(entries)) return []+ return entries+ .filter((e): e is RankedEntry => e !== null && typeof e === 'object')+ .map(e => ({ ...e, tri: trigrams(Array.isArray(e.words) ? e.words.filter(w => typeof w === 'string') : []) }))+ } catch {+ return []+ }+}++/**+ * The `[INTELLIGENCE]` block for a prompt, or null when nothing scores.+ *+ * @param prompt the prompt text+ * @param entries the ranked entries+ */+export function rankedContext(prompt: string, entries: readonly PreparedEntry[]): string | null {+ if (!prompt || entries.length === 0) return null+ const words = tokenize(prompt)+ if (words.length === 0) return null+ const promptTrigrams = trigrams(words)++ const scored: Array<RankedEntry & { score: number }> = []+ for (const entry of entries) {+ const pageRank = typeof entry.pageRank === 'number' ? entry.pageRank : 0+ const score = ALPHA * jaccard(promptTrigrams, entry.tri) + (1 - ALPHA) * pageRank+ if (score >= MIN_THRESHOLD) scored.push({ ...entry, score })+ }+ if (scored.length === 0) return null++ scored.sort((a, b) => b.score - a.score)+ const lines = ['[INTELLIGENCE] Relevant patterns for this task:']+ scored.slice(0, TOP_K).forEach((e, i) => {+ const display = String(e.summary || e.content || '').slice(0, 80)+ lines.push(` * (${e.score.toFixed(2)}) ${display} [rank #${i + 1}, ${e.accessCount || 0}x accessed]`)+ })+ return lines.join('\n')+}diff --git a/plugins/ruflo-mods/hooks/route/route-task.ts b/plugins/ruflo-mods/hooks/route/route-task.tsnew file mode 100644index 0000000000..32da48c04f--- /dev/null+++ b/plugins/ruflo-mods/hooks/route/route-task.ts@@ -0,0 +1,77 @@+/**+ * The static keyword router, in-process.+ *+ * A hooks module may import nothing outside its plugin folder, so this is a+ * copy of `.claude/helpers/router.cjs` (TASK_PATTERNS, word-boundary+ * matching, first match wins). It is not a fork: the parity test in+ * `v3/@claude-flow/cli/__tests__/mods/route-parity.test.ts` fails CI when the+ * table or the matching drifts from router.cjs.+ *+ * The one deliberate difference is #3567: a prompt nothing matched says so+ * (`matched: false`, `reason: "no-match-default"`) and carries the+ * NO_MATCH_CONFIDENCE prior that `hooks_route` uses, never a real match's.+ */++export type RouteResult = {+ readonly agent: string+ readonly confidence: number+ readonly matched: boolean+ readonly reason: string+}++/** A real keyword match's heuristic prior (router.cjs, #2257). */+export const MATCH_CONFIDENCE = 0.6++/** `NO_MATCH_CONFIDENCE` in cli/src/mcp-tools/hooks-tools.ts (#3567). */+export const NO_MATCH_CONFIDENCE = 0.3++export const TASK_PATTERNS: ReadonlyArray<{ readonly tokens: readonly string[]; readonly agent: string }> = [+ { tokens: ['implement', 'create', 'build', 'add', 'write code', 'refactor', 'debug'], agent: 'coder' },+ { tokens: ['test', 'tests', 'testing', 'spec', 'specs', 'coverage', 'unit test', 'integration test'], agent: 'tester' },+ { tokens: ['review', 'audit', 'check', 'validate', 'security'], agent: 'reviewer' },+ { tokens: ['research', 'find', 'search', 'documentation', 'explore'], agent: 'researcher' },+ { tokens: ['design', 'architect', 'architecture', 'structure', 'plan'], agent: 'architect' },+ { tokens: ['api', 'endpoint', 'server', 'backend', 'database'], agent: 'backend-dev' },+ { tokens: ['ui', 'frontend', 'component', 'react', 'css', 'style'], agent: 'frontend-dev' },+ { tokens: ['deploy', 'docker', 'ci', 'cd', 'ci/cd', 'pipeline', 'infrastructure', 'devops'], agent: 'devops' },+]++const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')++/** router.cjs `buildPattern`: phrases literal, single tokens `\b`-anchored. */+export function buildPattern(tokens: readonly string[]): RegExp {+ const alternatives = tokens.map(tok => {+ const escaped = escapeRegex(tok.toLowerCase())+ return /\s|\//.test(tok) ? escaped : `\\b${escaped}\\b`+ })+ return new RegExp(`(?:${alternatives.join('|')})`, 'i')+}++// Compiled once per module load: the hot path is one regex test per entry.+const COMPILED = TASK_PATTERNS.map(entry => ({+ agent: entry.agent,+ reason: `Matched keyword(s) from: ${entry.tokens.join('|')}`,+ regex: buildPattern(entry.tokens),+}))++/**+ * Routes a task description to an agent type.+ *+ * @param task the prompt text; anything else routes as no-match+ */+export function routeTask(task: unknown): RouteResult {+ const text = typeof task === 'string' ? task.toLowerCase() : ''++ for (const entry of COMPILED) {+ if (entry.regex.test(text)) {+ return { agent: entry.agent, confidence: MATCH_CONFIDENCE, matched: true, reason: entry.reason }+ }+ }++ return {+ agent: 'coder',+ confidence: NO_MATCH_CONFIDENCE,+ matched: false,+ reason: 'no-match-default',+ }+}diff --git a/plugins/ruflo-mods/hooks/session.ts b/plugins/ruflo-mods/hooks/session.tsnew file mode 100644index 0000000000..94235bd63f--- /dev/null+++ b/plugins/ruflo-mods/hooks/session.ts@@ -0,0 +1,71 @@+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'++const HELPER = '.claude/helpers/hook-handler.cjs'++/**+ * Where the mod notes that it started and what it owns, for `ruflo mods+ * doctor` to read. Display only: nothing decides by it.+ */+export const HEARTBEAT_PATH = '.claude-flow/mods/session.json'++/**+ * Whether every hook-handler.cjs a classic hook could run honours the+ * handshake. Settings name the project's copy, `$HOME`'s, or probe one then+ * the other (settings-generator `hookCmd`), so both are checked: one copy too+ * old for the handshake is enough to stand down. Unreadable counts as too+ * old. With neither present no classic route/post-edit can run at all.+ */+async function helperHonours($: EngineInterface): Promise<boolean> {+ const root = await $.session.root().catch(() => undefined)+ const home = await $.env.get('HOME').catch(() => undefined)+ for (const base of new Set([root, home])) {+ if (!base) continue+ const path = `${base}/${HELPER}`+ if (!(await $.fs.exists(path).catch(() => true))) continue+ const text = await $.fs.read(path).catch(() => '')+ if (!text.includes(HANDSHAKE_MARKER)) return false+ }+ return true+}++/** Whether a ruflo statusLine is configured: then the mod draws none. */+function hasClassicStatusLine(settings: unknown): boolean {+ const command = (settings as { statusLine?: { command?: unknown } } | null)?.statusLine?.command+ return typeof command === 'string' && /statusline\.c?js/.test(command)+}++/**+ * At session start: decide which events the mod owns and tell the classic+ * hooks through the process environment; register `/ruflo-mods`. Any failure+ * leaves the mod owning nothing, so every classic hook keeps running.+ */+export function registerSession(on: On, state: ModState, options: ModOptions) {+ on('session.start', async ($, e, next) => {+ state.root = await $.session.root()+ const settings = await $.settings.read()+ 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)+ await $.command+ .register({ name: 'ruflo-mods', description: 'ruflo mods: what this session routed, recorded and tightened' })+ .catch(() => undefined)+ const heartbeat = { startedAt: new Date().toISOString(), owned: [...state.owned], statusLine: state.statusLine }+ await $.fs.write(under(state, HEARTBEAT_PATH), `${JSON.stringify(heartbeat, null, 2)}\n`).catch(() => undefined)+ return next(e)+ }).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',+ })+ // 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)+ })++ on('command.run', { command: 'ruflo-mods' }, () => ({ text: report(state) }))+}diff --git a/plugins/ruflo-mods/hooks/state.ts b/plugins/ruflo-mods/hooks/state.tsnew file mode 100644index 0000000000..3ec32bc698--- /dev/null+++ b/plugins/ruflo-mods/hooks/state.ts@@ -0,0 +1,74 @@+import type { BudgetLevel } from './cost/budget'+import type { EditRecord } from './learn/insights'+import type { Ownable } from './ownership'+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.+ */+export type ModState = {+ /** The session's project root, where the classic helpers keep their files. */+ root: string+ owned: ReadonlySet<Ownable>+ statusLine: boolean+ lastRoute?: RouteResult+ routed: number+ tightened: number+ observed: number+ edits: EditRecord[]+ editCount: number+ policy: 'none' | 'legacy' | 'observe' | 'enforce' | 'unreadable'+ budget: { level: BudgetLevel; usd?: number; limit?: number }+}++export function createState(): ModState {+ return {+ root: '.',+ owned: new Set(),+ statusLine: false,+ routed: 0,+ tightened: 0,+ observed: 0,+ edits: [],+ editCount: 0,+ policy: 'none',+ budget: { level: 'OK' },+ }+}++/** 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}%)`)+ }+ 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(' · ')+}++/** What `/ruflo-mods` prints. */+export function report(s: ModState): string {+ const route = s.lastRoute+ ? `${s.lastRoute.agent} (${(s.lastRoute.confidence * 100).toFixed(0)}%, ${s.lastRoute.matched ? 'matched' : 'no match'})`+ : 'none yet'+ const budget =+ s.budget.limit === undefined+ ? 'off (set the costBudgetUsd option)'+ : `${s.budget.level}: $${(s.budget.usd ?? 0).toFixed(2)} of $${s.budget.limit.toFixed(2)}`+ return [+ 'ruflo mods (ADR-404, early access)',+ ` 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}`,+ ].join('\n')+}diff --git a/plugins/ruflo-mods/scripts/smoke.sh b/plugins/ruflo-mods/scripts/smoke.shnew file mode 100755index 0000000000..e6135c64ca--- /dev/null+++ b/plugins/ruflo-mods/scripts/smoke.sh@@ -0,0 +1,55 @@+#!/usr/bin/env bash+# Structural + security smoke for ruflo-mods v0.1.0 (ADR-404).+# 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`.+set -u+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+PASS=0+FAIL=0+step() { printf "→ %s ... " "$1"; }+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.1.0"+grep -q '"name": "ruflo-mods"' "$ROOT/.claude-plugin/plugin.json" \+ && grep -q '"version": "0.1.0"' "$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" \+ && ok || bad "hooks.json must be modules-only"++step "3. no import reaches outside the plugin folder"+# Modules live at most one folder below hooks/, so `../../` already leaves+# hooks/; the engine refuses anything outside the plugin, this keeps it to hooks/.+deep=$(grep -rnE "from ['\"](\.\./){2,}" "$HOOKS" || true)+[[ -z "$deep" ]] && ok || bad "$deep"++step "4. no network, process, model or MCP calls (no network by default)"+hits=$(grep -rnE '\$\.(http|process|model|mcp)\.' "$HOOKS" || true)+[[ -z "$hits" ]] && ok || bad "$hits"++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' "+[[ "$events" == "$expected" ]] && ok || bad "got: $events"++step "6. tool.check merges with stricter() (tighten-only)"+grep -q "stricter(chain" "$HOOKS/guard/index.ts" && ! grep -qE "decision: 'allow'" "$HOOKS/guard/index.ts" "$HOOKS/guard/policy.ts" \+ && ok || bad "guard must never answer allow of its own"++step "7. the only environment variable written is the handshake"+envw=$(grep -rhoE "\\\$\.env\.set\('[A-Z_]+'" "$HOOKS" | sort -u | tr '\n' ' ')+[[ "$envw" == "\$.env.set('RUFLO_MODS_OWNS' " ]] && ok || bad "got: $envw"++step "8. no secrets or credentials in the module"+sec=$(grep -rniE "(api[_-]?key|secret|password|token)\s*[:=]\s*['\"][^'\"]{8,}" "$HOOKS" || true)+[[ -z "$sec" ]] && ok || bad "$sec"++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"++printf "\n%d passed, %d failed\n" "$PASS" "$FAIL"+[[ $FAIL -eq 0 ]]diff --git a/plugins/ruflo-mods/tests/fixtures/world.ts b/plugins/ruflo-mods/tests/fixtures/world.tsnew file mode 100644index 0000000000..0df2026441--- /dev/null+++ b/plugins/ruflo-mods/tests/fixtures/world.ts@@ -0,0 +1,64 @@+import type { On } from 'claude-code'++/**+ * The world beneath the mod, answered from memory: a project at /work, a+ * file map, settings, the environment (read and written), and what the mod+ * drew. Each noun is answered with `{ value }` as the engine's own ops are.+ */+export type World = {+ readonly files: Map<string, string>+ readonly env: Map<string, string>+ readonly statuses: (string | undefined)[]+ readonly logs: string[]+ readonly commands: string[]+}++export const ROOT = '/work'+export const HELPER = `${ROOT}/.claude/helpers/hook-handler.cjs`++export function world(on: On, settings: unknown = {}, files: Record<string, string> = {}): World {+ const w: World = { files: new Map(Object.entries(files)), env: new Map(), statuses: [], logs: [], commands: [] }++ on('session.start', ($, e) => ({ cwd: e.cwd }))+ on('session.root', () => ({ value: ROOT }))+ on('settings.read', () => ({ value: settings as never }))+ on('env.get', ($, e) => ({ value: w.env.get(e.name) }))+ on('env.set', ($, e) => {+ if (e.value === undefined) w.env.delete(e.name)+ else w.env.set(e.name, e.value)+ return { value: undefined }+ })+ on('fs.exists', ($, e) => ({ value: w.files.has(e.path) }))+ on('fs.stat', ($, e) => {+ const text = w.files.get(e.path)+ if (text === undefined) return { deny: `ENOENT: no such file or directory, '${e.path}'` }+ return { value: { kind: 'file', size: text.length, mtimeMs: text.length, isLink: false } }+ })+ on('fs.read', ($, e) => {+ const text = w.files.get(e.path)+ if (text === undefined) return { deny: `ENOENT: no such file or directory, '${e.path}'` }+ return { value: text }+ })+ on('fs.write', ($, e) => {+ w.files.set(e.path, e.text)+ return { value: undefined }+ })+ on('command.register', ($, e) => {+ w.commands.push(e.name)+ return { value: { command: e.name } }+ })+ on('ui.status', ($, e) => {+ w.statuses.push(e.text)+ return { value: undefined }+ })+ on('ui.log', ($, e) => {+ w.logs.push(e.text)+ return { value: undefined }+ })+ return w+}++export const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const++/** A prompt the person typed and sent. */+export const prompt = (text: string) => ({ text, wait: false, origin: { kind: 'composer' } }) as constdiff --git a/plugins/ruflo-mods/tests/register.test.ts b/plugins/ruflo-mods/tests/register.test.tsnew file mode 100644index 0000000000..2870aec623--- /dev/null+++ b/plugins/ruflo-mods/tests/register.test.ts@@ -0,0 +1,109 @@+import { describe, expect, test, tier } from 'claude-code/testing'++import { HELPER, prompt, ROOT, START, world } from './fixtures/world'++tier('user')++const CLASSIC_ROUTE = {+ hooks: { UserPromptSubmit: [{ hooks: [{ command: 'node "$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs" route' }] }] },+}++describe('register', () => {+ 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)++ expect(w.env.get('RUFLO_MODS_OWNS')).toBe('route,post-edit')+ expect(w.commands).toEqual(['ruflo-mods'])+ expect(JSON.parse(w.files.get(`${ROOT}/.claude-flow/mods/session.json`) ?? '{}').owned).toEqual(['route', 'post-edit'])+ })++ test('stands down where a classic helper too old for the handshake runs route', async ($, on) => {+ const w = world(on, CLASSIC_ROUTE, { [HELPER]: '// an older helper' })+ let context: readonly string[] | undefined+ on('prompt.submit', ($, e) => ((context = e.context), { text: e.text }))++ await $.session.start(START)+ await $.prompt.submit(prompt('implement the api'))++ expect(w.env.get('RUFLO_MODS_OWNS')).toBe('post-edit')+ expect(context).toBeUndefined()+ })++ test('routes a prompt in-process: the route rides as context, #3567 no-match included', async ($, on) => {+ world(on, CLASSIC_ROUTE, { [HELPER]: '// RUFLO_MODS_OWNS' })+ const seen: (readonly string[] | undefined)[] = []+ on('prompt.submit', ($, e) => (seen.push(e.context), { text: e.text }))++ await $.session.start(START)+ await $.prompt.submit(prompt('write tests for the parser'))+ await $.prompt.submit(prompt('hello'))++ expect(seen[0]?.[0]).toContain('| Agent: tester')+ expect(seen[0]?.[0]).toContain('Confidence: 60.0%')+ expect(seen[1]?.[0]).toContain('Confidence: 30.0%')+ })++ test('tool.check: the dangerous-command list tightens an allow; a deny is never loosened', 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: 'Bash', input: { command: 'rm -rf /' } })).decision).toBe('deny')+ expect((await $.tool.check({ tool: 'Bash', input: { command: 'ls' } })).decision).toBe('allow')+ expect(await $.tool.check({ tool: 'Read', input: { file_path: '.env' } })).toEqual({+ decision: 'deny',+ reason: 'rule',+ rule: 'Read(.env)',+ })+ })++ test('tool.check: an enforced ruflo policy rule denies or asks; one that cannot be read asks', async ($, on) => {+ const projection = JSON.stringify({+ version: 1,+ mode: 'enforce',+ rules: [+ { id: 'no-push', effect: 'deny', actions: ['claude-code.tool.Bash'], resources: ['git push*'] },+ { id: 'review', effect: 'require_approval', actions: ['claude-code.tool.Edit'] },+ ],+ })+ const w = world(on, {}, { [`${ROOT}/.claude-flow/policy/claude-code.json`]: projection })+ on('tool.check', () => ({ decision: 'allow' }))+ await $.session.start(START)++ expect(await $.tool.check({ tool: 'Bash', input: { command: 'git push origin' } })).toMatchObject({ decision: 'deny' })+ expect(await $.tool.check({ tool: 'Edit', input: { file_path: 'a.ts' } })).toMatchObject({ decision: 'ask' })+ expect((await $.tool.check({ tool: 'Read', input: { file_path: 'a.ts' } })).decision).toBe('allow')++ w.files.set(`${ROOT}/.claude-flow/policy/claude-code.json`, '{ torn')+ expect((await $.tool.check({ tool: 'Read', input: { file_path: 'a.ts' } })).decision).toBe('ask')+ })++ test('records a finished edit once per turn, in the classic pending-insights format', async ($, on) => {+ const w = world(on)+ on('tool.call', () => ({ result: 'edited' }))+ on('turn.complete', ($, e) => ({ text: e.answer }))+ await $.session.start(START)++ await $.tool.call({ tool: 'Edit', file_path: `${ROOT}/a.ts`, old_string: 'a', new_string: 'b' })+ expect(w.files.has(`${ROOT}/.claude-flow/data/pending-insights.jsonl`)).toBe(false)+ await $.turn.complete({ answer: 'done', durationMs: 1, isAborted: false, turnId: 't1', reason: 'answer' })++ const line = JSON.parse(w.files.get(`${ROOT}/.claude-flow/data/pending-insights.jsonl`) ?? '{}')+ expect(line).toMatchObject({ type: 'edit', file: `${ROOT}/a.ts`, success: true, sessionId: null })+ })++ test('/ruflo-mods reports what the session did', async ($, on) => {+ world(on)+ on('prompt.submit', ($, e) => ({ text: e.text }))+ on('command.run', () => ({ text: 'core' }))+ await $.session.start(START)+ await $.prompt.submit(prompt('deploy with docker'))++ const { text } = await $.command.run({ command: 'ruflo-mods', args: '', origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } })+ expect(text).toContain('owns: route, post-edit')+ expect(text).toContain('last devops (60%, matched)')+ })+})diff --git a/plugins/ruflo-mods/tsconfig.json b/plugins/ruflo-mods/tsconfig.jsonnew file mode 100644index 0000000000..54f8e34062--- /dev/null+++ b/plugins/ruflo-mods/tsconfig.json@@ -0,0 +1,17 @@+{+ "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"]+}