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(plugins): migrations, music, neural-trader, observability as mods (tighten-only guard, /<x>-mod, status file)

ruv30cfae1c9551
diff --git a/plugins/ruflo-migrations/.claude-plugin/plugin.json b/plugins/ruflo-migrations/.claude-plugin/plugin.json
index d3d2d9b662..97f3f89c33 100644
--- a/plugins/ruflo-migrations/.claude-plugin/plugin.json
+++ b/plugins/ruflo-migrations/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-migrations",
- "description": "Schema migration management — generate, validate, dry-run, and rollback database migrations",
- "version": "0.2.1",
+ "description": "Schema migration management — generate, validate, dry-run, and rollback database migrations. As a mod (ADR-445): a tighten-only guard on its tools, /migrations-mod, and a status file the console shows",
+ "version": "0.3.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -16,6 +16,22 @@
"rollback",
"mcp",
"dry-run",
- "up-down-pairs"
- ]
+ "up-down-pairs",
+ "mod",
+ "function-hooks",
+ "guard"
+ ],
+ "userConfig": {
+ "guard": {
+ "type": "string",
+ "title": "Guard",
+ "description": "Refuse calls and memory writes that hold a secret or a database URL with a password. On by default.",
+ "required": false,
+ "default": "on",
+ "options": [
+ "on",
+ "off"
+ ]
+ }
+ }
}
diff --git a/plugins/ruflo-migrations/README.md b/plugins/ruflo-migrations/README.md
index 0e92f95244..766cac609d 100644
--- a/plugins/ruflo-migrations/README.md
+++ b/plugins/ruflo-migrations/README.md
@@ -93,3 +93,19 @@ bash plugins/ruflo-migrations/scripts/smoke.sh
## License
MIT
+
+## As a mod
+
+Function-hook mod (ADR-445 pattern, `hooks/register.ts`). It adds, with no network, no process spawning and no model call:
+
+- **Guard** (tighten-only, default on): refuses a memory write (memory_store, agentdb_*store/batch) that holds a secret or a database URL with an inline password. The deny reason names the rule, never the value.
+- **`/migrations-mod`**: local `status` and `scan <text>` (secret check, same rules as the guard); `/migrations-mod scan <sql>` lints SQL for DROP/TRUNCATE/DROP COLUMN/DELETE-without-WHERE (read-only).
+- **Status file** `.claude-flow/migrations-mod/status.json` (`{version:1, updatedMs, guard, checked, blocked, ...}`), written at session start and when counters change.
+
+Per-prompt context is deliberately not added: this plugin has nothing worth attaching to every prompt.
+
+| Option | Default | Effect |
+|---|---|---|
+| `guard` | `on` | refuse the calls above |
+
+Test: `claude plugin validate plugins/ruflo-migrations`, `claude plugin test plugins/ruflo-migrations`, `bash plugins/ruflo-migrations/scripts/smoke.sh`.
diff --git a/plugins/ruflo-migrations/hooks/command.ts b/plugins/ruflo-migrations/hooks/command.ts
new file mode 100644
index 0000000000..73af4863f0
--- /dev/null
+++ b/plugins/ruflo-migrations/hooks/command.ts
@@ -0,0 +1,35 @@
+import { secretsIn } from './screen'
+import type { ModOptions } from './options'
+import type { Stats } from './status'
+
+const HELP = ['/migrations-mod status', '/migrations-mod scan <sql>'].join('\n')
+
+// Read-only lint: statements that lose data and belong only in a reviewed, dry-run down migration.
+const DESTRUCTIVE: readonly (readonly [string, RegExp])[] = [
+ ['drop table, schema or database', /\bDROP\s+(?:TABLE|DATABASE|SCHEMA)\b/i],
+ ['truncate', /\bTRUNCATE\b/i],
+ ['drop column', /\bALTER\s+TABLE\b[^;]*\bDROP\s+COLUMN\b/i],
+ ['delete without where', /\bDELETE\s+FROM\s+[\w."`]+\s*(?:;|$)/im],
+]
+
+/** `/migrations-mod` is answered locally and takes no model turn. */
+export function answer(args: string, opts: ModOptions, stats: Stats): string {
+ const [verb = '', ...rest] = args.trim().split(/\s+/)
+ const arg = rest.join(' ')
+
+ if (verb === '' || verb === 'help') return HELP
+
+ if (verb === 'status') {
+ return [`guard ${opts.guard ? 'on' : 'off'}`, `checked ${stats.checked} · blocked ${stats.blocked}${stats.lastBlock ? ` · last: ${stats.lastBlock}` : ''}`].join('\n')
+ }
+
+ if (verb === 'scan') {
+ if (arg === '') return 'usage: /migrations-mod scan <sql>'
+ const lost = DESTRUCTIVE.filter(([, re]) => re.test(arg)).map(([name]) => name)
+ const secrets = secretsIn(arg)
+ const parts = [lost.length ? `destructive: ${lost.join(', ')}` : '', secrets.length ? `secrets: ${secrets.join(', ')}` : ''].filter(Boolean)
+ return parts.length ? `Review before applying (${parts.join('; ')}).` : 'Nothing destructive or secret-shaped found.'
+ }
+
+ return `Unknown: ${verb}\n${HELP}`
+}
diff --git a/plugins/ruflo-migrations/hooks/guard.ts b/plugins/ruflo-migrations/hooks/guard.ts
new file mode 100644
index 0000000000..52b4af9d19
--- /dev/null
+++ b/plugins/ruflo-migrations/hooks/guard.ts
@@ -0,0 +1,19 @@
+import { secretsIn, textsOf } from './screen'
+import type { ModOptions } from './options'
+import type { Stats } from './status'
+
+const WRITERS = new Set(['memory_store', 'agentdb_pattern-store', 'agentdb_hierarchical-store', 'agentdb_batch'])
+const toolOf = (name: string) => (name.startsWith('mcp__') ? name.slice(name.lastIndexOf('__') + 2) : name)
+
+/**
+ * The reason a call is refused, or undefined when it may go. Migration SQL and connection strings are routinely pasted into memory, so a
+ * memory write holding a secret or a database URL with an inline password is refused. Names the rule, never echoes the value.
+ */
+export function verdict(tool: string, input: unknown, _opts: ModOptions, stats: Stats): string | undefined {
+ if (!WRITERS.has(toolOf(tool))) return undefined
+ stats.checked++
+ const found = textsOf(input).flatMap(secretsIn)
+ if (found.length === 0) return undefined
+ stats.lastBlock = found[0]
+ return 'ruflo-migrations: this memory write holds what looks like a secret or a database URL with a password. Store the migration name and a reference to where the credential lives, not the value.'
+}
diff --git a/plugins/ruflo-migrations/hooks/hooks.json b/plugins/ruflo-migrations/hooks/hooks.json
new file mode 100644
index 0000000000..cbe2d85cea
--- /dev/null
+++ b/plugins/ruflo-migrations/hooks/hooks.json
@@ -0,0 +1,6 @@
+{
+ "description": "ruflo-migrations as a mod (ADR-445 pattern): a tighten-only guard on this plugin's own tools, /migrations-mod, and a status file the console reads.",
+ "modules": [
+ "./register.ts"
+ ]
+}
diff --git a/plugins/ruflo-migrations/hooks/options.ts b/plugins/ruflo-migrations/hooks/options.ts
new file mode 100644
index 0000000000..4c64eae7f1
--- /dev/null
+++ b/plugins/ruflo-migrations/hooks/options.ts
@@ -0,0 +1,14 @@
+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
+}
+
+export const flag = (value: unknown, fallback: boolean) =>
+ value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback
+
+export function readOptions(options: PluginOptions | undefined): ModOptions {
+ const o = options ?? {}
+ return { guard: flag(o.guard, true) }
+}
diff --git a/plugins/ruflo-migrations/hooks/register.ts b/plugins/ruflo-migrations/hooks/register.ts
new file mode 100644
index 0000000000..e40454d6ba
--- /dev/null
+++ b/plugins/ruflo-migrations/hooks/register.ts
@@ -0,0 +1,60 @@
+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'
+
+type Dollar = Parameters<Hook<'session.start'>>[0]
+
+/** Everything one session of the mod keeps: its settings, counters and the project root. */
+type Session = { readonly opts: ModOptions; readonly stats: Stats; root?: string }
+
+async function flush($: Dollar, s: Session): Promise<void> {
+ if (s.root === undefined) return
+ try {
+ await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.stats, { guard: s.opts.guard }, await $.clock.now()))
+ } catch {
+ /* the status file is a courtesy */
+ }
+}
+
+/**
+ * ruflo-migrations as a mod (ADR-445 pattern): a tighten-only guard on this plugin's own tools, `/migrations-mod`, and a status file the console
+ * reads. No network, no process spawning, no model call: only tools already connected.
+ */
+export const register: Register = (on, options) => {
+ const s: Session = { opts: readOptions(options), stats: newStats() }
+
+ on('session.start', async ($, e, next) => {
+ const result = await next(e)
+ s.root = (await $.session.root()) as string | undefined
+ try {
+ await $.command.register({ name: 'migrations-mod', description: 'ruflo-migrations mod: status, scan <sql>' })
+ } catch {
+ /* a name taken by another plugin must not stop the mod */
+ }
+ await flush($, s)
+ return result
+ })
+
+ if (s.opts.guard) {
+ on('tool.call', async ($, e, next) => {
+ const before = s.stats.checked
+ const reason = verdict(e.tool, e, s.opts, s.stats)
+ if (reason === undefined) {
+ if (s.stats.checked !== before) await flush($, s)
+ return next(e)
+ }
+ s.stats.blocked++
+ await flush($, s)
+ return { deny: reason }
+ })
+ }
+
+ /** `/migrations-mod` (the plugin's own command is a prompt command, which no hook can answer). */
+ on('command.run', { command: 'migrations-mod' }, async (_$, e) => {
+ const args = typeof e.args === 'string' ? e.args : ''
+ return { text: answer(args, s.opts, s.stats) }
+ })
+}
diff --git a/plugins/ruflo-migrations/hooks/screen.ts b/plugins/ruflo-migrations/hooks/screen.ts
new file mode 100644
index 0000000000..df741eca9c
--- /dev/null
+++ b/plugins/ruflo-migrations/hooks/screen.ts
@@ -0,0 +1,47 @@
+/**
+ * Pure text screening for the ruflo-migrations mod (ADR-445 pattern). Findings are NAMES only: the matched text is never returned, logged or
+ * counted by value, so a deny reason cannot leak what it caught.
+ */
+
+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[A-Za-z0-9_-]*(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i],
+ ['database url with password', /\b[a-z][a-z0-9+.-]{1,20}:\/\/[^\s:@/]+:[^\s@/]{3,}@[^\s/]+/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 > 0
+
+/** 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) {
+ // A string field is also read as `name=value`, so {api_secret: '...'} trips the key-assignment rule like a pasted line would.
+ return Object.entries(input)
+ .slice(0, 200)
+ .flatMap(([k, v]) => (typeof v === 'string' ? textsOf(`${k}=${v}`, budget, depth + 1) : textsOf(v, budget, depth + 1)))
+ }
+ return []
+}
diff --git a/plugins/ruflo-migrations/hooks/status.ts b/plugins/ruflo-migrations/hooks/status.ts
new file mode 100644
index 0000000000..311db83ffd
--- /dev/null
+++ b/plugins/ruflo-migrations/hooks/status.ts
@@ -0,0 +1,16 @@
+/** Counters the mod keeps for the session and writes to `.claude-flow/migrations-mod/status.json` for the console. */
+export type Stats = {
+ checked: number
+ blocked: number
+ /** Why the last call was refused: a rule name, never the text that tripped it. */
+ lastBlock?: string
+}
+
+export const newStats = (): Stats => ({ checked: 0, blocked: 0 })
+
+export const STATUS_PATH = '.claude-flow/migrations-mod/status.json'
+
+/** The file's text; `version` lets the console refuse a shape it does not know. */
+export function statusText(stats: Stats, mode: Record<string, unknown>, nowMs: number): string {
+ return `${JSON.stringify({ version: 1, updatedMs: nowMs, ...mode, ...stats }, null, 2)}\n`
+}
diff --git a/plugins/ruflo-migrations/scripts/smoke.sh b/plugins/ruflo-migrations/scripts/smoke.sh
index e297c072fa..2a79c97076 100755
--- a/plugins/ruflo-migrations/scripts/smoke.sh
+++ b/plugins/ruflo-migrations/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'"; else
miss=""
for k in mcp dry-run up-down-pairs; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
@@ -82,5 +82,23 @@ for f in "$ROOT"/skills/*/SKILL.md; do
done
[[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills"
+# M1-M3. The mod (ADR-445 pattern): hooks module registered, files within the 500-line rule, safe defaults, no network or process access
+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 command status register; 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 defaults 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 1
diff --git a/plugins/ruflo-migrations/tests/migrations-mod.test.ts b/plugins/ruflo-migrations/tests/migrations-mod.test.ts
new file mode 100644
index 0000000000..b28a942e84
--- /dev/null
+++ b/plugins/ruflo-migrations/tests/migrations-mod.test.ts
@@ -0,0 +1,103 @@
+import type { On } from 'claude-code'
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+tier('user')
+
+const ROOT = '/work'
+const STATUS = `${ROOT}/.claude-flow/migrations-mod/status.json`
+const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
+const slash = (args: string) => ({ command: 'migrations-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const
+const KEY = `ghp_${'a1B2'.repeat(10)}`
+
+/** The world beneath the mod: a project root, a file map, a command registry; every tool call is answered 'ok'. */
+function world(on: On) {
+ const files = new Map<string, string>()
+ const registered: string[] = []
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('session.root', () => ({ value: ROOT }))
+ on('command.register', ($, e) => (registered.push(e.name), { value: { command: e.name } }))
+ on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined }))
+ on('clock.now', () => ({ value: 1_700_000_000_000 }))
+ on('tool.call', () => ({ result: 'ok' }))
+ return { files, registered }
+}
+
+const call = (tool: string, input: Record<string, unknown>) => ({ tool, ...input }) as never
+const store = (value: string) => call('mcp__plugin_ruflo-core_ruflo__memory_store', { key: 'k', namespace: 'migrations', value })
+const status = (files: Map<string, string>) => JSON.parse(files.get(STATUS) ?? '{}')
+
+/** Runs the call; a denial surfaces as a rejection or a deny result, flattened to text either way. */
+async function outcome($: { tool: { call: (e: never) => Promise<unknown> } }, e: never): Promise<string> {
+ try {
+ return JSON.stringify(await $.tool.call(e))
+ } catch (err) {
+ return String(err)
+ }
+}
+
+describe('session', () => {
+ test('writes the status file and registers /migrations-mod, guard on by default', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ expect(w.registered).toEqual(['migrations-mod'])
+ expect(status(w.files)).toMatchObject({ version: 1, guard: true, checked: 0, blocked: 0 })
+ expect(typeof status(w.files).updatedMs).toBe('number')
+ })
+})
+
+describe('guard', () => {
+ test('refuses a secret in a memory write, passes a clean one, never echoes the value', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ const denied = await outcome($, store(`token ${KEY}`))
+ expect(denied).toContain('ruflo-migrations')
+ expect(denied).not.toContain('ghp_')
+ expect(await outcome($, store('prefer small reversible steps'))).toContain('ok')
+ expect(status(w.files)).toMatchObject({ checked: 2, blocked: 1, lastBlock: 'github token' })
+ })
+
+ test('ignores tools that are not this mod\'s business', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ expect(await outcome($, call('Bash', { command: `echo ${KEY}` }))).toContain('ok')
+ expect(status(w.files).checked).toBe(0)
+ })
+
+ test('guard: off lets the write through', { options: { guard: 'off' } }, async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect(await outcome($, store(`token ${KEY}`))).toContain('ok')
+ })
+
+ test('refuses a database URL with an inline password, allows one without', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ const denied = await outcome($, store('applied against postgres://app:[email protected]:5432/prod'))
+ expect(denied).toContain('database URL')
+ expect(denied).not.toContain('hunter2')
+ expect(await outcome($, store('applied against postgres://db.internal:5432/prod'))).toContain('ok')
+ })
+})
+
+describe('/migrations-mod', () => {
+ test('status and scan answer locally', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect((await $.command.run(slash('status'))).text).toContain('guard on')
+ const hit = (await $.command.run(slash(`scan key ${KEY}`))).text ?? ''
+ expect(hit).toContain('github token')
+ expect(hit).not.toContain('ghp_')
+ expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing')
+ const lint = (await $.command.run(slash('scan DROP TABLE users; DELETE FROM sessions;'))).text ?? ''
+ expect(lint).toContain('drop table, schema or database')
+ expect(lint).toContain('delete without where')
+ expect((await $.command.run(slash('scan DELETE FROM sessions WHERE id = 1;'))).text).toContain('Nothing destructive')
+ })
+
+ test('an unknown verb or none gets the help, not a model turn', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect((await $.command.run(slash('how do I do this'))).text).toContain('/migrations-mod status')
+ expect((await $.command.run(slash(''))).text).toContain('/migrations-mod scan')
+ })
+})
diff --git a/plugins/ruflo-migrations/tsconfig.json b/plugins/ruflo-migrations/tsconfig.json
new file mode 100644
index 0000000000..e4ba54993e
--- /dev/null
+++ b/plugins/ruflo-migrations/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"]
+}
diff --git a/plugins/ruflo-music/.claude-plugin/plugin.json b/plugins/ruflo-music/.claude-plugin/plugin.json
index fd7ba55fa1..7750ddb5ad 100644
--- a/plugins/ruflo-music/.claude-plugin/plugin.json
+++ b/plugins/ruflo-music/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-music",
- "description": "AI music generation via Cognitum Music (cogmusic MCP) — compose lyrics/prompts, generate tracks, separate stems, extract MIDI, and master through your own music.cognitum.one account",
- "version": "0.1.0",
+ "description": "AI music generation via Cognitum Music (cogmusic MCP) — compose lyrics/prompts, generate tracks, separate stems, extract MIDI, and master through your own music.cognitum.one account. As a mod (ADR-445): a tighten-only guard on its tools, /music-mod, and a status file the console shows",
+ "version": "0.2.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -19,6 +19,22 @@
"minimax-music3",
"stems",
"midi",
- "mastering"
- ]
+ "mastering",
+ "mod",
+ "function-hooks",
+ "guard"
+ ],
+ "userConfig": {
+ "guard": {
+ "type": "string",
+ "title": "Guard",
+ "description": "Refuse calls and memory writes that hold a secret. On by default.",
+ "required": false,
+ "default": "on",
+ "options": [
+ "on",
+ "off"
+ ]
+ }
+ }
}
diff --git a/plugins/ruflo-music/README.md b/plugins/ruflo-music/README.md
index ff22e84bf4..52c7e1e287 100644
--- a/plugins/ruflo-music/README.md
+++ b/plugins/ruflo-music/README.md
@@ -113,3 +113,19 @@ bash plugins/ruflo-music/scripts/smoke.sh
## License
MIT
+
+## As a mod
+
+Function-hook mod (ADR-445 pattern, `hooks/register.ts`). It adds, with no network, no process spawning and no model call:
+
+- **Guard** (tighten-only, default on): refuses a `cogmusic` call (create_production, separate_stems, master, extract_midi) or memory write whose prompt/lyrics/payload holds a secret (prompts leave the machine for music.cognitum.one). The deny reason names the rule, never the value.
+- **`/music-mod`**: local `status` and `scan <text>` (secret check, same rules as the guard); the status file also counts productions started.
+- **Status file** `.claude-flow/music-mod/status.json` (`{version:1, updatedMs, guard, checked, blocked, ...}`), written at session start and when counters change.
+
+Per-prompt context is deliberately not added: this plugin has nothing worth attaching to every prompt.
+
+| Option | Default | Effect |
+|---|---|---|
+| `guard` | `on` | refuse the calls above |
+
+Test: `claude plugin validate plugins/ruflo-music`, `claude plugin test plugins/ruflo-music`, `bash plugins/ruflo-music/scripts/smoke.sh`.
diff --git a/plugins/ruflo-music/hooks/command.ts b/plugins/ruflo-music/hooks/command.ts
new file mode 100644
index 0000000000..9be51fd1f8
--- /dev/null
+++ b/plugins/ruflo-music/hooks/command.ts
@@ -0,0 +1,28 @@
+import { secretsIn } from './screen'
+import type { ModOptions } from './options'
+import type { Stats } from './status'
+
+const HELP = ['/music-mod status', '/music-mod scan <text>'].join('\n')
+
+/** `/music-mod` is answered locally and takes no model turn. */
+export function answer(args: string, opts: ModOptions, stats: Stats): string {
+ const [verb = '', ...rest] = args.trim().split(/\s+/)
+ const arg = rest.join(' ')
+
+ if (verb === '' || verb === 'help') return HELP
+
+ if (verb === 'status') {
+ return [
+ `guard ${opts.guard ? 'on' : 'off'}`,
+ `checked ${stats.checked} · blocked ${stats.blocked} · productions started ${stats.productions}${stats.lastBlock ? ` · last: ${stats.lastBlock}` : ''}`,
+ ].join('\n')
+ }
+
+ if (verb === 'scan') {
+ if (arg === '') return 'usage: /music-mod scan <text>'
+ const found = secretsIn(arg)
+ return found.length ? `The guard would refuse a write or call carrying that (${found.join(', ')}).` : 'Nothing secret-shaped found: the guard would let that through.'
+ }
+
+ return `Unknown: ${verb}\n${HELP}`
+}
diff --git a/plugins/ruflo-music/hooks/guard.ts b/plugins/ruflo-music/hooks/guard.ts
new file mode 100644
index 0000000000..0434e16aa9
--- /dev/null
+++ b/plugins/ruflo-music/hooks/guard.ts
@@ -0,0 +1,30 @@
+import { secretsIn, textsOf } from './screen'
+import type { ModOptions } from './options'
+import type { Stats } from './status'
+
+const WRITERS = new Set(['memory_store', 'agentdb_pattern-store', 'agentdb_hierarchical-store'])
+const OWN = new Set(['create_production', 'separate_stems', 'master', 'extract_midi'])
+
+const toolOf = (name: string) => (name.startsWith('mcp__') ? name.slice(name.lastIndexOf('__') + 2) : name)
+const serverOf = (name: string) => (name.startsWith('mcp__') ? name.slice(5, name.lastIndexOf('__')) : '')
+/** The cogmusic server, however the plugin names it (`cogmusic` or `plugin_ruflo-music_cogmusic`). */
+const isCogmusic = (name: string) => serverOf(name).includes('cogmusic') && OWN.has(toolOf(name))
+
+/**
+ * The reason a call is refused, or undefined when it may go. Prompts and lyrics leave the machine for music.cognitum.one, and memory
+ * writes persist, so neither may carry a key, token or password. Names the rule, never echoes the value.
+ */
+export function verdict(tool: string, input: unknown, _opts: ModOptions, stats: Stats): string | undefined {
+ const sends = isCogmusic(tool)
+ if (!sends && !WRITERS.has(toolOf(tool))) return undefined
+ stats.checked++
+ const found = textsOf(input).flatMap(secretsIn)
+ if (found.length === 0) {
+ if (sends && toolOf(tool) === 'create_production') stats.productions++
+ return undefined
+ }
+ stats.lastBlock = found[0]
+ return sends
+ ? 'ruflo-music: this prompt or lyrics hold what looks like a secret (a key, token or password); they would be sent to the music service. Remove it and try again.'
+ : 'ruflo-music: this memory write holds what looks like a secret (a key, token or password). Store a reference to where it lives, not the value.'
+}
diff --git a/plugins/ruflo-music/hooks/hooks.json b/plugins/ruflo-music/hooks/hooks.json
new file mode 100644
index 0000000000..e45d64ffc5
--- /dev/null
+++ b/plugins/ruflo-music/hooks/hooks.json
@@ -0,0 +1,6 @@
+{
+ "description": "ruflo-music as a mod (ADR-445 pattern): a tighten-only guard on this plugin's own tools, /music-mod, and a status file the console reads.",
+ "modules": [
+ "./register.ts"
+ ]
+}
diff --git a/plugins/ruflo-music/hooks/options.ts b/plugins/ruflo-music/hooks/options.ts
new file mode 100644
index 0000000000..4c64eae7f1
--- /dev/null
+++ b/plugins/ruflo-music/hooks/options.ts
@@ -0,0 +1,14 @@
+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
+}
+
+export const flag = (value: unknown, fallback: boolean) =>
+ value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback
+
+export function readOptions(options: PluginOptions | undefined): ModOptions {
+ const o = options ?? {}
+ return { guard: flag(o.guard, true) }
+}
diff --git a/plugins/ruflo-music/hooks/register.ts b/plugins/ruflo-music/hooks/register.ts
new file mode 100644
index 0000000000..9141f29242
--- /dev/null
+++ b/plugins/ruflo-music/hooks/register.ts
@@ -0,0 +1,60 @@
+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'
+
+type Dollar = Parameters<Hook<'session.start'>>[0]
+
+/** Everything one session of the mod keeps: its settings, counters and the project root. */
+type Session = { readonly opts: ModOptions; readonly stats: Stats; root?: string }
+
+async function flush($: Dollar, s: Session): Promise<void> {
+ if (s.root === undefined) return
+ try {
+ await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.stats, { guard: s.opts.guard }, await $.clock.now()))
+ } catch {
+ /* the status file is a courtesy */
+ }
+}
+
+/**
+ * ruflo-music as a mod (ADR-445 pattern): a tighten-only guard on this plugin's own tools, `/music-mod`, and a status file the console
+ * reads. No network, no process spawning, no model call: only tools already connected.
+ */
+export const register: Register = (on, options) => {
+ const s: Session = { opts: readOptions(options), stats: newStats() }
+
+ on('session.start', async ($, e, next) => {
+ const result = await next(e)
+ s.root = (await $.session.root()) as string | undefined
+ try {
+ await $.command.register({ name: 'music-mod', description: 'ruflo-music mod: status, scan <text>' })
+ } catch {
+ /* a name taken by another plugin must not stop the mod */
+ }
+ await flush($, s)
+ return result
+ })
+
+ if (s.opts.guard) {
+ on('tool.call', async ($, e, next) => {
+ const before = s.stats.checked
+ const reason = verdict(e.tool, e, s.opts, s.stats)
+ if (reason === undefined) {
+ if (s.stats.checked !== before) await flush($, s)
+ return next(e)
+ }
+ s.stats.blocked++
+ await flush($, s)
+ return { deny: reason }
+ })
+ }
+
+ /** `/music-mod` (the plugin's own command is a prompt command, which no hook can answer). */
+ on('command.run', { command: 'music-mod' }, async (_$, e) => {
+ const args = typeof e.args === 'string' ? e.args : ''
+ return { text: answer(args, s.opts, s.stats) }
+ })
+}
diff --git a/plugins/ruflo-music/hooks/screen.ts b/plugins/ruflo-music/hooks/screen.ts
new file mode 100644
index 0000000000..1fcad54e84
--- /dev/null
+++ b/plugins/ruflo-music/hooks/screen.ts
@@ -0,0 +1,46 @@
+/**
+ * Pure text screening for the ruflo-music mod (ADR-445 pattern). Findings are NAMES only: the matched text is never returned, logged or
+ * counted by value, so a deny reason cannot leak what it caught.
+ */
+
+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[A-Za-z0-9_-]*(?: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 > 0
+
+/** 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) {
+ // A string field is also read as `name=value`, so {api_secret: '...'} trips the key-assignment rule like a pasted line would.
+ return Object.entries(input)
+ .slice(0, 200)
+ .flatMap(([k, v]) => (typeof v === 'string' ? textsOf(`${k}=${v}`, budget, depth + 1) : textsOf(v, budget, depth + 1)))
+ }
+ return []
+}
diff --git a/plugins/ruflo-music/hooks/status.ts b/plugins/ruflo-music/hooks/status.ts
new file mode 100644
index 0000000000..a6ce9a488f
--- /dev/null
+++ b/plugins/ruflo-music/hooks/status.ts
@@ -0,0 +1,18 @@
+/** Counters the mod keeps for the session and writes to `.claude-flow/music-mod/status.json` for the console. */
+export type Stats = {
+ checked: number
+ blocked: number
+ /** Productions started (create_production calls seen). */
+ productions: number
+ /** Why the last call was refused: a rule name, never the text that tripped it. */
+ lastBlock?: string
+}
+
+export const newStats = (): Stats => ({ checked: 0, blocked: 0, productions: 0 })
+
+export const STATUS_PATH = '.claude-flow/music-mod/status.json'
+
+/** The file's text; `version` lets the console refuse a shape it does not know. */
+export function statusText(stats: Stats, mode: Record<string, unknown>, nowMs: number): string {
+ return `${JSON.stringify({ version: 1, updatedMs: nowMs, ...mode, ...stats }, null, 2)}\n`
+}
diff --git a/plugins/ruflo-music/scripts/smoke.sh b/plugins/ruflo-music/scripts/smoke.sh
index 2e1b254899..22f031a863 100755
--- a/plugins/ruflo-music/scripts/smoke.sh
+++ b/plugins/ruflo-music/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.1.0 with expected keywords"
+step "1. plugin.json declares 0.2.0 with expected keywords"
v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [[ "$v" != "0.1.0" ]]; then bad "expected 0.1.0, got '$v'"; else
+if [[ "$v" != "0.2.0" ]]; then bad "expected 0.2.0, got '$v'"; else
miss=""
for k in cogmusic cognitum mcp; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
@@ -73,5 +73,23 @@ for f in "$ROOT"/skills/*/SKILL.md; do
done
[[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills"
+# M1-M3. The mod (ADR-445 pattern): hooks module registered, files within the 500-line rule, safe defaults, no network or process access
+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 command status register; 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 defaults 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 1
diff --git a/plugins/ruflo-music/tests/music-mod.test.ts b/plugins/ruflo-music/tests/music-mod.test.ts
new file mode 100644
index 0000000000..26a081a804
--- /dev/null
+++ b/plugins/ruflo-music/tests/music-mod.test.ts
@@ -0,0 +1,102 @@
+import type { On } from 'claude-code'
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+tier('user')
+
+const ROOT = '/work'
+const STATUS = `${ROOT}/.claude-flow/music-mod/status.json`
+const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
+const slash = (args: string) => ({ command: 'music-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const
+const KEY = `ghp_${'a1B2'.repeat(10)}`
+
+/** The world beneath the mod: a project root, a file map, a command registry; every tool call is answered 'ok'. */
+function world(on: On) {
+ const files = new Map<string, string>()
+ const registered: string[] = []
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('session.root', () => ({ value: ROOT }))
+ on('command.register', ($, e) => (registered.push(e.name), { value: { command: e.name } }))
+ on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined }))
+ on('clock.now', () => ({ value: 1_700_000_000_000 }))
+ on('tool.call', () => ({ result: 'ok' }))
+ return { files, registered }
+}
+
+const call = (tool: string, input: Record<string, unknown>) => ({ tool, ...input }) as never
+const store = (value: string) => call('mcp__plugin_ruflo-core_ruflo__memory_store', { key: 'k', namespace: 'music-briefs', value })
+const status = (files: Map<string, string>) => JSON.parse(files.get(STATUS) ?? '{}')
+
+/** Runs the call; a denial surfaces as a rejection or a deny result, flattened to text either way. */
+async function outcome($: { tool: { call: (e: never) => Promise<unknown> } }, e: never): Promise<string> {
+ try {
+ return JSON.stringify(await $.tool.call(e))
+ } catch (err) {
+ return String(err)
+ }
+}
+
+describe('session', () => {
+ test('writes the status file and registers /music-mod, guard on by default', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ expect(w.registered).toEqual(['music-mod'])
+ expect(status(w.files)).toMatchObject({ version: 1, guard: true, checked: 0, blocked: 0 })
+ expect(typeof status(w.files).updatedMs).toBe('number')
+ })
+})
+
+describe('guard', () => {
+ test('refuses a secret in a memory write, passes a clean one, never echoes the value', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ const denied = await outcome($, store(`token ${KEY}`))
+ expect(denied).toContain('ruflo-music')
+ expect(denied).not.toContain('ghp_')
+ expect(await outcome($, store('prefer small reversible steps'))).toContain('ok')
+ expect(status(w.files)).toMatchObject({ checked: 2, blocked: 1, lastBlock: 'github token' })
+ })
+
+ test('ignores tools that are not this mod\'s business', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ expect(await outcome($, call('Bash', { command: `echo ${KEY}` }))).toContain('ok')
+ expect(status(w.files).checked).toBe(0)
+ })
+
+ test('guard: off lets the write through', { options: { guard: 'off' } }, async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect(await outcome($, store(`token ${KEY}`))).toContain('ok')
+ })
+
+ test('cogmusic calls are screened, and productions are counted', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ const make = (prompt: string) => call('mcp__plugin_ruflo-music_cogmusic__create_production', { prompt })
+ const denied = await outcome($, make(`lofi beat, api_key=${KEY}`))
+ expect(denied).toContain('music service')
+ expect(denied).not.toContain('ghp_')
+ expect(await outcome($, make('lofi beat, rainy night'))).toContain('ok')
+ expect(await outcome($, call('mcp__plugin_ruflo-music_cogmusic__get_production', { id: KEY }))).toContain('ok')
+ expect(status(w.files)).toMatchObject({ productions: 1, blocked: 1 })
+ })
+})
+
+describe('/music-mod', () => {
+ test('status and scan answer locally', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect((await $.command.run(slash('status'))).text).toContain('guard on')
+ const hit = (await $.command.run(slash(`scan key ${KEY}`))).text ?? ''
+ expect(hit).toContain('github token')
+ expect(hit).not.toContain('ghp_')
+ expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing')
+ })
+
+ test('an unknown verb or none gets the help, not a model turn', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect((await $.command.run(slash('how do I do this'))).text).toContain('/music-mod status')
+ expect((await $.command.run(slash(''))).text).toContain('/music-mod scan')
+ })
+})
diff --git a/plugins/ruflo-music/tsconfig.json b/plugins/ruflo-music/tsconfig.json
new file mode 100644
index 0000000000..e4ba54993e
--- /dev/null
+++ b/plugins/ruflo-music/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"]
+}
diff --git a/plugins/ruflo-neural-trader/.claude-plugin/plugin.json b/plugins/ruflo-neural-trader/.claude-plugin/plugin.json
index 3b147bf0be..334ce3a070 100644
--- a/plugins/ruflo-neural-trader/.claude-plugin/plugin.json
+++ b/plugins/ruflo-neural-trader/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-neural-trader",
- "description": "Neural trading via npx neural-trader — self-learning strategies, Rust/NAPI backtesting, 112+ MCP tools, swarm coordination, and portfolio optimization",
- "version": "0.2.1",
+ "description": "Neural trading via npx neural-trader — self-learning strategies, Rust/NAPI backtesting, 112+ MCP tools, swarm coordination, and portfolio optimization. As a mod (ADR-445): a tighten-only guard on its tools, /trader-mod, and a status file the console shows",
+ "version": "0.3.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -21,6 +21,33 @@
"swarm",
"neural-trader-runtime",
"walk-forward",
- "monte-carlo"
- ]
+ "monte-carlo",
+ "mod",
+ "function-hooks",
+ "guard"
+ ],
+ "userConfig": {
+ "guard": {
+ "type": "string",
+ "title": "Guard",
+ "description": "Refuse calls and memory writes that hold a secret. On by default.",
+ "required": false,
+ "default": "on",
+ "options": [
+ "on",
+ "off"
+ ]
+ },
+ "liveGuard": {
+ "type": "string",
+ "title": "Live-order guard",
+ "description": "Refuse a live order call unless it carries confirm: true (or paper: true). On by default.",
+ "required": false,
+ "default": "on",
+ "options": [
+ "on",
+ "off"
+ ]
+ }
+ }
}
diff --git a/plugins/ruflo-neural-trader/README.md b/plugins/ruflo-neural-trader/README.md
index 384e3222d5..26351e63ea 100644
--- a/plugins/ruflo-neural-trader/README.md
+++ b/plugins/ruflo-neural-trader/README.md
@@ -326,3 +326,19 @@ bash plugins/ruflo-neural-trader/scripts/smoke.sh
## License
MIT
+
+## As a mod
+
+Function-hook mod (ADR-445 pattern, `hooks/register.ts`). It adds, with no network, no process spawning and no model call:
+
+- **Guard** (tighten-only, default on): refuses a trader-server call or memory write that holds a secret (broker keys), and a live order call (`execute_trade`, `place_order`, `live_*`, `close_all`) that lacks `confirm: true` (or `paper: true` / `dryRun: true`). The deny reason names the rule, never the value.
+- **`/trader-mod`**: local `status` and `scan <text>` (secret check, same rules as the guard); `status` also shows live orders refused.
+- **Status file** `.claude-flow/trader-mod/status.json` (`{version:1, updatedMs, guard, checked, blocked, ...}`), written at session start and when counters change.
+
+Per-prompt context is deliberately not added: this plugin has nothing worth attaching to every prompt.
+
+| Option | Default | Effect |
+|---|---|---|
+| `guard` | `on` | refuse the calls above | | `liveGuard` | `on` | refuse an unconfirmed live order |
+
+Test: `claude plugin validate plugins/ruflo-neural-trader`, `claude plugin test plugins/ruflo-neural-trader`, `bash plugins/ruflo-neural-trader/scripts/smoke.sh`.
diff --git a/plugins/ruflo-neural-trader/hooks/command.ts b/plugins/ruflo-neural-trader/hooks/command.ts
new file mode 100644
index 0000000000..a6aa70e105
--- /dev/null
+++ b/plugins/ruflo-neural-trader/hooks/command.ts
@@ -0,0 +1,28 @@
+import { secretsIn } from './screen'
+import type { ModOptions } from './options'
+import type { Stats } from './status'
+
+const HELP = ['/trader-mod status', '/trader-mod scan <text>'].join('\n')
+
+/** `/trader-mod` is answered locally and takes no model turn. */
+export function answer(args: string, opts: ModOptions, stats: Stats): string {
+ const [verb = '', ...rest] = args.trim().split(/\s+/)
+ const arg = rest.join(' ')
+
+ if (verb === '' || verb === 'help') return HELP
+
+ if (verb === 'status') {
+ return [
+ `guard ${opts.guard ? 'on' : 'off'} · live-order guard ${opts.liveGuard ? 'on' : 'off'}`,
+ `checked ${stats.checked} · blocked ${stats.blocked} · live orders refused ${stats.liveBlocked}${stats.lastBlock ? ` · last: ${stats.lastBlock}` : ''}`,
+ ].join('\n')
+ }
+
+ if (verb === 'scan') {
+ if (arg === '') return 'usage: /trader-mod scan <text>'
+ const found = secretsIn(arg)
+ return found.length ? `The guard would refuse a write or call carrying that (${found.join(', ')}).` : 'Nothing secret-shaped found: the guard would let that through.'
+ }
+
+ return `Unknown: ${verb}\n${HELP}`
+}
diff --git a/plugins/ruflo-neural-trader/hooks/guard.ts b/plugins/ruflo-neural-trader/hooks/guard.ts
new file mode 100644
index 0000000000..13b1d76569
--- /dev/null
+++ b/plugins/ruflo-neural-trader/hooks/guard.ts
@@ -0,0 +1,40 @@
+import { secretsIn, textsOf } from './screen'
+import type { ModOptions } from './options'
+import type { Stats } from './status'
+
+const WRITERS = new Set(['memory_store', 'agentdb_pattern-store', 'agentdb_hierarchical-store', 'agentdb_batch'])
+// Order placement on a neural-trader MCP server (`neural-trader mcp start`), however the plugin names the server.
+const ORDER = /^(?:execute|place|submit)[_-]?(?:trade|order)s?$|^live[_-]?(?:trade|order|execute)|^(?:close|cancel)[_-]?all/i
+
+const toolOf = (name: string) => (name.startsWith('mcp__') ? name.slice(name.lastIndexOf('__') + 2) : name)
+const serverOf = (name: string) => (name.startsWith('mcp__') ? name.slice(5, name.lastIndexOf('__')) : '')
+const isTrader = (name: string) => /neural[-_]?trader/i.test(serverOf(name))
+
+/** Whether the call states, in its own input, that it is a paper trade or carries an explicit confirm. */
+function confirmed(input: unknown): boolean {
+ const top = typeof input === 'object' && input !== null ? (input as Record<string, unknown>) : {}
+ const inner = typeof top.input === 'object' && top.input !== null ? (top.input as Record<string, unknown>) : {}
+ return [top, inner].some(o => o.confirm === true || o.confirmed === true || o.paper === true || o.dryRun === true || o.dry_run === true)
+}
+
+/**
+ * The reason a call is refused, or undefined when it may go. Two rules: a memory write or trader call holding a secret is refused
+ * (broker keys must not be stored or echoed), and a live order call without an explicit `confirm: true` (or `paper`/`dryRun`) is refused.
+ * Names the rule, never echoes the value.
+ */
+export function verdict(tool: string, input: unknown, opts: ModOptions, stats: Stats): string | undefined {
+ const trader = isTrader(tool)
+ if (!trader && !WRITERS.has(toolOf(tool))) return undefined
+ stats.checked++
+ const found = textsOf(input).flatMap(secretsIn)
+ if (found.length > 0) {
+ stats.lastBlock = found[0]
+ return 'ruflo-neural-trader: this call holds what looks like a secret (a broker key, token or password). Keep credentials in the environment and pass a reference, not the value.'
+ }
+ if (opts.liveGuard && trader && ORDER.test(toolOf(tool)) && !confirmed(input)) {
+ stats.liveBlocked++
+ stats.lastBlock = 'live order without confirm'
+ return 'ruflo-neural-trader: a live order needs an explicit confirm: true in the call (or paper: true to simulate). Re-run the paper backtest and risk gate first.'
+ }
+ return undefined
+}
diff --git a/plugins/ruflo-neural-trader/hooks/hooks.json b/plugins/ruflo-neural-trader/hooks/hooks.json
new file mode 100644
index 0000000000..3e6611fc51
--- /dev/null
+++ b/plugins/ruflo-neural-trader/hooks/hooks.json
@@ -0,0 +1,6 @@
+{
+ "description": "ruflo-neural-trader as a mod (ADR-445 pattern): a tighten-only guard on this plugin's own tools, /trader-mod, and a status file the console reads.",
+ "modules": [
+ "./register.ts"
+ ]
+}
diff --git a/plugins/ruflo-neural-trader/hooks/options.ts b/plugins/ruflo-neural-trader/hooks/options.ts
new file mode 100644
index 0000000000..a5322b6fe8
--- /dev/null
+++ b/plugins/ruflo-neural-trader/hooks/options.ts
@@ -0,0 +1,15 @@
+import type { PluginOptions } from 'claude-code'
+
+/** The plugin's `userConfig`, validated: a bad value is the default (both guards on). */
+export type ModOptions = {
+ readonly guard: boolean
+ readonly liveGuard: boolean
+}
+
+export const flag = (value: unknown, fallback: boolean) =>
+ value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback
+
+export function readOptions(options: PluginOptions | undefined): ModOptions {
+ const o = options ?? {}
+ return { guard: flag(o.guard, true), liveGuard: flag(o.liveGuard, true) }
+}
diff --git a/plugins/ruflo-neural-trader/hooks/register.ts b/plugins/ruflo-neural-trader/hooks/register.ts
new file mode 100644
index 0000000000..ae502f5c2a
--- /dev/null
+++ b/plugins/ruflo-neural-trader/hooks/register.ts
@@ -0,0 +1,60 @@
+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'
+
+type Dollar = Parameters<Hook<'session.start'>>[0]
+
+/** Everything one session of the mod keeps: its settings, counters and the project root. */
+type Session = { readonly opts: ModOptions; readonly stats: Stats; root?: string }
+
+async function flush($: Dollar, s: Session): Promise<void> {
+ if (s.root === undefined) return
+ try {
+ await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.stats, { guard: s.opts.guard, liveGuard: s.opts.liveGuard }, await $.clock.now()))
+ } catch {
+ /* the status file is a courtesy */
+ }
+}
+
+/**
+ * ruflo-neural-trader as a mod (ADR-445 pattern): a tighten-only guard on this plugin's own tools, `/trader-mod`, and a status file the console
+ * reads. No network, no process spawning, no model call: only tools already connected.
+ */
+export const register: Register = (on, options) => {
+ const s: Session = { opts: readOptions(options), stats: newStats() }
+
+ on('session.start', async ($, e, next) => {
+ const result = await next(e)
+ s.root = (await $.session.root()) as string | undefined
+ try {
+ await $.command.register({ name: 'trader-mod', description: 'ruflo-neural-trader mod: status, scan <text>' })
+ } catch {
+ /* a name taken by another plugin must not stop the mod */
+ }
+ await flush($, s)
+ return result
+ })
+
+ if (s.opts.guard) {
+ on('tool.call', async ($, e, next) => {
+ const before = s.stats.checked
+ const reason = verdict(e.tool, e, s.opts, s.stats)
+ if (reason === undefined) {
+ if (s.stats.checked !== before) await flush($, s)
+ return next(e)
+ }
+ s.stats.blocked++
+ await flush($, s)
+ return { deny: reason }
+ })
+ }
+
+ /** `/trader-mod` (the plugin's own command is a prompt command, which no hook can answer). */
+ on('command.run', { command: 'trader-mod' }, async (_$, e) => {
+ const args = typeof e.args === 'string' ? e.args : ''
+ return { text: answer(args, s.opts, s.stats) }
+ })
+}
diff --git a/plugins/ruflo-neural-trader/hooks/screen.ts b/plugins/ruflo-neural-trader/hooks/screen.ts
new file mode 100644
index 0000000000..8a6552c2f1
--- /dev/null
+++ b/plugins/ruflo-neural-trader/hooks/screen.ts
@@ -0,0 +1,46 @@
+/**
+ * Pure text screening for the ruflo-neural-trader mod (ADR-445 pattern). Findings are NAMES only: the matched text is never returned, logged or
+ * counted by value, so a deny reason cannot leak what it caught.
+ */
+
+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[A-Za-z0-9_-]*(?: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 > 0
+
+/** 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) {
+ // A string field is also read as `name=value`, so {api_secret: '...'} trips the key-assignment rule like a pasted line would.
+ return Object.entries(input)
+ .slice(0, 200)
+ .flatMap(([k, v]) => (typeof v === 'string' ? textsOf(`${k}=${v}`, budget, depth + 1) : textsOf(v, budget, depth + 1)))
+ }
+ return []
+}
diff --git a/plugins/ruflo-neural-trader/hooks/status.ts b/plugins/ruflo-neural-trader/hooks/status.ts
new file mode 100644
index 0000000000..a1ad79a4f0
--- /dev/null
+++ b/plugins/ruflo-neural-trader/hooks/status.ts
@@ -0,0 +1,18 @@
+/** Counters the mod keeps for the session and writes to `.claude-flow/trader-mod/status.json` for the console. */
+export type Stats = {
+ checked: number
+ blocked: number
+ /** Live order calls refused for want of an explicit confirm. */
+ liveBlocked: number
+ /** Why the last call was refused: a rule name, never the text that tripped it. */
+ lastBlock?: string
+}
+
+export const newStats = (): Stats => ({ checked: 0, blocked: 0, liveBlocked: 0 })
+
+export const STATUS_PATH = '.claude-flow/trader-mod/status.json'
+
+/** The file's text; `version` lets the console refuse a shape it does not know. */
+export function statusText(stats: Stats, mode: Record<string, unknown>, nowMs: number): string {
+ return `${JSON.stringify({ version: 1, updatedMs: nowMs, ...mode, ...stats }, null, 2)}\n`
+}
diff --git a/plugins/ruflo-neural-trader/scripts/smoke.sh b/plugins/ruflo-neural-trader/scripts/smoke.sh
index 350e4d36bc..63c327170e 100755
--- a/plugins/ruflo-neural-trader/scripts/smoke.sh
+++ b/plugins/ruflo-neural-trader/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'"; else
miss=""
for k in neural-trader-runtime walk-forward monte-carlo; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
@@ -82,5 +82,23 @@ for f in "$ROOT"/skills/*/SKILL.md; do
done
[[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills"
+# M1-M3. The mod (ADR-445 pattern): hooks module registered, files within the 500-line rule, safe defaults, no network or process access
+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 command status register; 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" && c.liveGuard && c.liveGuard.default === "on" ? 0 : 1)
+' "$ROOT/.claude-plugin/plugin.json" && ok || bad "userConfig defaults 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 1
diff --git a/plugins/ruflo-neural-trader/tests/trader-mod.test.ts b/plugins/ruflo-neural-trader/tests/trader-mod.test.ts
new file mode 100644
index 0000000000..7753d1e751
--- /dev/null
+++ b/plugins/ruflo-neural-trader/tests/trader-mod.test.ts
@@ -0,0 +1,118 @@
+import type { On } from 'claude-code'
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+tier('user')
+
+const ROOT = '/work'
+const STATUS = `${ROOT}/.claude-flow/trader-mod/status.json`
+const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
+const slash = (args: string) => ({ command: 'trader-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const
+const KEY = `ghp_${'a1B2'.repeat(10)}`
+
+/** The world beneath the mod: a project root, a file map, a command registry; every tool call is answered 'ok'. */
+function world(on: On) {
+ const files = new Map<string, string>()
+ const registered: string[] = []
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('session.root', () => ({ value: ROOT }))
+ on('command.register', ($, e) => (registered.push(e.name), { value: { command: e.name } }))
+ on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined }))
+ on('clock.now', () => ({ value: 1_700_000_000_000 }))
+ on('tool.call', () => ({ result: 'ok' }))
+ return { files, registered }
+}
+
+const call = (tool: string, input: Record<string, unknown>) => ({ tool, ...input }) as never
+const store = (value: string) => call('mcp__plugin_ruflo-core_ruflo__memory_store', { key: 'k', namespace: 'trading-signals', value })
+const status = (files: Map<string, string>) => JSON.parse(files.get(STATUS) ?? '{}')
+
+/** Runs the call; a denial surfaces as a rejection or a deny result, flattened to text either way. */
+async function outcome($: { tool: { call: (e: never) => Promise<unknown> } }, e: never): Promise<string> {
+ try {
+ return JSON.stringify(await $.tool.call(e))
+ } catch (err) {
+ return String(err)
+ }
+}
+
+describe('session', () => {
+ test('writes the status file and registers /trader-mod, guard on by default', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ expect(w.registered).toEqual(['trader-mod'])
+ expect(status(w.files)).toMatchObject({ version: 1, guard: true, checked: 0, blocked: 0 })
+ expect(typeof status(w.files).updatedMs).toBe('number')
+ })
+})
+
+describe('guard', () => {
+ test('refuses a secret in a memory write, passes a clean one, never echoes the value', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ const denied = await outcome($, store(`token ${KEY}`))
+ expect(denied).toContain('ruflo-neural-trader')
+ expect(denied).not.toContain('ghp_')
+ expect(await outcome($, store('prefer small reversible steps'))).toContain('ok')
+ expect(status(w.files)).toMatchObject({ checked: 2, blocked: 1, lastBlock: 'github token' })
+ })
+
+ test('ignores tools that are not this mod\'s business', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ expect(await outcome($, call('Bash', { command: `echo ${KEY}` }))).toContain('ok')
+ expect(status(w.files).checked).toBe(0)
+ })
+
+ test('guard: off lets the write through', { options: { guard: 'off' } }, async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect(await outcome($, store(`token ${KEY}`))).toContain('ok')
+ })
+
+ const order = (input: Record<string, unknown>) => call('mcp__neural-trader__execute_trade', { symbol: 'SPY', qty: 1, ...input })
+
+ test('a live order needs an explicit confirm or paper flag', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ expect(await outcome($, order({}))).toContain('confirm: true')
+ expect(await outcome($, order({ confirm: true }))).toContain('ok')
+ expect(await outcome($, order({ paper: true }))).toContain('ok')
+ expect(await outcome($, call('mcp__neural-trader__backtest', { symbol: 'SPY' }))).toContain('ok')
+ expect(status(w.files)).toMatchObject({ liveBlocked: 1, blocked: 1 })
+ })
+
+ test('a broker secret in a trader call is refused without echoing it', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ const denied = await outcome($, order({ confirm: true, api_secret: 'abcdEFGH1234ijklMNOP5678' }))
+ expect(denied).toContain('secret')
+ expect(denied).not.toContain('abcdEFGH')
+ })
+
+ test('liveGuard: off lets an unconfirmed order through (the secret guard stays)', { options: { liveGuard: 'off' } }, async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect(await outcome($, order({}))).toContain('ok')
+ expect(await outcome($, order({ api_secret: 'abcdEFGH1234ijklMNOP5678' }))).toContain('secret')
+ })
+})
+
+describe('/trader-mod', () => {
+ test('status and scan answer locally', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect((await $.command.run(slash('status'))).text).toContain('guard on')
+ const hit = (await $.command.run(slash(`scan key ${KEY}`))).text ?? ''
+ expect(hit).toContain('github token')
+ expect(hit).not.toContain('ghp_')
+ expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing')
+ expect((await $.command.run(slash('status'))).text).toContain('live-order guard on')
+ })
+
+ test('an unknown verb or none gets the help, not a model turn', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect((await $.command.run(slash('how do I do this'))).text).toContain('/trader-mod status')
+ expect((await $.command.run(slash(''))).text).toContain('/trader-mod scan')
+ })
+})
diff --git a/plugins/ruflo-neural-trader/tsconfig.json b/plugins/ruflo-neural-trader/tsconfig.json
new file mode 100644
index 0000000000..e4ba54993e
--- /dev/null
+++ b/plugins/ruflo-neural-trader/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"]
+}
diff --git a/plugins/ruflo-observability/.claude-plugin/plugin.json b/plugins/ruflo-observability/.claude-plugin/plugin.json
index 116a88e12b..93e16f60b3 100644
--- a/plugins/ruflo-observability/.claude-plugin/plugin.json
+++ b/plugins/ruflo-observability/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-observability",
- "description": "Structured logging, distributed tracing, and metrics — correlate agent swarm activity with application telemetry",
- "version": "0.2.1",
+ "description": "Structured logging, distributed tracing, and metrics — correlate agent swarm activity with application telemetry. As a mod (ADR-445): a tighten-only guard on its tools, /observe-mod, and a status file the console shows",
+ "version": "0.3.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -17,6 +17,22 @@
"telemetry",
"mcp",
"distributed-tracing",
- "anomaly-detection"
- ]
+ "anomaly-detection",
+ "mod",
+ "function-hooks",
+ "guard"
+ ],
+ "userConfig": {
+ "guard": {
+ "type": "string",
+ "title": "Guard",
+ "description": "Refuse calls and memory writes that hold a secret, SSN or card number. On by default.",
+ "required": false,
+ "default": "on",
+ "options": [
+ "on",
+ "off"
+ ]
+ }
+ }
}
diff --git a/plugins/ruflo-observability/README.md b/plugins/ruflo-observability/README.md
index e96c500b4d..4d3b8f96de 100644
--- a/plugins/ruflo-observability/README.md
+++ b/plugins/ruflo-observability/README.md
@@ -98,3 +98,19 @@ bash plugins/ruflo-observability/scripts/smoke.sh
## License
MIT
+
+## As a mod
+
+Function-hook mod (ADR-445 pattern, `hooks/register.ts`). It adds, with no network, no process spawning and no model call:
+
+- **Guard** (tighten-only, default on): refuses a memory write of telemetry (spans, logs, labels) that holds a secret, a US SSN or a spaced payment-card number (13-digit epoch timestamps are fine). The deny reason names the rule, never the value.
+- **`/observe-mod`**: local `status` and `scan <text>` (secret check, same rules as the guard).
+- **Status file** `.claude-flow/observe-mod/status.json` (`{version:1, updatedMs, guard, checked, blocked, ...}`), written at session start and when counters change.
+
+Per-prompt context is deliberately not added: this plugin has nothing worth attaching to every prompt.
+
+| Option | Default | Effect |
+|---|---|---|
+| `guard` | `on` | refuse the calls above |
+
+Test: `claude plugin validate plugins/ruflo-observability`, `claude plugin test plugins/ruflo-observability`, `bash plugins/ruflo-observability/scripts/smoke.sh`.
diff --git a/plugins/ruflo-observability/hooks/command.ts b/plugins/ruflo-observability/hooks/command.ts
new file mode 100644
index 0000000000..e2f701d05a
--- /dev/null
+++ b/plugins/ruflo-observability/hooks/command.ts
@@ -0,0 +1,28 @@
+import { secretsIn } from './screen'
+import type { ModOptions } from './options'
+import type { Stats } from './status'
+
+const HELP = ['/observe-mod status', '/observe-mod scan <text>'].join('\n')
+
+/** `/observe-mod` is answered locally and takes no model turn. */
+export function answer(args: string, opts: ModOptions, stats: Stats): string {
+ const [verb = '', ...rest] = args.trim().split(/\s+/)
+ const arg = rest.join(' ')
+
+ if (verb === '' || verb === 'help') return HELP
+
+ if (verb === 'status') {
+ return [
+ `guard ${opts.guard ? 'on' : 'off'}`,
+ `checked ${stats.checked} · blocked ${stats.blocked}${stats.lastBlock ? ` · last: ${stats.lastBlock}` : ''}`,
+ ].join('\n')
+ }
+
+ if (verb === 'scan') {
+ if (arg === '') return 'usage: /observe-mod scan <text>'
+ const found = secretsIn(arg)
+ return found.length ? `The guard would refuse a write or call carrying that (${found.join(', ')}).` : 'Nothing secret-shaped found: the guard would let that through.'
+ }
+
+ return `Unknown: ${verb}\n${HELP}`
+}
diff --git a/plugins/ruflo-observability/hooks/guard.ts b/plugins/ruflo-observability/hooks/guard.ts
new file mode 100644
index 0000000000..23e3f8f7a3
--- /dev/null
+++ b/plugins/ruflo-observability/hooks/guard.ts
@@ -0,0 +1,19 @@
+import { secretsIn, textsOf } from './screen'
+import type { ModOptions } from './options'
+import type { Stats } from './status'
+
+const WRITERS = new Set(['memory_store', 'agentdb_pattern-store', 'agentdb_hierarchical-store', 'agentdb_batch'])
+const toolOf = (name: string) => (name.startsWith('mcp__') ? name.slice(name.lastIndexOf('__') + 2) : name)
+
+/**
+ * The reason a call is refused, or undefined when it may go. Spans, logs and metric labels are stored as memory and outlive the run, so a
+ * write holding a secret, a US SSN or a payment card number is refused. Names the rule, never echoes the value.
+ */
+export function verdict(tool: string, input: unknown, _opts: ModOptions, stats: Stats): string | undefined {
+ if (!WRITERS.has(toolOf(tool))) return undefined
+ stats.checked++
+ const found = textsOf(input).flatMap(secretsIn)
+ if (found.length === 0) return undefined
+ stats.lastBlock = found[0]
+ return 'ruflo-observability: this telemetry write holds what looks like a secret or personal data (a key, token, SSN or card number). Redact it from the span, log or label first.'
+}
diff --git a/plugins/ruflo-observability/hooks/hooks.json b/plugins/ruflo-observability/hooks/hooks.json
new file mode 100644
index 0000000000..930ed64aef
--- /dev/null
+++ b/plugins/ruflo-observability/hooks/hooks.json
@@ -0,0 +1,6 @@
+{
+ "description": "ruflo-observability as a mod (ADR-445 pattern): a tighten-only guard on this plugin's own tools, /observe-mod, and a status file the console reads.",
+ "modules": [
+ "./register.ts"
+ ]
+}
diff --git a/plugins/ruflo-observability/hooks/options.ts b/plugins/ruflo-observability/hooks/options.ts
new file mode 100644
index 0000000000..4c64eae7f1
--- /dev/null
+++ b/plugins/ruflo-observability/hooks/options.ts
@@ -0,0 +1,14 @@
+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
+}
+
+export const flag = (value: unknown, fallback: boolean) =>
+ value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback
+
+export function readOptions(options: PluginOptions | undefined): ModOptions {
+ const o = options ?? {}
+ return { guard: flag(o.guard, true) }
+}
diff --git a/plugins/ruflo-observability/hooks/register.ts b/plugins/ruflo-observability/hooks/register.ts
new file mode 100644
index 0000000000..fb2a2caa59
--- /dev/null
+++ b/plugins/ruflo-observability/hooks/register.ts
@@ -0,0 +1,60 @@
+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'
+
+type Dollar = Parameters<Hook<'session.start'>>[0]
+
+/** Everything one session of the mod keeps: its settings, counters and the project root. */
+type Session = { readonly opts: ModOptions; readonly stats: Stats; root?: string }
+
+async function flush($: Dollar, s: Session): Promise<void> {
+ if (s.root === undefined) return
+ try {
+ await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.stats, { guard: s.opts.guard }, await $.clock.now()))
+ } catch {
+ /* the status file is a courtesy */
+ }
+}
+
+/**
+ * ruflo-observability as a mod (ADR-445 pattern): a tighten-only guard on this plugin's own tools, `/observe-mod`, and a status file the console
+ * reads. No network, no process spawning, no model call: only tools already connected.
+ */
+export const register: Register = (on, options) => {
+ const s: Session = { opts: readOptions(options), stats: newStats() }
+
+ on('session.start', async ($, e, next) => {
+ const result = await next(e)
+ s.root = (await $.session.root()) as string | undefined
+ try {
+ await $.command.register({ name: 'observe-mod', description: 'ruflo-observability mod: status, scan <text>' })
+ } catch {
+ /* a name taken by another plugin must not stop the mod */
+ }
+ await flush($, s)
+ return result
+ })
+
+ if (s.opts.guard) {
+ on('tool.call', async ($, e, next) => {
+ const before = s.stats.checked
+ const reason = verdict(e.tool, e, s.opts, s.stats)
+ if (reason === undefined) {
+ if (s.stats.checked !== before) await flush($, s)
+ return next(e)
+ }
+ s.stats.blocked++
+ await flush($, s)
+ return { deny: reason }
+ })
+ }
+
+ /** `/observe-mod` (the plugin's own command is a prompt command, which no hook can answer). */
+ on('command.run', { command: 'observe-mod' }, async (_$, e) => {
+ const args = typeof e.args === 'string' ? e.args : ''
+ return { text: answer(args, s.opts, s.stats) }
+ })
+}
diff --git a/plugins/ruflo-observability/hooks/screen.ts b/plugins/ruflo-observability/hooks/screen.ts
new file mode 100644
index 0000000000..17d77d8d58
--- /dev/null
+++ b/plugins/ruflo-observability/hooks/screen.ts
@@ -0,0 +1,48 @@
+/**
+ * Pure text screening for the ruflo-observability mod (ADR-445 pattern). Findings are NAMES only: the matched text is never returned, logged or
+ * counted by value, so a deny reason cannot leak what it caught.
+ */
+
+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[A-Za-z0-9_-]*(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i],
+ ['us ssn', /\b\d{3}-\d{2}-\d{4}\b/],
+ ['payment card number', /\b\d{4}[ -]\d{4}[ -]\d{4}[ -]\d{4}\b/],
+]
+
+// 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 > 0
+
+/** 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) {
+ // A string field is also read as `name=value`, so {api_secret: '...'} trips the key-assignment rule like a pasted line would.
+ return Object.entries(input)
+ .slice(0, 200)
+ .flatMap(([k, v]) => (typeof v === 'string' ? textsOf(`${k}=${v}`, budget, depth + 1) : textsOf(v, budget, depth + 1)))
+ }
+ return []
+}
diff --git a/plugins/ruflo-observability/hooks/status.ts b/plugins/ruflo-observability/hooks/status.ts
new file mode 100644
index 0000000000..59bcce0b35
--- /dev/null
+++ b/plugins/ruflo-observability/hooks/status.ts
@@ -0,0 +1,16 @@
+/** Counters the mod keeps for the session and writes to `.claude-flow/observe-mod/status.json` for the console. */
+export type Stats = {
+ checked: number
+ blocked: number
+ /** Why the last call was refused: a rule name, never the text that tripped it. */
+ lastBlock?: string
+}
+
+export const newStats = (): Stats => ({ checked: 0, blocked: 0 })
+
+export const STATUS_PATH = '.claude-flow/observe-mod/status.json'
+
+/** The file's text; `version` lets the console refuse a shape it does not know. */
+export function statusText(stats: Stats, mode: Record<string, unknown>, nowMs: number): string {
+ return `${JSON.stringify({ version: 1, updatedMs: nowMs, ...mode, ...stats }, null, 2)}\n`
+}
diff --git a/plugins/ruflo-observability/scripts/smoke.sh b/plugins/ruflo-observability/scripts/smoke.sh
index af65bd04c8..308302795a 100755
--- a/plugins/ruflo-observability/scripts/smoke.sh
+++ b/plugins/ruflo-observability/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'"; else
miss=""
for k in mcp distributed-tracing anomaly-detection; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
@@ -82,5 +82,23 @@ for f in "$ROOT"/skills/*/SKILL.md; do
done
[[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills"
+# M1-M3. The mod (ADR-445 pattern): hooks module registered, files within the 500-line rule, safe defaults, no network or process access
+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 command status register; 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 defaults 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 1
diff --git a/plugins/ruflo-observability/tests/observe-mod.test.ts b/plugins/ruflo-observability/tests/observe-mod.test.ts
new file mode 100644
index 0000000000..9a3444bc2c
--- /dev/null
+++ b/plugins/ruflo-observability/tests/observe-mod.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 STATUS = `${ROOT}/.claude-flow/observe-mod/status.json`
+const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
+const slash = (args: string) => ({ command: 'observe-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const
+const KEY = `ghp_${'a1B2'.repeat(10)}`
+
+/** The world beneath the mod: a project root, a file map, a command registry; every tool call is answered 'ok'. */
+function world(on: On) {
+ const files = new Map<string, string>()
+ const registered: string[] = []
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('session.root', () => ({ value: ROOT }))
+ on('command.register', ($, e) => (registered.push(e.name), { value: { command: e.name } }))
+ on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined }))
+ on('clock.now', () => ({ value: 1_700_000_000_000 }))
+ on('tool.call', () => ({ result: 'ok' }))
+ return { files, registered }
+}
+
+const call = (tool: string, input: Record<string, unknown>) => ({ tool, ...input }) as never
+const store = (value: string) => call('mcp__plugin_ruflo-core_ruflo__memory_store', { key: 'k', namespace: 'observability-traces', value })
+const status = (files: Map<string, string>) => JSON.parse(files.get(STATUS) ?? '{}')
+
+/** Runs the call; a denial surfaces as a rejection or a deny result, flattened to text either way. */
+async function outcome($: { tool: { call: (e: never) => Promise<unknown> } }, e: never): Promise<string> {
+ try {
+ return JSON.stringify(await $.tool.call(e))
+ } catch (err) {
+ return String(err)
+ }
+}
+
+describe('session', () => {
+ test('writes the status file and registers /observe-mod, guard on by default', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ expect(w.registered).toEqual(['observe-mod'])
+ expect(status(w.files)).toMatchObject({ version: 1, guard: true, checked: 0, blocked: 0 })
+ expect(typeof status(w.files).updatedMs).toBe('number')
+ })
+})
+
+describe('guard', () => {
+ test('refuses a secret in a memory write, passes a clean one, never echoes the value', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ const denied = await outcome($, store(`token ${KEY}`))
+ expect(denied).toContain('ruflo-observability')
+ expect(denied).not.toContain('ghp_')
+ expect(await outcome($, store('prefer small reversible steps'))).toContain('ok')
+ expect(status(w.files)).toMatchObject({ checked: 2, blocked: 1, lastBlock: 'github token' })
+ })
+
+ test('ignores tools that are not this mod\'s business', async ($, on) => {
+ const w = world(on)
+ await $.session.start(START)
+ expect(await outcome($, call('Bash', { command: `echo ${KEY}` }))).toContain('ok')
+ expect(status(w.files).checked).toBe(0)
+ })
+
+ test('guard: off lets the write through', { options: { guard: 'off' } }, async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect(await outcome($, store(`token ${KEY}`))).toContain('ok')
+ })
+
+ test('refuses an SSN or card number in a span, allows a 13-digit timestamp', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ const ssn = await outcome($, store('span attr user=123-45-6789'))
+ expect(ssn).toContain('personal data')
+ expect(ssn).not.toContain('123-45')
+ expect(await outcome($, store('card 4111 1111 1111 1111'))).toContain('personal data')
+ expect(await outcome($, store('span started_ms=1700000000123 duration=40'))).toContain('ok')
+ })
+})
+
+describe('/observe-mod', () => {
+ test('status and scan answer locally', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect((await $.command.run(slash('status'))).text).toContain('guard on')
+ const hit = (await $.command.run(slash(`scan key ${KEY}`))).text ?? ''
+ expect(hit).toContain('github token')
+ expect(hit).not.toContain('ghp_')
+ expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing')
+ })
+
+ test('an unknown verb or none gets the help, not a model turn', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect((await $.command.run(slash('how do I do this'))).text).toContain('/observe-mod status')
+ expect((await $.command.run(slash(''))).text).toContain('/observe-mod scan')
+ })
+})
diff --git a/plugins/ruflo-observability/tsconfig.json b/plugins/ruflo-observability/tsconfig.json
new file mode 100644
index 0000000000..e4ba54993e
--- /dev/null
+++ b/plugins/ruflo-observability/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"]
+}