🌊 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-ai-team): mod (guard/status/command) as function hooks, ADR-445 pattern
ruvae9ec364aa2f
diff --git a/plugins/ruflo-ai-team/.claude-plugin/plugin.json b/plugins/ruflo-ai-team/.claude-plugin/plugin.jsonindex a59dc1448b..a714f384a5 100644--- a/plugins/ruflo-ai-team/.claude-plugin/plugin.json+++ b/plugins/ruflo-ai-team/.claude-plugin/plugin.json@@ -1,8 +1,11 @@{"name": "ruflo-ai-team","description": "Give Claude a tenant-isolated AI team that divides work, coordinates progress, recalls approved context, and returns evidence-backed results.",- "version": "0.1.6",- "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" },+ "version": "0.2.0",+ "author": {+ "name": "ruvnet",+ "url": "https://github.com/ruvnet"+ },"homepage": "https://team.ruv.io","privacyPolicyUrl": "https://team.ruv.io/privacy","supportUrl": "https://team.ruv.io/support",@@ -11,5 +14,27 @@"termsOfServiceUrl": "https://team.ruv.io/terms","icon": ".claude-plugin/icon.svg","license": "MIT",- "keywords": ["ruflo", "ai-team", "multi-agent", "automation", "ruvector", "mcp"]+ "keywords": [+ "ruflo",+ "ai-team",+ "multi-agent",+ "automation",+ "ruvector",+ "mcp",+ "mod",+ "function-hooks"+ ],+ "userConfig": {+ "guard": {+ "type": "string",+ "title": "AI Team guard",+ "description": "Refuse what goes into team memory and task or run records (memory_remember, task_create, task_update, run_create on the ruflo-ai-team server) that hold a key, token or password.",+ "required": false,+ "default": "on",+ "options": [+ "on",+ "off"+ ]+ }+ }}diff --git a/plugins/ruflo-ai-team/README.md b/plugins/ruflo-ai-team/README.mdindex 2ad7fb10c3..b5bce30ea5 100644--- a/plugins/ruflo-ai-team/README.md+++ b/plugins/ruflo-ai-team/README.md@@ -59,3 +59,14 @@ The plugin owns the `ruflo-ai-team-*` namespace. Tenant data is never separated- [ADR-0002: Approval and external-action boundary](docs/adrs/0002-approval-and-external-action-boundary.md)- [ADR-0003: Tenant-scoped RuVector memory](docs/adrs/0003-tenant-scoped-ruvector-memory.md)- [ADR-0004: Metered unit budget](docs/adrs/0004-metered-unit-budget.md)++## As a mod++AI Team also ships as a function-hook mod (ADR-445 pattern; hooks in `hooks/`, loaded with the plugin). No network, no process, no model call.++- **Guard (default on)**: refuses a team write (`memory_remember`, `task_create`, `task_update`, `run_create` on the ruflo-ai-team server) that holds a key, token or password. It only tightens: it never allows anything the session would deny, and the refusal never repeats the secret. Turn it off with the `guard` option.+- **`/ai-team-mod`**: answered locally. `/ai-team-mod status`, `/ai-team-mod scan <text>`.+- **Status file**: `.claude-flow/ai-team-mod/status.json` (`version`, `updatedMs`, counters), written at session start and whenever a call is refused; the console reads it.+- **Options** (`userConfig`): `guard` (`on` by default).++Test: `claude plugin validate plugins/ruflo-ai-team`, `claude plugin test plugins/ruflo-ai-team`, and `bash plugins/ruflo-ai-team/scripts/smoke.sh`.diff --git a/plugins/ruflo-ai-team/hooks/command.ts b/plugins/ruflo-ai-team/hooks/command.tsnew file mode 100644index 0000000000..1e4573aee9--- /dev/null+++ b/plugins/ruflo-ai-team/hooks/command.ts@@ -0,0 +1,29 @@+import { scan } from './screen'+import type { ModOptions } from './options'+import type { Stats } from './status'++/** `/ai-team-mod` is answered locally and takes no model turn. */+export type CommandDeps = { readonly opts: ModOptions; readonly stats: Stats }++const HELP = ['/ai-team-mod status', '/ai-team-mod scan <text>'].join('\n')++export function answer(args: string, deps: CommandDeps): 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') {+ return `guard ${opts.guard ? 'on' : 'off'} · calls guarded ${stats.calls} · blocked ${stats.blocked}`+ }++ if (verb === 'scan') {+ if (arg === '') return 'usage: /ai-team-mod scan <text>'+ const found = scan(arg)+ const parts = [found.secrets.length ? `secrets: ${found.secrets.join(', ')}` : '', found.injection.length ? `injection phrasing: ${found.injection.join(', ')}` : ''].filter(Boolean)+ return parts.length ? `The guard would refuse a write of that (${parts.join('; ')}).` : 'Nothing found: the guard would let that through.'+ }++ return `Unknown: ${verb}\n${HELP}`+}diff --git a/plugins/ruflo-ai-team/hooks/guard.ts b/plugins/ruflo-ai-team/hooks/guard.tsnew file mode 100644index 0000000000..988bd5d2b9--- /dev/null+++ b/plugins/ruflo-ai-team/hooks/guard.ts@@ -0,0 +1,33 @@+import { hasSecret } from './screen'++/** `mcp__<server>__<tool>` into its two halves; tool names never hold a double underscore. */+export function splitName(name: string): { server: string; tool: string } | undefined {+ if (!name.startsWith('mcp__')) return undefined+ const at = name.lastIndexOf('__')+ return at > 5 ? { server: name.slice(5, at), tool: name.slice(at + 2) } : undefined+}++/** 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 []+}++/** True for the tool calls this plugin guards: what goes into team memory and task or run records (`memory_remember`, `task_create`, `task_update`, `run_create` on the ruflo-ai-team server). */+export function owns(tool: string, input: unknown): boolean {+ const parts = splitName(tool)+ const name = parts?.tool ?? tool+ return (parts?.server ?? '').includes('ruflo-ai-team') && ['memory_remember', 'task_create', 'task_update', 'run_create'].includes(name)+}++/** The reason a call is refused, or undefined when it may go. Never names or echoes the secret. */+export function verdict(tool: string, input: unknown): string | undefined {+ if (!owns(tool, input)) return undefined+ return textsOf(input).some(hasSecret) ? "ruflo-ai-team: this team write holds what looks like a secret (a key, token or password). Team memory and tasks are shared and retained as evidence; store a reference, not the value." : undefined+}diff --git a/plugins/ruflo-ai-team/hooks/hooks.json b/plugins/ruflo-ai-team/hooks/hooks.jsonnew file mode 100644index 0000000000..be32b1c30a--- /dev/null+++ b/plugins/ruflo-ai-team/hooks/hooks.json@@ -0,0 +1,6 @@+{+ "description": "AI Team as a mod (ADR-445 pattern): a tighten-only guard on what goes into team memory and task or run records (`memory_remember`, `task_create`, `task_update`, `run_create` on the ruflo-ai-team server), /ai-team-mod, and a status file the console reads.",+ "modules": [+ "./register.ts"+ ]+}diff --git a/plugins/ruflo-ai-team/hooks/options.ts b/plugins/ruflo-ai-team/hooks/options.tsnew file mode 100644index 0000000000..7fa90ff366--- /dev/null+++ b/plugins/ruflo-ai-team/hooks/options.ts@@ -0,0 +1,16 @@+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 {+ const o = options ?? {}+ return {+ guard: flag(o.guard, true),+ }+}diff --git a/plugins/ruflo-ai-team/hooks/register.ts b/plugins/ruflo-ai-team/hooks/register.tsnew file mode 100644index 0000000000..203754c040--- /dev/null+++ b/plugins/ruflo-ai-team/hooks/register.ts@@ -0,0 +1,57 @@+import type { Hook, Register } from 'claude-code'++import { answer } from './command'+import { owns, verdict } from './guard'+import { readOptions } from './options'+import { newStats, STATUS_PATH, statusText, type Stats } from './status'+import type { ModOptions } from './options'++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, await $.clock.now()))+ } catch {+ /* the status file is a courtesy */+ }+}++/**+ * AI Team as a mod (ADR-445 pattern): a tighten-only guard on what goes into team memory and task or run records (`memory_remember`, `task_create`, `task_update`, `run_create` on the ruflo-ai-team server), `/ai-team-mod`, and a status file the console reads.+ * No network, no process: only the hooks API.+ */+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+ s.stats.startedMs = await $.clock.now()+ try {+ await $.command.register({ name: 'ai-team-mod', description: 'AI Team 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) => {+ if (!owns(e.tool, e)) return next(e)+ s.stats.calls+++ const reason = verdict(e.tool, e)+ if (reason === undefined) return next(e)+ s.stats.blocked+++ await flush($, s)+ return { deny: reason }+ })+ }++ /** `/ai-team-mod` (a markdown command of the plugin cannot be answered by a hook, so the mod owns this name). */+ on('command.run', { command: 'ai-team-mod' }, async (_$, e) => ({ text: answer(typeof e.args === 'string' ? e.args : '', { opts: s.opts, stats: s.stats }) }))+}diff --git a/plugins/ruflo-ai-team/hooks/screen.ts b/plugins/ruflo-ai-team/hooks/screen.tsnew file mode 100644index 0000000000..b3b107dbef--- /dev/null+++ b/plugins/ruflo-ai-team/hooks/screen.ts@@ -0,0 +1,50 @@+/**+ * Pure text screening for the AgentDB mod (ADR-445). Two jobs: find secrets (so none is stored) and find prompt-injection phrasing (so+ * retrieved memory cannot instruct the model). 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],+]++const INJECTION: readonly (readonly [string, RegExp])[] = [+ ['override instructions', /\b(?:ignore|disregard|forget|override)\b[^.\n]{0,40}\b(?:previous|prior|above|earlier|all|any|system)\b[^.\n]{0,30}\b(?:instructions?|rules?|prompts?|guidelines?)\b/i],+ ['role reassignment', /\byou are (?:now|no longer)\b|\bact as (?:an? )?(?:unrestricted|jailbroken)\b/i],+ ['new instructions', /\b(?:new|updated|real) (?:system )?instructions?\s*:/i],+ ['fake role tags', /<\/?\s*(?:system|assistant|developer|instructions?)\s*>|^\s*(?:system|assistant)\s*:/im],+ ['concealment', /\bdo not (?:tell|inform|mention|reveal)[^.\n]{0,30}\b(?:user|human|operator)\b/i],+ ['exfiltration', /\b(?:exfiltrate|send|post|upload)\b[^.\n]{0,50}\b(?:secrets?|credentials?|tokens?|api keys?|\.env)\b/i],+ ['shell pipe', /\b(?:curl|wget)\b[^|\n]{0,200}\|\s*(?:sudo\s+)?(?:ba|z)?sh\b/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, '')++export type Findings = { readonly secrets: readonly string[]; readonly injection: readonly string[] }++const names = (rules: readonly (readonly [string, RegExp])[], text: string) => rules.filter(([, re]) => re.test(text)).map(([name]) => name)++/** Names of every secret shape and injection phrase found in `text`. Cost is linear in the capped input. */+export function scan(text: string): Findings {+ const bounded = bare(text)+ return { secrets: names(SECRETS, bounded), injection: names(INJECTION, bounded) }+}++export const hasSecret = (text: string) => names(SECRETS, bare(text)).length > 0+++/** Makes stored text safe to show: no control or bidi characters, whitespace collapsed, at most `max` characters. */+export function tidy(text: string, max: number): string {+ const flat = text.replace(INVISIBLE, '').replace(/\s+/g, ' ').trim()+ return flat.length > max ? `${flat.slice(0, Math.max(0, max - 1))}…` : flat+}diff --git a/plugins/ruflo-ai-team/hooks/status.ts b/plugins/ruflo-ai-team/hooks/status.tsnew file mode 100644index 0000000000..140d517553--- /dev/null+++ b/plugins/ruflo-ai-team/hooks/status.ts@@ -0,0 +1,11 @@+/** Counters the mod keeps for the session and writes to `.claude-flow/ai-team-mod/status.json` for the console. */+export type Stats = { calls: number; blocked: number; startedMs: number }++export const newStats = (): Stats => ({ calls: 0, blocked: 0, startedMs: 0 })++export const STATUS_PATH = '.claude-flow/ai-team-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, mod: 'ai-team', guard: mode.guard, ...stats }, null, 2)}\n`+}diff --git a/plugins/ruflo-ai-team/scripts/smoke.mjs b/plugins/ruflo-ai-team/scripts/smoke.mjsindex 6f1acdd2e7..489ccc2949 100644--- a/plugins/ruflo-ai-team/scripts/smoke.mjs+++ b/plugins/ruflo-ai-team/scripts/smoke.mjs@@ -15,4 +15,11 @@ check('four commands',readdirSync(new URL('commands/',root)).filter((name)=>nameconst server=read('src/server.mjs');check('fourteen MCP tools',(server.match(/mcp\.tool\('/g)||[]).length+(server.match(/mcp\.registerTool\('/g)||[]).length===14);check('explicit annotation factories',server.includes('readOnlyHint: true')&&server.includes('readOnlyHint: false')&&server.includes('destructiveHint: false')&&server.includes('idempotentHint:')&&server.includes('openWorldHint: false'));+// mod (ADR-445 pattern)+const hooksJson=JSON.parse(read('hooks/hooks.json'));+check('mod: hooks.json names register.ts',hooksJson.modules?.includes('./register.ts'));+for(const name of ['options','screen','guard','command','status','register']){check(`mod: hooks/${name}.ts present and <=500 lines`,existsSync(new URL(`hooks/${name}.ts`,root))&&read(`hooks/${name}.ts`).split('\n').length<=501)}+check('mod: guard defaults on',manifest.userConfig?.guard?.default==='on');+check('mod: no network or process in hooks',!['screen','guard','command','status','register','options'].some((name)=>/\$\.(http|process)\.|child_process|fetch\(/.test(read(`hooks/${name}.ts`))));+check('mod: /ai-team-mod collides with no command or skill',read('hooks/register.ts').includes("name: 'ai-team-mod'")&&!existsSync(new URL('commands/ai-team-mod.md',root))&&!existsSync(new URL('skills/ai-team-mod',root)));console.log(`smoke ok: ${checks.length} checks`);diff --git a/plugins/ruflo-ai-team/tests/mod.test.ts b/plugins/ruflo-ai-team/tests/mod.test.tsnew file mode 100644index 0000000000..633a855db4--- /dev/null+++ b/plugins/ruflo-ai-team/tests/mod.test.ts@@ -0,0 +1,86 @@+import type { On } from 'claude-code'+import { describe, expect, test, tier } from 'claude-code/testing'++import { readOptions } from '../hooks/options'++tier('user')++const ROOT = '/work'+const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const+const slash = (args: string) => ({ command: 'ai-team-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const+const STATUS = `${ROOT}/.claude-flow/ai-team-mod/status.json`++// Built at run time so no secret-shaped literal sits in the source.+const ghp = `ghp_${'a1B2'.repeat(10)}`++/** The world beneath the mod: a project root, a file map, command registration and a clock. */+function world(on: On) {+ const files = new Map<string, string>()+ const commands: string[] = []+ on('session.start', ($, e) => ({ cwd: e.cwd }))+ on('session.root', () => ({ value: ROOT }))+ on('command.register', ($, e) => (commands.push(e.name), { value: { command: e.name } }))+ on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined }))+ on('clock.now', () => ({ value: Date.now() }))+ return { files, commands }+}+const status = (files: Map<string, string>) => JSON.parse(files.get(STATUS) ?? '{}')++describe('defaults', () => {+ test('options: bad values fall back to the safe default', () => {+ expect(readOptions(undefined).guard).toBe(true)+ expect(readOptions({ guard: 'banana' }).guard).toBe(true)+ expect(readOptions({ guard: 'off' }).guard).toBe(false)+ })++ test('session start registers /ai-team-mod and writes the status file', async ($, on) => {+ const w = world(on)+ await $.session.start(START)+ expect(w.commands).toContain('ai-team-mod')+ expect(status(w.files)).toMatchObject({ version: 1, mod: 'ai-team', guard: true, blocked: 0 })+ expect(typeof status(w.files).updatedMs).toBe('number')+ })+})++describe('guard', () => {+ test('refuses a secret, passes a clean call, ignores tools it does not own, never echoes the secret', async ($, on) => {+ const w = world(on)+ on('tool.call', () => ({ result: 'went through' }))+ await $.session.start(START)++ const denied = await $.tool.call(({ tool: "mcp__plugin_ruflo-ai-team_ruflo-ai-team__memory_remember", text: `the key is ${ghp}` }) as never).then(+ r => r,+ (e: unknown) => ({ text: String(e) }),+ )+ expect(JSON.stringify(denied)).toContain('secret')+ expect(JSON.stringify(denied)).not.toContain('ghp_')+ expect(JSON.stringify(await $.tool.call(({ tool: "mcp__plugin_ruflo-ai-team_ruflo-ai-team__memory_remember", text: "we deploy on Fridays" }) as never))).toContain('went through')+ expect(JSON.stringify(await $.tool.call(({ tool: "mcp__plugin_ruflo-core_ruflo__memory_store", text: `${ghp}` }) as never))).toContain('went through')+ expect(status(w.files)).toMatchObject({ blocked: 1 })+ })++ 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(JSON.stringify(await $.tool.call(({ tool: "mcp__plugin_ruflo-ai-team_ruflo-ai-team__memory_remember", text: `the key is ${ghp}` }) as never))).toContain('went through')+ })+})++describe('/ai-team-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')+ expect((await $.command.run(slash(`scan key ${ghp}`))).text).toContain('github token')+ expect((await $.command.run(slash(`scan key ${ghp}`))).text).not.toContain('ghp_')+ expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found')+ })++ test('an unknown verb gets the help, not a model turn', async ($, on) => {+ world(on)+ await $.session.start(START)+ expect((await $.command.run(slash('what is this'))).text).toContain('/ai-team-mod status')+ expect((await $.command.run(slash(''))).text).toContain('/ai-team-mod status')+ })+})diff --git a/plugins/ruflo-ai-team/tsconfig.json b/plugins/ruflo-ai-team/tsconfig.jsonnew file mode 100644index 0000000000..e4ba54993e--- /dev/null+++ b/plugins/ruflo-ai-team/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"]+}