🌊 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-sparc): function-hook mod (guard, status file, local slash command)
ruv535cb4ec4f71
diff --git a/plugins/ruflo-sparc/.claude-plugin/plugin.json b/plugins/ruflo-sparc/.claude-plugin/plugin.jsonindex 986a03e1c9..f9f392ebfe 100644--- a/plugins/ruflo-sparc/.claude-plugin/plugin.json+++ b/plugins/ruflo-sparc/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-sparc","description": "SPARC methodology — Specification, Pseudocode, Architecture, Refinement, Completion phases with gate checks",- "version": "0.2.1",+ "version": "0.3.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"@@ -17,6 +17,21 @@"refinement","mcp","phase-gates",- "quality-gates"- ]+ "quality-gates",+ "function-hooks",+ "guard"+ ],+ "userConfig": {+ "guard": {+ "type": "string",+ "title": "Secret guard",+ "description": "Refuse specs and phase artifacts that hold a secret in sparc namespaces.",+ "required": false,+ "default": "on",+ "options": [+ "on",+ "off"+ ]+ }+ }}diff --git a/plugins/ruflo-sparc/README.md b/plugins/ruflo-sparc/README.mdindex 3968698599..828d1af167 100644--- a/plugins/ruflo-sparc/README.md+++ b/plugins/ruflo-sparc/README.md@@ -109,3 +109,14 @@ bash plugins/ruflo-sparc/scripts/smoke.sh## LicenseMIT++## 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 refuses to store a spec or phase artifact that holds a secret in a `sparc*` memory namespace. The refusal never repeats the secret.+- **Status file.** `.claude-flow/sparc-mod/status.json` (`{version: 1, updatedMs, guard, checked, blocked, seen}`), written at session start and when a counter changes.+- **`/sparc-mod`** answers locally: `status`, `scan <text>`, `phases`. (The plugin's own commands are prompt commands, which a hook cannot answer, so the mod has its own name.)+- **Option.** `guard` (`on` | `off`, default `on`) in the plugin's `userConfig`.++Test it: `claude plugin validate plugins/ruflo-sparc`, `claude plugin test plugins/ruflo-sparc`, `bash plugins/ruflo-sparc/scripts/smoke.sh`.diff --git a/plugins/ruflo-sparc/hooks/command.ts b/plugins/ruflo-sparc/hooks/command.tsnew file mode 100644index 0000000000..fdfd3b5ea8--- /dev/null+++ b/plugins/ruflo-sparc/hooks/command.ts@@ -0,0 +1,31 @@+import { secretsIn } from './screen'+import type { ModOptions } from './options'+import type { Stats } from './status'++/** `/sparc-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 = ['/sparc-mod status', '/sparc-mod scan <text>', '/sparc-mod phases'].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 [`guard ${opts.guard ? 'on' : 'off'} · checked ${stats.checked} · blocked ${stats.blocked}`, seen === '' ? 'no sparc-artifact calls this session' : seen].join('\n')+ }++ if (verb === 'scan') {+ if (arg === '') return 'usage: /sparc-mod scan <text>'+ const found = secretsIn(arg)+ return found.length ? `The guard would refuse that (looks like: ${found.join(', ')}).` : 'Nothing found: the guard would let that through.'+ }++ if (verb === 'phases') return ['S specification', 'P pseudocode', 'A architecture', 'R refinement', 'C completion', 'Artifacts go in memory namespaces starting with sparc; the guard screens them for secrets.'].join('\n')++ return `Unknown: ${verb}\n${HELP}`+}diff --git a/plugins/ruflo-sparc/hooks/guard.ts b/plugins/ruflo-sparc/hooks/guard.tsnew file mode 100644index 0000000000..119a29c4a0--- /dev/null+++ b/plugins/ruflo-sparc/hooks/guard.ts@@ -0,0 +1,38 @@+import { hasSecret } from './screen'++/** 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 NS = /^sparc/i+const WRITERS = new Set(['memory_store', 'agentdb_hierarchical-store', 'agentdb_pattern-store'])++/** The label of a write into a sparc namespace, else undefined: the guard only watches those. */+export function watched(tool: string, input: unknown): string | undefined {+ if (!WRITERS.has(shortName(tool))) return undefined+ return NS.test(field(input, 'namespace')) ? 'sparc artifact write' : undefined+}++/** The reason a sparc artifact write is refused, or undefined when it may go. Never names or echoes the secret. */+export function verdict(tool: string, input: unknown): string | undefined {+ if (watched(tool, input) === undefined) return undefined+ return textsOf(input).some(hasSecret)+ ? 'ruflo-sparc: this spec or artifact holds what looks like a secret (a key, token or password). Write a placeholder and name where the real value lives.'+ : undefined+}diff --git a/plugins/ruflo-sparc/hooks/hooks.json b/plugins/ruflo-sparc/hooks/hooks.jsonnew file mode 100644index 0000000000..e2de51af7e--- /dev/null+++ b/plugins/ruflo-sparc/hooks/hooks.json@@ -0,0 +1,6 @@+{+ "description": "SPARC as a mod (ADR-445 pattern): a guard that keeps secrets out of specs and phase artifacts stored in sparc memory namespaces, `/sparc-mod`, and a status file the console reads.",+ "modules": [+ "./register.ts"+ ]+}diff --git a/plugins/ruflo-sparc/hooks/options.ts b/plugins/ruflo-sparc/hooks/options.tsnew file mode 100644index 0000000000..a5d4812327--- /dev/null+++ b/plugins/ruflo-sparc/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-sparc/hooks/register.ts b/plugins/ruflo-sparc/hooks/register.tsnew file mode 100644index 0000000000..756c3944c0--- /dev/null+++ b/plugins/ruflo-sparc/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 */+ }+}++/**+ * SPARC as a mod (ADR-445 pattern): a guard that keeps secrets out of specs and phase artifacts stored in sparc memory namespaces, `/sparc-mod`, and a status file the console reads. No network, no process: only tools already connected.+ */+export const register: Register = (on, options) => {+ const s: Session = { opts: readOptions(options), stats: newStats() }++ on('session.start', async ($, e, next) => {+ const result = await next(e)+ s.root = (await $.session.root()) as string | undefined+ try {+ await $.command.register({ name: 'sparc-mod', description: 'SPARC mod: status, scan <text>, phases' })+ } 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 }+ })++ /** `/sparc-mod` (the plugin's own commands are prompt commands, which no hook can answer). */+ on('command.run', { command: 'sparc-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-sparc/hooks/screen.ts b/plugins/ruflo-sparc/hooks/screen.tsnew file mode 100644index 0000000000..0bc8f69b8d--- /dev/null+++ b/plugins/ruflo-sparc/hooks/screen.ts@@ -0,0 +1,29 @@+/**+ * Secret screening for the SPARC mod (copied from the ADR-445 AgentDB screen). Findings are NAMES only: the matched text is never+ * returned, logged or counted by value.+ */++const SECRETS: readonly (readonly [string, RegExp])[] = [+ ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],+ ['aws access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/],+ ['github token', /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/],+ ['slack token', /\bxox[abprs]-[A-Za-z0-9-]{10,}/],+ ['google api key', /\bAIza[0-9A-Za-z_-]{35}\b/],+ ['anthropic or openai key', /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{24,}/],+ ['jwt', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/],+ ['bearer token', /\bBearer\s+[A-Za-z0-9._~+/=-]{24,}/],+ ['key assignment', /\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i],+]++// C0/C1 controls (keeping tab and newline), DEL, zero-width and bidi override characters.+const INVISIBLE = new RegExp('[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\ufeff]', 'g')++const bare = (text: string) => (text.length > 20_000 ? text.slice(0, 20_000) : text).replace(INVISIBLE, '')++/** Names of every secret shape found in `text`. Cost is linear in the capped input. */+export const secretsIn = (text: string): string[] => {+ const bounded = bare(text)+ return SECRETS.filter(([, re]) => re.test(bounded)).map(([name]) => name)+}++export const hasSecret = (text: string) => secretsIn(text).length > 0diff --git a/plugins/ruflo-sparc/hooks/status.ts b/plugins/ruflo-sparc/hooks/status.tsnew file mode 100644index 0000000000..66b90f60d6--- /dev/null+++ b/plugins/ruflo-sparc/hooks/status.ts@@ -0,0 +1,11 @@+/** Counters the mod keeps for the session and writes to `.claude-flow/sparc-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/sparc-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-sparc/scripts/smoke.sh b/plugins/ruflo-sparc/scripts/smoke.shindex 86d403510d..1a2a5e4d9d 100755--- a/plugins/ruflo-sparc/scripts/smoke.sh+++ b/plugins/ruflo-sparc/scripts/smoke.sh@@ -7,9 +7,9 @@ step() { printf "→ %s ... " "$1"; }ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }-step "1. plugin.json declares 0.2.1 with new keywords"+step "1. plugin.json declares 0.3.0 with new keywords"v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)-if [[ "$v" != "0.2.1" ]]; then bad "expected 0.2.1, got '$v'"; else+if [[ "$v" != "0.3.0" ]]; then bad "expected 0.3.0, got '$v'"; elsemiss=""for k in mcp phase-gates quality-gates; dogrep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"@@ -87,5 +87,24 @@ for f in "$ROOT"/skills/*/SKILL.md; dodone[[ -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 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: userConfig defaults are safe (guard defaults on)"+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 1diff --git a/plugins/ruflo-sparc/tests/mod.test.ts b/plugins/ruflo-sparc/tests/mod.test.tsnew file mode 100644index 0000000000..55aa7140a7--- /dev/null+++ b/plugins/ruflo-sparc/tests/mod.test.ts@@ -0,0 +1,114 @@+import type { On } from 'claude-code'+import { describe, expect, test, tier } from 'claude-code/testing'++import { answer } from '../hooks/command'+import { readOptions } from '../hooks/options'+import { hasSecret, secretsIn } from '../hooks/screen'+import { newStats } from '../hooks/status'++tier('user')++const ROOT = '/work'+const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const+const slash = (args: string) => ({ command: 'sparc-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const+const STATUS = `${ROOT}/.claude-flow/sparc-mod/status.json`++// Built at run time so no secret-shaped literal sits in the source.+const ghp = `ghp_${'a1B2'.repeat(10)}`+const bearer = 'Zm9vYmFyYmF6cXV4MTIzNDU2Nzg5MGFiY2RlZg'++/** The world beneath the mod: a project, a file map, and the connected tools. */+function world(on: On, tools: readonly string[] = ['mcp__plugin_ruflo-core_ruflo__x_federation_publish']) {+ 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: tools.map(name => ({ name, description: '', mcp: true })) }))+ on('clock.now', () => ({ value: 1_700_000_000_000 }))+ on('clock.sleep', () => ({ value: undefined }))+ return files+}++const deny = async (call: () => Promise<unknown>) => JSON.stringify(await call().then(r => r, (e: unknown) => ({ text: String(e) })))++describe('defaults', () => {+ test('guard on; a bad value is the default', () => {+ expect(readOptions(undefined)).toEqual({ guard: true })+ expect(readOptions({ guard: 'off' })).toEqual({ guard: false })+ expect(readOptions({ guard: 'banana' })).toEqual({ guard: true })+ })+})++describe('screen', () => {+ test('names secret shapes and never returns the value', () => {+ expect(secretsIn(`k ${ghp}`)).toEqual(['github token'])+ expect(JSON.stringify(secretsIn(`k ${ghp}`))).not.toContain('ghp_')+ expect(hasSecret('password = hunter2hunter2hunter2')).toBe(true)+ expect(hasSecret('the password field is validated server side')).toBe(false)+ expect(hasSecret(`ghp_\u200b${'a1B2'.repeat(10)}`)).toBe(true)+ })+})++describe('status file', () => {+ test('written at session start with version and mode', async ($, on) => {+ const files = world(on)+ await $.session.start(START)+ expect(JSON.parse(files.get(STATUS) ?? '{}')).toMatchObject({ version: 1, guard: true, checked: 0, blocked: 0 })+ })+})++describe('guard', () => {+ const BAD = { tool: 'mcp__plugin_ruflo-core_ruflo__memory_store', namespace: 'sparc-spec', key: 's1', value: `db password = hunter2hunter2hunter2` } as never+ const GOOD = { tool: 'mcp__plugin_ruflo-core_ruflo__memory_store', namespace: 'sparc-spec', key: 's1', value: 'S: users can reset a password by email' } as never+ const OTHER = { tool: 'mcp__plugin_ruflo-core_ruflo__memory_store', namespace: 'patterns', key: 's1', value: `token ${ghp}` } as never++ test('refuses a secret, never echoes it, and counts it in the status file', async ($, on) => {+ const files = world(on)+ on('tool.call', () => ({ result: 'done' }))+ await $.session.start(START)+ const out = await deny(() => $.tool.call(BAD))+ expect(out).toContain('secret')+ expect(out).not.toContain(ghp)+ expect(out).not.toContain(bearer)+ expect(JSON.parse(files.get(STATUS) ?? '{}')).toMatchObject({ checked: 1, blocked: 1, seen: { 'sparc artifact write': 1 } })+ })++ test('passes clean input and ignores calls that are not this plugin\'s', async ($, on) => {+ world(on)+ on('tool.call', () => ({ result: 'done' }))+ await $.session.start(START)+ expect(await deny(() => $.tool.call(GOOD))).toContain('done')+ expect(await deny(() => $.tool.call(OTHER))).toContain('done')+ })++ test('off lets the call through', { options: { guard: 'off' } }, async ($, on) => {+ world(on)+ on('tool.call', () => ({ result: 'done' }))+ await $.session.start(START)+ expect(await deny(() => $.tool.call(BAD))).toContain('done')+ })+})++describe('/sparc-mod', () => {+ test('status, scan and phases answer locally', async ($, on) => {+ world(on)+ await $.session.start(START)+ expect((await $.command.run(slash('status'))).text).toContain('guard on')+ expect((await $.command.run(slash(`scan key ${ghp}`))).text).toContain('github token')+ expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found')+ expect((await $.command.run(slash('phases'))).text).toContain('S specification')+ })++ test('an unknown verb 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('/sparc-mod status')+ expect((await $.command.run(slash(''))).text).toContain('/sparc-mod status')+ })++ test('answer() is pure over its inputs', async () => {+ const text = await answer('status', { opts: { guard: false }, stats: newStats(), tools: async () => [] })+ expect(text).toContain('guard off')+ })+})diff --git a/plugins/ruflo-sparc/tsconfig.json b/plugins/ruflo-sparc/tsconfig.jsonnew file mode 100644index 0000000000..e4ba54993e--- /dev/null+++ b/plugins/ruflo-sparc/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"]+}