Merge branch 'mods/batch-04' into feat/plugins-as-mods

This commit is contained in:
ruv committed 2026-10-04 15:37:55 -04:00
commit b59ddab6b4
46 files changed
+1984 -32

No files matched your search

@@ -1,7 +1,7 @@
{
"name": "ruflo-jujutsu",
"description": "Advanced git workflows with diff analysis, risk scoring, change classification (feature/bugfix/refactor/...), and reviewer recommendations — wraps 6 analyze_* MCP tools (diff, diff-risk, diff-classify, diff-reviewers, file-risk, diff-stats)",
"version": "0.2.1",
"description": "Advanced git workflows with diff analysis, risk scoring, change classification (feature/bugfix/refactor/...), and reviewer recommendations — wraps 6 analyze_* MCP tools (diff, diff-risk, diff-classify, diff-reviewers, file-risk, diff-stats). As a mod (ADR-445): a PR-text and merge/close guard, /jujutsu-mod, and a status file the console shows",
"version": "0.3.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -17,6 +17,33 @@
"risk-analysis",
"mcp",
"change-classification",
"reviewer-recommendation"
]
"reviewer-recommendation",
"mod",
"function-hooks",
"guard"
],
"userConfig": {
"guard": {
"type": "string",
"title": "Guard",
"description": "Refuse tool calls that are clearly harmful in this plugin's domain (see README, As a mod).",
"required": false,
"default": "on",
"options": [
"on",
"off"
]
},
"confirmPrActions": {
"type": "string",
"title": "Confirm PR merge and close",
"description": "Require confirm: true on github_pr_manage merge and close.",
"required": false,
"default": "on",
"options": [
"on",
"off"
]
}
}
}
+12
View File
@@ -73,3 +73,15 @@ bash plugins/ruflo-jujutsu/scripts/smoke.sh
- `ruflo-adr` — `/adr check` consumes this plugin's `analyze_diff` output
- `ruflo-agentdb` — namespace convention owner
## As a mod
This plugin ships a function-hook mod (ADR-445, `hooks/register.ts`). It makes no network call, spawns no process and makes no model call.
- **Guard** (tighten-only, on by default): Refuses `github_pr_manage` create/review whose title or body holds a key, token or password (PR text is public), and `merge`/`close` unless the call carries `confirm: true`. A refusal never echoes the secret.
- **`/jujutsu-mod`**: `status`, `recent`, `tools` (which of this plugin's tools are connected) and `scan <text>` (would the guard refuse it). Answered locally.
- **Status file**: `.claude-flow/jujutsu-mod/status.json` (`{version: 1, updatedMs, guard, calls, total, blocked, recent}`, counters only, never tool input), written at session start and after every call to this plugin's tools.
Options (`userConfig`): `guard` (on), `confirmPrActions` (on).
Test it: `claude plugin validate plugins/ruflo-jujutsu`, `claude plugin test plugins/ruflo-jujutsu`, `bash plugins/ruflo-jujutsu/scripts/smoke.sh`.
+39
View File
@@ -0,0 +1,39 @@
import { hasSecret } from './screen'
import type { ModOptions } from './options'
/** `mcp__<server>__<tool>` into its tool half; tool names never hold a double underscore. */
export function shortName(name: string): string {
const at = name.lastIndexOf('__')
return name.startsWith('mcp__') && at > 5 ? name.slice(at + 2) : name
}
/** 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 []
}
const field = (input: unknown, key: string): unknown => (typeof input === 'object' && input !== null ? (input as Record<string, unknown>)[key] : undefined)
/** The tools this plugin owns: the six analyze_* tools and the three github_* tools its skills use. */
export const isOwn = (name: string, _input?: unknown): boolean => name.startsWith('analyze_') || ['github_pr_manage', 'github_repo_analyze', 'github_metrics'].includes(name)
/** The reason a call is refused, or undefined when it may go. Never names or echoes a secret. */
export function verdict(name: string, input: unknown, opts: ModOptions, _calls: Record<string, number>): string | undefined {
if (name !== 'github_pr_manage') return undefined
const action = field(input, 'action')
if (['create', 'review'].includes(String(action)) && textsOf(input).some(hasSecret)) {
return 'ruflo-jujutsu: this pull request text holds what looks like a secret (a key, token or password). PR text is public; remove it and retry.'
}
if (opts.confirmPrActions && (action === 'merge' || action === 'close') && field(input, 'confirm') !== true) {
return `ruflo-jujutsu: ${String(action)} changes a pull request for everyone. Ask the user, then retry with confirm: true.`
}
return undefined
}
+4
View File
@@ -0,0 +1,4 @@
{
"description": "Jujutsu as a mod (ADR-445): a tighten-only guard on the diff and PR tools (no secrets in public PR text, merge and close need an explicit confirm), a status file the console reads, and /jujutsu-mod.",
"modules": ["./register.ts"]
}
+13
View File
@@ -0,0 +1,13 @@
import type { PluginOptions } from 'claude-code'
/** The plugin's `userConfig`, validated: a bad value is the default (guard on, PR merge and close confirmed). */
export type ModOptions = { readonly guard: boolean; readonly confirmPrActions: boolean; readonly extra: Readonly<Record<string, unknown>> }
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 ?? {}
const confirmPrActions = flag(o.confirmPrActions, true)
return { guard: flag(o.guard, true), confirmPrActions, extra: { confirmPrActions } }
}
+108
View File
@@ -0,0 +1,108 @@
import type { Hook, Register } from 'claude-code'
import { isOwn, shortName, verdict } from './guard'
import { readOptions, type ModOptions } from './options'
import { scan } from './screen'
const COMMAND = 'jujutsu-mod'
const STATUS_PATH = '.claude-flow/jujutsu-mod/status.json'
const RECENT = 5
type Dollar = Parameters<Hook<'session.start'>>[0]
/** Everything one session of the mod keeps: its settings, per-tool counters, what was refused and the project root. */
type Session = {
readonly opts: ModOptions
readonly calls: Record<string, number>
blocked: number
readonly recent: string[]
root?: string
}
const total = (s: Session) => Object.values(s.calls).reduce((a, b) => a + b, 0)
function note(s: Session, line: string): void {
s.recent.push(line)
if (s.recent.length > RECENT) s.recent.splice(0, s.recent.length - RECENT)
}
/** The status file the console reads; `version` lets it refuse a shape it does not know. Counters only, never tool input. */
async function flush($: Dollar, s: Session): Promise<void> {
if (s.root === undefined) return
const body = { version: 1, updatedMs: await $.clock.now(), guard: s.opts.guard, ...s.opts.extra, calls: s.calls, total: total(s), blocked: s.blocked, recent: s.recent }
try {
await $.fs.write(`${s.root}/${STATUS_PATH}`, `${JSON.stringify(body, null, 2)}\n`)
} catch {
/* the status file is a courtesy */
}
}
/** The connected tools this plugin owns, by short name. */
async function connected($: Dollar): Promise<string[]> {
const tools = await $.tool.list()
return tools.filter(t => t.mcp && isOwn(shortName(t.name))).map(t => shortName(t.name))
}
const HELP = ['/jujutsu-mod status', '/jujutsu-mod scan <text>', '/jujutsu-mod recent', '/jujutsu-mod tools'].join('\n')
async function answer($: Dollar, s: Session, args: string): Promise<string> {
const [verb = '', ...rest] = args.trim().split(/\s+/)
const arg = rest.join(' ')
if (verb === '' || verb === 'help') return HELP
if (verb === 'status') {
const per = Object.entries(s.calls).map(([k, v]) => `${k} ${v}`).join(' · ')
return [`guard ${s.opts.guard ? 'on' : 'off'}${Object.entries(s.opts.extra).map(([k, v]) => ` · ${k} ${String(v)}`).join('')}`, `${total(s)} call${total(s) === 1 ? '' : 's'}${per ? ` (${per})` : ''} · refused ${s.blocked}`].join('\n')
}
if (verb === 'recent') return s.recent.length ? s.recent.map(r => `- ${r}`).join('\n') : 'Nothing has gone through this session.'
if (verb === 'tools') {
const names = await connected($)
return names.length ? names.join('\n') : 'None of this plugin\'s tools are connected. Connect the ruflo MCP server and try again.'
}
if (verb === 'scan') {
if (arg === '') return 'usage: /jujutsu-mod scan <text>'
const found = scan(arg)
return found.secrets.length ? `The guard would refuse that (${found.secrets.join(', ')}).` : 'Nothing found: the guard would let that through.'
}
return `Unknown: ${verb}\n${HELP}`
}
/**
* Jujutsu as a mod (ADR-445): a tighten-only guard on this plugin's own tools, a status file the console reads, and `/jujutsu-mod`.
* No network, no process, no model call.
*/
export const register: Register = (on, options) => {
const s: Session = { opts: readOptions(options), calls: {}, blocked: 0, recent: [] }
on('session.start', async ($, e, next) => {
const result = await next(e)
s.root = (await $.session.root()) as string | undefined
try {
await $.command.register({ name: COMMAND, description: 'Jujutsu mod: status, scan <text>, recent, tools' })
} catch {
/* a name taken by another plugin must not stop the mod */
}
await flush($, s)
return result
})
on('tool.call', async ($, e, next) => {
const name = shortName(e.tool)
if (!isOwn(name, e)) return next(e)
if (s.opts.guard) {
const reason = verdict(name, e, s.opts, s.calls)
if (reason !== undefined) {
s.blocked++
note(s, `refused ${name}`)
await flush($, s)
return { deny: reason }
}
}
s.calls[name] = (s.calls[name] ?? 0) + 1
note(s, name)
await flush($, s)
return next(e)
})
/** `/jujutsu-mod`: the plugin's own commands are prompt commands, which no hook can answer. */
on('command.run', { command: COMMAND }, async ($, e) => ({ text: await answer($, s, typeof e.args === 'string' ? e.args : '') }))
}
+50
View File
@@ -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
}
+21 -2
View File
@@ -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 change-classification reviewer-recommendation; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
@@ -71,5 +71,24 @@ for f in "$ROOT"/skills/*/SKILL.md; do
done
[[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills"
# M1-M3. The mod (ADR-445): 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 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), the command name is jujutsu-mod"
node -e '
const c = require(process.argv[1]).userConfig || {}
process.exit(c.guard && c.guard.default === "on" ? 0 : 1)
' "$ROOT/.claude-plugin/plugin.json" && grep -q "'jujutsu-mod'" "$ROOT/hooks/register.ts" && ok || bad "userConfig defaults or command name 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
@@ -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 P = 'mcp__plugin_ruflo-core_ruflo__'
const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
const slash = (args: string) => ({ command: 'jujutsu-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const
const TOOLS = ["analyze_diff","analyze_diff-risk","github_pr_manage"].map(name => ({ name: P + name, description: '', mcp: true }))
/** The world beneath the mod: a project root, a file map, the connected tools, and a stub that answers every tool call. */
function world(on: On, tools = TOOLS) {
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('tool.list', () => ({ value: tools }))
on('clock.now', () => ({ value: Date.now() }))
on('tool.call', () => ({ result: 'ran' }))
return { files, registered, status: () => JSON.parse(files.get(`${ROOT}/.claude-flow/jujutsu-mod/status.json`) ?? '{}') }
}
const attempt = async ($: Parameters<Parameters<typeof test>[2]>[0], call: object) =>
JSON.stringify(await $.tool.call(call as never).then(r => r, (e: unknown) => ({ text: String(e) })))
describe('guard', () => {
test('refuses: secret in PR text, and never echoes the secret', async ($, on) => {
world(on)
await $.session.start(START)
const out = await attempt($, { tool: P + 'github_pr_manage', action: 'create', title: 'fix', body: `token ghp_${'a1B2'.repeat(10)}` })
expect(out).not.toContain('ran')
expect(out).toContain('ruflo-jujutsu')
expect(out).not.toContain('ghp_')
expect(out).not.toContain('abcd1234')
expect(out).not.toContain('Zx9Qm2')
})
test('refuses: merge without confirm, and never echoes the secret', async ($, on) => {
world(on)
await $.session.start(START)
const out = await attempt($, { tool: P + 'github_pr_manage', action: 'merge', prNumber: 7 })
expect(out).not.toContain('ran')
expect(out).toContain('ruflo-jujutsu')
expect(out).not.toContain('ghp_')
expect(out).not.toContain('abcd1234')
expect(out).not.toContain('Zx9Qm2')
})
test('passes good calls through', async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'github_pr_manage', action: 'merge', prNumber: 7, confirm: true })).toContain('ran') // merge with confirm
expect(await attempt($, { tool: P + 'github_pr_manage', action: 'list' })).toContain('ran') // list
expect(await attempt($, { tool: P + 'analyze_diff', diff: '+const a = 1' })).toContain('ran') // analysis
})
test('turning that option off lets the call through', { options: { confirmPrActions: 'off' } }, async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'github_pr_manage', action: 'close', prNumber: 7 })).toContain('ran')
})
test('ignores tools that belong to someone else', async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'some_other_tool', value: `token ghp_${'a1B2'.repeat(10)}` })).toContain('ran')
})
})
describe('status file and /jujutsu-mod', () => {
test('the status file is written at session start with the shape the console reads', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.registered).toEqual(['jujutsu-mod'])
expect(w.status()).toMatchObject({ version: 1, guard: true, total: 0, blocked: 0, calls: {} })
expect(typeof w.status().updatedMs).toBe('number')
})
test('counters move when own tools run and when the guard refuses', async ($, on) => {
const w = world(on)
await $.session.start(START)
await attempt($, { tool: P + 'analyze_diff', diff: '+const a = 1' })
await attempt($, { tool: P + 'github_pr_manage', action: 'create', title: 'fix', body: `token ghp_${'a1B2'.repeat(10)}` })
expect(w.status()).toMatchObject({ total: 1, blocked: 1 })
expect(Object.keys(w.status().calls)).toHaveLength(1)
expect(JSON.stringify(w.status())).not.toContain('ghp_')
})
test('status, tools, recent, scan and help 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('tools'))).text).toContain('analyze_diff')
expect((await $.command.run(slash('recent'))).text).toContain('Nothing')
expect((await $.command.run(slash(`scan key ghp_${'a1B2'.repeat(10)}`))).text).toContain('github token')
expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found')
expect((await $.command.run(slash(''))).text).toContain('/jujutsu-mod status')
expect((await $.command.run(slash('what is this'))).text).toContain('Unknown')
})
test('tools says so plainly when none are connected', async ($, on) => {
world(on, [])
await $.session.start(START)
expect((await $.command.run(slash('tools'))).text).toContain('None of this plugin')
})
})
describe('defaults', () => {
test('with no options the guard is on', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.status().guard).toBe(true)
expect(w.status()).toHaveProperty('confirmPrActions')
})
})
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "./.claude-plugin/types/tsconfig.json"
}
@@ -1,7 +1,7 @@
{
"name": "ruflo-knowledge-graph",
"description": "Knowledge graph construction \u2014 entity extraction, relation mapping, and pathfinder graph traversal",
"version": "0.2.1",
"description": "Knowledge graph construction — entity extraction, relation mapping, and pathfinder graph traversal. As a mod (ADR-445): keeps secrets out of the graph, confirms graph deletes, /kg-mod, and a status file the console shows",
"version": "0.3.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -16,6 +16,33 @@
"pathfinder",
"mcp",
"pathfinder-traversal",
"entity-extraction"
]
"entity-extraction",
"mod",
"function-hooks",
"guard"
],
"userConfig": {
"guard": {
"type": "string",
"title": "Guard",
"description": "Refuse tool calls that are clearly harmful in this plugin's domain (see README, As a mod).",
"required": false,
"default": "on",
"options": [
"on",
"off"
]
},
"confirmDeletes": {
"type": "string",
"title": "Confirm graph deletes",
"description": "Require confirm: true on causal node and edge deletes.",
"required": false,
"default": "on",
"options": [
"on",
"off"
]
}
}
}
+12
View File
@@ -97,3 +97,15 @@ bash plugins/ruflo-knowledge-graph/scripts/smoke.sh
## License
MIT
## As a mod
This plugin ships a function-hook mod (ADR-445, `hooks/register.ts`). It makes no network call, spawns no process and makes no model call.
- **Guard** (tighten-only, on by default): Refuses graph writes (`agentdb_causal-edge`, `agentdb_hierarchical-store`, `agentdb_pattern-store`) that hold a key, token or password, and `agentdb_causal-edge-delete` / `agentdb_causal-node-delete` unless the call carries `confirm: true`. A refusal never echoes the secret.
- **`/kg-mod`**: `status`, `recent`, `tools` (which of this plugin's tools are connected) and `scan <text>` (would the guard refuse it). Answered locally.
- **Status file**: `.claude-flow/kg-mod/status.json` (`{version: 1, updatedMs, guard, calls, total, blocked, recent}`, counters only, never tool input), written at session start and after every call to this plugin's tools.
Options (`userConfig`): `guard` (on), `confirmDeletes` (on).
Test it: `claude plugin validate plugins/ruflo-knowledge-graph`, `claude plugin test plugins/ruflo-knowledge-graph`, `bash plugins/ruflo-knowledge-graph/scripts/smoke.sh`.
@@ -0,0 +1,52 @@
import { hasSecret } from './screen'
import type { ModOptions } from './options'
/** `mcp__<server>__<tool>` into its tool half; tool names never hold a double underscore. */
export function shortName(name: string): string {
const at = name.lastIndexOf('__')
return name.startsWith('mcp__') && at > 5 ? name.slice(at + 2) : name
}
/** 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 []
}
const field = (input: unknown, key: string): unknown => (typeof input === 'object' && input !== null ? (input as Record<string, unknown>)[key] : undefined)
const OWN = new Set([
'agentdb_causal-edge',
'agentdb_causal-edge-delete',
'agentdb_causal-node-delete',
'agentdb_hierarchical-store',
'agentdb_hierarchical-recall',
'agentdb_pattern-store',
'agentdb_pattern-search',
'agentdb_context-synthesize',
'agentdb_semantic-route',
'embeddings_generate',
])
const WRITERS = new Set(['agentdb_causal-edge', 'agentdb_hierarchical-store', 'agentdb_pattern-store'])
const DELETERS = new Set(['agentdb_causal-edge-delete', 'agentdb_causal-node-delete'])
/** The tools this plugin owns: the AgentDB graph and pattern tools its skills name. */
export const isOwn = (name: string, _input?: unknown): boolean => OWN.has(name)
/** The reason a call is refused, or undefined when it may go. Never names or echoes a secret. */
export function verdict(name: string, input: unknown, opts: ModOptions, _calls: Record<string, number>): string | undefined {
if (WRITERS.has(name) && textsOf(input).some(hasSecret)) {
return 'ruflo-knowledge-graph: this graph write holds what looks like a secret (a key, token or password). Store a reference to where it lives, not the value.'
}
if (opts.confirmDeletes && DELETERS.has(name) && field(input, 'confirm') !== true) {
return 'ruflo-knowledge-graph: deleting graph nodes or edges cannot be undone. Ask the user, then retry with confirm: true.'
}
return undefined
}
@@ -0,0 +1,4 @@
{
"description": "Knowledge graph as a mod (ADR-445): a tighten-only guard on graph writes (no secrets into the graph, graph deletes need an explicit confirm), a status file the console reads, and /kg-mod.",
"modules": ["./register.ts"]
}
@@ -0,0 +1,13 @@
import type { PluginOptions } from 'claude-code'
/** The plugin's `userConfig`, validated: a bad value is the default (guard on, graph deletes confirmed). */
export type ModOptions = { readonly guard: boolean; readonly confirmDeletes: boolean; readonly extra: Readonly<Record<string, unknown>> }
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 ?? {}
const confirmDeletes = flag(o.confirmDeletes, true)
return { guard: flag(o.guard, true), confirmDeletes, extra: { confirmDeletes } }
}
@@ -0,0 +1,108 @@
import type { Hook, Register } from 'claude-code'
import { isOwn, shortName, verdict } from './guard'
import { readOptions, type ModOptions } from './options'
import { scan } from './screen'
const COMMAND = 'kg-mod'
const STATUS_PATH = '.claude-flow/kg-mod/status.json'
const RECENT = 5
type Dollar = Parameters<Hook<'session.start'>>[0]
/** Everything one session of the mod keeps: its settings, per-tool counters, what was refused and the project root. */
type Session = {
readonly opts: ModOptions
readonly calls: Record<string, number>
blocked: number
readonly recent: string[]
root?: string
}
const total = (s: Session) => Object.values(s.calls).reduce((a, b) => a + b, 0)
function note(s: Session, line: string): void {
s.recent.push(line)
if (s.recent.length > RECENT) s.recent.splice(0, s.recent.length - RECENT)
}
/** The status file the console reads; `version` lets it refuse a shape it does not know. Counters only, never tool input. */
async function flush($: Dollar, s: Session): Promise<void> {
if (s.root === undefined) return
const body = { version: 1, updatedMs: await $.clock.now(), guard: s.opts.guard, ...s.opts.extra, calls: s.calls, total: total(s), blocked: s.blocked, recent: s.recent }
try {
await $.fs.write(`${s.root}/${STATUS_PATH}`, `${JSON.stringify(body, null, 2)}\n`)
} catch {
/* the status file is a courtesy */
}
}
/** The connected tools this plugin owns, by short name. */
async function connected($: Dollar): Promise<string[]> {
const tools = await $.tool.list()
return tools.filter(t => t.mcp && isOwn(shortName(t.name))).map(t => shortName(t.name))
}
const HELP = ['/kg-mod status', '/kg-mod scan <text>', '/kg-mod recent', '/kg-mod tools'].join('\n')
async function answer($: Dollar, s: Session, args: string): Promise<string> {
const [verb = '', ...rest] = args.trim().split(/\s+/)
const arg = rest.join(' ')
if (verb === '' || verb === 'help') return HELP
if (verb === 'status') {
const per = Object.entries(s.calls).map(([k, v]) => `${k} ${v}`).join(' · ')
return [`guard ${s.opts.guard ? 'on' : 'off'}${Object.entries(s.opts.extra).map(([k, v]) => ` · ${k} ${String(v)}`).join('')}`, `${total(s)} call${total(s) === 1 ? '' : 's'}${per ? ` (${per})` : ''} · refused ${s.blocked}`].join('\n')
}
if (verb === 'recent') return s.recent.length ? s.recent.map(r => `- ${r}`).join('\n') : 'Nothing has gone through this session.'
if (verb === 'tools') {
const names = await connected($)
return names.length ? names.join('\n') : 'None of this plugin\'s tools are connected. Connect the ruflo MCP server and try again.'
}
if (verb === 'scan') {
if (arg === '') return 'usage: /kg-mod scan <text>'
const found = scan(arg)
return found.secrets.length ? `The guard would refuse that (${found.secrets.join(', ')}).` : 'Nothing found: the guard would let that through.'
}
return `Unknown: ${verb}\n${HELP}`
}
/**
* Knowledge graph as a mod (ADR-445): a tighten-only guard on this plugin's own tools, a status file the console reads, and `/kg-mod`.
* No network, no process, no model call.
*/
export const register: Register = (on, options) => {
const s: Session = { opts: readOptions(options), calls: {}, blocked: 0, recent: [] }
on('session.start', async ($, e, next) => {
const result = await next(e)
s.root = (await $.session.root()) as string | undefined
try {
await $.command.register({ name: COMMAND, description: 'Knowledge graph mod: status, scan <text>, recent, tools' })
} catch {
/* a name taken by another plugin must not stop the mod */
}
await flush($, s)
return result
})
on('tool.call', async ($, e, next) => {
const name = shortName(e.tool)
if (!isOwn(name, e)) return next(e)
if (s.opts.guard) {
const reason = verdict(name, e, s.opts, s.calls)
if (reason !== undefined) {
s.blocked++
note(s, `refused ${name}`)
await flush($, s)
return { deny: reason }
}
}
s.calls[name] = (s.calls[name] ?? 0) + 1
note(s, name)
await flush($, s)
return next(e)
})
/** `/kg-mod`: the plugin's own commands are prompt commands, which no hook can answer. */
on('command.run', { command: COMMAND }, async ($, e) => ({ text: await answer($, s, typeof e.args === 'string' ? e.args : '') }))
}
@@ -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
}
+21 -2
View File
@@ -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 pathfinder-traversal entity-extraction; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
@@ -83,5 +83,24 @@ for f in "$ROOT"/skills/*/SKILL.md; do
done
[[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills"
# M1-M3. The mod (ADR-445): 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 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), the command name is kg-mod"
node -e '
const c = require(process.argv[1]).userConfig || {}
process.exit(c.guard && c.guard.default === "on" ? 0 : 1)
' "$ROOT/.claude-plugin/plugin.json" && grep -q "'kg-mod'" "$ROOT/hooks/register.ts" && ok || bad "userConfig defaults or command name 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
@@ -0,0 +1,117 @@
import type { On } from 'claude-code'
import { describe, expect, test, tier } from 'claude-code/testing'
tier('user')
const ROOT = '/work'
const P = 'mcp__plugin_ruflo-core_ruflo__'
const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
const slash = (args: string) => ({ command: 'kg-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const
const TOOLS = ["agentdb_causal-edge","agentdb_hierarchical-store","agentdb_causal-node-delete"].map(name => ({ name: P + name, description: '', mcp: true }))
/** The world beneath the mod: a project root, a file map, the connected tools, and a stub that answers every tool call. */
function world(on: On, tools = TOOLS) {
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('tool.list', () => ({ value: tools }))
on('clock.now', () => ({ value: Date.now() }))
on('tool.call', () => ({ result: 'ran' }))
return { files, registered, status: () => JSON.parse(files.get(`${ROOT}/.claude-flow/kg-mod/status.json`) ?? '{}') }
}
const attempt = async ($: Parameters<Parameters<typeof test>[2]>[0], call: object) =>
JSON.stringify(await $.tool.call(call as never).then(r => r, (e: unknown) => ({ text: String(e) })))
describe('guard', () => {
test('refuses: secret in a graph write, and never echoes the secret', async ($, on) => {
world(on)
await $.session.start(START)
const out = await attempt($, { tool: P + 'agentdb_hierarchical-store', key: 'n1', value: `token ghp_${'a1B2'.repeat(10)}` })
expect(out).not.toContain('ran')
expect(out).toContain('ruflo-knowledge-graph')
expect(out).not.toContain('ghp_')
expect(out).not.toContain('abcd1234')
expect(out).not.toContain('Zx9Qm2')
})
test('refuses: node delete without confirm, and never echoes the secret', async ($, on) => {
world(on)
await $.session.start(START)
const out = await attempt($, { tool: P + 'agentdb_causal-node-delete', id: 'n1' })
expect(out).not.toContain('ran')
expect(out).toContain('ruflo-knowledge-graph')
expect(out).not.toContain('ghp_')
expect(out).not.toContain('abcd1234')
expect(out).not.toContain('Zx9Qm2')
})
test('passes good calls through', async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'agentdb_causal-node-delete', id: 'n1', confirm: true })).toContain('ran') // delete with confirm
expect(await attempt($, { tool: P + 'agentdb_causal-edge', source: 'a', target: 'b', relation: 'imports' })).toContain('ran') // clean edge
})
test('turning that option off lets the call through', { options: { confirmDeletes: 'off' } }, async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'agentdb_causal-node-delete', id: 'n1' })).toContain('ran')
})
test('ignores tools that belong to someone else', async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'some_other_tool', value: `token ghp_${'a1B2'.repeat(10)}` })).toContain('ran')
})
})
describe('status file and /kg-mod', () => {
test('the status file is written at session start with the shape the console reads', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.registered).toEqual(['kg-mod'])
expect(w.status()).toMatchObject({ version: 1, guard: true, total: 0, blocked: 0, calls: {} })
expect(typeof w.status().updatedMs).toBe('number')
})
test('counters move when own tools run and when the guard refuses', async ($, on) => {
const w = world(on)
await $.session.start(START)
await attempt($, { tool: P + 'agentdb_causal-edge', source: 'a', target: 'b', relation: 'imports' })
await attempt($, { tool: P + 'agentdb_hierarchical-store', key: 'n1', value: `token ghp_${'a1B2'.repeat(10)}` })
expect(w.status()).toMatchObject({ total: 1, blocked: 1 })
expect(Object.keys(w.status().calls)).toHaveLength(1)
expect(JSON.stringify(w.status())).not.toContain('ghp_')
})
test('status, tools, recent, scan and help 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('tools'))).text).toContain('agentdb_causal-edge')
expect((await $.command.run(slash('recent'))).text).toContain('Nothing')
expect((await $.command.run(slash(`scan key ghp_${'a1B2'.repeat(10)}`))).text).toContain('github token')
expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found')
expect((await $.command.run(slash(''))).text).toContain('/kg-mod status')
expect((await $.command.run(slash('what is this'))).text).toContain('Unknown')
})
test('tools says so plainly when none are connected', async ($, on) => {
world(on, [])
await $.session.start(START)
expect((await $.command.run(slash('tools'))).text).toContain('None of this plugin')
})
})
describe('defaults', () => {
test('with no options the guard is on', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.status().guard).toBe(true)
expect(w.status()).toHaveProperty('confirmDeletes')
})
})
@@ -1,7 +1,7 @@
{
"name": "ruflo-loop-workers",
"description": "Cache-aware /loop workers and CronCreate background automation — wraps 5 hooks_worker-* MCP tools (list/dispatch/status/detect/cancel) and exposes 12 background worker triggers (ultralearn, optimize, consolidate, predict, audit, map, preload, deepdive, document, refactor, benchmark, testgaps)",
"version": "0.2.1",
"description": "Cache-aware /loop workers and CronCreate background automation — wraps 5 hooks_worker-* MCP tools (list/dispatch/status/detect/cancel) and exposes 12 background worker triggers (ultralearn, optimize, consolidate, predict, audit, map, preload, deepdive, document, refactor, benchmark, testgaps). As a mod (ADR-445): a per-session dispatch cap, no secrets in worker context, /loop-mod, and a status file the console shows",
"version": "0.3.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -17,6 +17,29 @@
"mcp",
"background-workers",
"cache-aware",
"schedule-wakeup"
]
"schedule-wakeup",
"mod",
"function-hooks",
"guard"
],
"userConfig": {
"guard": {
"type": "string",
"title": "Guard",
"description": "Refuse tool calls that are clearly harmful in this plugin's domain (see README, As a mod).",
"required": false,
"default": "on",
"options": [
"on",
"off"
]
},
"maxDispatch": {
"type": "number",
"title": "Worker dispatch cap",
"description": "Most hooks_worker-dispatch calls per session, 1 to 1000.",
"required": false,
"default": 100
}
}
}
+12
View File
@@ -93,3 +93,15 @@ bash plugins/ruflo-loop-workers/scripts/smoke.sh
- `ruflo-autopilot` — owns the 270s cache-aware /loop heartbeat contract
- `ruflo-docs`, `ruflo-security-audit`, `ruflo-testgen`, `ruflo-knowledge-graph`, etc. — worker-trigger consumers per the table above
- `ruflo-agentdb` — namespace convention owner; backing store for worker-history
## As a mod
This plugin ships a function-hook mod (ADR-445, `hooks/register.ts`). It makes no network call, spawns no process and makes no model call.
- **Guard** (tighten-only, on by default): Refuses `hooks_worker-dispatch` whose context holds a key, token or password (workers log their context), and any dispatch past the per-session cap, which catches a stuck loop that keeps dispatching. A refusal never echoes the secret.
- **`/loop-mod`**: `status`, `recent`, `tools` (which of this plugin's tools are connected) and `scan <text>` (would the guard refuse it). Answered locally.
- **Status file**: `.claude-flow/loop-mod/status.json` (`{version: 1, updatedMs, guard, calls, total, blocked, recent}`, counters only, never tool input), written at session start and after every call to this plugin's tools.
Options (`userConfig`): `guard` (on), `maxDispatch` (100, range 1 to 1000).
Test it: `claude plugin validate plugins/ruflo-loop-workers`, `claude plugin test plugins/ruflo-loop-workers`, `bash plugins/ruflo-loop-workers/scripts/smoke.sh`.
+38
View File
@@ -0,0 +1,38 @@
import { hasSecret } from './screen'
import type { ModOptions } from './options'
/** `mcp__<server>__<tool>` into its tool half; tool names never hold a double underscore. */
export function shortName(name: string): string {
const at = name.lastIndexOf('__')
return name.startsWith('mcp__') && at > 5 ? name.slice(at + 2) : name
}
/** 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 []
}
const field = (input: unknown, key: string): unknown => (typeof input === 'object' && input !== null ? (input as Record<string, unknown>)[key] : undefined)
/** The tools this plugin owns: the hooks_worker-* family. */
export const isOwn = (name: string, _input?: unknown): boolean => name.startsWith('hooks_worker-')
/** The reason a call is refused, or undefined when it may go. Never names or echoes a secret. */
export function verdict(name: string, input: unknown, opts: ModOptions, calls: Record<string, number>): string | undefined {
if (name !== 'hooks_worker-dispatch') return undefined
if (textsOf(input).some(hasSecret)) {
return 'ruflo-loop-workers: this worker context holds what looks like a secret (a key, token or password). Workers log their context; pass a reference to where it lives.'
}
if ((calls[name] ?? 0) >= opts.maxDispatch) {
return `ruflo-loop-workers: ${opts.maxDispatch} workers were dispatched this session, the cap. A loop that keeps dispatching is probably stuck; check hooks_worker-status, or raise maxDispatch.`
}
return undefined
}
@@ -0,0 +1,4 @@
{
"description": "Loop workers as a mod (ADR-445): a tighten-only guard on worker dispatch (no secrets in worker context, a per-session dispatch cap), a status file the console reads, and /loop-mod.",
"modules": ["./register.ts"]
}
@@ -0,0 +1,18 @@
import type { PluginOptions } from 'claude-code'
/** The plugin's `userConfig`, validated: a bad value is the default (guard on, 100 dispatches per session). */
export type ModOptions = { readonly guard: boolean; readonly maxDispatch: number; readonly extra: Readonly<Record<string, unknown>> }
const flag = (value: unknown, fallback: boolean) =>
value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback
const clamp = (value: unknown, min: number, max: number, fallback: number) => {
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN
return Number.isFinite(n) ? Math.min(max, Math.max(min, Math.round(n))) : fallback
}
export function readOptions(options: PluginOptions | undefined): ModOptions {
const o = options ?? {}
const maxDispatch = clamp(o.maxDispatch, 1, 1000, 100)
return { guard: flag(o.guard, true), maxDispatch, extra: { maxDispatch } }
}
@@ -0,0 +1,108 @@
import type { Hook, Register } from 'claude-code'
import { isOwn, shortName, verdict } from './guard'
import { readOptions, type ModOptions } from './options'
import { scan } from './screen'
const COMMAND = 'loop-mod'
const STATUS_PATH = '.claude-flow/loop-mod/status.json'
const RECENT = 5
type Dollar = Parameters<Hook<'session.start'>>[0]
/** Everything one session of the mod keeps: its settings, per-tool counters, what was refused and the project root. */
type Session = {
readonly opts: ModOptions
readonly calls: Record<string, number>
blocked: number
readonly recent: string[]
root?: string
}
const total = (s: Session) => Object.values(s.calls).reduce((a, b) => a + b, 0)
function note(s: Session, line: string): void {
s.recent.push(line)
if (s.recent.length > RECENT) s.recent.splice(0, s.recent.length - RECENT)
}
/** The status file the console reads; `version` lets it refuse a shape it does not know. Counters only, never tool input. */
async function flush($: Dollar, s: Session): Promise<void> {
if (s.root === undefined) return
const body = { version: 1, updatedMs: await $.clock.now(), guard: s.opts.guard, ...s.opts.extra, calls: s.calls, total: total(s), blocked: s.blocked, recent: s.recent }
try {
await $.fs.write(`${s.root}/${STATUS_PATH}`, `${JSON.stringify(body, null, 2)}\n`)
} catch {
/* the status file is a courtesy */
}
}
/** The connected tools this plugin owns, by short name. */
async function connected($: Dollar): Promise<string[]> {
const tools = await $.tool.list()
return tools.filter(t => t.mcp && isOwn(shortName(t.name))).map(t => shortName(t.name))
}
const HELP = ['/loop-mod status', '/loop-mod scan <text>', '/loop-mod recent', '/loop-mod tools'].join('\n')
async function answer($: Dollar, s: Session, args: string): Promise<string> {
const [verb = '', ...rest] = args.trim().split(/\s+/)
const arg = rest.join(' ')
if (verb === '' || verb === 'help') return HELP
if (verb === 'status') {
const per = Object.entries(s.calls).map(([k, v]) => `${k} ${v}`).join(' · ')
return [`guard ${s.opts.guard ? 'on' : 'off'}${Object.entries(s.opts.extra).map(([k, v]) => ` · ${k} ${String(v)}`).join('')}`, `${total(s)} call${total(s) === 1 ? '' : 's'}${per ? ` (${per})` : ''} · refused ${s.blocked}`].join('\n')
}
if (verb === 'recent') return s.recent.length ? s.recent.map(r => `- ${r}`).join('\n') : 'Nothing has gone through this session.'
if (verb === 'tools') {
const names = await connected($)
return names.length ? names.join('\n') : 'None of this plugin\'s tools are connected. Connect the ruflo MCP server and try again.'
}
if (verb === 'scan') {
if (arg === '') return 'usage: /loop-mod scan <text>'
const found = scan(arg)
return found.secrets.length ? `The guard would refuse that (${found.secrets.join(', ')}).` : 'Nothing found: the guard would let that through.'
}
return `Unknown: ${verb}\n${HELP}`
}
/**
* Loop workers as a mod (ADR-445): a tighten-only guard on this plugin's own tools, a status file the console reads, and `/loop-mod`.
* No network, no process, no model call.
*/
export const register: Register = (on, options) => {
const s: Session = { opts: readOptions(options), calls: {}, blocked: 0, recent: [] }
on('session.start', async ($, e, next) => {
const result = await next(e)
s.root = (await $.session.root()) as string | undefined
try {
await $.command.register({ name: COMMAND, description: 'Loop workers mod: status, scan <text>, recent, tools' })
} catch {
/* a name taken by another plugin must not stop the mod */
}
await flush($, s)
return result
})
on('tool.call', async ($, e, next) => {
const name = shortName(e.tool)
if (!isOwn(name, e)) return next(e)
if (s.opts.guard) {
const reason = verdict(name, e, s.opts, s.calls)
if (reason !== undefined) {
s.blocked++
note(s, `refused ${name}`)
await flush($, s)
return { deny: reason }
}
}
s.calls[name] = (s.calls[name] ?? 0) + 1
note(s, name)
await flush($, s)
return next(e)
})
/** `/loop-mod`: the plugin's own commands are prompt commands, which no hook can answer. */
on('command.run', { command: COMMAND }, async ($, e) => ({ text: await answer($, s, typeof e.args === 'string' ? e.args : '') }))
}
@@ -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
}
+21 -2
View File
@@ -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 background-workers cache-aware schedule-wakeup; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
@@ -91,5 +91,24 @@ for f in "$ROOT"/skills/*/SKILL.md; do
done
[[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills"
# M1-M3. The mod (ADR-445): 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 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), the command name is loop-mod"
node -e '
const c = require(process.argv[1]).userConfig || {}
process.exit(c.guard && c.guard.default === "on" ? 0 : 1)
' "$ROOT/.claude-plugin/plugin.json" && grep -q "'loop-mod'" "$ROOT/hooks/register.ts" && ok || bad "userConfig defaults or command name 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
@@ -0,0 +1,128 @@
import type { On } from 'claude-code'
import { describe, expect, test, tier } from 'claude-code/testing'
tier('user')
const ROOT = '/work'
const P = 'mcp__plugin_ruflo-core_ruflo__'
const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
const slash = (args: string) => ({ command: 'loop-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const
const TOOLS = ["hooks_worker-dispatch","hooks_worker-status"].map(name => ({ name: P + name, description: '', mcp: true }))
/** The world beneath the mod: a project root, a file map, the connected tools, and a stub that answers every tool call. */
function world(on: On, tools = TOOLS) {
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('tool.list', () => ({ value: tools }))
on('clock.now', () => ({ value: Date.now() }))
on('tool.call', () => ({ result: 'ran' }))
return { files, registered, status: () => JSON.parse(files.get(`${ROOT}/.claude-flow/loop-mod/status.json`) ?? '{}') }
}
const attempt = async ($: Parameters<Parameters<typeof test>[2]>[0], call: object) =>
JSON.stringify(await $.tool.call(call as never).then(r => r, (e: unknown) => ({ text: String(e) })))
describe('guard', () => {
test('refuses: secret in worker context, and never echoes the secret', async ($, on) => {
world(on)
await $.session.start(START)
const out = await attempt($, { tool: P + 'hooks_worker-dispatch', trigger: 'audit', context: `token ghp_${'a1B2'.repeat(10)}` })
expect(out).not.toContain('ran')
expect(out).toContain('ruflo-loop-workers')
expect(out).not.toContain('ghp_')
expect(out).not.toContain('abcd1234')
expect(out).not.toContain('Zx9Qm2')
})
test('passes good calls through', async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'hooks_worker-dispatch', trigger: 'audit', context: 'src/auth' })).toContain('ran') // clean dispatch
expect(await attempt($, { tool: P + 'hooks_worker-status' })).toContain('ran') // status
})
test('turning that option off lets the call through', { options: { guard: 'off' } }, async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'hooks_worker-dispatch', trigger: 'audit', context: `token ghp_${'a1B2'.repeat(10)}` })).toContain('ran')
})
test('ignores tools that belong to someone else', async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'some_other_tool', value: `token ghp_${'a1B2'.repeat(10)}` })).toContain('ran')
})
})
describe('status file and /loop-mod', () => {
test('the status file is written at session start with the shape the console reads', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.registered).toEqual(['loop-mod'])
expect(w.status()).toMatchObject({ version: 1, guard: true, total: 0, blocked: 0, calls: {} })
expect(typeof w.status().updatedMs).toBe('number')
})
test('counters move when own tools run and when the guard refuses', async ($, on) => {
const w = world(on)
await $.session.start(START)
await attempt($, { tool: P + 'hooks_worker-status' })
await attempt($, { tool: P + 'hooks_worker-dispatch', trigger: 'audit', context: `token ghp_${'a1B2'.repeat(10)}` })
expect(w.status()).toMatchObject({ total: 1, blocked: 1 })
expect(Object.keys(w.status().calls)).toHaveLength(1)
expect(JSON.stringify(w.status())).not.toContain('ghp_')
})
test('status, tools, recent, scan and help 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('tools'))).text).toContain('hooks_worker-dispatch')
expect((await $.command.run(slash('recent'))).text).toContain('Nothing')
expect((await $.command.run(slash(`scan key ghp_${'a1B2'.repeat(10)}`))).text).toContain('github token')
expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found')
expect((await $.command.run(slash(''))).text).toContain('/loop-mod status')
expect((await $.command.run(slash('what is this'))).text).toContain('Unknown')
})
test('tools says so plainly when none are connected', async ($, on) => {
world(on, [])
await $.session.start(START)
expect((await $.command.run(slash('tools'))).text).toContain('None of this plugin')
})
})
describe('defaults', () => {
test('with no options the guard is on', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.status().guard).toBe(true)
expect(w.status()).toHaveProperty('maxDispatch')
})
})
describe('dispatch cap', () => {
const dispatch = { tool: P + 'hooks_worker-dispatch', trigger: 'audit', context: 'src/auth' }
test('the Nth+1 dispatch is refused with the cap named; status calls still pass', { options: { maxDispatch: 2 } }, async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(await attempt($, dispatch)).toContain('ran')
expect(await attempt($, dispatch)).toContain('ran')
const out = await attempt($, dispatch)
expect(out).not.toContain('ran')
expect(out).toContain('2 workers')
expect(await attempt($, { tool: P + 'hooks_worker-status' })).toContain('ran')
expect(w.status()).toMatchObject({ maxDispatch: 2, blocked: 1, calls: { 'hooks_worker-dispatch': 2, 'hooks_worker-status': 1 } })
})
test('the cap defaults to 100 and is clamped', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.status().maxDispatch).toBe(100)
})
})
@@ -1,7 +1,7 @@
{
"name": "ruflo-market-data",
"description": "Market data ingestion — feed normalization, OHLCV vectorization, and HNSW-indexed pattern matching",
"version": "0.2.1",
"description": "Market data ingestion — feed normalization, OHLCV vectorization, and HNSW-indexed pattern matching. As a mod (ADR-445): keeps credentials and credentialed feed URLs out of market memory, /market-mod, and a status file the console shows",
"version": "0.3.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -16,6 +16,22 @@
"patterns",
"mcp",
"candlestick-patterns",
"namespace-routing"
]
"namespace-routing",
"mod",
"function-hooks",
"guard"
],
"userConfig": {
"guard": {
"type": "string",
"title": "Guard",
"description": "Refuse tool calls that are clearly harmful in this plugin's domain (see README, As a mod).",
"required": false,
"default": "on",
"options": [
"on",
"off"
]
}
}
}
+12
View File
@@ -96,3 +96,15 @@ bash plugins/ruflo-market-data/scripts/smoke.sh
## License
MIT
## As a mod
This plugin ships a function-hook mod (ADR-445, `hooks/register.ts`). It makes no network call, spawns no process and makes no model call.
- **Guard** (tighten-only, on by default): Refuses writes to a `market*` namespace (`memory_store`, `agentdb_pattern-store`, `agentdb_hierarchical-store`, `ruvllm_hnsw_add`) that hold a key or token, or a feed URL with a credential in its query string or as `user:pass@host`. Other namespaces are untouched. A refusal never echoes the secret.
- **`/market-mod`**: `status`, `recent`, `tools` (which of this plugin's tools are connected) and `scan <text>` (would the guard refuse it). Answered locally.
- **Status file**: `.claude-flow/market-mod/status.json` (`{version: 1, updatedMs, guard, calls, total, blocked, recent}`, counters only, never tool input), written at session start and after every call to this plugin's tools.
Options (`userConfig`): `guard` (on).
Test it: `claude plugin validate plugins/ruflo-market-data`, `claude plugin test plugins/ruflo-market-data`, `bash plugins/ruflo-market-data/scripts/smoke.sh`.
+45
View File
@@ -0,0 +1,45 @@
import { hasSecret } from './screen'
import type { ModOptions } from './options'
/** `mcp__<server>__<tool>` into its tool half; tool names never hold a double underscore. */
export function shortName(name: string): string {
const at = name.lastIndexOf('__')
return name.startsWith('mcp__') && at > 5 ? name.slice(at + 2) : name
}
/** 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 []
}
const field = (input: unknown, key: string): unknown => (typeof input === 'object' && input !== null ? (input as Record<string, unknown>)[key] : undefined)
// A feed URL that carries its credential in the query string, or in user:pass@host form. Built from strings so no literal is easy to mistake for a key.
const FEED_CREDENTIAL = new RegExp('[?&](?:api_?key|apikey|token|access_token|secret)=[A-Za-z0-9._~-]{12,}|://[^/\\s:@]+:[^/\\s@]{6,}@', 'i')
const WRITERS = new Set(['memory_store', 'agentdb_pattern-store', 'agentdb_hierarchical-store', 'ruvllm_hnsw_add'])
const READERS = new Set(['memory_search', 'memory_list', 'agentdb_pattern-search', 'agentdb_hierarchical-recall', 'agentdb_semantic-route', 'embeddings_generate', 'ruvllm_hnsw_route', 'ruvllm_hnsw_create'])
const inMarketNamespace = (input: unknown): boolean => /^market/.test(String(field(input, 'namespace') ?? ''))
/** The tools this plugin owns: the HNSW router, and the memory and pattern tools when they address a `market-*` namespace. */
export const isOwn = (name: string, input?: unknown): boolean =>
name.startsWith('ruvllm_hnsw_') || ((WRITERS.has(name) || READERS.has(name)) && (input === undefined || inMarketNamespace(input)))
/** The reason a call is refused, or undefined when it may go. Never names or echoes a secret. */
export function verdict(name: string, input: unknown, _opts: ModOptions, _calls: Record<string, number>): string | undefined {
if (!WRITERS.has(name)) return undefined
const texts = textsOf(input)
if (texts.some(hasSecret) || texts.some(t => FEED_CREDENTIAL.test(t))) {
return 'ruflo-market-data: this market write holds what looks like a credential (a key, a token, or a feed URL with one in it). Store the feed name, not the credentialed URL.'
}
return undefined
}
@@ -0,0 +1,4 @@
{
"description": "Market data as a mod (ADR-445): a tighten-only guard on market writes (no secrets or credentialed feed URLs stored), a status file the console reads, and /market-mod.",
"modules": ["./register.ts"]
}
@@ -0,0 +1,12 @@
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; readonly extra: Readonly<Record<string, unknown>> }
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), extra: {} }
}
+108
View File
@@ -0,0 +1,108 @@
import type { Hook, Register } from 'claude-code'
import { isOwn, shortName, verdict } from './guard'
import { readOptions, type ModOptions } from './options'
import { scan } from './screen'
const COMMAND = 'market-mod'
const STATUS_PATH = '.claude-flow/market-mod/status.json'
const RECENT = 5
type Dollar = Parameters<Hook<'session.start'>>[0]
/** Everything one session of the mod keeps: its settings, per-tool counters, what was refused and the project root. */
type Session = {
readonly opts: ModOptions
readonly calls: Record<string, number>
blocked: number
readonly recent: string[]
root?: string
}
const total = (s: Session) => Object.values(s.calls).reduce((a, b) => a + b, 0)
function note(s: Session, line: string): void {
s.recent.push(line)
if (s.recent.length > RECENT) s.recent.splice(0, s.recent.length - RECENT)
}
/** The status file the console reads; `version` lets it refuse a shape it does not know. Counters only, never tool input. */
async function flush($: Dollar, s: Session): Promise<void> {
if (s.root === undefined) return
const body = { version: 1, updatedMs: await $.clock.now(), guard: s.opts.guard, ...s.opts.extra, calls: s.calls, total: total(s), blocked: s.blocked, recent: s.recent }
try {
await $.fs.write(`${s.root}/${STATUS_PATH}`, `${JSON.stringify(body, null, 2)}\n`)
} catch {
/* the status file is a courtesy */
}
}
/** The connected tools this plugin owns, by short name. */
async function connected($: Dollar): Promise<string[]> {
const tools = await $.tool.list()
return tools.filter(t => t.mcp && isOwn(shortName(t.name))).map(t => shortName(t.name))
}
const HELP = ['/market-mod status', '/market-mod scan <text>', '/market-mod recent', '/market-mod tools'].join('\n')
async function answer($: Dollar, s: Session, args: string): Promise<string> {
const [verb = '', ...rest] = args.trim().split(/\s+/)
const arg = rest.join(' ')
if (verb === '' || verb === 'help') return HELP
if (verb === 'status') {
const per = Object.entries(s.calls).map(([k, v]) => `${k} ${v}`).join(' · ')
return [`guard ${s.opts.guard ? 'on' : 'off'}${Object.entries(s.opts.extra).map(([k, v]) => ` · ${k} ${String(v)}`).join('')}`, `${total(s)} call${total(s) === 1 ? '' : 's'}${per ? ` (${per})` : ''} · refused ${s.blocked}`].join('\n')
}
if (verb === 'recent') return s.recent.length ? s.recent.map(r => `- ${r}`).join('\n') : 'Nothing has gone through this session.'
if (verb === 'tools') {
const names = await connected($)
return names.length ? names.join('\n') : 'None of this plugin\'s tools are connected. Connect the ruflo MCP server and try again.'
}
if (verb === 'scan') {
if (arg === '') return 'usage: /market-mod scan <text>'
const found = scan(arg)
return found.secrets.length ? `The guard would refuse that (${found.secrets.join(', ')}).` : 'Nothing found: the guard would let that through.'
}
return `Unknown: ${verb}\n${HELP}`
}
/**
* Market data as a mod (ADR-445): a tighten-only guard on this plugin's own tools, a status file the console reads, and `/market-mod`.
* No network, no process, no model call.
*/
export const register: Register = (on, options) => {
const s: Session = { opts: readOptions(options), calls: {}, blocked: 0, recent: [] }
on('session.start', async ($, e, next) => {
const result = await next(e)
s.root = (await $.session.root()) as string | undefined
try {
await $.command.register({ name: COMMAND, description: 'Market data mod: status, scan <text>, recent, tools' })
} catch {
/* a name taken by another plugin must not stop the mod */
}
await flush($, s)
return result
})
on('tool.call', async ($, e, next) => {
const name = shortName(e.tool)
if (!isOwn(name, e)) return next(e)
if (s.opts.guard) {
const reason = verdict(name, e, s.opts, s.calls)
if (reason !== undefined) {
s.blocked++
note(s, `refused ${name}`)
await flush($, s)
return { deny: reason }
}
}
s.calls[name] = (s.calls[name] ?? 0) + 1
note(s, name)
await flush($, s)
return next(e)
})
/** `/market-mod`: the plugin's own commands are prompt commands, which no hook can answer. */
on('command.run', { command: COMMAND }, async ($, e) => ({ text: await answer($, s, typeof e.args === 'string' ? e.args : '') }))
}
+50
View File
@@ -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
}
+21 -2
View File
@@ -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 candlestick-patterns namespace-routing; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
@@ -84,5 +84,24 @@ ADR="$ROOT/docs/adrs/0001-market-data-contract.md"
[[ -f "$ADR" ]] && grep -qE "^status:[[:space:]]*Accepted" "$ADR" \
&& ok || bad "ADR missing or status != Accepted"
# M1-M3. The mod (ADR-445): 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 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), the command name is market-mod"
node -e '
const c = require(process.argv[1]).userConfig || {}
process.exit(c.guard && c.guard.default === "on" ? 0 : 1)
' "$ROOT/.claude-plugin/plugin.json" && grep -q "'market-mod'" "$ROOT/hooks/register.ts" && ok || bad "userConfig defaults or command name 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
@@ -0,0 +1,116 @@
import type { On } from 'claude-code'
import { describe, expect, test, tier } from 'claude-code/testing'
tier('user')
const ROOT = '/work'
const P = 'mcp__plugin_ruflo-core_ruflo__'
const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
const slash = (args: string) => ({ command: 'market-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const
const TOOLS = ["memory_store","ruvllm_hnsw_add"].map(name => ({ name: P + name, description: '', mcp: true }))
/** The world beneath the mod: a project root, a file map, the connected tools, and a stub that answers every tool call. */
function world(on: On, tools = TOOLS) {
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('tool.list', () => ({ value: tools }))
on('clock.now', () => ({ value: Date.now() }))
on('tool.call', () => ({ result: 'ran' }))
return { files, registered, status: () => JSON.parse(files.get(`${ROOT}/.claude-flow/market-mod/status.json`) ?? '{}') }
}
const attempt = async ($: Parameters<Parameters<typeof test>[2]>[0], call: object) =>
JSON.stringify(await $.tool.call(call as never).then(r => r, (e: unknown) => ({ text: String(e) })))
describe('guard', () => {
test('refuses: API key in a market write, and never echoes the secret', async ($, on) => {
world(on)
await $.session.start(START)
const out = await attempt($, { tool: P + 'memory_store', namespace: 'market-data', key: 'feed', value: `apikey=abcd1234abcd1234abcd1234` })
expect(out).not.toContain('ran')
expect(out).toContain('ruflo-market-data')
expect(out).not.toContain('ghp_')
expect(out).not.toContain('abcd1234')
expect(out).not.toContain('Zx9Qm2')
})
test('refuses: credentialed feed URL, and never echoes the secret', async ($, on) => {
world(on)
await $.session.start(START)
const out = await attempt($, { tool: P + 'memory_store', namespace: 'market-data', key: 'feed', value: 'https://feed.example/v1?token=Zx9Qm2LpR7vK4nT8' })
expect(out).not.toContain('ran')
expect(out).toContain('ruflo-market-data')
expect(out).not.toContain('ghp_')
expect(out).not.toContain('abcd1234')
expect(out).not.toContain('Zx9Qm2')
})
test('passes good calls through', async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'memory_store', namespace: 'notes', key: 'k', value: `token ghp_${'a1B2'.repeat(10)}` })).toContain('ran') // other namespace untouched
expect(await attempt($, { tool: P + 'memory_store', namespace: 'market-data', key: 'AAPL', value: 'o=1 h=2 l=0.5 c=1.5' })).toContain('ran') // clean OHLCV
})
test('turning that option off lets the call through', { options: { guard: 'off' } }, async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'memory_store', namespace: 'market-data', key: 'feed', value: `token ghp_${'a1B2'.repeat(10)}` })).toContain('ran')
})
test('ignores tools that belong to someone else', async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'some_other_tool', value: `token ghp_${'a1B2'.repeat(10)}` })).toContain('ran')
})
})
describe('status file and /market-mod', () => {
test('the status file is written at session start with the shape the console reads', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.registered).toEqual(['market-mod'])
expect(w.status()).toMatchObject({ version: 1, guard: true, total: 0, blocked: 0, calls: {} })
expect(typeof w.status().updatedMs).toBe('number')
})
test('counters move when own tools run and when the guard refuses', async ($, on) => {
const w = world(on)
await $.session.start(START)
await attempt($, { tool: P + 'memory_store', namespace: 'market-data', key: 'AAPL', value: 'o=1 h=2 l=0.5 c=1.5' })
await attempt($, { tool: P + 'memory_store', namespace: 'market-data', key: 'feed', value: `apikey=abcd1234abcd1234abcd1234` })
expect(w.status()).toMatchObject({ total: 1, blocked: 1 })
expect(Object.keys(w.status().calls)).toHaveLength(1)
expect(JSON.stringify(w.status())).not.toContain('ghp_')
})
test('status, tools, recent, scan and help 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('tools'))).text).toContain('memory_store')
expect((await $.command.run(slash('recent'))).text).toContain('Nothing')
expect((await $.command.run(slash(`scan key ghp_${'a1B2'.repeat(10)}`))).text).toContain('github token')
expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found')
expect((await $.command.run(slash(''))).text).toContain('/market-mod status')
expect((await $.command.run(slash('what is this'))).text).toContain('Unknown')
})
test('tools says so plainly when none are connected', async ($, on) => {
world(on, [])
await $.session.start(START)
expect((await $.command.run(slash('tools'))).text).toContain('None of this plugin')
})
})
describe('defaults', () => {
test('with no options the guard is on', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.status().guard).toBe(true)
})
})
@@ -1,7 +1,7 @@
{
"name": "ruflo-metaharness",
"description": "MetaHarness integration for ruflo — surfaces score/genome/mint/mcp-scan/threat-model via skills; pairs with @metaharness/router (ADR-148/149) for cost-optimal model routing; honors ADR-150's architectural constraint that MetaHarness remains an optional augmentation, never a required runtime dependency",
"version": "0.1.1",
"description": "MetaHarness integration for ruflo — surfaces score/genome/mint/mcp-scan/threat-model via skills; pairs with @metaharness/router (ADR-148/149) for cost-optimal model routing; honors ADR-150's architectural constraint that MetaHarness remains an optional augmentation, never a required runtime dependency. As a mod (ADR-445): confirms flywheel promotion, keeps secrets out of inputs, /metaharness-mod, and a status file the console shows",
"version": "0.2.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -27,6 +27,22 @@
"namespace-routing",
"verified",
"ci",
"phase-1-mvp"
]
"phase-1-mvp",
"mod",
"function-hooks",
"guard"
],
"userConfig": {
"guard": {
"type": "string",
"title": "Guard",
"description": "Refuse tool calls that are clearly harmful in this plugin's domain (see README, As a mod).",
"required": false,
"default": "on",
"options": [
"on",
"off"
]
}
}
}
+12
View File
@@ -70,3 +70,15 @@ This means:
- [Research dossier](https://gist.github.com/ruvnet/19d166ff9acf368c9da4172d91ac9113) — full graded-evidence sourcing
- [Upstream](https://github.com/ruvnet/agent-harness-generator) — `metaharness` source
- ADR-148/149 — `@metaharness/router` cost-optimal routing (sibling integration)
## As a mod
This plugin ships a function-hook mod (ADR-445, `hooks/register.ts`). It makes no network call, spawns no process and makes no model call.
- **Guard** (tighten-only, on by default): Refuses any `metaharness_*` input that holds a key, token or password (MetaHarness writes its inputs to audit memory), and `metaharness_flywheel` `promote` / `evidence-reset` unless the call carries `confirm: true`. A refusal never echoes the secret.
- **`/metaharness-mod`**: `status`, `recent`, `tools` (which of this plugin's tools are connected) and `scan <text>` (would the guard refuse it). Answered locally.
- **Status file**: `.claude-flow/metaharness-mod/status.json` (`{version: 1, updatedMs, guard, calls, total, blocked, recent}`, counters only, never tool input), written at session start and after every call to this plugin's tools.
Options (`userConfig`): `guard` (on).
Test it: `claude plugin validate plugins/ruflo-metaharness`, `claude plugin test plugins/ruflo-metaharness`, `bash plugins/ruflo-metaharness/scripts/smoke.sh`.
+37
View File
@@ -0,0 +1,37 @@
import { hasSecret } from './screen'
import type { ModOptions } from './options'
/** `mcp__<server>__<tool>` into its tool half; tool names never hold a double underscore. */
export function shortName(name: string): string {
const at = name.lastIndexOf('__')
return name.startsWith('mcp__') && at > 5 ? name.slice(at + 2) : name
}
/** 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 []
}
const field = (input: unknown, key: string): unknown => (typeof input === 'object' && input !== null ? (input as Record<string, unknown>)[key] : undefined)
/** The tools this plugin owns: every `metaharness_*` tool. */
export const isOwn = (name: string, _input?: unknown): boolean => name.startsWith('metaharness_')
/** The reason a call is refused, or undefined when it may go. Never names or echoes a secret. */
export function verdict(name: string, input: unknown, _opts: ModOptions, _calls: Record<string, number>): string | undefined {
if (textsOf(input).some(hasSecret)) {
return 'ruflo-metaharness: this input holds what looks like a secret (a key, token or password). MetaHarness records its inputs in audit memory; pass a path or a reference instead.'
}
if (name === 'metaharness_flywheel' && ['promote', 'evidence-reset'].includes(String(field(input, 'operation'))) && field(input, 'confirm') !== true) {
return 'ruflo-metaharness: promoting a receipt or resetting evidence changes the active harness. Ask the user, then retry with confirm: true.'
}
return undefined
}
@@ -0,0 +1,4 @@
{
"description": "MetaHarness as a mod (ADR-445): a tighten-only guard on the metaharness tools (promotion needs an explicit confirm, no secrets in inputs), a status file the console reads, and /metaharness-mod.",
"modules": ["./register.ts"]
}
@@ -0,0 +1,12 @@
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; readonly extra: Readonly<Record<string, unknown>> }
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), extra: {} }
}
+108
View File
@@ -0,0 +1,108 @@
import type { Hook, Register } from 'claude-code'
import { isOwn, shortName, verdict } from './guard'
import { readOptions, type ModOptions } from './options'
import { scan } from './screen'
const COMMAND = 'metaharness-mod'
const STATUS_PATH = '.claude-flow/metaharness-mod/status.json'
const RECENT = 5
type Dollar = Parameters<Hook<'session.start'>>[0]
/** Everything one session of the mod keeps: its settings, per-tool counters, what was refused and the project root. */
type Session = {
readonly opts: ModOptions
readonly calls: Record<string, number>
blocked: number
readonly recent: string[]
root?: string
}
const total = (s: Session) => Object.values(s.calls).reduce((a, b) => a + b, 0)
function note(s: Session, line: string): void {
s.recent.push(line)
if (s.recent.length > RECENT) s.recent.splice(0, s.recent.length - RECENT)
}
/** The status file the console reads; `version` lets it refuse a shape it does not know. Counters only, never tool input. */
async function flush($: Dollar, s: Session): Promise<void> {
if (s.root === undefined) return
const body = { version: 1, updatedMs: await $.clock.now(), guard: s.opts.guard, ...s.opts.extra, calls: s.calls, total: total(s), blocked: s.blocked, recent: s.recent }
try {
await $.fs.write(`${s.root}/${STATUS_PATH}`, `${JSON.stringify(body, null, 2)}\n`)
} catch {
/* the status file is a courtesy */
}
}
/** The connected tools this plugin owns, by short name. */
async function connected($: Dollar): Promise<string[]> {
const tools = await $.tool.list()
return tools.filter(t => t.mcp && isOwn(shortName(t.name))).map(t => shortName(t.name))
}
const HELP = ['/metaharness-mod status', '/metaharness-mod scan <text>', '/metaharness-mod recent', '/metaharness-mod tools'].join('\n')
async function answer($: Dollar, s: Session, args: string): Promise<string> {
const [verb = '', ...rest] = args.trim().split(/\s+/)
const arg = rest.join(' ')
if (verb === '' || verb === 'help') return HELP
if (verb === 'status') {
const per = Object.entries(s.calls).map(([k, v]) => `${k} ${v}`).join(' · ')
return [`guard ${s.opts.guard ? 'on' : 'off'}${Object.entries(s.opts.extra).map(([k, v]) => ` · ${k} ${String(v)}`).join('')}`, `${total(s)} call${total(s) === 1 ? '' : 's'}${per ? ` (${per})` : ''} · refused ${s.blocked}`].join('\n')
}
if (verb === 'recent') return s.recent.length ? s.recent.map(r => `- ${r}`).join('\n') : 'Nothing has gone through this session.'
if (verb === 'tools') {
const names = await connected($)
return names.length ? names.join('\n') : 'None of this plugin\'s tools are connected. Connect the ruflo MCP server and try again.'
}
if (verb === 'scan') {
if (arg === '') return 'usage: /metaharness-mod scan <text>'
const found = scan(arg)
return found.secrets.length ? `The guard would refuse that (${found.secrets.join(', ')}).` : 'Nothing found: the guard would let that through.'
}
return `Unknown: ${verb}\n${HELP}`
}
/**
* MetaHarness as a mod (ADR-445): a tighten-only guard on this plugin's own tools, a status file the console reads, and `/metaharness-mod`.
* No network, no process, no model call.
*/
export const register: Register = (on, options) => {
const s: Session = { opts: readOptions(options), calls: {}, blocked: 0, recent: [] }
on('session.start', async ($, e, next) => {
const result = await next(e)
s.root = (await $.session.root()) as string | undefined
try {
await $.command.register({ name: COMMAND, description: 'MetaHarness mod: status, scan <text>, recent, tools' })
} catch {
/* a name taken by another plugin must not stop the mod */
}
await flush($, s)
return result
})
on('tool.call', async ($, e, next) => {
const name = shortName(e.tool)
if (!isOwn(name, e)) return next(e)
if (s.opts.guard) {
const reason = verdict(name, e, s.opts, s.calls)
if (reason !== undefined) {
s.blocked++
note(s, `refused ${name}`)
await flush($, s)
return { deny: reason }
}
}
s.calls[name] = (s.calls[name] ?? 0) + 1
note(s, name)
await flush($, s)
return next(e)
})
/** `/metaharness-mod`: the plugin's own commands are prompt commands, which no hook can answer. */
on('command.run', { command: COMMAND }, async ($, e) => ({ text: await answer($, s, typeof e.args === 'string' ? e.args : '') }))
}
+50
View File
@@ -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
}
+23 -4
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# Structural smoke test for ruflo-metaharness v0.1.1 (ADR-150 Phase 1).
# Structural smoke test for ruflo-metaharness v0.2.0 (ADR-150 Phase 1).
set -u
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PASS=0
@@ -32,10 +32,10 @@ else
bad "extraction-regex-rot: EXPECTED_TOOLS=$EXPECTED_TOOLS EXPECTED_SUBS=$EXPECTED_SUBS"
fi
step "1. plugin.json declares 0.1.1 with adr-150 keywords"
step "1. plugin.json declares 0.2.0 with adr-150 keywords"
v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
if [[ "$v" != "0.1.1" ]]; then
bad "expected 0.1.1, got '$v'"
if [[ "$v" != "0.2.0" ]]; then
bad "expected 0.2.0, got '$v'"
else
miss=""
for k in ruflo metaharness harness scorecard genome mcp-scan threat-model router adr-150 adr-148 adr-149 optional-dependency graceful-degradation subprocess phase-1-mvp; do
@@ -2449,5 +2449,24 @@ LOADER="$ROOT/../../v3/@claude-flow/cli/src/commands/index.ts"
grep -q "eject: () => import" "$LOADER" 2>/dev/null || miss="$miss not-registered-in-loader"
[[ -z "$miss" ]] && ok || bad "$miss"
# M1-M3. The mod (ADR-445): 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 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), the command name is metaharness-mod"
node -e '
const c = require(process.argv[1]).userConfig || {}
process.exit(c.guard && c.guard.default === "on" ? 0 : 1)
' "$ROOT/.claude-plugin/plugin.json" && grep -q "'metaharness-mod'" "$ROOT/hooks/register.ts" && ok || bad "userConfig defaults or command name 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
@@ -0,0 +1,117 @@
import type { On } from 'claude-code'
import { describe, expect, test, tier } from 'claude-code/testing'
tier('user')
const ROOT = '/work'
const P = 'mcp__plugin_ruflo-core_ruflo__'
const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const
const slash = (args: string) => ({ command: 'metaharness-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const
const TOOLS = ["metaharness_score","metaharness_flywheel"].map(name => ({ name: P + name, description: '', mcp: true }))
/** The world beneath the mod: a project root, a file map, the connected tools, and a stub that answers every tool call. */
function world(on: On, tools = TOOLS) {
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('tool.list', () => ({ value: tools }))
on('clock.now', () => ({ value: Date.now() }))
on('tool.call', () => ({ result: 'ran' }))
return { files, registered, status: () => JSON.parse(files.get(`${ROOT}/.claude-flow/metaharness-mod/status.json`) ?? '{}') }
}
const attempt = async ($: Parameters<Parameters<typeof test>[2]>[0], call: object) =>
JSON.stringify(await $.tool.call(call as never).then(r => r, (e: unknown) => ({ text: String(e) })))
describe('guard', () => {
test('refuses: flywheel promote without confirm, and never echoes the secret', async ($, on) => {
world(on)
await $.session.start(START)
const out = await attempt($, { tool: P + 'metaharness_flywheel', operation: 'promote', receiptId: 'r1' })
expect(out).not.toContain('ran')
expect(out).toContain('ruflo-metaharness')
expect(out).not.toContain('ghp_')
expect(out).not.toContain('abcd1234')
expect(out).not.toContain('Zx9Qm2')
})
test('refuses: secret in an input, and never echoes the secret', async ($, on) => {
world(on)
await $.session.start(START)
const out = await attempt($, { tool: P + 'metaharness_score', path: `/repo token ghp_${'a1B2'.repeat(10)}` })
expect(out).not.toContain('ran')
expect(out).toContain('ruflo-metaharness')
expect(out).not.toContain('ghp_')
expect(out).not.toContain('abcd1234')
expect(out).not.toContain('Zx9Qm2')
})
test('passes good calls through', async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'metaharness_flywheel', operation: 'promote', receiptId: 'r1', confirm: true })).toContain('ran') // promote with confirm
expect(await attempt($, { tool: P + 'metaharness_flywheel', operation: 'status' })).toContain('ran') // flywheel status
expect(await attempt($, { tool: P + 'metaharness_score', path: '.' })).toContain('ran') // score
})
test('turning that option off lets the call through', { options: { guard: 'off' } }, async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'metaharness_flywheel', operation: 'promote', receiptId: 'r1' })).toContain('ran')
})
test('ignores tools that belong to someone else', async ($, on) => {
world(on)
await $.session.start(START)
expect(await attempt($, { tool: P + 'some_other_tool', value: `token ghp_${'a1B2'.repeat(10)}` })).toContain('ran')
})
})
describe('status file and /metaharness-mod', () => {
test('the status file is written at session start with the shape the console reads', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.registered).toEqual(['metaharness-mod'])
expect(w.status()).toMatchObject({ version: 1, guard: true, total: 0, blocked: 0, calls: {} })
expect(typeof w.status().updatedMs).toBe('number')
})
test('counters move when own tools run and when the guard refuses', async ($, on) => {
const w = world(on)
await $.session.start(START)
await attempt($, { tool: P + 'metaharness_score', path: '.' })
await attempt($, { tool: P + 'metaharness_flywheel', operation: 'promote', receiptId: 'r1' })
expect(w.status()).toMatchObject({ total: 1, blocked: 1 })
expect(Object.keys(w.status().calls)).toHaveLength(1)
expect(JSON.stringify(w.status())).not.toContain('ghp_')
})
test('status, tools, recent, scan and help 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('tools'))).text).toContain('metaharness_score')
expect((await $.command.run(slash('recent'))).text).toContain('Nothing')
expect((await $.command.run(slash(`scan key ghp_${'a1B2'.repeat(10)}`))).text).toContain('github token')
expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found')
expect((await $.command.run(slash(''))).text).toContain('/metaharness-mod status')
expect((await $.command.run(slash('what is this'))).text).toContain('Unknown')
})
test('tools says so plainly when none are connected', async ($, on) => {
world(on, [])
await $.session.start(START)
expect((await $.command.run(slash('tools'))).text).toContain('None of this plugin')
})
})
describe('defaults', () => {
test('with no options the guard is on', async ($, on) => {
const w = world(on)
await $.session.start(START)
expect(w.status().guard).toBe(true)
})
})