Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

feat(ruflo-testgen): function-hook mod (guard, status file, local slash command)

ruv4277e7ee8991
diff --git a/plugins/ruflo-testgen/.claude-plugin/plugin.json b/plugins/ruflo-testgen/.claude-plugin/plugin.json
index e5095127f4..3793573524 100644
--- a/plugins/ruflo-testgen/.claude-plugin/plugin.json
+++ b/plugins/ruflo-testgen/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-testgen",
"description": "Test gap detection, coverage analysis, and automated test generation — drives the testgaps background worker via hooks_worker-dispatch; SPARC Refinement-phase canonical owner",
- "version": "0.2.1",
+ "version": "0.3.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -16,6 +16,7 @@
"test-generation",
"mcp",
"tdd-london-school",
- "coverage-routing"
+ "coverage-routing",
+ "function-hooks"
]
}
diff --git a/plugins/ruflo-testgen/README.md b/plugins/ruflo-testgen/README.md
index b596c25ecf..24f8e4ae98 100644
--- a/plugins/ruflo-testgen/README.md
+++ b/plugins/ruflo-testgen/README.md
@@ -72,3 +72,14 @@ bash plugins/ruflo-testgen/scripts/smoke.sh
- `ruflo-sparc` — Refinement-phase canonical handoff
- `ruflo-jujutsu` — diff-aware refactor companion in the Refinement gate
- `ruflo-agentdb` — namespace convention owner
+
+## As a mod
+
+This plugin also loads as a function-hook mod (ADR-445 pattern, `hooks/hooks.json` → `register.ts`). No network, no process spawn, no model call.
+
+- **Guard (default on, tighten-only).** It counts the `hooks_worker-dispatch` and coverage calls made this session. It is observe-only: testgen has no harmful input to guard, so it never denies and has nothing to configure.
+- **Status file.** `.claude-flow/testgen-mod/status.json` (`{version: 1, updatedMs, guard, checked, blocked, seen}`), written at session start and when a counter changes.
+- **`/testgen-mod`** answers locally: `status`, `workers`. (The plugin's own commands are prompt commands, which a hook cannot answer, so the mod has its own name.)
+- **Options.** None.
+
+Test it: `claude plugin validate plugins/ruflo-testgen`, `claude plugin test plugins/ruflo-testgen`, `bash plugins/ruflo-testgen/scripts/smoke.sh`.
diff --git a/plugins/ruflo-testgen/hooks/command.ts b/plugins/ruflo-testgen/hooks/command.ts
new file mode 100644
index 0000000000..91c64cf543
--- /dev/null
+++ b/plugins/ruflo-testgen/hooks/command.ts
@@ -0,0 +1,27 @@
+import type { ModOptions } from './options'
+import type { Stats } from './status'
+
+/** `/testgen-mod` is answered locally and takes no model turn. */
+export type CommandDeps = { readonly opts: ModOptions; readonly stats: Stats; readonly tools: () => Promise<readonly string[]> }
+
+const HELP = ['/testgen-mod status', '/testgen-mod workers'].join('\n')
+
+export async function answer(args: string, deps: CommandDeps): Promise<string> {
+ const [verb = '', ...rest] = args.trim().split(/\s+/)
+ const arg = rest.join(' ')
+ const { opts, stats } = deps
+
+ if (verb === '' || verb === 'help') return HELP
+
+ if (verb === 'status') {
+ const seen = Object.entries(stats.seen).map(([k, n]) => `${k} ${n}`).join(' · ')
+ return [`observe-only · checked ${stats.checked}`, seen === '' ? 'no testgen calls this session' : seen].join('\n')
+ }
+
+ if (verb === 'workers') {
+ const n = stats.seen['worker dispatch'] ?? 0
+ return n === 0 ? 'No worker has been dispatched this session. The testgaps worker runs through hooks_worker-dispatch.' : `${n} worker dispatch${n === 1 ? '' : 'es'} this session.`
+ }
+
+ return `Unknown: ${verb}\n${HELP}`
+}
diff --git a/plugins/ruflo-testgen/hooks/guard.ts b/plugins/ruflo-testgen/hooks/guard.ts
new file mode 100644
index 0000000000..aa9ebd9cb0
--- /dev/null
+++ b/plugins/ruflo-testgen/hooks/guard.ts
@@ -0,0 +1,36 @@
+/** Every string in a tool's input, to a bounded depth and size: what the guard reads. */
+export function textsOf(input: unknown, budget = { left: 20_000 }, depth = 0): string[] {
+ if (budget.left <= 0 || depth > 6) return []
+ if (typeof input === 'string') {
+ budget.left -= input.length
+ return [input]
+ }
+ if (Array.isArray(input)) return input.slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1))
+ if (typeof input === 'object' && input !== null) return Object.values(input).slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1))
+ return []
+}
+
+/** The tool's short name: `mcp__<server>__<tool>` to `<tool>`. */
+export const shortName = (name: string) => (name.startsWith('mcp__') && name.lastIndexOf('__') > 5 ? name.slice(name.lastIndexOf('__') + 2) : name)
+
+const field = (input: unknown, key: string): string => {
+ const v = typeof input === 'object' && input !== null ? (input as Record<string, unknown>)[key] : undefined
+ return typeof v === 'string' ? v : ''
+}
+
+const WATCH: Readonly<Record<string, string>> = {
+ 'hooks_worker-dispatch': 'worker dispatch',
+ 'hooks_coverage-gaps': 'coverage gaps',
+ 'hooks_coverage-route': 'coverage route',
+ 'hooks_coverage-suggest': 'coverage suggest',
+}
+
+/** The label of a testgen-related call, else undefined. Observed only: nothing here ever denies. */
+export function watched(tool: string, _input: unknown): string | undefined {
+ return WATCH[shortName(tool)]
+}
+
+/** Never refuses: testgen is observe-only. */
+export function verdict(_tool: string, _input: unknown): string | undefined {
+ return undefined
+}
diff --git a/plugins/ruflo-testgen/hooks/hooks.json b/plugins/ruflo-testgen/hooks/hooks.json
new file mode 100644
index 0000000000..b3a4e109c7
--- /dev/null
+++ b/plugins/ruflo-testgen/hooks/hooks.json
@@ -0,0 +1,6 @@
+{
+ "description": "Test generation as a mod (ADR-445 pattern): a status file and `/testgen-mod` that count the worker dispatches and coverage calls this session. Observe-only: testgen has no harmful input in its domain, so there is no guard and nothing to configure.",
+ "modules": [
+ "./register.ts"
+ ]
+}
diff --git a/plugins/ruflo-testgen/hooks/options.ts b/plugins/ruflo-testgen/hooks/options.ts
new file mode 100644
index 0000000000..a5d4812327
--- /dev/null
+++ b/plugins/ruflo-testgen/hooks/options.ts
@@ -0,0 +1,11 @@
+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 function readOptions(options: PluginOptions | undefined): ModOptions {
+ return { guard: flag((options ?? {}).guard, true) }
+}
diff --git a/plugins/ruflo-testgen/hooks/register.ts b/plugins/ruflo-testgen/hooks/register.ts
new file mode 100644
index 0000000000..63fbde946e
--- /dev/null
+++ b/plugins/ruflo-testgen/hooks/register.ts
@@ -0,0 +1,60 @@
+import type { Hook, Register } from 'claude-code'
+
+import { answer } from './command'
+import { verdict, watched } 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, its 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, await $.clock.now()))
+ } catch {
+ /* the status file is a courtesy */
+ }
+}
+
+/**
+ * Test generation as a mod (ADR-445 pattern): a status file and `/testgen-mod` that count the worker dispatches and coverage calls this session. Observe-only: testgen has no harmful input in its domain, so there is no guard and nothing to configure. No network, no process: 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: 'testgen-mod', description: 'Testgen mod: status, workers' })
+ } catch {
+ /* a name taken by another plugin must not stop the mod */
+ }
+ await flush($, s)
+ return result
+ })
+
+ // Tighten-only: a deny, or the event unchanged. Only this plugin's own tools are looked at.
+ on('tool.call', async ($, e, next) => {
+ const label = watched(e.tool, e)
+ if (label === undefined) return next(e)
+ s.stats.checked++
+ s.stats.seen[label] = (s.stats.seen[label] ?? 0) + 1
+ const reason = s.opts.guard ? verdict(e.tool, e) : undefined
+ if (reason !== undefined) {
+ s.stats.blocked++
+ s.stats.lastReason = reason.slice(0, 160)
+ }
+ await flush($, s)
+ return reason === undefined ? next(e) : { deny: reason }
+ })
+
+ /** `/testgen-mod` (the plugin's own commands are prompt commands, which no hook can answer). */
+ on('command.run', { command: 'testgen-mod' }, async ($, e) => {
+ const args = typeof e.args === 'string' ? e.args : ''
+ return { text: await answer(args, { opts: s.opts, stats: s.stats, tools: async () => (await $.tool.list()).map(t => t.name) }) }
+ })
+}
diff --git a/plugins/ruflo-testgen/hooks/status.ts b/plugins/ruflo-testgen/hooks/status.ts
new file mode 100644
index 0000000000..2793979d5f
--- /dev/null
+++ b/plugins/ruflo-testgen/hooks/status.ts
@@ -0,0 +1,11 @@
+/** Counters the mod keeps for the session and writes to `.claude-flow/testgen-mod/status.json` for the console. */
+export type Stats = { checked: number; blocked: number; seen: Record<string, number>; lastReason?: string }
+
+export const newStats = (): Stats => ({ checked: 0, blocked: 0, seen: {} })
+
+export const STATUS_PATH = '.claude-flow/testgen-mod/status.json'
+
+/** The file's text; `version` lets the console refuse a shape it does not know. */
+export function statusText(stats: Stats, mode: { guard: boolean }, nowMs: number): string {
+ return `${JSON.stringify({ version: 1, updatedMs: nowMs, guard: mode.guard, ...stats }, null, 2)}\n`
+}
diff --git a/plugins/ruflo-testgen/scripts/smoke.sh b/plugins/ruflo-testgen/scripts/smoke.sh
index 9c22f0876f..470feb06ae 100755
--- a/plugins/ruflo-testgen/scripts/smoke.sh
+++ b/plugins/ruflo-testgen/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 tdd-london-school coverage-routing; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
@@ -75,5 +75,24 @@ for f in "$ROOT"/skills/*/SKILL.md; do
done
[[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills"
+# M. 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 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: userConfig defaults are safe (none to configure: observe-only)"
+node -e '
+const c = require(process.argv[1]).userConfig || {}
+process.exit(Object.keys(c).length === 0 ? 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-testgen/tests/mod.test.ts b/plugins/ruflo-testgen/tests/mod.test.ts
new file mode 100644
index 0000000000..5c90b7072e
--- /dev/null
+++ b/plugins/ruflo-testgen/tests/mod.test.ts
@@ -0,0 +1,66 @@
+import type { On } from 'claude-code'
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import { answer } from '../hooks/command'
+import { newStats } from '../hooks/status'
+import { verdict, watched } from '../hooks/guard'
+
+tier('user')
+
+const ROOT = '/work'
+const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
+const slash = (args: string) => ({ command: 'testgen-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const
+const STATUS = `${ROOT}/.claude-flow/testgen-mod/status.json`
+const DISPATCH = 'mcp__plugin_ruflo-core_ruflo__hooks_worker-dispatch'
+
+function world(on: On) {
+ 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('tool.list', () => ({ value: [] }))
+ on('clock.now', () => ({ value: 1_700_000_000_000 }))
+ return files
+}
+
+describe('guard (observe-only)', () => {
+ test('watches testgen calls by label and never refuses anything', () => {
+ expect(watched(DISPATCH, {})).toBe('worker dispatch')
+ expect(watched('mcp__plugin_ruflo-core_ruflo__memory_store', {})).toBeUndefined()
+ expect(verdict(DISPATCH, { trigger: 'testgaps', note: 'ghp_' + 'a1B2'.repeat(10) })).toBeUndefined()
+ })
+
+ test('a watched call passes through unchanged and is counted in the status file', async ($, on) => {
+ const files = world(on)
+ on('tool.call', () => ({ result: 'done' }))
+ await $.session.start(START)
+ expect(JSON.stringify(await $.tool.call({ tool: DISPATCH, trigger: 'testgaps' } as never))).toContain('done')
+ expect(JSON.stringify(await $.tool.call({ tool: 'mcp__plugin_ruflo-core_ruflo__memory_store', key: 'k' } as never))).toContain('done')
+ expect(JSON.parse(files.get(STATUS) ?? '{}')).toMatchObject({ version: 1, checked: 1, blocked: 0, seen: { 'worker dispatch': 1 } })
+ })
+})
+
+describe('status file', () => {
+ test('written at session start', async ($, on) => {
+ const files = world(on)
+ await $.session.start(START)
+ expect(JSON.parse(files.get(STATUS) ?? '{}')).toMatchObject({ version: 1, checked: 0, blocked: 0 })
+ })
+})
+
+describe('/testgen-mod', () => {
+ test('status and workers answer locally; unknown verbs get the help', async ($, on) => {
+ world(on)
+ await $.session.start(START)
+ expect((await $.command.run(slash('status'))).text).toContain('observe-only')
+ expect((await $.command.run(slash('workers'))).text).toContain('No worker has been dispatched')
+ expect((await $.command.run(slash('what now'))).text).toContain('/testgen-mod workers')
+ })
+
+ test('workers counts dispatches', async () => {
+ const stats = newStats()
+ stats.seen['worker dispatch'] = 2
+ expect(await answer('workers', { opts: { guard: true }, stats, tools: async () => [] })).toContain('2 worker dispatches')
+ })
+})
diff --git a/plugins/ruflo-testgen/tsconfig.json b/plugins/ruflo-testgen/tsconfig.json
new file mode 100644
index 0000000000..e4ba54993e
--- /dev/null
+++ b/plugins/ruflo-testgen/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"]
+}