🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(ruflo-docs): function-hook mod (secret guard, /docs-mod, status file)
ruvcb2fcafbdede
diff --git a/plugins/ruflo-docs/.claude-plugin/plugin.json b/plugins/ruflo-docs/.claude-plugin/plugin.jsonindex 4ce141c4b0..226838404a 100644--- a/plugins/ruflo-docs/.claude-plugin/plugin.json+++ b/plugins/ruflo-docs/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-docs","description": "Documentation generation, API docs (JSDoc/TSDoc/OpenAPI), and drift detection — drives the `document` background worker via hooks_worker-dispatch; uses Haiku model for cost-efficient docs work",- "version": "0.2.1",+ "version": "0.3.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"@@ -15,6 +15,22 @@"drift-detection","jsdoc","openapi",- "mcp"- ]+ "mcp",+ "mod",+ "function-hooks",+ "guard"+ ],+ "userConfig": {+ "guard": {+ "type": "string",+ "title": "Secret guard",+ "description": "Refuse docs memory writes and the document worker that hold a key, token or password. On by default; it only ever tightens.",+ "required": false,+ "default": "on",+ "options": [+ "on",+ "off"+ ]+ }+ }}diff --git a/plugins/ruflo-docs/README.md b/plugins/ruflo-docs/README.mdindex 4403cc104d..04597aeccf 100644--- a/plugins/ruflo-docs/README.md+++ b/plugins/ruflo-docs/README.md@@ -70,3 +70,14 @@ bash plugins/ruflo-docs/scripts/smoke.sh- `ruflo-loop-workers` — defines the `document` background worker- `ruflo-adr` — ADRs trigger doc generation when status changes- `ruflo-sparc` — Documenter mode (Phase 5 Refinement) consumes this plugin++## As a mod++Since this version the plugin is also a function-hook mod (ADR-445 pattern; needs Claude Code 2.1.287 or later). It never calls the network or spawns a process, and it only tightens: it can refuse a call, never allow one.++- **Guard** (default on): refuses `doc-*` memory writes and the `document` worker dispatch that hold a key, token or password. The reason names the kind of secret, never the value.+- **`/docs-mod`**: answered locally, no model turn: `status`, `scan <text>` (would the guard refuse this?), and `docs` (markdown files in `docs/`).+- **Status file**: `.claude-flow/docs-mod/status.json` (`{version, updatedMs, guard, blocked}`), written at session start and when a call is blocked.+- **Option**: `guard` (`on` | `off`, default `on`) in the plugin's `userConfig`.++Test it: `claude plugin test plugins/ruflo-docs` and `bash plugins/ruflo-docs/scripts/smoke.sh`.diff --git a/plugins/ruflo-docs/hooks/command.ts b/plugins/ruflo-docs/hooks/command.tsnew file mode 100644index 0000000000..655963b52a--- /dev/null+++ b/plugins/ruflo-docs/hooks/command.ts@@ -0,0 +1,43 @@+import type { FsEntry } from 'claude-code'++import { secretNames } from './screen'+import type { Stats } from './status'++/** `/docs-mod` is answered locally and takes no model turn. Everything it reads is already connected; nothing is written. */+export type CommandDeps = {+ readonly guard: boolean+ readonly stats: Stats+ readonly tools: () => Promise<readonly string[]>+ readonly list: (path: string) => Promise<readonly FsEntry[]>+}++const HELP = ['/docs-mod status', '/docs-mod scan <text>', '/docs-mod docs'].join('\n')++export async function answer(args: string, deps: CommandDeps): Promise<string> {+ const [verb = '', ...rest] = args.trim().split(/\s+/)+ const arg = rest.join(' ')++ if (verb === '' || verb === 'help') return HELP++ if (verb === 'status') return `guard ${deps.guard ? 'on' : 'off'} · calls blocked ${deps.stats.blocked}`++ if (verb === 'scan') {+ if (arg === '') return 'usage: /docs-mod scan <text>'+ const found = secretNames(arg)+ return found.length ? `The guard would refuse that (${found.join(', ')}).` : 'Nothing found: the guard would let that through.'+ }++ if (verb === 'docs') {+ let entries: readonly FsEntry[]+ try {+ entries = await deps.list('docs')+ } catch {+ return 'No docs/ folder in this project.'+ }+ const md = entries.filter(e => e.kind === 'file' && /\.mdx?$/i.test(e.name))+ const newest = [...md].sort((a, b) => b.mtimeMs - a.mtimeMs)[0]+ return `docs/: ${md.length} markdown file${md.length === 1 ? '' : 's'}, ${entries.filter(e => e.kind === 'dir').length} folder${entries.filter(e => e.kind === 'dir').length === 1 ? '' : 's'}${newest ? `; newest ${newest.name}` : ''}`+ }++ return `Unknown: ${verb}\n${HELP}`+}diff --git a/plugins/ruflo-docs/hooks/guard.ts b/plugins/ruflo-docs/hooks/guard.tsnew file mode 100644index 0000000000..37be70e367--- /dev/null+++ b/plugins/ruflo-docs/hooks/guard.ts@@ -0,0 +1,18 @@+import { hasSecret, textsOf } from './screen'++/** The tool name without its `mcp__<server>__` prefix. */+const tail = (name: string) => (name.startsWith('mcp__') ? name.slice(name.lastIndexOf('__') + 2) : name)++const isDocWrite = (input: unknown) => {+ const o = (typeof input === 'object' && input !== null ? input : {}) as Record<string, unknown>+ return ['key', 'namespace'].some(k => typeof o[k] === 'string' && /^doc|[-_]doc/i.test(o[k] as string))+}++/** The reason a docs write is refused, or undefined when it may go: doc-* memory entries and the document worker's dispatch. */+export function verdict(tool: string, input: unknown): string | undefined {+ const t = tail(tool)+ if (!((t === 'memory_store' && isDocWrite(input)) || (t === 'hooks_worker-dispatch' && JSON.stringify(input ?? {}).includes('"document"')))) return undefined+ return textsOf(input).some(hasSecret)+ ? 'ruflo-docs: this docs entry holds what looks like a secret (a key, token or password). Generated documentation is shared: describe where the value lives, not the value.'+ : undefined+}diff --git a/plugins/ruflo-docs/hooks/hooks.json b/plugins/ruflo-docs/hooks/hooks.jsonnew file mode 100644index 0000000000..33d8441693--- /dev/null+++ b/plugins/ruflo-docs/hooks/hooks.json@@ -0,0 +1,4 @@+{+ "description": "Docs as a mod: a guard that keeps secrets out of docs memory writes and the document worker, /docs-mod, and a status file.",+ "modules": ["./register.ts"]+}diff --git a/plugins/ruflo-docs/hooks/options.ts b/plugins/ruflo-docs/hooks/options.tsnew file mode 100644index 0000000000..e18352b921--- /dev/null+++ b/plugins/ruflo-docs/hooks/options.ts@@ -0,0 +1,9 @@+import type { PluginOptions } from 'claude-code'++/** The plugin's `userConfig`, validated: a bad value is the default (guard on). */+export type ModOptions = { readonly guard: boolean }++const flag = (value: unknown, fallback: boolean) =>+ value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback++export const readOptions = (options: PluginOptions | undefined): ModOptions => ({ guard: flag((options ?? {}).guard, true) })diff --git a/plugins/ruflo-docs/hooks/register.ts b/plugins/ruflo-docs/hooks/register.tsnew file mode 100644index 0000000000..89ba4db762--- /dev/null+++ b/plugins/ruflo-docs/hooks/register.ts@@ -0,0 +1,62 @@+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, s.opts.guard, await $.clock.now()))+ } catch {+ /* the status file is a courtesy */+ }+}++/**+ * ruflo-docs as a mod (ADR-445 pattern): a tighten-only guard on this plugin's own tools, `/docs-mod` and a status file. No network, no process+ * spawning: 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: 'docs-mod', description: 'ruflo-docs mod: status, scan <text>, plus a read-only listing' })+ } 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 reason = verdict(e.tool, e)+ if (reason === undefined) return next(e)+ s.stats.blocked+++ await flush($, s)+ return { deny: reason }+ })+ }++ /** `/docs-mod` is answered locally and takes no model turn. */+ on('command.run', { command: 'docs-mod' }, async ($, e) => {+ const args = typeof e.args === 'string' ? e.args : ''+ const text = await answer(args, {+ guard: s.opts.guard,+ stats: s.stats,+ tools: async () => (await $.tool.list()).map(t => t.name),+ list: path => $.fs.list(path),+ })+ return { text }+ })+}diff --git a/plugins/ruflo-docs/hooks/screen.ts b/plugins/ruflo-docs/hooks/screen.tsnew file mode 100644index 0000000000..14e017efed--- /dev/null+++ b/plugins/ruflo-docs/hooks/screen.ts@@ -0,0 +1,41 @@+/**+ * Pure secret screening for this mod (copied from ruflo-agentdb's ADR-445 screen.ts, injection rules dropped). Findings are NAMES only: the+ * matched text is never returned, logged or counted by value.+ */++const SECRETS: readonly (readonly [string, RegExp])[] = [+ ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],+ ['aws access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/],+ ['github token', /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/],+ ['slack token', /\bxox[abprs]-[A-Za-z0-9-]{10,}/],+ ['google api key', /\bAIza[0-9A-Za-z_-]{35}\b/],+ ['anthropic or openai key', /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{24,}/],+ ['jwt', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/],+ ['bearer token', /\bBearer\s+[A-Za-z0-9._~+/=-]{24,}/],+ ['key assignment', /\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i],+]++// C0/C1 controls (keeping tab and newline), DEL, zero-width and bidi override characters; built with escapes, never raw.+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 secretNames = (text: string): string[] => {+ const bounded = bare(text)+ return SECRETS.filter(([, re]) => re.test(bounded)).map(([name]) => name)+}++export const hasSecret = (text: string) => secretNames(text).length > 0++/** Every string in a tool's input, to a bounded depth and size: what a guard reads. */+export function textsOf(input: unknown, budget = { left: 20_000 }, depth = 0): string[] {+ if (budget.left <= 0 || depth > 6) return []+ if (typeof input === 'string') {+ budget.left -= input.length+ return [input]+ }+ if (Array.isArray(input)) return input.slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1))+ if (typeof input === 'object' && input !== null) return Object.values(input).slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1))+ return []+}diff --git a/plugins/ruflo-docs/hooks/status.ts b/plugins/ruflo-docs/hooks/status.tsnew file mode 100644index 0000000000..3cddf07ab2--- /dev/null+++ b/plugins/ruflo-docs/hooks/status.ts@@ -0,0 +1,10 @@+/** Counters the mod keeps for the session and writes to `.claude-flow/docs-mod/status.json`. */+export type Stats = { blocked: number }++export const newStats = (): Stats => ({ blocked: 0 })++export const STATUS_PATH = '.claude-flow/docs-mod/status.json'++/** The file's text; `version` lets a reader refuse a shape it does not know. */+export const statusText = (stats: Stats, guard: boolean, nowMs: number): string =>+ `${JSON.stringify({ version: 1, updatedMs: nowMs, guard, ...stats }, null, 2)}\n`diff --git a/plugins/ruflo-docs/scripts/smoke.sh b/plugins/ruflo-docs/scripts/smoke.shindex c9ddc708dc..8a2bfad0cc 100755--- a/plugins/ruflo-docs/scripts/smoke.sh+++ b/plugins/ruflo-docs/scripts/smoke.sh@@ -7,9 +7,9 @@ step() { printf "→ %s ... " "$1"; }ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }-step "1. plugin.json declares 0.2.1 with new keywords"+step "1. plugin.json declares 0.3.0 with new keywords"v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)-if [[ "$v" != "0.2.1" ]]; then bad "expected 0.2.1, got '$v'"; else+if [[ "$v" != "0.3.0" ]]; then bad "expected 0.3.0, got '$v'"; elsemiss=""for k in jsdoc openapi mcp; dogrep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"@@ -67,5 +67,24 @@ step "10. agent uses Haiku model (cost-efficient)"grep -qE "^model:[[:space:]]*haiku" "$ROOT/agents/docs-writer.md" \&& ok || bad "agent model is not Haiku"+# M1. The mod (ADR-445 pattern): hooks module registered, files within the 500-line rule, no network or process access in the hooks+step "M1. mod: hooks.json names register.ts, every hook file is present and under 500 lines"+mod_ok=1+grep -q '"./register.ts"' "$ROOT/hooks/hooks.json" || mod_ok=0+for f in options screen guard 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, and it is the only userConfig option"+node -e '+const c = require(process.argv[1]).userConfig || {}+process.exit(c.guard && c.guard.default === "on" && Object.keys(c).length === 1 ? 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 1diff --git a/plugins/ruflo-docs/tests/mod.test.ts b/plugins/ruflo-docs/tests/mod.test.tsnew file mode 100644index 0000000000..f65094e2f2--- /dev/null+++ b/plugins/ruflo-docs/tests/mod.test.ts@@ -0,0 +1,110 @@+import type { On } from 'claude-code'+import { describe, expect, test, tier } from 'claude-code/testing'++tier('user')++const ROOT = '/work'+const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const+const slash = (args: string) => ({ command: 'docs-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const+const STATUS = `${ROOT}/.claude-flow/docs-mod/status.json`+const SECRET = `ghp_${'a1B2'.repeat(10)}`++/** The world beneath the mod: a project root, a file map, a tool list and a directory map. */+function world(on: On, tools: readonly string[] = [], dirs: Record<string, { name: string; kind: 'file' | 'dir'; mtimeMs?: number }[]> = {}) {+ const files = new Map<string, string>()+ on('session.start', ($, e) => ({ cwd: e.cwd }))+ on('session.root', () => ({ value: ROOT }))+ on('command.register', ($, e) => ({ value: { command: e.name } }))+ on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined }))+ on('fs.list', ($, e) => {+ const key = Object.keys(dirs).find(k => e.path === k || e.path.endsWith(`/${k}`))+ const entries = key === undefined ? undefined : dirs[key]+ if (!entries) throw new Error('ENOENT')+ return { value: entries.map(x => ({ size: 0, mtimeMs: 0, isLink: false, ...x })) }+ })+ on('tool.list', () => ({ value: tools.map(name => ({ name, description: '', mcp: true })) }))+ on('clock.now', () => ({ value: 1_700_000_000_000 }))+ return { files }+}++const call = (input: Record<string, unknown>) => input as never+const denied = (r: unknown) => JSON.stringify(r)++describe('guard', () => {+ test('refuses a secret, never echoes it, and counts the block in the status file', async ($, on) => {+ const w = world(on)+ on('tool.call', () => ({ result: 'went through' }))+ await $.session.start(START)+ const r = await $.tool.call(call(((s: string) => ({ tool: 'mcp__plugin_ruflo-core_ruflo__memory_store', key: 'doc-pattern', namespace: 'patterns', value: `key ${s}` }))(SECRET))).then(+ x => x,+ (e: unknown) => ({ text: String(e) }),+ )+ expect(denied(r)).toContain('ruflo-')+ expect(denied(r)).not.toContain('went through')+ expect(denied(r)).not.toContain('ghp_')+ expect(JSON.parse(w.files.get(STATUS) ?? '{}')).toMatchObject({ version: 1, guard: true, blocked: 1 })+ })++ test('passes clean input and tools the plugin does not own', async ($, on) => {+ world(on)+ on('tool.call', () => ({ result: 'went through' }))+ await $.session.start(START)+ expect(denied(await $.tool.call(call({ tool: 'mcp__plugin_ruflo-core_ruflo__memory_store', key: 'doc-pattern', value: 'JSDoc first' })))).toContain('went through')+ expect(denied(await $.tool.call(call({ tool: 'Read', file_path: `/tmp/${SECRET}` })))).toContain('went through')+ })++ test('guard: off lets the call through', { options: { guard: 'off' } }, async ($, on) => {+ world(on)+ on('tool.call', () => ({ result: 'went through' }))+ await $.session.start(START)+ expect(denied(await $.tool.call(call(((s: string) => ({ tool: 'mcp__plugin_ruflo-core_ruflo__memory_store', key: 'doc-pattern', namespace: 'patterns', value: `key ${s}` }))(SECRET))))).toContain('went through')+ })+})++describe('guard scope', () => {+ test('the document worker dispatch is screened too, other workers are not', async ($, on) => {+ world(on)+ on('tool.call', () => ({ result: 'went through' }))+ await $.session.start(START)+ const r = await $.tool.call(call({ tool: 'mcp__plugin_ruflo-core_ruflo__hooks_worker-dispatch', trigger: 'document', scope: `api ${SECRET}` })).then(+ x => x,+ (e: unknown) => ({ text: String(e) }),+ )+ expect(denied(r)).not.toContain('went through')+ expect(denied(await $.tool.call(call({ tool: 'mcp__plugin_ruflo-core_ruflo__hooks_worker-dispatch', trigger: 'audit', scope: `x ${SECRET}` })))).toContain('went through')+ expect(denied(await $.tool.call(call({ tool: 'mcp__plugin_ruflo-core_ruflo__memory_store', key: 'note', namespace: 'tasks', value: `x ${SECRET}` })))).toContain('went through')+ })+})++describe('status file', () => {+ test('is written at session start with the defaults', async ($, on) => {+ const w = world(on)+ await $.session.start(START)+ expect(JSON.parse(w.files.get(STATUS) ?? '{}')).toEqual({ version: 1, updatedMs: 1_700_000_000_000, guard: true, blocked: 0 })+ })+})++describe('/docs-mod', () => {+ test('status and scan answer locally, and help is the fallback', async ($, on) => {+ world(on)+ await $.session.start(START)+ expect((await $.command.run(slash('status'))).text).toBe('guard on · calls blocked 0')+ expect((await $.command.run(slash(`scan key ${SECRET}`))).text).toContain('github token')+ expect((await $.command.run(slash(`scan key ${SECRET}`))).text).not.toContain('ghp_')+ expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found')+ expect((await $.command.run(slash(''))).text).toContain('/docs-mod scan <text>')+ expect((await $.command.run(slash('what is this'))).text).toContain('Unknown: what')+ })++ test('docs counts the markdown files and names the newest', async ($, on) => {+ world(on, [], { docs: [{ name: 'a.md', kind: 'file', mtimeMs: 1 }, { name: 'b.md', kind: 'file', mtimeMs: 9 }, { name: 'img.png', kind: 'file' }, { name: 'adr', kind: 'dir' }] })+ await $.session.start(START)+ expect((await $.command.run(slash('docs'))).text).toBe('docs/: 2 markdown files, 1 folder; newest b.md')+ })++ test('docs says plainly when there is no docs/ folder', async ($, on) => {+ world(on)+ await $.session.start(START)+ expect((await $.command.run(slash('docs'))).text).toContain('No docs/ folder')+ })+})diff --git a/plugins/ruflo-docs/tsconfig.json b/plugins/ruflo-docs/tsconfig.jsonnew file mode 100644index 0000000000..e4ba54993e--- /dev/null+++ b/plugins/ruflo-docs/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"]+}