🌊 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-rag-memory): function-hook mod (ADR-445)
ruv35cb4fd59698
diff --git a/plugins/ruflo-rag-memory/.claude-plugin/plugin.json b/plugins/ruflo-rag-memory/.claude-plugin/plugin.jsonindex 71f0e7fafc..fcd243cf03 100644--- a/plugins/ruflo-rag-memory/.claude-plugin/plugin.json+++ b/plugins/ruflo-rag-memory/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-rag-memory",- "description": "RuVector memory with HNSW search, AgentDB, and semantic retrieval",- "version": "0.2.1",+ "description": "RuVector memory with HNSW search, AgentDB, and semantic retrieval. As a mod (ADR-445): a write guard that keeps secrets out of memory, /rag-mod, and a status file the console shows",+ "version": "0.3.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"@@ -17,6 +17,22 @@"vector-search","mcp","claude-memories",- "bridged-memory"- ]+ "bridged-memory",+ "mod",+ "function-hooks",+ "guard"+ ],+ "userConfig": {+ "guard": {+ "type": "string",+ "title": "Secret guard",+ "description": "Refuse calls to this plugin's write tools that hold a key, token or password.",+ "required": false,+ "default": "on",+ "options": [+ "on",+ "off"+ ]+ }+ }}diff --git a/plugins/ruflo-rag-memory/README.md b/plugins/ruflo-rag-memory/README.mdindex 677d786e85..0b65175eaf 100644--- a/plugins/ruflo-rag-memory/README.md+++ b/plugins/ruflo-rag-memory/README.md@@ -226,3 +226,15 @@ bash plugins/ruflo-rag-memory/scripts/smoke.sh## LicenseMIT++## As a mod++Function-hook mod (ADR-445, pattern of `ruflo-agentdb`). It loads from `hooks/hooks.json` → `hooks/register.ts`.++A write guard for memory: `memory_store`, `agentdb_hierarchical-store` and `agentdb_pattern-store` refuse secrets, so credentials never land in the vector store.++- **Command**: `/rag-mod` answers locally with no model call. Verbs: `status`, `scan <text>` (would the guard refuse this?), `tools` (which memory tools are connected).+- **Status file**: `.claude-flow/rag-mod/status.json` (`{version, updatedMs, ...counters}`), written at session start and as counters change.+- **Safety**: no network, no process spawning; it only uses tools already connected.+- **Option** `guard` (`on` by default, `off` to disable): a tighten-only `tool.call` guard. A call to one of the tools above whose input holds a key, token, private key or password is denied. The reason never repeats the secret.+- **Test**: `claude plugin validate plugins/ruflo-rag-memory`, `claude plugin test plugins/ruflo-rag-memory`, `bash plugins/ruflo-rag-memory/scripts/smoke.sh`.diff --git a/plugins/ruflo-rag-memory/hooks/command.ts b/plugins/ruflo-rag-memory/hooks/command.tsnew file mode 100644index 0000000000..003ae8928a--- /dev/null+++ b/plugins/ruflo-rag-memory/hooks/command.ts@@ -0,0 +1,36 @@+import type { ToolInfo } from 'claude-code'++import type { ModOptions } from './options'+import { secretsIn } from './screen'+import type { Stats } from './status'+import { isOwned, shortName } from './tools'++/** `/rag-mod` is answered locally and takes no model turn. */+export type CommandDeps = { readonly opts: ModOptions; readonly stats: Stats; readonly tools: () => Promise<readonly ToolInfo[]> }++const HELP = ['/rag-mod status', '/rag-mod scan <text>', '/rag-mod tools'].join('\n')++export async function answer(args: string, deps: CommandDeps): Promise<string> {+ const [verb = '', ...rest] = args.trim().split(/\s+/)+ const arg = rest.join(' ')+ const { opts, stats } = deps++ if (verb === '' || verb === 'help') return HELP++ if (verb === 'status') {+ return `guard ${opts.guard ? 'on' : 'off'} · calls seen ${stats.seen} · blocked ${stats.blocked}${stats.lastBlocked ? ` · last blocked ${stats.lastBlocked}` : ''}`+ }++ if (verb === 'scan') {+ if (arg === '') return 'usage: /rag-mod scan <text>'+ const found = secretsIn(arg)+ return found.length ? `The guard would refuse a call carrying that (${found.join(', ')}).` : 'Nothing found: the guard would let that through.'+ }++ if (verb === 'tools') {+ const names = (await deps.tools()).filter(t => t.mcp && isOwned(t.name)).map(t => shortName(t.name))+ return names.length ? `${names.length} connected: ${[...new Set(names)].sort().join(', ')}` : 'None of this plugin\'s tools is connected. Connect the MCP server and try again.'+ }++ return `Unknown: ${verb}\n${HELP}`+}diff --git a/plugins/ruflo-rag-memory/hooks/guard.ts b/plugins/ruflo-rag-memory/hooks/guard.tsnew file mode 100644index 0000000000..8abb5bff31--- /dev/null+++ b/plugins/ruflo-rag-memory/hooks/guard.ts@@ -0,0 +1,22 @@+import { hasSecret } from './screen'+import { isWriter } from './tools'++/** Every string in a tool's input, to a bounded depth and size: what the guard reads. */+export function textsOf(input: unknown, budget = { left: 20_000 }, depth = 0): string[] {+ if (budget.left <= 0 || depth > 6) return []+ if (typeof input === 'string') {+ budget.left -= input.length+ return [input]+ }+ if (Array.isArray(input)) return input.slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1))+ if (typeof input === 'object' && input !== null) return Object.values(input).slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1))+ return []+}++/** The reason a call is refused, or undefined when it may go. Never names or echoes the secret. */+export function verdict(tool: string, input: unknown): string | undefined {+ if (!isWriter(tool)) return undefined+ return textsOf(input).some(hasSecret)+ ? 'ruflo-rag-memory: this call holds what looks like a secret (a key, token or password). Store a reference to where it lives, not the value.'+ : undefined+}diff --git a/plugins/ruflo-rag-memory/hooks/hooks.json b/plugins/ruflo-rag-memory/hooks/hooks.jsonnew file mode 100644index 0000000000..4bc9389f2b--- /dev/null+++ b/plugins/ruflo-rag-memory/hooks/hooks.json@@ -0,0 +1,4 @@+{+ "description": "ruflo-rag-memory as a mod (ADR-445): a tighten-only guard that keeps secrets out of its write tools, /rag-mod, and a status file the console reads.",+ "modules": ["./register.ts"]+}diff --git a/plugins/ruflo-rag-memory/hooks/options.ts b/plugins/ruflo-rag-memory/hooks/options.tsnew file mode 100644index 0000000000..e18352b921--- /dev/null+++ b/plugins/ruflo-rag-memory/hooks/options.ts@@ -0,0 +1,9 @@+import type { PluginOptions } from 'claude-code'++/** The plugin's `userConfig`, validated: a bad value is the default (guard on). */+export type ModOptions = { readonly guard: boolean }++const flag = (value: unknown, fallback: boolean) =>+ value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback++export const readOptions = (options: PluginOptions | undefined): ModOptions => ({ guard: flag((options ?? {}).guard, true) })diff --git a/plugins/ruflo-rag-memory/hooks/register.ts b/plugins/ruflo-rag-memory/hooks/register.tsnew file mode 100644index 0000000000..b119cef619--- /dev/null+++ b/plugins/ruflo-rag-memory/hooks/register.ts@@ -0,0 +1,78 @@+import type { Hook, Register } from 'claude-code'++import { answer } from './command'+import { verdict } from './guard'+import { readOptions, type ModOptions } from './options'+import { newStats, STATUS_PATH, statusText, type Stats } from './status'+import { isOwned, isWriter, shortName } from './tools'++const FLUSH_EVERY_MS = 5000++type Dollar = Parameters<Hook<'session.start'>>[0]++/** Everything one session of the mod keeps: its settings, counters, the project root and when the status file was last written. */+type Session = { readonly opts: ModOptions; readonly stats: Stats; root?: string; flushedMs: number }++async function flush($: Dollar, s: Session): Promise<void> {+ if (s.root === undefined) return+ try {+ const now = await $.clock.now()+ s.flushedMs = now+ await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.stats, s.opts, now))+ } catch {+ /* the status file is a courtesy */+ }+}++/** Counts a call to one of this plugin's tools; the file is rewritten at most every few seconds. */+async function note($: Dollar, s: Session): Promise<void> {+ s.stats.seen+++ try {+ if ((await $.clock.now()) - s.flushedMs >= FLUSH_EVERY_MS) await flush($, s)+ } catch {+ /* counting never fails a tool call */+ }+}++/**+ * ruflo-rag-memory as a mod (ADR-445): a tighten-only guard that keeps secrets out of this plugin's write tools, `/rag-mod`, and a status+ * file the console reads. No network, no process: only tools already connected.+ */+export const register: Register = (on, options) => {+ const s: Session = { opts: readOptions(options), stats: newStats(), flushedMs: 0 }++ on('session.start', async ($, e, next) => {+ const result = await next(e)+ try {+ s.root = (await $.session.root()) as string | undefined+ } catch {+ /* no project root: the mod still answers, it just writes no status file */+ }+ try {+ await $.command.register({ name: 'rag-mod', description: 'ruflo-rag-memory mod: status, scan <text>, tools' })+ } catch {+ /* a name taken by another plugin must not stop the mod */+ }+ await flush($, s)+ return result+ })++ on('tool.call', async ($, e, next) => {+ if (!isOwned(e.tool) && !isWriter(e.tool)) return next(e)+ const reason = s.opts.guard ? verdict(e.tool, e) : undefined+ if (reason === undefined) {+ await note($, s)+ return next(e)+ }+ s.stats.blocked+++ s.stats.lastBlocked = shortName(e.tool)+ await flush($, s)+ return { deny: reason }+ })++ /** `/rag-mod` (a name the plugin's own commands and skills do not use). */+ on('command.run', { command: 'rag-mod' }, async ($, e) => {+ const text = await answer(typeof e.args === 'string' ? e.args : '', { opts: s.opts, stats: s.stats, tools: () => $.tool.list() })+ return { text }+ })+}diff --git a/plugins/ruflo-rag-memory/hooks/screen.ts b/plugins/ruflo-rag-memory/hooks/screen.tsnew file mode 100644index 0000000000..620c591de5--- /dev/null+++ b/plugins/ruflo-rag-memory/hooks/screen.ts@@ -0,0 +1,29 @@+/**+ * Pure secret screening for the ruflo-rag-memory mod (ADR-445 screen.ts, secrets only). Findings are NAMES only: the matched text is never+ * returned, logged or counted by value.+ */++const SECRETS: readonly (readonly [string, RegExp])[] = [+ ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],+ ['aws access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/],+ ['github token', /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/],+ ['slack token', /\bxox[abprs]-[A-Za-z0-9-]{10,}/],+ ['google api key', /\bAIza[0-9A-Za-z_-]{35}\b/],+ ['anthropic or openai key', /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{24,}/],+ ['jwt', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/],+ ['bearer token', /\bBearer\s+[A-Za-z0-9._~+/=-]{24,}/],+ ['key assignment', /\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i],+]++// C0/C1 controls (keeping tab and newline), DEL, zero-width and bidi override characters.+const INVISIBLE = new RegExp('[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\ufeff]', 'g')++const bare = (text: string) => (text.length > 20_000 ? text.slice(0, 20_000) : text).replace(INVISIBLE, '')++/** Names of every secret shape found in `text`. Cost is linear in the capped input. */+export const secretsIn = (text: string): string[] => {+ const bounded = bare(text)+ return SECRETS.filter(([, re]) => re.test(bounded)).map(([name]) => name)+}++export const hasSecret = (text: string) => secretsIn(text).length > 0diff --git a/plugins/ruflo-rag-memory/hooks/status.ts b/plugins/ruflo-rag-memory/hooks/status.tsnew file mode 100644index 0000000000..16f15875df--- /dev/null+++ b/plugins/ruflo-rag-memory/hooks/status.ts@@ -0,0 +1,12 @@+import type { ModOptions } from './options'++/** Counters the mod keeps for the session and writes to `.claude-flow/rag-mod/status.json`. */+export type Stats = { seen: number; blocked: number; lastBlocked?: string }++export const newStats = (): Stats => ({ seen: 0, blocked: 0 })++export const STATUS_PATH = '.claude-flow/rag-mod/status.json'++/** The file's text; `version` lets a reader refuse a shape it does not know. */+export const statusText = (stats: Stats, opts: ModOptions, nowMs: number): string =>+ `${JSON.stringify({ version: 1, updatedMs: nowMs, guard: opts.guard, ...stats }, null, 2)}\n`diff --git a/plugins/ruflo-rag-memory/hooks/tools.ts b/plugins/ruflo-rag-memory/hooks/tools.tsnew file mode 100644index 0000000000..3090e825ad--- /dev/null+++ b/plugins/ruflo-rag-memory/hooks/tools.ts@@ -0,0 +1,34 @@+/** `mcp__<server>__<tool>` into its two halves; tool names never hold a double underscore. */+export function splitName(name: string): { server: string; tool: string } | undefined {+ if (!name.startsWith('mcp__')) return undefined+ const at = name.lastIndexOf('__')+ return at > 5 ? { server: name.slice(5, at), tool: name.slice(at + 2) } : undefined+}++const bare = (name: string) => splitName(name)?.tool ?? name++/** The name without its `mcp__<server>__` prefix. */+export const shortName = bare++/** This plugin's tools: counted in the status file. */+const OWNED = new Set([+ 'memory_search',+ 'memory_search_unified',+ 'memory_retrieve',+ 'memory_list',+ 'memory_store',+ 'memory_bridge_status',+ 'memory_import_claude',+ 'agentdb_context-synthesize',+ 'agentdb_pattern-search',+])++/** The tools that put text somewhere durable or shared. A call through any of them is screened by the guard. */+const WRITERS = new Set([+ 'memory_store',+ 'agentdb_hierarchical-store',+ 'agentdb_pattern-store',+])++export const isOwned = (name: string) => OWNED.has(bare(name))+export const isWriter = (name: string) => WRITERS.has(bare(name))diff --git a/plugins/ruflo-rag-memory/scripts/smoke.sh b/plugins/ruflo-rag-memory/scripts/smoke.shindex 5927ff7868..c9410b8c69 100755--- a/plugins/ruflo-rag-memory/scripts/smoke.sh+++ b/plugins/ruflo-rag-memory/scripts/smoke.sh@@ -7,9 +7,9 @@ step() { printf "→ %s ... " "$1"; }ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }-step "1. plugin.json declares 0.2.1 with new keywords"+step "1. plugin.json declares 0.3.0 with new keywords"v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)-if [[ "$v" != "0.2.1" ]]; then bad "expected 0.2.1, got '$v'"; else+if [[ "$v" != "0.3.0" ]]; then bad "expected 0.3.0, got '$v'"; elsemiss=""for k in mcp claude-memories bridged-memory; dogrep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"@@ -80,5 +80,24 @@ for f in "$ROOT"/skills/*/SKILL.md; dodone[[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills"+# M1. The mod (ADR-445): hooks module registered, files within the 500-line rule, no network or process access in the hooks+step "M1. mod: hooks.json names register.ts, every hook file is present and under 500 lines"+mod_ok=1+grep -q '"./register.ts"' "$ROOT/hooks/hooks.json" || mod_ok=0+for f in options screen guard status command register tools; do+ [[ -f "$ROOT/hooks/$f.ts" ]] || mod_ok=0+ [[ $(wc -l < "$ROOT/hooks/$f.ts" 2>/dev/null || echo 9999) -le 500 ]] || mod_ok=0+done+[[ $mod_ok -eq 1 ]] && ok || bad "mod hooks incomplete or too long"++step "M2. mod: guard defaults on (userConfig)"+node -e '+const c = require(process.argv[1]).userConfig || {}+process.exit(c.guard && c.guard.default === "on" ? 0 : 1)+' "$ROOT/.claude-plugin/plugin.json" && ok || bad "userConfig default wrong"++step "M3. mod: hooks never touch the network or spawn a process"+if grep -nE '\$\.(http|process)\.|child_process|fetch\(' "$ROOT"/hooks/*.ts >/dev/null; then bad "network or process call in hooks"; else ok; fi+printf "\n%s passed, %s failed\n" "$PASS" "$FAIL"[[ $FAIL -eq 0 ]] || exit 1diff --git a/plugins/ruflo-rag-memory/tests/rag.test.ts b/plugins/ruflo-rag-memory/tests/rag.test.tsnew file mode 100644index 0000000000..236974116c--- /dev/null+++ b/plugins/ruflo-rag-memory/tests/rag.test.ts@@ -0,0 +1,100 @@+import type { On } from 'claude-code'+import { describe, expect, test, tier } from 'claude-code/testing'++tier('user')++const ROOT = '/work'+const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const+const STATUS = `${ROOT}/.claude-flow/rag-mod/status.json`+const slash = (args: string) => ({ command: 'rag-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const++const WRITER = 'mcp__plugin_ruflo-core_ruflo__memory_store'+const READER = 'mcp__plugin_ruflo-core_ruflo__memory_search'+const TOOLS = [WRITER, READER].map(name => ({ name, description: '', mcp: true }))+const SECRET = `ghp_${'a1B2'.repeat(10)}`++/** The world beneath the mod: a project root, a file map, connected tools, a fixed clock. */+function world(on: On, tools: readonly { name: string; description: string; mcp: boolean }[] = TOOLS) {+ const files = new Map<string, string>()+ let t = 1_000+ on('session.start', ($, e) => ({ cwd: e.cwd }))+ on('session.root', () => ({ value: ROOT }))+ on('command.register', ($, e) => ({ value: { command: e.name } }))+ on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined }))+ on('tool.list', () => ({ value: tools }))+ on('clock.now', () => ({ value: (t += 10_000) }))+ on('tool.call', () => ({ result: 'done' }))+ return { files, status: () => JSON.parse(files.get(STATUS) ?? '{}') }+}++const call = (tool: string, value: string) => ({ tool, key: 'k', value }) as never+const attempt = (p: Promise<unknown>) => p.then(r => r, (e: unknown) => ({ text: String(e) }))++describe('guard', () => {+ test('refuses a secret in a write, never echoes it, passes clean input and other tools', async ($, on) => {+ const w = world(on)+ await $.session.start(START)++ const denied = JSON.stringify(await attempt($.tool.call(call(WRITER, `token ${SECRET}`))))+ expect(denied).toContain('secret')+ expect(denied).not.toContain('ghp_')+ expect(JSON.stringify(await $.tool.call(call(WRITER, 'a plain note about indexing')))).toContain('done')+ expect(JSON.stringify(await $.tool.call(call(READER, `query ${SECRET}`)))).toContain('done')+ expect(w.status()).toMatchObject({ version: 1, guard: true, blocked: 1, lastBlocked: WRITER.split('__').pop() })+ })++ test('a nested secret is found; a tool from nowhere is ignored', async ($, on) => {+ world(on)+ await $.session.start(START)+ const nested = { tool: WRITER, entries: [{ meta: { note: `Bearer ${'x9'.repeat(14)}` } }] } as never+ expect(JSON.stringify(await attempt($.tool.call(nested)))).toContain('secret')+ expect(JSON.stringify(await $.tool.call(call('Bash', `echo ${SECRET}`)))).toContain('done')+ })++ test('guard: off lets the write through', { options: { guard: 'off' } }, async ($, on) => {+ const w = world(on)+ await $.session.start(START)+ expect(JSON.stringify(await $.tool.call(call(WRITER, SECRET)))).toContain('done')+ expect(w.status()).toMatchObject({ guard: false, blocked: 0 })+ })+})++describe('status file', () => {+ test('written at session start with the defaults', async ($, on) => {+ const w = world(on)+ await $.session.start(START)+ expect(w.status()).toMatchObject({ version: 1, guard: true, seen: 0, blocked: 0 })+ expect(typeof w.status().updatedMs).toBe('number')+ })++ test('counts calls to the plugin\'s tools', async ($, on) => {+ const w = world(on)+ await $.session.start(START)+ await $.tool.call(call(READER, 'q'))+ await $.tool.call(call(READER, 'q'))+ const n = (await $.command.run(slash('status'))).text ?? ''+ expect(n).toContain('calls seen 2')+ expect(w.status().version).toBe(1)+ })+})++describe('/rag-mod', () => {+ test('status, scan and tools answer locally', async ($, on) => {+ world(on)+ await $.session.start(START)+ expect((await $.command.run(slash('status'))).text).toContain('guard on')+ const scan = (await $.command.run(slash(`scan key ${SECRET}`))).text ?? ''+ expect(scan).toContain('github token')+ expect(scan).not.toContain('ghp_')+ expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found')+ expect((await $.command.run(slash('tools'))).text).toContain('2 connected')+ })++ test('no connected tool is said plainly; an unknown verb gets the help', async ($, on) => {+ world(on, [])+ await $.session.start(START)+ expect((await $.command.run(slash('tools'))).text).toContain('None of this plugin')+ expect((await $.command.run(slash('how do I do it'))).text).toContain('/rag-mod scan <text>')+ expect((await $.command.run(slash(''))).text).toContain('/rag-mod status')+ })+})diff --git a/plugins/ruflo-rag-memory/tsconfig.json b/plugins/ruflo-rag-memory/tsconfig.jsonnew file mode 100644index 0000000000..e4ba54993e--- /dev/null+++ b/plugins/ruflo-rag-memory/tsconfig.json@@ -0,0 +1,19 @@+{+ "//": "Self-contained on purpose: bundlers (vite/esbuild in the root CI vitest) load this file for every module they transform, so it must not extend a file that only exists after Claude Code (>= 2.1.287) has loaded the plugin. Claude Code writes its declarations to .claude-plugin/types/ (gitignored) on load or validate; tsc -p . then reads them through typeRoots.",+ "compilerOptions": {+ "target": "es2023",+ "lib": ["es2023"],+ "module": "esnext",+ "moduleResolution": "bundler",+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "noEmit": true,+ "skipLibCheck": true,+ "jsx": "react",+ "jsxFactory": "h",+ "jsxFragmentFactory": "Fragment",+ "typeRoots": ["./.claude-plugin/types"],+ "types": ["claude-code", "claude-code-tools", "claude-code-mcp"]+ },+ "include": ["hooks", "tests"]+}