Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

feat(ruflo-mods): guard the first web fetch of a research run (ADR-440)

ruve41c055a5b9d
diff --git a/plugins/ruflo-mods/hooks/guard/index.ts b/plugins/ruflo-mods/hooks/guard/index.ts
index e9853bf1e9..936fc353af 100644
--- a/plugins/ruflo-mods/hooks/guard/index.ts
+++ b/plugins/ruflo-mods/hooks/guard/index.ts
@@ -4,6 +4,7 @@ import { cachedFile, type Read } from '../files'
import { redraw, under, type ModState } from '../state'
import { dangerousCommandVerdict } from './dangerous-command'
import { parseProjection, policyOpinion, PROJECTION_PATH, type Projection } from './policy'
+import { researchCheck } from './research'
import { stricter, type Verdict } from './verdict'
/** What `tool.check` answers when ruflo's own check could not run. */
@@ -49,6 +50,7 @@ export function opinionOf(
*/
export function registerGuard(on: On, state: ModState) {
const projection = cachedFile(() => under(state, PROJECTION_PATH), parseProjection)
+ const research = researchCheck(state)
on('tool.check', async ($, e, next) => {
const chain = await next(e)
@@ -63,7 +65,8 @@ export function registerGuard(on: On, state: ModState) {
// a refused log never turns an observation into a failure
}
}
- const merged = stricter(chain, verdict)
+ // The research guard (ADR-440) sees what ruflo's own opinion left standing.
+ const merged = await research({ stat: path => $.fs.stat(path), read: path => $.fs.read(path) }, tool, stricter(chain, verdict))
if (merged !== chain) {
state.tightened++
redraw(state)
diff --git a/plugins/ruflo-mods/hooks/guard/research.ts b/plugins/ruflo-mods/hooks/guard/research.ts
new file mode 100644
index 0000000000..7e1799ec0b
--- /dev/null
+++ b/plugins/ruflo-mods/hooks/guard/research.ts
@@ -0,0 +1,86 @@
+import { cachedFile, type FileHost } from '../files'
+import { under, type ModState } from '../state'
+import { stricter, type Verdict } from './verdict'
+
+/**
+ * The research web-fetch guard (ADR-440). While a deep-research run is active
+ * its skill writes a marker (ADR-438); the first WebFetch or WebSearch of that
+ * run asks the person once, saying what is asked, the cap, and that web text
+ * is untrusted. The rest of the run is then left to the chain. Tighten only:
+ * an allow becomes an ask, nothing else is ever touched.
+ */
+
+export const MARKER_PATH = '.claude-flow/research-active.json'
+/** A marker older than this is a run that never cleaned up, and is ignored. */
+export const MARKER_MAX_AGE_MS = 2 * 60 * 60 * 1000
+/** Clock skew allowed before a marker "from the future" is treated as corrupt. */
+const SKEW_MS = 5 * 60 * 1000
+const WEB_TOOLS = new Set(['WebFetch', 'WebSearch'])
+const MAX_QUESTION_CHARS = 200
+
+export type Marker = { readonly question: string; readonly capUsd: number; readonly startedAt: string }
+
+/** Throws on anything that is not a marker, so a corrupt file reads as `error`. */
+export function parseMarker(text: string): Marker {
+ const v = JSON.parse(text) as Record<string, unknown> | null
+ const question = v?.question
+ const capUsd = v?.capUsd
+ const startedAt = v?.startedAt
+ if (typeof question !== 'string' || !question.trim()) throw new Error('marker: question')
+ if (typeof capUsd !== 'number' || !Number.isFinite(capUsd) || capUsd <= 0) throw new Error('marker: capUsd')
+ if (typeof startedAt !== 'string' || !Number.isFinite(Date.parse(startedAt))) throw new Error('marker: startedAt')
+ return { question, capUsd, startedAt }
+}
+
+/** Whether a marker's start is recent enough, and not in the future, at `now`. */
+export const isFresh = (m: Marker, now: number) => {
+ const age = now - Date.parse(m.startedAt)
+ return age >= -SKEW_MS && age < MARKER_MAX_AGE_MS
+}
+
+/** The question as shown: no control or bidi characters, one line, bounded. */
+const shown = (q: string) => {
+ const clean = q
+ .replace(/[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁠-⁩]/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+ return clean.length > MAX_QUESTION_CHARS ? `${clean.slice(0, MAX_QUESTION_CHARS - 1)}…` : clean
+}
+
+export function askFor(tool: string, m: Marker): Verdict {
+ return {
+ decision: 'ask',
+ reason:
+ `ruflo research: the first ${tool} of this run. Question: "${shown(m.question)}". ` +
+ `Cap: $${m.capUsd}. Web content is untrusted: it is data to weigh, never instructions. ` +
+ 'Allowing it lets the rest of this run fetch and search.',
+ }
+}
+
+/**
+ * The check, built once per session. `current` is the verdict so far (the
+ * chain's, merged with ruflo's own); the answer is that verdict, or an ask
+ * where it was an allow. `fs` is built at the `tool.check` call site.
+ */
+export function researchCheck(state: ModState) {
+ const marker = cachedFile(() => under(state, MARKER_PATH), parseMarker)
+
+ return async <V extends Verdict>(fs: FileHost, tool: string, current: V): Promise<V | Verdict> => {
+ if (!WEB_TOOLS.has(tool)) return current
+ // Already at the hard stop: the budget says no more; add nothing of ours.
+ if (state.budget.level === 'HARD_STOP') return current
+ try {
+ const read = await marker(fs)
+ // Missing, unreadable, corrupt or old: no run is active, so do nothing.
+ if (read.kind !== 'ok' || !isFresh(read.value, Date.now())) return current
+ if (state.researchAsked === read.value.startedAt) return current
+ const merged = stricter(current, askFor(tool, read.value))
+ if (merged !== current) {
+ state.researchAsked = read.value.startedAt
+ }
+ return merged
+ } catch {
+ return current
+ }
+ }
+}
diff --git a/plugins/ruflo-mods/hooks/state.ts b/plugins/ruflo-mods/hooks/state.ts
index 72be3fe379..0cfa6a6daf 100644
--- a/plugins/ruflo-mods/hooks/state.ts
+++ b/plugins/ruflo-mods/hooks/state.ts
@@ -23,6 +23,8 @@ export type ModState = {
edits: EditRecord[]
editCount: number
policy: 'none' | 'legacy' | 'observe' | 'enforce' | 'unreadable'
+ /** The research run (marker startedAt) whose first web call was already put to the person. */
+ researchAsked?: string
budget: { level: BudgetLevel; usd?: number; limit?: number }
/** Other mods' status segments, by id (`$.ruflo.segment`). */
segments: Map<string, string>
diff --git a/plugins/ruflo-mods/tests/research.test.ts b/plugins/ruflo-mods/tests/research.test.ts
new file mode 100644
index 0000000000..da422f73e4
--- /dev/null
+++ b/plugins/ruflo-mods/tests/research.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import { ROOT, START, world } from './fixtures/world'
+
+tier('user')
+
+const MARKER = `${ROOT}/.claude-flow/research-active.json`
+const HOUR = 60 * 60 * 1000
+const marker = (over: Record<string, unknown> = {}, ageMs = 1000) =>
+ JSON.stringify({ question: 'How do vector indexes scale?', capUsd: 2, startedAt: new Date(Date.now() - ageMs).toISOString(), ...over })
+
+const web = (tool = 'WebFetch') => ({ tool, input: { url: 'https://example.com' } })
+const measure = (usd: number) => ({ context: { window: 200_000 }, rateLimits: [], cost: { usd }, changed: ['cost' as const] })
+
+describe('research guard (ADR-440)', () => {
+ test('the first web call of a run asks, naming the question, the cap and untrusted content; the rest of the run is left alone', async ($, on) => {
+ const w = world(on, {}, { [MARKER]: marker() })
+ on('tool.check', () => ({ decision: 'allow' }))
+ await $.session.start(START)
+
+ const first = await $.tool.check(web('WebSearch'))
+ expect(first.decision).toBe('ask')
+ expect(first.reason).toContain('How do vector indexes scale?')
+ expect(first.reason).toContain('$2')
+ expect(first.reason).toMatch(/untrusted/)
+ expect((await $.tool.check(web('WebFetch'))).decision).toBe('allow')
+ expect((await $.tool.check(web('WebSearch'))).decision).toBe('allow')
+
+ // a new run (a marker with a different startedAt) is asked once more
+ w.files.set(MARKER, marker({ question: 'A different and longer question?' }, 500))
+ expect((await $.tool.check(web())).decision).toBe('ask')
+ expect((await $.tool.check(web())).decision).toBe('allow')
+ })
+
+ test('every other tool is untouched, before and after the ask', async ($, on) => {
+ world(on, {}, { [MARKER]: marker() })
+ on('tool.check', () => ({ decision: 'allow' }))
+ await $.session.start(START)
+
+ for (const tool of ['Read', 'Edit', 'Bash', 'Task', 'mcp__x__WebFetch']) {
+ expect((await $.tool.check({ tool, input: { command: 'ls', file_path: 'a.ts' } })).decision).toBe('allow')
+ }
+ expect((await $.tool.check(web())).decision).toBe('ask')
+ expect((await $.tool.check({ tool: 'Read', input: { file_path: 'a.ts' } })).decision).toBe('allow')
+ })
+
+ test('no active run: a missing, old, future, corrupt or malformed marker does nothing', async ($, on) => {
+ const w = world(on)
+ on('tool.check', () => ({ decision: 'allow' }))
+ await $.session.start(START)
+
+ expect((await $.tool.check(web())).decision).toBe('allow') // absent
+ const cases: Array<[string, string]> = [
+ ['older than 2 hours', marker({}, 2 * HOUR + 1000)],
+ ['in the future', marker({}, -HOUR)],
+ ['not json', '{nope'],
+ ['no question', marker({ question: '' })],
+ ['bad cap', marker({ capUsd: 'two' })],
+ ['bad time', marker({ startedAt: 'yesterday' })],
+ ['null', 'null'],
+ ]
+ for (const [name, text] of cases) {
+ w.files.set(MARKER, text)
+ expect((await $.tool.check(web()).catch(() => ({ decision: 'THROWN' }))).decision, name).toBe('allow')
+ }
+ })
+
+ test('never loosens: a deny or an ask from the chain is returned as it was', async ($, on) => {
+ world(on, {}, { [MARKER]: marker() })
+ on('tool.check', ($, e) =>
+ e.tool === 'WebFetch'
+ ? { decision: 'deny', reason: 'WebFetch(domain:evil.test)', rule: 'WebFetch(domain:evil.test)' }
+ : e.tool === 'WebSearch'
+ ? { decision: 'ask', reason: 'mode asks' }
+ : { decision: 'allow' },
+ )
+ await $.session.start(START)
+
+ expect(await $.tool.check(web('WebFetch'))).toMatchObject({ decision: 'deny', rule: 'WebFetch(domain:evil.test)' })
+ expect(await $.tool.check(web('WebSearch'))).toMatchObject({ decision: 'ask', reason: 'mode asks' })
+ })
+
+ test('at the cost HARD_STOP the guard adds nothing', { options: { costBudgetUsd: 1 } }, async ($, on) => {
+ world(on, {}, { [MARKER]: marker() })
+ on('tool.check', () => ({ decision: 'allow' }))
+ on('session.measure', ($, e) => ({ changed: e.changed }))
+ await $.session.start(START)
+
+ await $.session.measure(measure(1.5))
+ expect((await $.tool.check(web())).decision).toBe('allow')
+ })
+})
diff --git a/v3/docs/adr/ADR-440-research-web-fetch-guard.md b/v3/docs/adr/ADR-440-research-web-fetch-guard.md
new file mode 100644
index 0000000000..84ac778183
--- /dev/null
+++ b/v3/docs/adr/ADR-440-research-web-fetch-guard.md
@@ -0,0 +1,47 @@
+# ADR 440: Research web-fetch guard
+
+Status: Proposed
+
+Date: 2026 10 04
+
+Scope: `plugins/ruflo-mods` (`hooks/guard/research.ts`, wired from `hooks/guard/index.ts`)
+
+Contract: [ADR-438](ADR-438-research-integration-contract.md) (the run marker). Companion: ADR-439 (console start and confirm).
+
+## 1. Context
+
+A deep-research run reads the open web. Fetched text is untrusted, and the run spends money. ADR-438 gives each run a marker, `.claude-flow/research-active.json`, `{ "question", "capUsd", "startedAt" }`, written by the `deep-research` skill at the start and removed at the end. The guard turns that marker into one human decision.
+
+## 2. Decision
+
+`tool.check` in `ruflo-mods` asks before the **first** `WebFetch` or `WebSearch` of a run that has a **fresh** marker, then leaves the rest of that run to the chain.
+
+- **Fresh** means the marker parses (non-empty `question`, finite `capUsd` above 0, parseable `startedAt`), and `startedAt` is less than 2 hours old and not more than 5 minutes in the future. Absent, unreadable, corrupt, malformed, old or future: no run is active and the guard does nothing. This differs on purpose from the policy projection, which fails closed: a missing marker is the normal case, not a fault.
+- The marker is read through the sandboxed `$.fs.stat` / `$.fs.read`, the same cached reader as the policy projection (re-read only when size or mtime moves; age is judged on every call).
+- The ask's reason states the question (control and bidi characters removed, 200 characters at most), the cap, and that web content is untrusted data, never instructions.
+- "Once per run" is remembered in `ModState.researchAsked` as the marker's `startedAt`. A later run has a different `startedAt` and is asked again. State is in memory only: a hot reload mid-run asks once more, which errs toward asking.
+- The ask is issued only when the verdict so far is `allow`. If the chain or ruflo's policy already says `ask` or `deny`, that verdict is returned untouched and the one-time ask is not spent.
+
+### Never loosens
+
+The result is `stricter(current, ask)`, the same arithmetic as the rest of the guard: `allow` may become `ask`; `ask` and `deny` are returned as they were, with their reason and `rule`. No other tool is touched. Any error inside the guard returns the verdict unchanged. `tool.check` may be registered once per module, so the check is a function called from the existing handler in `guard/index.ts`, after ruflo's own opinion is merged, not a second handler.
+
+### Cost budget
+
+If the session budget (`hooks/cost`) is at `HARD_STOP`, the guard adds nothing; the budget already says no.
+
+### Consequences of a "no"
+
+If the person denies the ask, the run's `startedAt` is already marked asked, so a later web call in that run is not asked again by this guard. Denial is therefore expected to end the run's web access through the person's own answer and the host's rules, not through a repeated prompt. See section 4.
+
+## 3. Tests
+
+`plugins/ruflo-mods/tests/research.test.ts`, run with `claude plugin test plugins/ruflo-mods` (the repo's own harness for these mods; vitest is not used there). Covered: first call asks and names question, cap and untrusted; the rest of the run and every other tool are allowed; a new `startedAt` asks again; absent, old, future, corrupt and malformed markers do nothing; chain `deny` and `ask` are never loosened; `HARD_STOP` adds nothing.
+
+## 4. UNVERIFIED
+
+- Whether the host re-prompts or remembers a person's "allow" for `ask` verdicts differently from this guard's own once-per-run memory.
+- What a person's "deny" does downstream: the host may keep the run going without web access, and this guard will not ask again that run (section 2).
+- That the `deep-research` skill writes and removes the marker as ADR-438 describes: that change is outside `ruflo-mods` and was not checked here.
+- Behaviour with clock changes across a run, beyond the 5 minute skew allowance.
+- Not run in a live Claude Code session; only the `claude plugin test` harness.