Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

feat(ruflo-agentdb): screen the file memory_import reads (0.4.6)

ruvc07e41850d1f
diff --git a/plugins/ruflo-agentdb/.claude-plugin/plugin.json b/plugins/ruflo-agentdb/.claude-plugin/plugin.json
index 47b420ac3a..0b0aeadc29 100644
--- a/plugins/ruflo-agentdb/.claude-plugin/plugin.json
+++ b/plugins/ruflo-agentdb/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-agentdb",
"description": "Substrate plugin for Ruflo memory: AgentDB controller bridge (15 agentdb_* MCP tools), RuVector ONNX embeddings (10 embeddings_* tools incl. RaBitQ 32x quantization), and WASM HNSW pattern router (3 ruvllm_hnsw_* tools). As a mod (ADR-445): opt-in safe recall into the prompt, a write guard that keeps secrets out of memory, /agentdb, and a status file the console shows",
- "version": "0.4.5",
+ "version": "0.4.6",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-agentdb/README.md b/plugins/ruflo-agentdb/README.md
index be5b83bca3..25f98e096b 100644
--- a/plugins/ruflo-agentdb/README.md
+++ b/plugins/ruflo-agentdb/README.md
@@ -205,13 +205,14 @@ bash plugins/ruflo-agentdb/scripts/smoke.sh
The smoke script is the contract. It calls each documented MCP tool, exercises the RaBitQ workflow, and source-inspects the fallback path (no env-var gate exists to force the fallback live).
-## As a mod (0.4.5, ADR-445)
+## As a mod (0.4.6, ADR-445)
A function-hook mod ships beside the skills. Needs a Claude Code with mods (2.1.287+); older builds ignore it.
| Piece | Default | What it does |
|---|---|---|
| **Secret guard** | on | Refuses a memory write (`agentdb_hierarchical-store`, `agentdb_pattern-store`, `agentdb_batch`, `agentdb_causal-edge`, `memory_store`, `hooks_remember`, `hooks_intelligence_pattern-store`, `agentdb_feedback`, `agentdb_session-end`, `hive-mind_memory`, `session_save`) that holds a private key, cloud/GitHub/Slack token, bearer token, JWT or key-like assignment. The secret is never echoed. The shared screen (`hooks/screen.ts`, copied to every mod by `scripts/sync-mod-screen.mjs`) judges an assignment by its value: calls, env references, identifier paths, placeholders, UUIDs, secret-manager paths and hyphenated names are not secrets; a literal needs two character classes (one a digit or symbol) and at least 2.5 bits of entropy per character. Vendor keys (Stripe, npm, HuggingFace, SendGrid, Twilio, Slack webhooks) and `scheme://user:pass@host` URLs are matched by shape; input is scanned in one pass up to 200 KB (head and tail beyond that). |
+| **Import file screen** | on (with the guard) | `memory_import` takes only a path, so the guard also reads the file at `inputPath` and refuses the import when it holds a secret (same message, never echoing it). Best effort, not a gate, and it **fails open**: a file over 1 MB, a directory, a missing or unreadable file, a path outside the project root and your home, a path with `..`, a backslash or a null byte, a non-string path, or a stat/read error all let the import proceed unread. Symlinks are not resolved. `rvf_ingest` is still unguarded. |
| **Recall into prompts** | **off** | Attaches the best 1–5 memories to each prompt as framed, per-prompt context (the prompt cache is not disturbed). Read through the already-connected tools, in order: `memory_search` (semantic: the only reader that finds a paraphrase; its 60-character cut is completed with `memory_retrieve`), `agentdb_hierarchical-recall` and `agentdb_pattern-search` (substring matches, so also asked with the prompt's salient words), ruvector `hooks_recall`. A result scoring under 0.25 is noise and skipped. No CLI, no network. Skipped for slash commands, `!` lines and short prompts; gives up after `recallDeadlineMs` (800; the first recall of a fresh session takes 0.5–1.5 s, so consider 1500); cached 10 minutes. |
| **Untrusted memory** | always | A retrieved memory with a secret or an instruction-to-the-model phrase is dropped; the rest are control-character-stripped, capped (5 items, 400 chars each, 1500 total) and framed as data. |
| **`/agentdb-mod`** | — | `status`, `recall <text>`, `scan <text>`, `recent`; answered locally, no model call. |
diff --git a/plugins/ruflo-agentdb/hooks/guard.ts b/plugins/ruflo-agentdb/hooks/guard.ts
index 81d21966c1..256bbf57b3 100644
--- a/plugins/ruflo-agentdb/hooks/guard.ts
+++ b/plugins/ruflo-agentdb/hooks/guard.ts
@@ -41,12 +41,17 @@ export function extras(input: unknown): { readonly pairs: string[]; readonly ove
return { pairs, oversize: false }
}
+export const SECRET_REFUSAL = 'ruflo-agentdb: this memory write holds what looks like a secret (a key, token or password). Store a reference to where it lives, not the value.'
+
+/** Whether `input` holds a secret, judged like a write but never refusing for size: the best-effort file layer fails open past the budgets. */
+export const holdsSecret = (input: unknown): boolean => textsOf(input).some(hasSecret) || extras(input).pairs.some(hasSecret)
+
/** The reason a memory write 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
const { pairs, oversize } = extras(input)
if (oversize) return 'ruflo-agentdb: this memory write is too large to screen for secrets in full. Store it in smaller pieces.'
return textsOf(input).some(hasSecret) || pairs.some(hasSecret)
- ? 'ruflo-agentdb: this memory write holds what looks like a secret (a key, token or password). Store a reference to where it lives, not the value.'
+ ? SECRET_REFUSAL
: undefined
}
diff --git a/plugins/ruflo-agentdb/hooks/import.ts b/plugins/ruflo-agentdb/hooks/import.ts
new file mode 100644
index 0000000000..c6e86a0c71
--- /dev/null
+++ b/plugins/ruflo-agentdb/hooks/import.ts
@@ -0,0 +1,55 @@
+import { holdsSecret, SECRET_REFUSAL } from './guard'
+import { splitName } from './tools'
+
+/** The most a `memory_import` file may weigh for the guard to read it; past this the import goes through unread. */
+export const IMPORT_MAX_BYTES = 1_000_000
+
+/** Whether `name` is `memory_import`, bare or under any MCP server prefix. */
+export const isImport = (name: string) => (splitName(name)?.tool ?? name) === 'memory_import'
+
+/** `path` as an absolute, normalised path when it sits under `base`, else undefined. Pure string work: no `..`, no backslash, no null byte. */
+function inside(path: string, base: string | undefined): string | undefined {
+ if (base === undefined || !base.startsWith('/')) return undefined
+ const root = base.replace(/\/+$/, '')
+ const parts = (path.startsWith('/') ? path : `${root}/${path}`).split('/').filter(p => p !== '' && p !== '.')
+ const full = `/${parts.join('/')}`
+ return root !== '' && full.startsWith(`${root}/`) ? full : undefined
+}
+
+/**
+ * The file a `memory_import` call would read, as an absolute path the guard may read: a string `inputPath` with no null byte, backslash or `..`
+ * segment, under the project root or the user's home. Anything else is undefined (not read). Symlinks are not resolved: the file API has no way to.
+ */
+export function importPath(input: unknown, root: string | undefined, home: string | undefined): string | undefined {
+ const raw = typeof input === 'object' && input !== null ? (input as { inputPath?: unknown }).inputPath : undefined
+ if (typeof raw !== 'string' || raw === '' || raw.length > 4096 || /[\0\\]/.test(raw) || raw.split('/').includes('..')) return undefined
+ return inside(raw, root) ?? inside(raw, home)
+}
+
+/** The refusal when the imported file's text holds a secret, else undefined. A JSON file is read as its values (so name/value pairs are judged together), anything else as text. */
+export function importVerdict(text: string): string | undefined {
+ let value: unknown = text
+ try {
+ value = JSON.parse(text)
+ } catch {
+ /* not JSON: screen the raw text */
+ }
+ return holdsSecret(value) ? SECRET_REFUSAL : undefined
+}
+
+/** What the guard needs of a file system: `$.fs.stat` and `$.fs.read`, spelled at the call site. */
+export type ImportFiles = {
+ readonly stat: (path: string) => Promise<{ readonly kind: string; readonly size: number }>
+ readonly read: (path: string) => Promise<string>
+}
+
+/** Stats first, reads only a regular file within the bound; undefined (fail open) on any error, a directory or an oversize file. */
+export async function readImport(files: ImportFiles, path: string): Promise<string | undefined> {
+ try {
+ const stat = await files.stat(path)
+ if (stat.kind !== 'file' || stat.size > IMPORT_MAX_BYTES) return undefined
+ return await files.read(path)
+ } catch {
+ return undefined
+ }
+}
diff --git a/plugins/ruflo-agentdb/hooks/register.ts b/plugins/ruflo-agentdb/hooks/register.ts
index d4f988aec0..8f8f84cfcd 100644
--- a/plugins/ruflo-agentdb/hooks/register.ts
+++ b/plugins/ruflo-agentdb/hooks/register.ts
@@ -3,6 +3,7 @@ import type { Hook, Register } from 'claude-code'
import { answer } from './command'
import { expandTruncated } from './expand'
import { verdict } from './guard'
+import { importPath, importVerdict, isImport, readImport } from './import'
import { readOptions, type ModOptions } from './options'
import { cacheKey, frame, keywords, parse, screen, worthRecalling } from './recall'
import { tidy } from './screen'
@@ -42,6 +43,18 @@ async function flush($: Dollar, s: Session): Promise<void> {
}
}
+/**
+ * Best-effort extra layer for `memory_import`, whose input is only a path: reads the file (bounded, regular, under the project root or home) and screens it.
+ * Undefined, so the import proceeds, on any path, stat or read problem.
+ */
+async function importRefusal($: Dollar, s: Session, input: unknown): Promise<string | undefined> {
+ const home = await $.env.get('HOME').catch(() => undefined)
+ const path = importPath(input, s.root, home)
+ if (path === undefined) return undefined
+ const text = await readImport({ stat: p => $.fs.stat(p), read: p => $.fs.read(p) }, path)
+ return text === undefined ? undefined : importVerdict(text)
+}
+
/** One memory's full text through `memory_retrieve`; undefined on any failure (the cut text is then kept). */
async function full($: Dollar, server: string, tool: string, key: string, namespace: string | undefined): Promise<string | undefined> {
const res = await $.mcp.call(server, tool, namespace === undefined ? { key } : { key, namespace })
@@ -170,7 +183,7 @@ export const register: Register = (on, options) => {
if (s.opts.guard) {
on('tool.call', async ($, e, next) => {
- const reason = verdict(e.tool, e)
+ const reason = verdict(e.tool, e) ?? (isImport(e.tool) ? await importRefusal($, s, e) : undefined)
if (reason === undefined) return next(e)
s.stats.blocked++
await flush($, s)
diff --git a/plugins/ruflo-agentdb/scripts/smoke.sh b/plugins/ruflo-agentdb/scripts/smoke.sh
index cda1a101a8..05fc5ba254 100755
--- a/plugins/ruflo-agentdb/scripts/smoke.sh
+++ b/plugins/ruflo-agentdb/scripts/smoke.sh
@@ -48,10 +48,10 @@ grep -q "## Namespace convention" "$ROOT/README.md" \
&& ok || bad "Namespace convention section missing"
# 1. Plugin version + new keywords
-step "1. plugin.json declares version 0.4.5 with rabitq + namespace-convention keywords"
+step "1. plugin.json declares version 0.4.6 with rabitq + namespace-convention keywords"
v=$(grep -E '"version"[[:space:]]*:' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [[ "$v" != "0.4.5" ]]; then
- bad "expected 0.4.5, got '$v'"
+if [[ "$v" != "0.4.6" ]]; then
+ bad "expected 0.4.6, got '$v'"
else
miss=""
for k in rabitq quantization namespace-convention controller-bridge; do
diff --git a/plugins/ruflo-agentdb/tests/import.test.ts b/plugins/ruflo-agentdb/tests/import.test.ts
new file mode 100644
index 0000000000..ece74de25b
--- /dev/null
+++ b/plugins/ruflo-agentdb/tests/import.test.ts
@@ -0,0 +1,107 @@
+import type { On } from 'claude-code'
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import { importPath, importVerdict, IMPORT_MAX_BYTES, isImport, readImport } from '../hooks/import'
+
+tier('user')
+
+const ROOT = '/work'
+const HOME = '/home/u'
+const TOKEN = 'ghp_Zq8vT3mK9wX2LpR7sNd4Zq8vT3mK9wX2LpR7'
+const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
+const call = (tool: string, input: Record<string, unknown>) => ({ tool, ...input }) as never
+
+describe('which file memory_import would read', () => {
+ test('inside the project root or the home', () => {
+ expect(importPath({ inputPath: '/work/data/m.json' }, ROOT, HOME)).toBe('/work/data/m.json')
+ expect(importPath({ inputPath: 'data/./m.json' }, ROOT, HOME)).toBe('/work/data/m.json')
+ expect(importPath({ inputPath: '/home/u/notes/m.json' }, ROOT, HOME)).toBe('/home/u/notes/m.json')
+ })
+
+ test('traversal, outside paths, null bytes and non-strings are not read', () => {
+ for (const inputPath of ['/work/../etc/passwd', '../x.json', '/etc/passwd', '/workshop/m.json', '/work', 'a\0b.json', 'a\\..\\b', '', 7, null, ['/work/m.json']])
+ expect(importPath({ inputPath }, ROOT, HOME)).toBeUndefined()
+ expect(importPath({}, ROOT, HOME)).toBeUndefined()
+ expect(importPath('/work/m.json', ROOT, HOME)).toBeUndefined()
+ expect(importPath({ inputPath: 'm.json' }, undefined, undefined)).toBeUndefined()
+ })
+
+ test('the tool is memory_import, bare or prefixed', () => {
+ expect(isImport('memory_import')).toBe(true)
+ expect(isImport('mcp__ruflo__memory_import')).toBe(true)
+ expect(isImport('memory_import_claude')).toBe(false)
+ expect(isImport('memory_export')).toBe(false)
+ })
+})
+
+describe('the screen and the bounded read', () => {
+ test('a file holding a secret is refused without echoing it', () => {
+ const reason = importVerdict(JSON.stringify({ entries: [{ key: 'note', value: `token ${TOKEN}` }] }))
+ expect(reason).toMatch(/secret/)
+ expect(reason).not.toContain(TOKEN)
+ expect(importVerdict(JSON.stringify({ rows: [['api_key', 'Zq8vT3mK9wX2LpR7sNd4']] }))).toMatch(/secret/)
+ expect(importVerdict(`plain text with ${TOKEN}`)).toMatch(/secret/)
+ })
+
+ test('a clean file passes', () => {
+ expect(importVerdict(JSON.stringify({ entries: [{ key: 'note', value: 'see the vault' }] }))).toBeUndefined()
+ })
+
+ const files = (stat: () => Promise<{ kind: string; size: number }>, read = async () => 'x') => ({ stat, read })
+
+ test('an oversize file, a directory and any error fail open', async () => {
+ let reads = 0
+ const read = async () => (reads++, TOKEN)
+ expect(await readImport(files(async () => ({ kind: 'file', size: IMPORT_MAX_BYTES + 1 }), read), '/work/a')).toBeUndefined()
+ expect(await readImport(files(async () => ({ kind: 'dir', size: 10 }), read), '/work/a')).toBeUndefined()
+ expect(await readImport(files(async () => Promise.reject(new Error('ENOENT')), read), '/work/a')).toBeUndefined()
+ expect(await readImport(files(async () => ({ kind: 'file', size: 10 }), async () => Promise.reject(new Error('EACCES'))), '/work/a')).toBeUndefined()
+ expect(reads).toBe(0)
+ expect(await readImport(files(async () => ({ kind: 'file', size: IMPORT_MAX_BYTES }), read), '/work/a')).toBe(TOKEN)
+ })
+})
+
+/** The mod's tool.call hook over a file map, with the guard on (its default). */
+function world(on: On, fs: Map<string, { kind: string; size: number; text: string }>) {
+ const reads: string[] = []
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('session.root', () => ({ value: ROOT }))
+ on('command.register', ($, e) => ({ value: { command: e.name } }))
+ on('fs.write', () => ({ value: undefined }))
+ on('env.get', () => ({ value: HOME }))
+ on('fs.stat', ($, e) => {
+ const f = fs.get(e.path)
+ if (!f) throw new Error(`ENOENT: ${e.path}`)
+ return { value: { kind: f.kind, size: f.size, mtimeMs: 1 } }
+ })
+ on('fs.read', ($, e) => (reads.push(e.path), { value: fs.get(e.path)?.text ?? '' }))
+ return reads
+}
+
+type Dollar = Parameters<Parameters<typeof test>[1]>[0]
+const run = ($: Dollar, tool: string, inputPath: unknown) => $.tool.call(call(tool, { inputPath })).then(r => r, (e: unknown) => ({ text: String(e) }))
+
+const file = (text: string, kind = 'file') => ({ kind, size: text.length, text })
+
+describe('memory_import through the mod', () => {
+ test('refuses a file with a secret, under either name, and passes a clean one', async ($, on) => {
+ on('tool.call', () => ({ result: 'imported' }))
+ world(on, new Map([['/work/bad.json', file(`{"v":"${TOKEN}"}`)], ['/work/ok.json', file('{"v":"see the vault"}')]]))
+ await $.session.start(START)
+ for (const tool of ['memory_import', 'mcp__ruflo__memory_import']) {
+ const bad = await run($, tool, '/work/bad.json')
+ expect(JSON.stringify(bad)).toMatch(/secret/)
+ expect(JSON.stringify(bad)).not.toContain(TOKEN)
+ expect(JSON.stringify(await $.tool.call(call(tool, { inputPath: '/work/ok.json' })))).not.toMatch(/secret/)
+ }
+ })
+
+ test('missing file, directory, oversize file, traversal and non-string all pass unread', async ($, on) => {
+ on('tool.call', () => ({ result: 'imported' }))
+ const reads = world(on, new Map([['/work/dir', file('', 'dir')], ['/work/big.json', { kind: 'file', size: IMPORT_MAX_BYTES + 1, text: TOKEN }]]))
+ await $.session.start(START)
+ for (const inputPath of ['/work/none.json', '/work/dir', '/work/big.json', '/work/../etc/x', 42])
+ expect(JSON.stringify(await run($, 'memory_import', inputPath))).toContain('imported')
+ expect(reads).toEqual([])
+ })
+})