Skip to content

Instantly share code, notes, and snippets.

@ruvnet
Created May 19, 2026 02:08
Show Gist options
  • Select an option

  • Save ruvnet/05bc60cc7d5a91a1acc8938ec0af7d07 to your computer and use it in GitHub Desktop.

Select an option

Save ruvnet/05bc60cc7d5a91a1acc8938ec0af7d07 to your computer and use it in GitHub Desktop.
RuFlo Graph Intelligence Engine — ruflo-graph-intelligence@0.1.0-alpha.1 (ADR-123)

RuFlo Graph Intelligence Engine — ruflo-graph-intelligence@0.1.0-alpha.1

Real-time relationship intelligence with complexity-aware execution. Built on sublinear-time-solver@1.7.0. 12 graph wedges, signed reasoning artifacts, federation-distributable PageRank vectors. 104/104 tests. MIT.

Introduction

Most AI memory systems recompute everything. RuFlo computes only what changed enough to matter — and only at the depth the runtime can afford.

This release adds two new layers to the RuFlo substrate:

Layer What it does
Graph Intelligence Relationship reasoning over eleven live RuFlo graphs (causal, trust, knowledge, RAG, cost, span, suspicion, import, MCTS, agent-transition, HNSW) via single-entry personalized PageRank in O(log n)
Complexity Runtime governance — every MCP call accepts a maxComplexityClass budget gate (12 tiers from constant to unbounded); edge devices use is_edge_safe() to reject unsafe workloads

Together they make ruflo the first agent platform where intelligence understands its own computational cost — not as marketing copy, but as a typed runtime contract every call negotiates against.

Why this matters operationally

Every team running agents has hit one of these:

  • cost overruns from runaway compute
  • runaway agents that don't know when to stop
  • browser UIs that freeze on heavy reasoning
  • edge / battery / Pi-class devices that can't afford full graphs
  • federation peers that can't negotiate compute budgets
  • distributed systems where state changes faster than full re-solves can complete

maxComplexityClass is computational QoS for intelligence systems. Agents request bounded computation, edge devices reject unsafe workloads, browsers stay responsive, federation peers negotiate budgets. Contract enforcement is on the solver, not on hopeful retry-and-cancel scaffolding.

Features

Core

  • 6 MCP tools under sublinear/*: page-rank-entry / solve / solve-on-change / analyze / feasibility / jl-embed
  • Every tool accepts maxComplexityClass + coherenceThreshold
  • 12-tier ComplexityClass enum with fitsBudget() + is_edge_safe() helpers
  • Structured error taxonomy (complexity-budget-exceeded, coherence-rejected, etc.)

Eleven wedges across RuFlo

  1. Browser causal-recovery — selector-break PR scoring (ADR-122 Phase 2)
  2. MCTS branch value — global PR augment for UCT (ADR-122 Phase 4)
  3. Federation trust — transitive trust closure for peer mesh
  4. Knowledge-graph importance — entity PR over kg-extract graphs
  5. RAG personalized PR — query-seeded retrieval over chunk graphs
  6. Cost attribution — root-cause spend tracking through agent → MCP → model
  7. Trace span influence — slow-span attribution in O(log spans)
  8. Portfolio mean-variance — SPD covariance → CG solve (40-60× vs Neumann)
  9. GOAP feasibility LP — pre-flight check before A* search
  10. AIDefence suspicion — reverse-direction call-graph PR
  11. Jujutsu blast-radius — file-import PR for PR-time impact scoring

Beyond SOTA

  • Wedge 12 streamingsolve_on_change over append-only event streams. Federation deltas, span streams, cost spend events, AIDefence flag updates all become O(nnz(δ) · log N) per event instead of full re-solves.
  • Signed PR artifacts (Phase 7) — Ed25519 envelopes embedding complexity_class + coherence_score + resultHash echoes. Verification covers provenance + budget compliance + input stability.
  • Federation distribution (Phase 8) — 4 wire message types over ADR-104. Peers exchange precomputed PR vectors with cryptographic provenance; consumers verify against trust list and fall back to local recompute on stale/untrusted responses.

Installation

npm install ruflo-graph-intelligence

or

npx ruflo-graph-intelligence

Usage — Practical

1. Score causal-graph brittleness (browser self-healing)

import {
  registerBrowserCausalAdapter,
  graphIntelligenceTools,
} from 'ruflo-graph-intelligence';

// At browser-plugin init time:
registerBrowserCausalAdapter({
  origin: 'https://example.com',
  source: causalRecoveryService, // ADR-122 Phase 2
});

// Anywhere downstream:
const tool = graphIntelligenceTools.find(t => t.name === 'sublinear/page-rank-entry')!;
const r = await tool.handler({
  graphId: 'browser:causal:https://example.com',
  nodeId: '@e3',
  alpha: 0.85,
  maxComplexityClass: 'logarithmic',  // tier-1, $0 budget
});
console.log(r.result.score);  // brittleness score in [0,1]
console.log(r.result.complexityClass);  // 'logarithmic' if within budget

2. Federation peer trust closure

import {
  registerFederationTrustAdapter,
  FEDERATION_TRUST_GRAPH_ID,
} from 'ruflo-graph-intelligence';

registerFederationTrustAdapter({ source: peerMeshService });

// "How much do I transitively trust peer C?"
const trust = await tool.handler({
  graphId: FEDERATION_TRUST_GRAPH_ID,
  nodeId: 'peer-C',
  alpha: 0.7,
  maxComplexityClass: 'sublinear',  // edge-safe budget
});

3. Cost attribution — which root prompt cost the most?

import { registerCostAttributionAdapter } from 'ruflo-graph-intelligence';

registerCostAttributionAdapter({
  sessionId: 's-2026-05-19',
  source: costTrackerService,
});

// Returns the share of downstream spend attributable to root prompt
const blame = await tool.handler({
  graphId: 'ruflo-cost-tracker:causation:s-2026-05-19',
  nodeId: 'prompt-root',
  seedNodes: ['prompt-root'],   // personalized PR from this prompt outward
  alpha: 0.85,
});

4. Knowledge graph importance — which entity is most central?

import {
  registerKnowledgeGraphAdapter,
  KNOWLEDGE_GRAPH_ID,
} from 'ruflo-graph-intelligence';

registerKnowledgeGraphAdapter({ source: kgService });

const importance = await tool.handler({
  graphId: KNOWLEDGE_GRAPH_ID,
  nodeId: 'Claude',
  alpha: 0.85,
});

5. Portfolio mean-variance via sublinear CG

import {
  registerPortfolioCovarianceAdapter,
  portfolioGraphId,
} from 'ruflo-graph-intelligence';

registerPortfolioCovarianceAdapter({
  portfolioId: 'tech-only',
  ridge: 1e-4,
  source: traderService,
});

const solveTool = graphIntelligenceTools.find(t => t.name === 'sublinear/solve')!;
const r = await solveTool.handler({
  graphId: portfolioGraphId('tech-only'),
  rhs: [0.08, 0.09, 0.10, 0.07],  // expected returns μ
  algorithm: 'cg',
});
console.log(r.result.x);  // optimal portfolio weights

Usage — Streaming (Wedge 12)

Continuous trust updates without full re-solve

import { StreamingBridge } from 'ruflo-graph-intelligence';

const bridge = new StreamingBridge({
  adapter: federationTrustAdapter,
  initialRhs: peerMesh.everyone.map(() => 1 / peerMesh.everyone.length),
  algorithm: 'cg',
  maxComplexityClass: 'sublinear',
  deltaRatioThreshold: 0.05,   // 5% — go full re-solve if δ density exceeds
  refreshEvery: 50,
});

await bridge.coldStart();

// Each new trust update is now O(nnz(δ) · log N):
peerMesh.onTrustEdgeUpdate(async (event) => {
  const update = await bridge.pushDelta({
    indices: [event.peerIndex],
    values: [event.deltaWeight],
  });
  console.log(update.mode);  // 'delta' or 'full-resolve'
});

Usage — Exotic

1. Federation-distributable signed PR vectors

import {
  FederationServer,
  FederationClient,
  generateWitnessKey,
} from 'ruflo-graph-intelligence';

// Producer side (installation that holds the canonical graph):
const witnessKey = generateWitnessKey();
const server = new FederationServer({
  installationId: 'compliance-org-A',
  witnessKey,
  witnessKeyId: 'key-v2026',
  transport: adr104Transport,  // your real ADR-104 transport
  rateLimitPerPeerPerMinute: 30,
});
server.start();

// Consumer side (peer that wants a precomputed PR with provenance):
const client = new FederationClient({
  installationId: 'compliance-org-B',
  transport: adr104Transport,
  trustedPublicKeys: [witnessKey.publicKeyHex],  // explicit trust
});

const result = await client.fetchPageRank({
  peer: 'compliance-org-A',
  graphId: 'ruflo-knowledge-graph:entities',
  nodeId: 'AAPL',
  lastKnownGraphHash: localGraphHash,  // stale-detection
});

if (result.origin === 'peer') {
  console.log('verifiable PR from peer:', result.verification);
} else {
  console.log('fell back:', result.origin, result.fallbackReason);
}

2. Audit-grade compliance reasoning

The signed envelope carries everything an auditor needs to replay the computation independently:

  • installationId + witnessKeyId — who computed it, with which key
  • graphHash + graphTimestamp — the input the computation was over
  • algorithm / alpha / epsilon / queryNode / seedNodes — the exact query
  • complexityClass — the budget actually used
  • coherenceScore — the input's DD-margin (stability of the math)
  • resultHash — fingerprint of the score itself

An auditor — or a regulator, or a federation peer that doesn't trust the producer — replays single-entry forward-push over the same input and confirms the bytes match. No SNARK needed: the algorithm is public, the inputs are content-addressable, the only secret is the signing key (and the signature proves authorship without revealing it).

3. Cross-installation knowledge-graph sharing

Three organizations each maintain a partial knowledge graph. Each periodically computes signed PR vectors over its own graph and publishes them through the federation transport. Any peer can:

  • request a fresh PR vector with cryptographic provenance
  • verify the producer's identity via the witness public key
  • detect if the graph has drifted since their last cached version (graphHash mismatch)
  • fall back gracefully to local recompute on any verification or staleness failure

No competing memory framework (LangGraph, AutoGen, Letta, MemGPT, Mem0, HippoRAG) ships verifiable + federation-distributable graph-reasoning artifacts.

4. Edge-AI deployment with strict complexity budgets

// Pi Zero / Cloudflare Worker context:
import { isEdgeSafe } from 'ruflo-graph-intelligence';

const r = await tool.handler({
  graphId: 'ruflo-knowledge-graph:entities',
  nodeId: 'Claude',
  maxComplexityClass: 'polylogarithmic', // is_edge_safe() = true
  coherenceThreshold: 0.1,                // reject ambiguous inputs
});

if (!r.success && r.error?.kind === 'complexity-budget-exceeded') {
  // Graceful degradation: shed work back to a stronger node
  return shedToCloud(r);
}

5. Real-time MCTS branch value (ADR-122 Phase 4)

Augment the existing UCT formula in @claude-flow/browser Phase 4 MctsExplorer with a global PageRank computed over the MCTS tree itself, queried single-entry:

// Composing ADR-122 Phase 4 + ADR-123:
const localScore = productionUct(branch, weights);  // ADR-122 Phase 7
const globalValue = await tool.handler({
  graphId: 'browser:mcts:' + runId,
  nodeId: branch.id,
  alpha: 0.9,
  maxComplexityClass: 'sublinear',
});
const composite = localScore + λ_global * globalValue.result.score;

Architecture

┌──────────────────────────────────────────────────────────────────┐
│  11 owning plugins  (browser • federation • KG • RAG • cost ...)│
└─────────────────────────┬────────────────────────────────────────┘
                          │ exportAsSparseMatrix(opts) — adapter contract
                          ▼
┌──────────────────────────────────────────────────────────────────┐
│  ruflo-graph-intelligence                                        │
│  - 6 MCP tools (sublinear/*)                                     │
│  - SublinearAdapter registry                                     │
│  - solver-bridge (forward-push, CG, Neumann, solve_on_change)   │
│  - StreamingBridge (Wedge 12)                                    │
│  - witness-signer + signed PR envelope (Phase 7)                 │
│  - FederationServer/Client + protocol (Phase 8)                  │
└─────────────────────────┬────────────────────────────────────────┘
                          │ npx sublinear-time-solver@1.7.0
                          ▼
┌──────────────────────────────────────────────────────────────────┐
│  sublinear-time-solver  —  Rust + WASM                          │
│  - 12-tier ComplexityClass + is_edge_safe()                      │
│  - Coherence gate (DD margin check)                              │
│  - solve_on_change incremental solver                            │
│  - Forward-push / Backward-push / Bidirectional                  │
└──────────────────────────────────────────────────────────────────┘

Performance

Sub-millisecond for every primitive on representative test matrices. Detailed benchmarks coming in 0.2.0-alpha.1; baselines from the underlying sublinear-time-solver@1.7.0 release benchmark:

Operation Performance (n=256)
Optimized CG 816 ns (40-60× faster than Neumann on SPD inputs)
Single-entry forward-push O(log N) per query on DD inputs
Incremental solve_on_change O(nnz(δ) · log N) per event

Test status

  • 104/104 passing (11 test files)
  • TypeScript strict, tsc --noEmit clean
  • CI guard added in .github/workflows/v3-ci.yml
  • Published: ruflo-graph-intelligence@0.1.0-alpha.1 (latest + alpha)
  • Fresh install smoke confirms all 12 phase exports load + tools are functional

References

🤖 Built with RuFlo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment