dream(security) (evaluated): enforce allowShell/allowNetwork/allowFileWrite in MCP policy enforcer (#5127)

* dream(security): enforce allowShell/allowNetwork/allowFileWrite in MCP policy enforcer

.harness/mcp-policy.json declares allowShell/allowNetwork/allowFileWrite:
false, but policy-enforcer.ts never read them -- decorative, on the false
premise that shell/network/filesystem access isn't reachable from this
MCP server's own tool surface. Two independent dream-cycle research
passes tonight traced the real handlers: terminal_execute (execSync),
http_fetch (raw network), hooks_fast-apply/hooks_codemod (direct
writeFileSync) all perform these operations directly inside their own
MCP tool handlers, contradicting that premise.

Adds a small, explicitly-traced MCP_TOOL_CAPABILITY table and
checkCapabilityAllowed(), wired into evaluateToolCall(), to deny calls to
those four tools when the corresponding flag is explicitly false and
RUFLO_MCP_ENFORCE_POLICY=1 is set. A tool outside the table, or a flag
left undefined, keeps today's behavior unchanged. Corrects the matching
false claim in mcp-policy.json's $comment/rationale and the module's own
docstring; regenerates manifest.json's sha256 per .harness/README.md's
documented procedure.

Scoped to the four tools traced end-to-end tonight -- the broader surface
found during research (github_* exec paths, browser_* execFileSync, more
fetch()/writeFileSync call sites, and the separate HTTP/WebSocket
dispatcher that never calls this enforcement module at all) is disclosed
as follow-up, not fixed here.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH2qNAWsw4W8Gror5vV

* dream(security): #5126 add 2026-11-26 research gist

Research gist for tonight's Dream Cycle (DEEP=security, SCAN=intelligence,swarm):
MCP policy allowShell/allowNetwork/allowFileWrite decorative-enforcement gap,
competitor comparison, hypothesis, evaluation receipt, independent adversarial
critique, Darwin skip rationale, witness, and scan findings (intelligence SONA
EWC inert for 3/5 modes; swarm PBFT leader-impersonation gap in byzantine.ts).

gh gist create unavailable (GH_TOKEN invalid, no gist MCP tool) -- committed
in-repo per established precedent since 2026-09-30.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH2qNAWsw4W8Gror5vV

* dream(security): #5126 update LEDGER for 2026-11-26

Appends tonight's row (security, #5126/#5127, ACCEPT) and a note confirming
the 2026-11-25 ledger-append gap is the same recurring cosmetic STEP 25 issue
flagged by several prior nights, not a pipeline failure (branch/PR #5112/#5113
both verified to exist via list_pull_requests).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH2qNAWsw4W8Gror5vV

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
rUvandClaude authored and GitHub committed 2026-11-26 08:34:15 -05:00
1 parent d48671d961
commit adbe1e2ff7
6 files changed
+222 -16

No files matched your search

+5 -3
View File
@@ -8,12 +8,14 @@
"description": "Ruflo — multi-agent orchestration platform built on @claude-flow/cli",
"host": "claude-code"
},
"hosts": ["claude-code"],
"hosts": [
"claude-code"
],
"files": {
".harness/mcp-policy.json": "4b4c5826c9d1cdb8bd70a5c097a1d1b9a79b2d4850fdf05149b9ea84bfefa502",
".harness/mcp-policy.json": "4c856ac6d94117a85e2fd13811e9553d9b0d9b8bf2a3607de0719c4deff1ff28",
".claude/settings.json": "ba278b1f9ccf8e170e4cef3748a6bcb4efc0850b7ec66d34690fec328fdabeb1"
},
"generated_at": "2026-06-16T20:00:00.000Z",
"generated_at": "2026-11-26T07:19:52.780Z",
"meta": {
"surface": "cli",
"adr_anchor": "ADR-150 — ruflo's metaharness integration; this manifest covers the security-relevant surface that mcp-policy.json governs"
+2 -2
View File
@@ -1,10 +1,10 @@
{
"$comment": "ADR-150 iter 30 — MCP governance policy for ruflo's claude-flow MCP server. Closes the 'no-policy' HIGH finding from `harness mcp-scan`. Configured to reflect ruflo's ACTUAL MCP-layer posture: the claude-flow MCP server exposes 314 tools that operate via higher-level abstractions (memory_*, hooks_*, agentdb_*) — NOT raw shell, network, or filesystem. Those primitives are reached via native Claude Code tools (Bash / Write / Edit / WebFetch) which are governed by Claude Code's own permission system, not this MCP policy. Hence: this policy denies all three at the MCP layer.",
"$comment": "ADR-150 iter 30 — MCP governance policy for ruflo's claude-flow MCP server. Closes the 'no-policy' HIGH finding from `harness mcp-scan`. Most of the claude-flow MCP server's 314 tools operate via higher-level abstractions (memory_*, hooks_*, agentdb_*) with no raw shell/network/filesystem access. A small named subset does not fit that pattern and performs these operations directly inside its own MCP handler: `terminal_execute` (shell, via execSync), `http_fetch` (raw outbound network), `hooks_fast-apply`/`hooks_codemod` (direct filesystem writes) — confirmed by code trace, dream-cycle 2026-11-26 (corrects an earlier version of this comment that claimed shell/network/filesystem were never reachable from this server's tool surface at all). allowShell/allowNetwork/allowFileWrite below are enforced against exactly that named subset (see MCP_TOOL_CAPABILITY in policy-enforcer.ts) once RUFLO_MCP_ENFORCE_POLICY=1 is set; the remaining ~300 pure-data tools are unaffected by these three flags either way.",
"schema": 1,
"policyVersion": 2,
"harnessId": "claude-flow",
"rationale": "ADR-022 default-deny posture. The claude-flow MCP server's tools are pure-data operations (read/write via AgentDB, route via embeddings, dispatch via hooks). Shell / network / file-write are NOT in this server's tool surface — they happen at the native-Claude-Code layer, outside this policy's jurisdiction.",
"rationale": "ADR-022 default-deny posture. Most of the claude-flow MCP server's tools are pure-data operations (read/write via AgentDB, route via embeddings, dispatch via hooks); a small, named, independently-traced subset (terminal_execute, http_fetch, hooks_fast-apply, hooks_codemod) performs shell/network/file-write directly inside this server's own tool surface and is exactly what allowShell/allowNetwork/allowFileWrite below govern — not the native-Claude-Code Bash/Write/Edit/WebFetch layer, which remains a separate, independently configured permission system.",
"defaultDeny": true,
+2
View File
@@ -289,3 +289,5 @@ as a first-class, high-priority candidate, not a background note.
**Note (2026-11-23):** direct verification tonight (`git ls-remote --heads origin "dream/*"` + `gh api search/issues` over 2026-11-19..22, both is:pr and is:issue, plus PR state checks on 2026-11-12/13/16/17/18) found: (1) a genuine 4-night no-run gap, **2026-11-19 through 11-22** — zero `dream/*` branches, zero `dream(...)` PRs, despite plenty of other repo activity those nights (releases 3.78.0→3.80.1); no in-repo cause found (checked for a workflow/scheduler/disabled-trigger artifact, found none). (2) PRs #4973 (11-12), #4983 (11-13), #5012 (11-17), #5034 (11-18) are individually `merged:false`/closed, but **not rejected** — their content (plus #4660/11-02 and two older PRs #4081/#3650) was folded into a human-driven integration PR **#5041, merged 2026-11-19T06:44:34Z** (operator comment on #5033 confirms the 11-18 fix landed via `89a00242b`). #4989 (11-14) and #5004 (11-16) merged directly/separately the same day. Net over the 10 most recent real dream-cycle nights with a PR: **0 genuinely rejected** — everything reaching evaluation either merged directly or was batch-integrated. Healthy-throughput signal, not a STEP-1.1 "zero of last 14 merged" trigger.
| 2026-11-23 | memory | `ReasoningBank.detectContradictions()` (`v3/@claude-flow/neural/src/reasoning-bank.ts`) marks the lower-quality side of a contradicting memory pair `consolidated=true`, with an explicit "to exclude from retrieval" comment — but `retrieve()`/`retrieveByContent()` never checked that flag, so a self-judged-stale/contradicted memory kept being served into every future agent trajectory forever (consolidate()'s contradiction half was a no-op beyond a `getStats()` counter). Added a `.filter(c => !c.entry.consolidated)` / `.filter(e => !e.consolidated)` in both read paths; byte-identical for any entry never flagged. Independently found by two research roles (external-literature-driven Deep Researcher citing arXiv:2606.15903's "detected-but-not-enforced" failure class, and a pure-code Architecture Reviewer) before either saw the other's output. SCAN: plugins (`PluginStoreConfig`/`code-intelligence`/`ResourceLimits` dead-config findings confirmed still open; new finding — `EnhancedPluginRegistry.resolveConflict()`'s `namespace` strategy deletes the original owner key on first collision, so a 3rd colliding plugin silently reclaims the bare name, defeating the strategy for 3+-way collisions, deferred), automation (`hooks worker dispatch --priority` confirmed still dead; worker-fabricates-work anti-pattern confirmed still fixed; new finding — `DEFAULT_WORKERS` omits 5 of 12 documented worker types (`ultralearn`/`preload`/`deepdive`/`refactor`/`benchmark`), so dispatching them silently no-ops despite being advertised everywhere, deferred) | #5081 | #5082 | yes | ACCEPT | 2 new discriminating tests, stash-isolated baseline fails both exactly as predicted (1 control passes vacuously, 3/3 total); candidate 3/3 new, full `@claude-flow/neural` suite 184/184 (181 pre-existing + 3 new), `tsc --noEmit` clean both ways; independently reproduced byte-identical by a fresh-context adversarial critic, which also independently traced production-reachability (`index.ts`, 5 live MCP hook handlers, the `consolidate` background daemon) — verdict CONFIRMED, 2 non-blocking disclosed limitations (HNSW over-fetch-then-filter can under-return `k` if the over-fetched set is mostly consolidated; `usedHnsw` stats counted before the filter, cosmetic); Darwin skipped (binary guard, no tunable parameter, precedent 11-14); `harness mcp-scan`/`threat-model` MEDIUM(3)/0-high, byte-identical to baseline | 48c5020b... | See note above (11-19..22 genuine gap; 11-12/13/14/16/17/18 all real, 0 genuinely rejected — merged directly or via integration PR #5041). Prior gist (11-18, memory) scored 10/10 (2+2+2+2+1+1) — independently confirmed implemented on `main` via #5041 per the operator's own comment on #5033 |
| 2026-11-24 | swarm | `QLearningRouter.initialize()`'s `@ruvector/core` native-engine probe (`v3/@claude-flow/cli/src/ruvector/q-learning-router.ts`) — deferred twice before (10-29, 11-14) under a "wrong package" framing — turns out to be one level deeper: `route()`/`update()` never read `this.ruvectorEngine` back at all, confirmed by 3 independent agents via full-class trace, so no package swap could ever have changed any routing decision; the only consumer anywhere is a cosmetic `route stats` CLI field. `@claude-flow/neural`'s real `createQLearning` confirmed API-incompatible (trajectory-batch vs. per-call string API) — not a same-night swap, closes the recurring thread as "design question, correctly deferred" rather than reopening a 3rd time. Removed the dead probe/field, documented why `useNative` stays permanently false. SCAN: ruview-integration (confirmed stable/no-change, independently re-verified against ADR-326 + product-plane.ts + the metaharness template list), ruvector-integration (no material change beyond the DEEP finding itself; quick sanity pass on tiny-dancer/learning-wasm/rabitq-wasm/mincut-bridge found nothing new) | #5096 | #5097 | yes | ACCEPT | 2 new tests (1 discriminating static source-guard — regex over the dead dynamic-import call, since `vitest.config.ts`'s `externalize-optional-deps` plugin prevents `vi.mock` from intercepting `@ruvector/*` dynamic imports, so a runtime spy can't discriminate here; 1 non-discriminating control proving route()/update() unaffected), stash-isolated baseline fails the discriminating test exactly as predicted → candidate 47/47; targeted related suite 437 passed/52 skipped vs baseline 435/52 (exactly +2, 0 regressions, 1 unrelated pre-existing failure identical both ways); `tsc --noEmit` 19 pre-existing errors byte-identical both ways, none in changed files; independent adversarial critique (fresh context, own stash/pop reproduction, own `require.resolve` check, own suite+tsc runs) CONFIRMED-WITH-CAVEATS — 1 non-blocking caveat (the static source-guard is a narrow regex, bypassable in principle by a differently-worded reintroduction, tracked not blocking); Darwin skipped (binary guard, no tunable parameter, precedent 11-14/11-23); `harness mcp-scan` 3 findings/0-high, byte-identical to baseline | c87edd85... | q-learning-router thread (10-29, 11-14) now closed as a correctly-deferred design question rather than reopened a 3rd time — see §1.1 duplicate-direction note above. Fate TBD next night. |
**Note (2026-11-26):** 2026-11-25 (performance, `dream/2026-11-25-performance`, #5112/#5113) has no row below — confirmed via `list_pull_requests` that the branch and PR genuinely exist (PR OPEN/draft, unreviewed) — this is the same recurring STEP 25 live-append gap flagged by several prior nights' notes (11-12/13/16/17/18), not a new pipeline failure. Over the last 6 real nights with a PR: 11-16 #5004 MERGED, 11-17 #5012 CLOSED-not-merged, 11-18 #5034 CLOSED-not-merged, 11-23 #5082 MERGED, 11-24 #5097 MERGED, 11-25 #5113 OPEN. #5012/#5034 were both closed within 2 seconds of each other on 2026-11-19, near #5004's merge — looks like a human batch-review event, not evidence those candidates were wrong. Merge rate 3/6, not zero — no STEP 1.1 forced-small-patch trigger.
| 2026-11-26 | security | `.harness/mcp-policy.json`'s `allowShell`/`allowNetwork`/`allowFileWrite:false` were purely decorative since the file was written — `policy-enforcer.ts` never read them, on the false premise (stated in both the policy's own `$comment` and the module's docstring) that shell/network/filesystem access isn't reachable from this MCP server's tool surface. Disclosed for 4 consecutive nights since 2026-10-26, never before tested — two independent research roles (Deep Researcher + Architecture Reviewer, neither saw the other's output) traced real counterexamples: `terminal_execute` (`execSync`), `http_fetch` (raw network), `hooks_fast-apply`/`hooks_codemod` (direct `writeFileSync`), all inside this MCP server's own handlers. Added a small, explicitly-traced `MCP_TOOL_CAPABILITY` table + `checkCapabilityAllowed()`, wired into `evaluateToolCall()`, denying those 4 tools when the matching flag is explicitly `false` and `RUFLO_MCP_ENFORCE_POLICY=1` is set; corrected the matching false claim in the policy file and the module docstring. Broader surface (`github-tools.ts`/`browser-tools.ts`/9 more `fetch(` files/22 more `writeFileSync` files) and the HTTP/WebSocket dispatcher (never calls this module at all) disclosed as follow-up, not fixed. SCAN: intelligence (`SONAManager`'s EWC-consolidation snapshot method implemented by only 2 of 5 SONA modes — `real-time`/`batch`/`edge` configure non-zero `ewcLambda` but never run `consolidateEWC()`, deferred), swarm (`ByzantineConsensus.handlePrePrepare()` never checks `senderId` matches the view's primary — any node's `pre-prepare` is accepted as legitimate, a PBFT leader-impersonation gap distinct from the known Raft `prevLogIndex` issue, deferred) | #5126 | #5127 | yes | ACCEPT | 12 new tests (full capability-table coverage, undefined/true-flag permissiveness, budget-isolation on denial, `memory_store` control), stash-isolated baseline fails to even load (`MCP_TOOL_CAPABILITY` undefined) → candidate 40/43 (3 pre-existing environmental failures, root-sandbox `/nonexistent-dir-xyz/` unwritable-path assumption false, reproduced identically on baseline); `tsc --noEmit` 534 pre-existing errors byte-identical both ways, 0 in changed files; independent adversarial critique (fresh context, own stash/pop reproduction, own `tsc`/mcp-scan runs, own reads of all 3 real call sites across `mcp-server.ts`/`bin/cli.js`/`bin/mcp-server.js` and all 4 tool files) CONFIRMED-WITH-CAVEATS — all non-blocking: (a) 4-tool table is narrow vs. the full traced surface, disclosed not silently safe; (c) new finding — capability denial skips budget but still forces a mandatory audit-log write, an un-rate-limited disk-write path under `auditLog:true`, tracked follow-up; (d) HTTP/WebSocket dispatcher still uncovered (pre-existing); Darwin skipped (binary guard, no tunable parameter, precedent 11-14/11-23/11-24/11-25); `harness mcp-scan`/`threat-model` MEDIUM(3)/0-high / clean, byte-identical to baseline | 29d887c8... | See note above (11-25 ledger-append gap confirmed cosmetic via `list_pull_requests`, not a pipeline failure). Prior gist (11-25, performance) scored 9/10 (2+2+2+2+1+0 — valid-looking witness, <1500 words, but a pickup of a previously-deferred 10-30 finding, not genuinely novel) |
+64
View File
@@ -0,0 +1,64 @@
# Security SOTA Report — 2026-11-26
TL;DR: `.harness/mcp-policy.json`'s `allowShell: false` / `allowNetwork: false` / `allowFileWrite: false` have been purely decorative since the policy file was written — nothing in `policy-enforcer.ts` ever read them, on the premise that shell/network/filesystem access "is NOT in this server's tool surface." Two independent research passes tonight traced the real tool handlers and found that premise false: `terminal_execute` runs `execSync` on caller-supplied input, `http_fetch` performs raw outbound HTTP(S), and `hooks_fast-apply`/`hooks_codemod` write files directly — all inside this MCP server's own ~300-tool surface, not Claude Code's separate Bash/Write/WebFetch layer. This is the fourth consecutive dream-cycle night this gap was disclosed (since 2026-10-26) and the first night it was actually fixed: `evaluateToolCall()` now denies calls to those four named tools when the corresponding flag is `false` and enforcement is opted in (`RUFLO_MCP_ENFORCE_POLICY=1`).
## What's New in 2026
| Finding | Source | Confidence |
|---|---|---|
| MCP "tool poisoning" (malicious instructions hidden in tool descriptions/schemas, not user input) is OWASP's own MCP03:2025 category and the most prevalent client-side MCP vulnerability class | OWASP MCP Top 10; arXiv:2603.21642 (7-client study); Trail of Bits (2025-04-21) | B |
| OWASP's MCP04:2025 "software supply-chain attacks" — ~3,500+ MCP servers on Smithery.ai, 92% unverified; a cloned/trojanized "Oura Ring" MCP server shipped a functionally-identical fork before activating a payload | OWASP MCP04:2025; UpGuard; Straiker/NHI Mgmt (Feb 2026) | B |
| Simon Willison's "lethal trifecta" (private-data access + untrusted-content exposure + external-comms channel) plus the MCP spec's own `security_best_practices` page, which documents tool annotations as advisory-only, not security boundaries | simonwillison.net (Jun 2025 + 2026 follow-ups); modelcontextprotocol.io spec | A |
| A March 2026 empirical study of 7 real MCP clients found very different real-world exposure to cross-tool/tool-poisoning injection under the same protocol (Claude Desktop strongest guardrails; Cursor highly susceptible) | arXiv:2603.21642 | B |
| Anthropic acknowledged a Cato Networks MCP "confused deputy" finding (Nov 2025) mapped to the spec's own named scenario; no public confirmation found of what shipped | Cato Networks (2025-11-13); MCP spec | C |
## Ruflo Current Capability
`.harness/mcp-policy.json` is a single, versioned, machine-readable governance artifact — `defaultDeny`, `allowShell`/`allowNetwork`/`allowFileWrite`, `requireApprovalForDangerous`, `auditLog`, regex `dangerousPatterns`, and wall-clock rate limiting (`maxToolCallsPerTurn`/`turnWindowMs`). Until tonight, only `auditLog` and the rate limit were actually enforced (`policy-enforcer.ts`, opt-in via `RUFLO_MCP_ENFORCE_POLICY=1`, stdio dispatch only); `allowShell`/`allowNetwork`/`allowFileWrite` were declared but never read by any enforcement branch anywhere in the codebase — confirmed by grep, the only hits were the interface declaration and a comment explaining they were "intentionally left unenforced" on the (false) premise that shell/network/filesystem access doesn't happen inside this MCP server. Tonight's fix wires those three fields against a small, explicitly-traced table (`MCP_TOOL_CAPABILITY`) of the four tools proven to need it. The already-disclosed, not-yet-fixed scope limit remains: the separate HTTP/WebSocket dispatch path (`startHttpServer()`, via `@claude-flow/mcp`) never calls this enforcement module at all, with or without the env flag.
## Competitor Comparison
| Framework | MCP / tool-authority security posture | Source | Grade |
|---|---|---|---|
| LangGraph | No native per-tool MCP authorization layer; sensitive actions gated only via the generic `interrupt()` human-in-the-loop primitive. Scoped credential issuance is filled by a third party (Arcade.dev), not shipped. | Arcade.dev; Permit.io | C |
| AutoGen / AG2 | No built-in credential broker or MCP tool-scoping; isolation is pushed to Docker/Daytona sandboxed code execution instead — a deliberate architectural choice, not an oversight. | arXiv:2509.08646; docs.ag2.ai | B |
| CrewAI | No built-in MCP authorization engine or audit log. Official docs explicitly tell users to "only connect to MCP servers you fully trust" — a named, acknowledged gap, deferred to third-party add-ons. | docs.crewai.com/MCP Security (official) | A (for the official text itself) |
| OpenAI Agents SDK | Strongest native human-in-the-loop model: `require_approval` pauses execution with resumable `RunState`. A practitioner critique notes approval ≠ authorization — no persistent re-scoping, credentials typically app-embedded. | developers.openai.com (official); independent critique | A / C |
Ruflo's own policy sits **ahead** of LangGraph/CrewAI on having a single declarative, audited policy artifact at all, roughly **at parity** with OpenAI's SDK on "require approval before dangerous actions," and **behind** it on resumable per-tool approval state. Tonight's fix closes the specific split-enforcement gap researchers name as where "advisory, not security boundary" controls get exploited: a flag that looks like it governs a capability but doesn't.
## Hypothesis
> Given the claude-flow MCP server's opt-in policy enforcement (`RUFLO_MCP_ENFORCE_POLICY=1`, `evaluateToolCall()`), where `.harness/mcp-policy.json` declares `allowShell: false` / `allowNetwork: false` / `allowFileWrite: false` but these fields are never read by any enforcement code — confirmed decorative, independently, by two research roles with file:line evidence that `terminal_execute` (shell), `http_fetch` (network), and `hooks_fast-apply`/`hooks_codemod` (filesystem) are registered MCP tools performing these operations directly — when `evaluateToolCall()` is extended to check a tool-name→capability table against the matching `allow*` flag and deny when it is explicitly `false`, then calling those four tools under the existing committed policy with enforcement enabled should be denied (which it currently is not), while every other registered tool and every existing enforcement behavior (budget, audit log, fail-closed) stays byte-identical, subject to: zero regression to the existing 31-test suite, enforcement stays fully opt-in, and a tool whose flag is left `undefined` keeps today's permissive behavior.
## Benchmarks
Vitest 4.1.8 (`@claude-flow/cli`), run directly against `src/` in a freshly-installed checkout (no `node_modules` existed at session start; `npm install` + `pnpm install` run first). Stash-isolated baseline (reverting `policy-enforcer.ts`/`mcp-policy.json`/`manifest.json`, keeping the new test file): the suite fails to even load (`MCP_TOOL_CAPABILITY` is `undefined`), a hard discriminating failure. Candidate: 40/43 pass — the 3 failures are pre-existing and environmental (tests assert `/nonexistent-dir-xyz/...` is unwritable; this sandbox runs as root, which can create that path; reproduced byte-identical on baseline too, confirmed via a direct `whoami`/`mkdirSync` probe). `tsc --noEmit -p .`: 534 pre-existing errors both before and after (unbuilt monorepo siblings), 0 in either changed file.
## Evaluation
12 new tests (capability-table coverage for all 4 tools, undefined/true-flag permissiveness, budget-isolation on a capability denial, a control proving `memory_store` is unaffected). `harness mcp-scan .` and `harness threat-model .`: MEDIUM (3 findings, 0 high) / clean — byte-identical to the standing baseline (2 pre-existing risky-bash-allow findings, 1 pre-existing unpinned-deps finding; none touch this diff).
**Independent adversarial critique** (fresh-context `reviewer` subagent, own stash/pop reproduction, own `tsc`/mcp-scan runs, own code reads): **CONFIRMED-WITH-CAVEATS**, all non-blocking. New facts it surfaced: `evaluateToolCall()` actually has 3 real call sites sharing one compiled module (`mcp-server.ts:997`, `bin/cli.js:306`, `bin/mcp-server.js:177`) — all three stdio dispatchers, confirming the module's own docstring claim rather than contradicting it. Caveats: (a) the 4-tool `MCP_TOOL_CAPABILITY` table is real but narrow — `github-tools.ts`/`browser-tools.ts` and ~25 more files with `fetch(`/`writeFileSync` are outside it, honestly disclosed, not silently safe; (c) a capability-denied call skips the budget counter but still forces a mandatory audit-log write — an un-rate-limited disk-write path when `auditLog:true`, worth its own follow-up ticket; (d) the separate HTTP/WebSocket dispatcher still never calls this module at all (pre-existing, not worsened). `defaultDeny`, `dangerousPatterns`, and `requireApprovalForDangerous` remain just as unenforced as `allowShell`/`allowNetwork`/`allowFileWrite` were before tonight — not claimed fixed.
## Darwin Results
**Skipped — binary guard, no tunable parameter**, same precedent as every recent structural/correctness fix in this ledger (11-14, 11-23, 11-24, 11-25). The fix is a fixed table of 4 tool→capability mappings resolved by direct code trace, not a continuous or categorical parameter space to search.
## SOTA Proof & Witness
```
Session commit: 48b04dce286a1df4af0411923821cf63399d7c8b
Candidate commit: 1d62958eeebfe92e8d561bf5fc790f8008c76df4
Gist SHA-256 (pre-witness): c5a85dc7c1d5e031bab480590b85d172b2a7b6450db1822128bf6461d04d20ec
Witness stamp: 29d887c85c647d62c34f747f0b56e5f82c858d03c7fd8082c18095d1b162ac58
```
Verifier: fetch this file from the branch, replace the Gist SHA-256 and Witness stamp fields above with the literal text `PENDING`, SHA-256 the result, concatenate with the Session commit value, SHA-256 again — must equal the Witness stamp.
## Recommended Next Steps
1. **Extend `MCP_TOOL_CAPABILITY` to the broader traced surface.** Tonight's research found more direct shell/network/filesystem call sites inside MCP handlers than the 4 fixed tonight: `github-tools.ts`'s `execSync`/`execFileSync`, `browser-tools.ts`'s `execFileSync`, `auto-install.ts`'s `spawnSync`, `memory-tools.ts`'s git `execFileSync`, `metaharness-tools.ts`/`testgen-tools.ts`'s `spawn`, plus 9 files with raw `fetch(` and 22 with raw filesystem writes. Each needs its own capability classification and risk judgment — not safe to batch into one patch.
2. **Wire enforcement into the HTTP/WebSocket MCP dispatcher.** `startHttpServer()` (via `@claude-flow/mcp`) never calls `evaluateToolCall()` at all, with or without `RUFLO_MCP_ENFORCE_POLICY=1` — a disclosed, pre-existing gap, now more consequential since the stdio path actually enforces something real.
3. **PBFT leader-impersonation gap in `byzantine.ts:325-329`** (found tonight by the swarm SCAN, not implemented): `handlePrePrepare()` validates `viewNumber` but never checks `message.senderId` matches the primary computed for that view — any node can broadcast a `pre-prepare` and every receiver accepts it as legitimate. Distinct from the already-known Raft `prevLogIndex` gap; a strong next DEEP=security or DEEP=swarm candidate.
**Scan findings (disclosed, not implemented tonight):** intelligence — `SONAManager`'s EWC-consolidation snapshot method (`getConsolidationSnapshot()`) is implemented by only 2 of 5 SONA modes (`balanced`, `research`); `real-time`, `batch`, and `edge` configure a non-zero `ewcLambda` but never actually run `consolidateEWC()` — catastrophic-forgetting prevention is inert for the lowest-latency modes. swarm — see Recommendation #3 above.
@@ -21,6 +21,8 @@ import {
checkAndRecordCall,
appendAuditLog,
evaluateToolCall,
checkCapabilityAllowed,
MCP_TOOL_CAPABILITY,
resetPolicyEnforcerState,
setAuditLogPathForTesting,
getAuditLogPath,
@@ -269,6 +271,76 @@ describe('evaluateToolCall — single enforcement entry point (fail-closed)', ()
});
});
describe('checkCapabilityAllowed — allowShell/allowNetwork/allowFileWrite (dream-cycle 2026-11-26)', () => {
it('allows a tool outside MCP_TOOL_CAPABILITY regardless of policy flags', () => {
const policy: McpPolicy = { allowShell: false, allowNetwork: false, allowFileWrite: false };
expect(checkCapabilityAllowed(policy, 'memory_store').allowed).toBe(true);
});
it('allows a known tool when its flag is left undefined (no behavior change absent an explicit false)', () => {
expect(checkCapabilityAllowed({}, 'terminal_execute').allowed).toBe(true);
});
it('allows a known tool when its flag is explicitly true', () => {
expect(checkCapabilityAllowed({ allowShell: true }, 'terminal_execute').allowed).toBe(true);
});
it.each(Object.entries(MCP_TOOL_CAPABILITY))(
'denies %s when its capability (%s) flag is explicitly false, with a reason naming the field and tool',
(toolName, capability) => {
const field = { shell: 'allowShell', network: 'allowNetwork', fileWrite: 'allowFileWrite' }[capability] as string;
const result = checkCapabilityAllowed({ [field]: false } as McpPolicy, toolName);
expect(result.allowed).toBe(false);
expect(result.reason).toContain(field);
expect(result.reason).toContain(toolName);
},
);
it('does not cross-wire capabilities: denying allowShell does not deny a fileWrite tool', () => {
expect(checkCapabilityAllowed({ allowShell: false }, 'hooks_codemod').allowed).toBe(true);
});
});
describe('evaluateToolCall — capability denial (dream-cycle 2026-11-26)', () => {
let logFile: string;
beforeEach(() => {
resetPolicyEnforcerState();
logFile = path.join(os.tmpdir(), `mcp-audit-cap-${Date.now()}-${Math.random()}.jsonl`);
setAuditLogPathForTesting(logFile);
});
afterEach(() => {
setAuditLogPathForTesting(null);
if (fs.existsSync(logFile)) fs.unlinkSync(logFile);
});
it('denies terminal_execute under the committed .harness/mcp-policy.json shape (allowShell:false) even though budget would allow it', () => {
const policy: McpPolicy = { auditLog: true, allowShell: false, maxToolCallsPerTurn: 5 };
const result = evaluateToolCall(policy, 's1', 'terminal_execute');
expect(result.allowed).toBe(false);
expect(result.reason).toMatch(/allowShell is false/);
const lines = fs.readFileSync(logFile, 'utf-8').trim().split('\n');
expect(lines).toHaveLength(1);
expect(JSON.parse(lines[0]).allowed).toBe(false);
});
it('does not consume turn budget on a capability denial — the next unrelated call still has its full budget', () => {
const policy: McpPolicy = { allowShell: false, maxToolCallsPerTurn: 1 };
expect(evaluateToolCall(policy, 's1', 'terminal_execute').allowed).toBe(false);
// memory_store is unaffected by allowShell and should still get its one slot.
expect(evaluateToolCall(policy, 's1', 'memory_store').allowed).toBe(true);
});
it('leaves every other registered tool byte-identical: memory_store still allowed with all three capability flags false', () => {
const policy: McpPolicy = { allowShell: false, allowNetwork: false, allowFileWrite: false, maxToolCallsPerTurn: 5 };
expect(evaluateToolCall(policy, 's1', 'memory_store').allowed).toBe(true);
});
it('allows terminal_execute once allowShell is true (opt-in capability, not a new hardcoded deny)', () => {
const policy: McpPolicy = { allowShell: true, maxToolCallsPerTurn: 5 };
expect(evaluateToolCall(policy, 's1', 'terminal_execute').allowed).toBe(true);
});
});
describe('getAuditLogPath', () => {
afterEach(() => setAuditLogPathForTesting(null));
it('defaults to the current project log directory', () => {
@@ -8,15 +8,26 @@
* live `tools/call` dispatch never consulted it. Any connected MCP client
* could call every registered tool with no audit trail and no call budget.
*
* This module wires the two policy fields that are actually in this
* server's jurisdiction, per the policy file's own rationale comment
* (`dangerousPatterns` / `allowShell` / `allowNetwork` / `allowFileWrite`
* describe the native-Claude-Code-tool layer — Bash/Write/Edit/WebFetch —
* not this MCP server's memory_-, hooks_-, agentdb_-prefixed tool surface,
* so they are intentionally left unenforced here):
* This module wires the policy fields that are actually in this server's
* jurisdiction:
* - `auditLog`: append a JSONL record for every `tools/call`.
* - `maxToolCallsPerTurn`: bound calls per MCP *session* (one stdio
* process lifetime), deny once exceeded.
* - `allowShell` / `allowNetwork` / `allowFileWrite` (dream-cycle
* 2026-11-26): deny a call when the tool is listed in
* `MCP_TOOL_CAPABILITY` below — proven, by two independent research
* passes that traced the call chain file:line, to perform that
* capability directly inside its own MCP handler — and the
* corresponding flag is explicitly `false`. Earlier revisions of this
* module claimed these three fields describe only the native-Claude-
* Code-tool layer (Bash/Write/Edit/WebFetch) and were "intentionally
* left unenforced" here on that basis; that premise was false
* (`terminal_execute` runs `execSync` on caller-supplied input,
* `http_fetch` performs raw outbound HTTP(S), `hooks_fast-apply` and
* `hooks_codemod` write files directly — all inside this MCP server's
* own tool surface, not Claude Code's). Scoped to the tools actually
* traced end-to-end tonight; a tool not in `MCP_TOOL_CAPABILITY` is
* unaffected by these three flags, same as before.
*
* Fully opt-in via `RUFLO_MCP_ENFORCE_POLICY=1` (or `true`). Unset/false
* means every function below is a no-op on the hot path — the pre-existing
@@ -73,6 +84,12 @@ export interface McpPolicy {
/** Rotated segments retained in addition to the active log. Default 5, maximum 100. */
auditLogMaxFiles?: number;
requireApprovalForDangerous?: boolean;
/** Deny tools in `MCP_TOOL_CAPABILITY` whose capability is 'shell', when explicitly `false`. */
allowShell?: boolean;
/** Deny tools in `MCP_TOOL_CAPABILITY` whose capability is 'network', when explicitly `false`. */
allowNetwork?: boolean;
/** Deny tools in `MCP_TOOL_CAPABILITY` whose capability is 'fileWrite', when explicitly `false`. */
allowFileWrite?: boolean;
toolTimeoutMs?: number;
/**
* Despite the name, this is a WALL-CLOCK rate limit, not a literal
@@ -127,6 +144,51 @@ export interface PolicyCheckResult {
reason?: string;
}
export type McpToolCapability = 'shell' | 'network' | 'fileWrite';
/**
* Tool name -> capability it is proven (dream-cycle 2026-11-26, two
* independent research passes, file:line traced) to exercise directly
* inside its own MCP handler: `terminal_execute` (`execSync` on
* caller-supplied input), `http_fetch` (raw outbound HTTP/S), and
* `hooks_fast-apply`/`hooks_codemod` (direct `writeFileSync`). This is
* deliberately the narrow, traced subset, not every tool the broader scan
* also turned up (github_*, browser_*, several more exec/fetch call
* sites) — those are a disclosed, not-yet-audited follow-up, not implied
* safe by omission from this table.
*/
export const MCP_TOOL_CAPABILITY: Readonly<Record<string, McpToolCapability>> = Object.freeze({
terminal_execute: 'shell',
http_fetch: 'network',
'hooks_fast-apply': 'fileWrite',
hooks_codemod: 'fileWrite',
});
const CAPABILITY_POLICY_FIELD: Readonly<Record<McpToolCapability, 'allowShell' | 'allowNetwork' | 'allowFileWrite'>> =
Object.freeze({
shell: 'allowShell',
network: 'allowNetwork',
fileWrite: 'allowFileWrite',
});
/**
* Denies a call only when `toolName` is in `MCP_TOOL_CAPABILITY` AND the
* matching `allow*` flag is explicitly `false`. A tool outside the table,
* or a flag left `undefined`, is unaffected — this closes the gap for the
* specific tools proven to need it; it does not invent a new default-deny
* posture for the rest of the ~300-tool surface.
*/
export function checkCapabilityAllowed(policy: McpPolicy, toolName: string): PolicyCheckResult {
const capability = MCP_TOOL_CAPABILITY[toolName];
if (!capability) return { allowed: true };
const field = CAPABILITY_POLICY_FIELD[capability];
if (policy[field] !== false) return { allowed: true };
return {
allowed: false,
reason: `policy.${field} is false and '${toolName}' performs direct ${capability} access`,
};
}
/**
* Checks (and, if allowed, records) a tool call against
* `policy.maxToolCallsPerTurn`, counted over a sliding window of
@@ -259,10 +321,13 @@ export function appendAuditLog(policy: McpPolicy, entry: AuditLogEntry): boolean
/**
* Single enforcement entry point for a `tools/call` dispatch. Combines, in
* order: fail-closed on a missing/malformed policy, the per-session call
* budget, and fail-closed on a failed mandatory audit-log write. `policy`
* is the result of `loadMcpPolicy()` — pass `null` straight through when it
* failed to load, rather than re-deciding that here.
* order: fail-closed on a missing/malformed policy, the `allowShell`/
* `allowNetwork`/`allowFileWrite` capability check (`checkCapabilityAllowed`),
* the per-session call budget, and fail-closed on a failed mandatory
* audit-log write. A capability denial skips the budget check entirely —
* it is not counted against `maxToolCallsPerTurn`. `policy` is the result
* of `loadMcpPolicy()` — pass `null` straight through when it failed to
* load, rather than re-deciding that here.
*/
export function evaluateToolCall(
policy: McpPolicy | null,
@@ -277,7 +342,8 @@ export function evaluateToolCall(
};
}
const budget = checkAndRecordCall(policy, sessionId, now);
const capability = checkCapabilityAllowed(policy, toolName);
const budget = capability.allowed ? checkAndRecordCall(policy, sessionId, now) : capability;
const auditOk = appendAuditLog(policy, {
timestamp: new Date(now).toISOString(),
sessionId,