Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

fix(mods): compose guidance inside native event handlers

rUve999b0625c17
diff --git a/plugins/ruflo-mods/hooks/guard/index.ts b/plugins/ruflo-mods/hooks/guard/index.ts
index 936fc353af..2fa7665697 100644
--- a/plugins/ruflo-mods/hooks/guard/index.ts
+++ b/plugins/ruflo-mods/hooks/guard/index.ts
@@ -1,6 +1,7 @@
import type { On } from 'claude-code'
import { cachedFile, type Read } from '../files'
+import type { GuidanceHooks } from '../guidance'
import { redraw, under, type ModState } from '../state'
import { dangerousCommandVerdict } from './dangerous-command'
import { parseProjection, policyOpinion, PROJECTION_PATH, type Projection } from './policy'
@@ -48,11 +49,12 @@ export function opinionOf(
* becomes looser. The dangerous-command list always applies; ruflo policy
* applies when the CLI projected rules for Claude Code tools.
*/
-export function registerGuard(on: On, state: ModState) {
+export function registerGuard(on: On, state: ModState, guidance?: GuidanceHooks) {
const projection = cachedFile(() => under(state, PROJECTION_PATH), parseProjection)
const research = researchCheck(state)
on('tool.check', async ($, e, next) => {
+ const task = guidance?.active()
const chain = await next(e)
const tool = typeof e.tool === 'string' ? e.tool : ''
const read = await projection({ stat: path => $.fs.stat(path), read: path => $.fs.read(path) })
@@ -71,11 +73,14 @@ export function registerGuard(on: On, state: ModState) {
state.tightened++
redraw(state)
}
+ guidance?.check(task, merged.decision)
return merged
}).catch(async ($, e, next) => {
// ruflo could not judge. Fail closed by one step: the chain's verdict
// stands where it is already ask or deny; an allow is put to the person.
const chain = await next(e).catch(() => undefined)
- return chain ? stricter(chain, CHECK_FAILED) : CHECK_FAILED
+ const result = chain ? stricter(chain, CHECK_FAILED) : CHECK_FAILED
+ guidance?.check(guidance.active(), result.decision)
+ return result
})
}
diff --git a/plugins/ruflo-mods/hooks/guidance/index.ts b/plugins/ruflo-mods/hooks/guidance/index.ts
index 1cacdae4a6..602a82c2b4 100644
--- a/plugins/ruflo-mods/hooks/guidance/index.ts
+++ b/plugins/ruflo-mods/hooks/guidance/index.ts
@@ -1,85 +1,85 @@
-import type { On } from 'claude-code'
-
-import { cachedFile } from '../files'
+import { cachedFile, type FileHost } from '../files'
import type { ModOptions } from '../options'
import { under, type ModState } from '../state'
-import { finishTask, flushObservations, newRunId, OBSERVATIONS_DIR } from './observations'
+import { finishTask, flushObservations, newRunId, OBSERVATIONS_DIR, type ActiveTask } from './observations'
import { MAX_PROJECTION_BYTES, parseProjection, PROJECTION_PATH, selectGuidance } from './projection'
-/** Optional retrieval and candidate telemetry. No training, authority or promotion. */
-export function registerGuidance(on: On, state: ModState, options: ModOptions) {
+export type GuidanceHooks = {
+ start: () => void
+ prompt: (text: string, fs: FileHost) => Promise<string | undefined>
+ active: () => ActiveTask | undefined
+ check: (task: ActiveTask | undefined, decision: unknown) => void
+ tool: (task: ActiveTask | undefined, event: unknown, result: { deny?: unknown; isError?: boolean }) => void
+ complete: (turnId: unknown, isAborted?: boolean) => void
+ end: () => void
+ flush: (fs: { read: (path: string) => Promise<string>; write: (path: string, text: string) => Promise<void> }) => Promise<void>
+}
+
+/**
+ * Optional feature helpers composed INSIDE the existing hooks. Claude Code
+ * permits one unmatched handler per event per plugin. No second tool, prompt,
+ * session or turn handler is registered, and no new host capability is added.
+ */
+export function createGuidance(state: ModState, options: ModOptions): GuidanceHooks | undefined {
+ if (!options.guidanceContext && !options.guidanceLearning) return undefined
const s = state.guidance
- const enabled = options.guidanceContext || options.guidanceLearning
- if (!enabled) return
const projection = cachedFile(() => under(state, PROJECTION_PATH), parseProjection)
- const queuePath = () => under(state, `${OBSERVATIONS_DIR}/${s.runId}.json`)
-
- on('session.start', ($, e, next) => {
- if (enabled && !s.runId) { s.runId = newRunId(); s.status = 'missing' }
- return next(e)
- })
-
- on('prompt.submit', async ($, e, next) => {
- if (!enabled || !s.runId) return next(e)
- if (options.guidanceLearning) finishTask(s, 'interrupted')
- const read = await projection({
- stat: async path => {
- const stat = await $.fs.stat(path)
- if (stat.isLink || stat.size > MAX_PROJECTION_BYTES) throw new Error('invalid guidance file')
- return stat
- },
- read: path => $.fs.read(path),
- })
- s.status = read.kind === 'ok' ? 'ready' : read.kind === 'absent' ? 'missing' : 'unreadable'
- if (read.kind !== 'ok') return next(e)
- const selected = selectGuidance(e.text, read.value)
- if (options.guidanceLearning) {
- s.active = { taskId: ++s.taskSeq, projection: read.value, ruleIds: options.guidanceContext ? selected.ids : [], checks: { allow: 0, ask: 0, deny: 0 }, tools: { ok: 0, error: 0, denied: 0 }, toolIds: new Set() }
- }
- return next(options.guidanceContext && selected.context ? { ...e, context: [...(e.context ?? []), selected.context] } : e)
- }).catch(($, e, next) => next(e))
- on('tool.check', async ($, e, next) => {
- const task = s.active
- const result = await next(e)
- if (task && ['allow', 'ask', 'deny'].includes(result.decision)) task.checks[result.decision as 'allow' | 'ask' | 'deny']++
- return result
- }).catch(($, e, next) => next(e))
-
- on('tool.call', async ($, e, next) => {
- // Capture before awaiting: another prompt cannot acquire this event.
- const task = s.active
- const result = await next(e)
- if (!task) return result
- // Host ids only deduplicate telemetry in memory; never persist arbitrary ids/inputs.
- const id = (e as unknown as { tool_use_id?: unknown }).tool_use_id
- if (typeof id === 'string') {
- if (task.toolIds.has(id)) return result
- if (task.toolIds.size >= 256) return result
- task.toolIds.add(id)
- }
- if (result.deny !== undefined) task.tools.denied++
- else if (result.isError === true) task.tools.error++
- else task.tools.ok++
- return result
- }).catch(($, e, next) => next(e))
-
- on('turn.complete', async ($, e, next) => {
- if (options.guidanceLearning && s.runId) {
- if (!s.seenTurns.has(e.turnId)) {
- if (s.seenTurns.size < 256) s.seenTurns.add(e.turnId)
- finishTask(s, e.isAborted ? 'aborted' : 'completed')
+ return {
+ start() {
+ if (!s.runId) { s.runId = newRunId(); s.status = 'missing' }
+ },
+ async prompt(text, fs) {
+ if (!s.runId) return undefined
+ if (options.guidanceLearning) finishTask(s, 'interrupted')
+ const read = await projection({
+ stat: async path => {
+ const stat = await fs.stat(path)
+ if (stat.isLink || stat.size > MAX_PROJECTION_BYTES) throw new Error('invalid guidance file')
+ return stat
+ },
+ read: fs.read,
+ })
+ s.status = read.kind === 'ok' ? 'ready' : read.kind === 'absent' ? 'missing' : 'unreadable'
+ if (read.kind !== 'ok') return undefined
+ const selected = selectGuidance(text, read.value)
+ if (options.guidanceLearning) {
+ s.active = { taskId: ++s.taskSeq, projection: read.value, ruleIds: options.guidanceContext ? selected.ids : [], checks: { allow: 0, ask: 0, deny: 0 }, tools: { ok: 0, error: 0, denied: 0 }, toolIds: new Set() }
}
- await flushObservations(s, queuePath(), { read: path => $.fs.read(path), write: (path, text) => $.fs.write(path, text) })
- }
- return next(e)
- }).catch(($, e, next) => next(e))
-
- on('session.end', async ($, e, next) => {
- if (options.guidanceLearning && s.runId) {
- finishTask(s, 'interrupted')
- await flushObservations(s, queuePath(), { read: path => $.fs.read(path), write: (path, text) => $.fs.write(path, text) })
- }
- return next(e)
- }).catch(($, e, next) => next(e))
+ return options.guidanceContext ? selected.context : undefined
+ },
+ active: () => s.active,
+ check(task, decision) {
+ if (task && (decision === 'allow' || decision === 'ask' || decision === 'deny')) task.checks[decision]++
+ },
+ tool(task, event, result) {
+ if (!task) return
+ try {
+ const id = (event as { tool_use_id?: unknown }).tool_use_id
+ if (typeof id === 'string') {
+ if (task.toolIds.has(id) || task.toolIds.size >= 256) return
+ task.toolIds.add(id)
+ }
+ if (result.deny !== undefined) task.tools.denied++
+ else if (result.isError === true) task.tools.error++
+ else task.tools.ok++
+ } catch {
+ // Observation failure preserves the underlying tool's settled result.
+ }
+ },
+ complete(turnId, isAborted) {
+ if (!options.guidanceLearning || !s.runId) return
+ if (typeof turnId === 'string') {
+ if (s.seenTurns.has(turnId)) return
+ if (s.seenTurns.size < 256) s.seenTurns.add(turnId)
+ }
+ finishTask(s, isAborted ? 'aborted' : 'completed')
+ },
+ end() {
+ if (options.guidanceLearning && s.runId) finishTask(s, 'interrupted')
+ },
+ async flush(fs) {
+ if (options.guidanceLearning && s.runId) await flushObservations(s, under(state, `${OBSERVATIONS_DIR}/${s.runId}.json`), fs)
+ },
+ }
}
diff --git a/plugins/ruflo-mods/hooks/learn/index.ts b/plugins/ruflo-mods/hooks/learn/index.ts
index 23b86145cf..05c87e60de 100644
--- a/plugins/ruflo-mods/hooks/learn/index.ts
+++ b/plugins/ruflo-mods/hooks/learn/index.ts
@@ -1,6 +1,7 @@
import type { EngineInterface, On } from 'claude-code'
import { isMissing } from '../files'
+import type { GuidanceHooks } from '../guidance'
import { redraw, under, type ModState } from '../state'
import { appendRecords, EDIT_TOOLS, editedFile, MAX_LINES, PENDING_PATH, rufloSessionId, SESSION_PATH } from './insights'
@@ -40,9 +41,11 @@ export async function flushEdits($: EngineInterface, state: ModState): Promise<v
* a denied one never ran, as PostToolUse never fires for it). Written per
* turn at `turn.complete`, and at `session.end`.
*/
-export function registerLearn(on: On, state: ModState) {
+export function registerLearn(on: On, state: ModState, guidance?: GuidanceHooks) {
on('tool.call', async ($, e, next) => {
+ const task = guidance?.active()
const result = await next(e)
+ guidance?.tool(task, e, result)
if (!state.owned.has('post-edit') || !EDIT_TOOLS.has(e.tool) || result.deny !== undefined) return result
state.edits.push({
@@ -60,11 +63,19 @@ export function registerLearn(on: On, state: ModState) {
on('turn.complete', async ($, e, next) => {
const result = await next(e)
+ if (guidance) {
+ guidance.complete(e.turnId, e.isAborted)
+ await guidance.flush({ read: path => $.fs.read(path), write: (path, text) => $.fs.write(path, text) })
+ }
await flushEdits($, state)
return result
})
on('session.end', async ($, e, next) => {
+ if (guidance) {
+ guidance.end()
+ await guidance.flush({ read: path => $.fs.read(path), write: (path, text) => $.fs.write(path, text) })
+ }
await flushEdits($, state)
return next(e)
})
diff --git a/plugins/ruflo-mods/hooks/register.ts b/plugins/ruflo-mods/hooks/register.ts
index 1809b6fe4d..dcbff81e42 100644
--- a/plugins/ruflo-mods/hooks/register.ts
+++ b/plugins/ruflo-mods/hooks/register.ts
@@ -2,7 +2,7 @@ import type { Register } from 'claude-code'
import { registerCost } from './cost'
import { registerGuard } from './guard'
-import { registerGuidance } from './guidance'
+import { createGuidance } from './guidance'
import { registerLearn } from './learn'
import { registerNoun } from './noun'
import { readOptions } from './options'
@@ -26,13 +26,13 @@ import { registerTrust } from './trust'
export const register: Register = (on, options) => {
const state = createState()
const opts = readOptions(options)
+ const guidance = createGuidance(state, opts)
registerTrust(on, opts.modTrust, opts.modTrustAllow)
registerNoun(on, state)
- registerSession(on, state, opts)
- registerGuidance(on, state, opts)
- registerRoute(on, state, opts)
- registerGuard(on, state)
- registerLearn(on, state)
+ registerSession(on, state, opts, guidance)
+ registerRoute(on, state, opts, guidance)
+ registerGuard(on, state, guidance)
+ registerLearn(on, state, guidance)
registerCost(on, state, opts)
}
diff --git a/plugins/ruflo-mods/hooks/route/index.ts b/plugins/ruflo-mods/hooks/route/index.ts
index eaf44d5b75..42000f3652 100644
--- a/plugins/ruflo-mods/hooks/route/index.ts
+++ b/plugins/ruflo-mods/hooks/route/index.ts
@@ -1,6 +1,7 @@
import type { On } from 'claude-code'
import { cachedFile } from '../files'
+import type { GuidanceHooks } from '../guidance'
import type { ModOptions } from '../options'
import { redraw, under, type ModState } from '../state'
import { formatRoute } from './format'
@@ -16,13 +17,14 @@ export const RANKED_PATH = '.claude-flow/data/ranked-context.json'
* the one injection point sec-default leaves to a person's plugins
* (`prompt.context` is continued past the user tier).
*/
-export function registerRoute(on: On, state: ModState, options: ModOptions) {
+export function registerRoute(on: On, state: ModState, options: ModOptions, guidance?: GuidanceHooks) {
const ranked = cachedFile(() => under(state, RANKED_PATH), parseRanked)
on('prompt.submit', async ($, e, next) => {
- if (!state.owned.has('route')) return next(e)
-
const text = typeof e.text === 'string' ? e.text : ''
+ const advisory = guidance ? await guidance.prompt(text, { stat: path => $.fs.stat(path), read: path => $.fs.read(path) }) : undefined
+ const context = [...(e.context ?? []), ...(advisory ? [advisory] : [])]
+ if (!state.owned.has('route')) return next(advisory ? { ...e, context } : e)
const result = routeTask(text)
state.lastRoute = result
state.routed++
@@ -36,6 +38,6 @@ export function registerRoute(on: On, state: ModState, options: ModOptions) {
blocks.push(formatRoute(text, result))
redraw(state)
- return next({ ...e, context: [...(e.context ?? []), blocks.join('\n')] })
+ return next({ ...e, context: [...context, blocks.join('\n')] })
}).catch(($, e, next) => next(e)) // a broken plugin never blocks a prompt
}
diff --git a/plugins/ruflo-mods/hooks/session.ts b/plugins/ruflo-mods/hooks/session.ts
index d424b57df3..be577e196e 100644
--- a/plugins/ruflo-mods/hooks/session.ts
+++ b/plugins/ruflo-mods/hooks/session.ts
@@ -1,4 +1,5 @@
import type { EngineInterface, On } from 'claude-code'
+import type { GuidanceHooks } from './guidance'
import { HANDSHAKE_MARKER, ownedEvents } from './ownership'
import type { ModOptions } from './options'
@@ -43,13 +44,14 @@ function hasClassicStatusLine(settings: unknown): boolean {
* hooks through the process environment; register `/ruflo-mods`. Any failure
* leaves the mod owning nothing, so every classic hook keeps running.
*/
-export function registerSession(on: On, state: ModState, options: ModOptions) {
+export function registerSession(on: On, state: ModState, options: ModOptions, guidance?: GuidanceHooks) {
on('session.start', async ($, e, next) => {
state.root = await $.session.root()
const settings = await $.settings.read()
state.owned = new Set(ownedEvents(settings, await helperHonours($)))
await $.env.set('RUFLO_MODS_OWNS', state.owned.size ? [...state.owned].join(',') : undefined)
state.statusLine = options.statusLine && !hasClassicStatusLine(settings)
+ guidance?.start()
redraw(state)
await $.command
.register({ name: 'ruflo-mods', description: 'Same as /ruflo mods: what this session routed, recorded and tightened' })
diff --git a/plugins/ruflo-mods/tests/guidance.test.ts b/plugins/ruflo-mods/tests/guidance.test.ts
index 44177b499f..291f032794 100644
--- a/plugins/ruflo-mods/tests/guidance.test.ts
+++ b/plugins/ruflo-mods/tests/guidance.test.ts
@@ -1,9 +1,7 @@
import { describe, expect, test, tier } from 'claude-code/testing'
import type { Plugin } from 'claude-code/testing'
-import { registerGuidance } from '../hooks/guidance'
-import { readOptions } from '../hooks/options'
-import { createState } from '../hooks/state'
+import { register } from '../hooks/register'
import { prompt, ROOT, START, world } from './fixtures/world'
@@ -23,11 +21,7 @@ const options = { guidanceContext: true, guidanceLearning: true, routeContext: f
// Exercise production registration directly: the 2.1.283 kit does not apply
// per-test option overrides. Current kits may also run these same contracts.
const enabledGuidance: Plugin = {
- name: 'guidance-contract', tier: 'user', register: on => {
- const state = createState()
- on('session.start', async ($, e, next) => { state.root = await $.session.root(); return next(e) })
- registerGuidance(on, state, readOptions(options))
- },
+ name: 'guidance-contract', tier: 'user', register: on => register(on, options),
}
const complete = (turnId: string, isAborted = false) => ({ answer: 'EXAMPLE_ANSWER_SENTINEL', durationMs: 1, isAborted, turnId, reason: 'answer' }) as const
const queued = (files: Map<string, string>) => [...files].filter(([path]) => path.includes('/guidance/observations/'))
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-guidance-e2e.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-guidance-e2e.test.ts
index 3257f8f452..83ee8cc760 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-guidance-e2e.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-guidance-e2e.test.ts
@@ -9,6 +9,8 @@ import { register } from '../../../../../plugins/ruflo-mods/hooks/register';
import { parseProjection, PROJECTION_PATH, MAX_CONTEXT_CHARS, safeText, selectGuidance } from '../../../../../plugins/ruflo-mods/hooks/guidance/projection';
import { finishTask, flushObservations, guidanceState, validObservation, MAX_OBSERVATIONS } from '../../../../../plugins/ruflo-mods/hooks/guidance/observations';
import { buildModProjection, collectModCandidates, MOD_GUIDANCE_DIR, parseModObservations, writeModProjection } from '../../src/guidance/mod-projection';
+import { guidanceCommand } from '../../src/commands/guidance';
+import { output } from '../../src/output';
import { loadMod, memoryWorld, realWorld, type World } from './harness';
const REVISION = '8ce24908c51c26aa859308bdb2e7e819e4f9fc88';
@@ -162,14 +164,20 @@ describe('guidance lifecycle', () => {
describe('candidate boundary', () => {
it('real filesystem roundtrip exports compiler guidance, retrieves it, records observations and creates review candidates', async () => {
const root = project(); const sourcePath = join(root, 'CLAUDE.md'); writeFileSync(sourcePath, SOURCE);
- const p = buildModProjection(new GuidanceCompiler().compile(readFileSync(sourcePath, 'utf8')), REVISION);
- await writeModProjection(join(root, MOD_GUIDANCE_DIR), p);
+ vi.spyOn(output, 'writeln').mockImplementation(() => undefined);
+ const compile = guidanceCommand.subcommands!.find(c => c.name === 'compile')!;
+ const exported = await compile.action!({ flags: { root: sourcePath, 'mod-projection': true, revision: REVISION, output: join(root, MOD_GUIDANCE_DIR), json: true } } as never);
+ expect(exported.success).toBe(true);
+ const p = (exported.data as { projection: ReturnType<typeof projection> }).projection;
const mod = await start(realWorld(root));
const submitted = await prompt(mod); expect(submitted.context.join('\n')).toContain(p.bundleId);
await mod.dispatch('tool.check', { tool: 'Read', input: { file_path: sourcePath } }, () => ({ decision: 'deny', rule: 'host' }));
await mod.dispatch('tool.call', { tool: 'Read', tool_use_id: 'r1' }, () => ({ isError: true, result: 'fixture failure' }));
await complete(mod); await complete(mod); await end(mod);
- const report = await collectModCandidates(join(root, MOD_GUIDANCE_DIR, 'observations'), p.bundleId);
+ const review = guidanceCommand.subcommands!.find(c => c.name === 'mod-candidates')!;
+ const reviewed = await review.action!({ flags: { directory: join(root, MOD_GUIDANCE_DIR, 'observations'), 'bundle-id': p.bundleId, json: true } } as never);
+ expect(reviewed.success).toBe(true);
+ const report = reviewed.data as Awaited<ReturnType<typeof collectModCandidates>>;
expect(report).toMatchObject({ observations: 1, status: 'pending-independent-verification', learningEligible: false });
expect(report.candidates.find(c => c.ruleId === 'TEST-001')).toMatchObject({ toolErrors: 1, deniedChecks: 1 });
const empty = await collectModCandidates(join(root, MOD_GUIDANCE_DIR, 'observations'), 'f'.repeat(64));
diff --git a/v3/@claude-flow/cli/vitest.config.ts b/v3/@claude-flow/cli/vitest.config.ts
index 0c39e5596c..6dff721cba 100644
--- a/v3/@claude-flow/cli/vitest.config.ts
+++ b/v3/@claude-flow/cli/vitest.config.ts
@@ -10,6 +10,10 @@ export default defineConfig({
// prefix-match, so '@claude-flow/security' alone would rewrite
// '@claude-flow/security/safe-git' to '.../src/index.ts/safe-git'.
alias: [
+ {
+ find: '@claude-flow/guidance/compiler',
+ replacement: fileURLToPath(new URL('../guidance/src/compiler.ts', import.meta.url)),
+ },
{
find: '@claude-flow/security/safe-git',
replacement: fileURLToPath(new URL('../security/src/safe-git.ts', import.meta.url)),