π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(graph-intelligence): #2044 ADR-123 Phase 8 β federation distribution of signed PR vectors
ruv3cec3bf94a0f
diff --git a/plugins/ruflo-graph-intelligence/src/application/federation-client.ts b/plugins/ruflo-graph-intelligence/src/application/federation-client.tsnew file mode 100644index 0000000000..0f8feae0b6--- /dev/null+++ b/plugins/ruflo-graph-intelligence/src/application/federation-client.ts@@ -0,0 +1,147 @@+/**+ * Federation Client for PR Artifacts (Phase 8 β beyond-SOTA, ADR-123)+ *+ * Sends `pr_artifact_request` to peers, verifies inbound `pr_artifact_response`+ * envelopes via Phase 7 verifier with the consumer's trust list, falls back+ * to local recompute on stale/untrusted responses.+ */++import { verifyArtifact } from '../infrastructure/witness-signer.js';+import { runPageRank } from '../infrastructure/solver-bridge.js';+import { getRegistry } from '../domain/adapter.js';+import type {+ FederationMessage,+ FederationTransport,+ PrArtifactRequest,+ PrArtifactResponse,+ PrArtifactStale,+} from '../domain/federation-protocol.js';+import type { ArtifactVerificationResult } from '../domain/signed-artifact.js';+import type { PageRankResult } from '../domain/types.js';++export interface FederationClientOptions {+ installationId: string;+ transport: FederationTransport;+ /** Public keys we trust. Empty = trust any valid signature. */+ trustedPublicKeys?: string[];+}++export interface FetchPrResult {+ /** How the result was obtained. */+ origin: 'peer' | 'local-fallback' | 'stale-fallback' | 'untrusted-fallback';+ result: PageRankResult;+ /** If origin === 'peer', the verification report. */+ verification?: ArtifactVerificationResult;+ /** Optional reason when we fell back. */+ fallbackReason?: string;+}++export class FederationClient {+ private readonly installationId: string;+ private readonly transport: FederationTransport;+ private readonly trustedPublicKeys: string[];++ constructor(options: FederationClientOptions) {+ this.installationId = options.installationId;+ this.transport = options.transport;+ this.trustedPublicKeys = options.trustedPublicKeys ?? [];+ }++ /**+ * Fetch a single-entry PR score for `nodeId` over `graphId`. Tries the+ * peer first; on stale/untrusted/missing, falls back to local recompute.+ */+ async fetchPageRank(input: {+ peer: string;+ graphId: string;+ nodeId: string;+ alpha?: number;+ epsilon?: number;+ seedNodes?: string[];+ lastKnownGraphHash?: string;+ lastKnownResultHash?: string;+ }): Promise<FetchPrResult> {+ const request: PrArtifactRequest = {+ type: 'pr_artifact_request',+ fromInstallation: this.installationId,+ graphId: input.graphId,+ queryNode: input.nodeId,+ alpha: input.alpha ?? 0.85,+ epsilon: input.epsilon ?? 1e-3,+ seedNodes: input.seedNodes ?? [],+ lastKnownGraphHash: input.lastKnownGraphHash,+ lastKnownResultHash: input.lastKnownResultHash,+ };+ const response = await this.transport.send(input.peer, request);+ if (response && response.type === 'pr_artifact_response') {+ const verification = verifyArtifact(response.envelope, {+ trustedPublicKeys: this.trustedPublicKeys.length > 0 ? this.trustedPublicKeys : undefined,+ });+ if (verification.valid) {+ return {+ origin: 'peer',+ result: response.envelope.payload.result,+ verification,+ };+ }+ return {+ origin: 'untrusted-fallback',+ result: await this.localCompute(input),+ verification,+ fallbackReason: verification.reason ?? 'verification failed',+ };+ }+ if (response && response.type === 'pr_artifact_stale') {+ return {+ origin: 'stale-fallback',+ result: await this.localCompute(input),+ fallbackReason: response.reason,+ };+ }+ // No usable response+ return {+ origin: 'local-fallback',+ result: await this.localCompute(input),+ fallbackReason: 'no usable response from peer',+ };+ }++ private async localCompute(input: {+ graphId: string;+ nodeId: string;+ alpha?: number;+ epsilon?: number;+ seedNodes?: string[];+ }): Promise<PageRankResult> {+ const adapter = getRegistry().get(input.graphId);+ if (!adapter) {+ throw new Error(`localCompute: no adapter for graphId=${input.graphId}`);+ }+ const matrix = await adapter.exportAsSparseMatrix();+ return runPageRank(matrix, {+ graphId: input.graphId,+ nodeId: input.nodeId,+ alpha: input.alpha ?? 0.85,+ epsilon: input.epsilon ?? 1e-3,+ seedNodes: input.seedNodes ?? [],+ maxComplexityClass: 'polynomial',+ coherenceThreshold: 0,+ });+ }+}++/**+ * Helper: an in-process transport stitching a client to a server. Useful for+ * testing the Phase 8 round-trip without spinning up real ADR-104 wiring.+ */+export function inProcessTransport(server: { handle: (msg: FederationMessage) => Promise<FederationMessage | null> }): FederationTransport {+ return {+ async send(_to, msg) {+ return server.handle(msg);+ },+ onMessage() {+ // not used in the in-process variant+ return () => {};+ },+ };+}diff --git a/plugins/ruflo-graph-intelligence/src/application/federation-server.ts b/plugins/ruflo-graph-intelligence/src/application/federation-server.tsnew file mode 100644index 0000000000..b73b7781d8--- /dev/null+++ b/plugins/ruflo-graph-intelligence/src/application/federation-server.ts@@ -0,0 +1,158 @@+/**+ * Federation Server for PR Artifacts (Phase 8 β beyond-SOTA, ADR-123)+ *+ * Receives `pr_artifact_request` messages and serves either a fresh signed+ * artifact (if the holder has one cached or computes one on demand) or a+ * stale-rejection. The server uses Phase 7's sealArtifact for signing and+ * Phase 2-6 adapters for graph access.+ *+ * Pluggable via FederationTransport so ADR-104's real wire layer fits in+ * unchanged.+ */++import { sealArtifact, type WitnessKey } from '../infrastructure/witness-signer.js';+import { runPageRank } from '../infrastructure/solver-bridge.js';+import { getRegistry } from '../domain/adapter.js';+import type {+ FederationMessage,+ FederationTransport,+ PrArtifactRequest,+ PrArtifactResponse,+ PrArtifactStale,+} from '../domain/federation-protocol.js';++export interface FederationServerOptions {+ installationId: string;+ witnessKey: WitnessKey;+ witnessKeyId: string;+ transport: FederationTransport;+ /** Per-graph rate-limit budget β requests per peer per minute. */+ rateLimitPerPeerPerMinute?: number;+}++interface RateBucket {+ count: number;+ resetAt: number;+}++export class FederationServer {+ private readonly installationId: string;+ private readonly witnessKey: WitnessKey;+ private readonly witnessKeyId: string;+ private readonly transport: FederationTransport;+ private readonly rateLimit: number;+ private rateBuckets = new Map<string, RateBucket>();+ private unsubscribe?: () => void;++ constructor(options: FederationServerOptions) {+ this.installationId = options.installationId;+ this.witnessKey = options.witnessKey;+ this.witnessKeyId = options.witnessKeyId;+ this.transport = options.transport;+ this.rateLimit = options.rateLimitPerPeerPerMinute ?? 60;+ }++ start(): void {+ this.unsubscribe = this.transport.onMessage((m) => this.handle(m));+ }++ stop(): void {+ this.unsubscribe?.();+ }++ /** Public test seam β handles a single inbound message. */+ async handle(msg: FederationMessage): Promise<FederationMessage | null> {+ if (msg.type !== 'pr_artifact_request') return null;+ return this.handleRequest(msg);+ }++ private async handleRequest(req: PrArtifactRequest): Promise<FederationMessage> {+ // Rate-limit per peer+ if (!this.checkRate(req.fromInstallation)) {+ return {+ type: 'pr_artifact_stale',+ fromInstallation: this.installationId,+ graphId: req.graphId,+ currentGraphHash: 'rate-limited'.padEnd(64, '0'),+ reason: 'rate limit exceeded',+ } satisfies PrArtifactStale;+ }++ const adapter = getRegistry().get(req.graphId);+ if (!adapter) {+ return {+ type: 'pr_artifact_stale',+ fromInstallation: this.installationId,+ graphId: req.graphId,+ currentGraphHash: '0'.repeat(64),+ reason: `no adapter for graphId=${req.graphId}`,+ } satisfies PrArtifactStale;+ }++ const matrix = await adapter.exportAsSparseMatrix();+ const currentGraphHash = matrix.contentHash ?? '0'.repeat(64);++ // Stale-check: if the requester's lastKnownGraphHash differs, send stale+ if (req.lastKnownGraphHash && req.lastKnownGraphHash !== currentGraphHash) {+ return {+ type: 'pr_artifact_stale',+ fromInstallation: this.installationId,+ graphId: req.graphId,+ currentGraphHash,+ reason: 'graph has changed since requester last cached',+ } satisfies PrArtifactStale;+ }++ if (!req.queryNode) {+ return {+ type: 'pr_artifact_stale',+ fromInstallation: this.installationId,+ graphId: req.graphId,+ currentGraphHash,+ reason: 'full-vector requests not yet supported (Phase 8 only)',+ } satisfies PrArtifactStale;+ }++ // Compute and seal+ const prResult = runPageRank(matrix, {+ graphId: req.graphId,+ nodeId: req.queryNode,+ alpha: req.alpha,+ epsilon: req.epsilon,+ seedNodes: req.seedNodes,+ maxComplexityClass: 'polynomial',+ coherenceThreshold: 0,+ });+ const { envelope } = sealArtifact({+ installationId: this.installationId,+ witnessKeyId: this.witnessKeyId,+ graphId: req.graphId,+ graphHash: currentGraphHash,+ graphTimestamp: matrix.capturedAt,+ algorithm: 'forward-push',+ alpha: req.alpha,+ epsilon: req.epsilon,+ queryNode: req.queryNode,+ seedNodes: req.seedNodes,+ result: prResult,+ witnessKey: this.witnessKey,+ });+ return {+ type: 'pr_artifact_response',+ fromInstallation: this.installationId,+ envelope,+ } satisfies PrArtifactResponse;+ }++ private checkRate(peer: string): boolean {+ const now = Date.now();+ const bucket = this.rateBuckets.get(peer);+ if (!bucket || now >= bucket.resetAt) {+ this.rateBuckets.set(peer, { count: 1, resetAt: now + 60_000 });+ return true;+ }+ if (bucket.count >= this.rateLimit) return false;+ bucket.count++;+ return true;+ }+}diff --git a/plugins/ruflo-graph-intelligence/src/domain/federation-protocol.ts b/plugins/ruflo-graph-intelligence/src/domain/federation-protocol.tsnew file mode 100644index 0000000000..565e02a903--- /dev/null+++ b/plugins/ruflo-graph-intelligence/src/domain/federation-protocol.ts@@ -0,0 +1,95 @@+/**+ * Federation Protocol for PR Artifacts (Phase 8 β beyond-SOTA, ADR-123)+ *+ * Wire message types over the ADR-104 federation transport. Peers can ask+ * for a precomputed signed PageRank vector instead of re-walking the graph,+ * verify via the Phase 7 signer, and fall back to local recompute when the+ * artifact is stale (graphHash mismatch) or the holder isn't trusted.+ */++import { z } from 'zod';+import { SignedPageRankEnvelopeSchema } from './signed-artifact.js';++// ============================================================================+// Request types+// ============================================================================++export const PrArtifactRequestSchema = z.object({+ type: z.literal('pr_artifact_request'),+ /** Requesting installation id. */+ fromInstallation: z.string().min(1),+ /** Adapter graph id to query. */+ graphId: z.string().min(1),+ /** Query node for single-entry PR. Omit for full-vector requests. */+ queryNode: z.string().optional(),+ alpha: z.number().positive().lt(1).default(0.85),+ epsilon: z.number().positive().default(1e-3),+ seedNodes: z.array(z.string()).default([]),+ /** Hash of the graph the requester has locally. Holder uses this to decide+ * whether to ship a fresh artifact or a delta. */+ lastKnownGraphHash: z.string().regex(/^[0-9a-f]{64}$/).optional(),+ /** Hash of any previous PR result the requester has cached. */+ lastKnownResultHash: z.string().regex(/^[0-9a-f]{64}$/).optional(),+});+export type PrArtifactRequest = z.infer<typeof PrArtifactRequestSchema>;++// ============================================================================+// Response types β either a full artifact, a delta, or a stale-rejection+// ============================================================================++export const PrArtifactResponseSchema = z.object({+ type: z.literal('pr_artifact_response'),+ /** Responding installation id. */+ fromInstallation: z.string().min(1),+ /** The Phase 7 signed envelope. */+ envelope: SignedPageRankEnvelopeSchema,+});+export type PrArtifactResponse = z.infer<typeof PrArtifactResponseSchema>;++/** Lightweight delta β only the score difference + new resultHash. */+export const PrArtifactDeltaSchema = z.object({+ type: z.literal('pr_artifact_delta'),+ fromInstallation: z.string().min(1),+ graphId: z.string().min(1),+ /** Hash the delta is based on. */+ baseResultHash: z.string().regex(/^[0-9a-f]{64}$/),+ /** New resultHash after delta applied. */+ newResultHash: z.string().regex(/^[0-9a-f]{64}$/),+ /** Score delta (single-entry) or sparse delta indices+values (vector). */+ scoreDelta: z.number().optional(),+ sparseDelta: z.object({+ indices: z.array(z.number().int().nonnegative()),+ values: z.array(z.number()),+ }).optional(),+});+export type PrArtifactDelta = z.infer<typeof PrArtifactDeltaSchema>;++export const PrArtifactStaleSchema = z.object({+ type: z.literal('pr_artifact_stale'),+ fromInstallation: z.string().min(1),+ graphId: z.string().min(1),+ /** The holder's current graph hash so the requester can decide what to do. */+ currentGraphHash: z.string().regex(/^[0-9a-f]{64}$/),+ /** Why the request was stale-rejected. */+ reason: z.string(),+});+export type PrArtifactStale = z.infer<typeof PrArtifactStaleSchema>;++export const FederationMessageSchema = z.discriminatedUnion('type', [+ PrArtifactRequestSchema,+ PrArtifactResponseSchema,+ PrArtifactDeltaSchema,+ PrArtifactStaleSchema,+]);+export type FederationMessage = z.infer<typeof FederationMessageSchema>;++// ============================================================================+// Transport contract β ADR-104 plugs in here+// ============================================================================++export interface FederationTransport {+ /** Send a message to a specific peer. Returns the response message. */+ send(toInstallation: string, message: FederationMessage): Promise<FederationMessage | null>;+ /** Subscribe to inbound messages. */+ onMessage(handler: (msg: FederationMessage) => Promise<FederationMessage | null>): () => void;+}diff --git a/plugins/ruflo-graph-intelligence/src/index.ts b/plugins/ruflo-graph-intelligence/src/index.tsindex b08a948a0d..9588ccfe18 100644--- a/plugins/ruflo-graph-intelligence/src/index.ts+++ b/plugins/ruflo-graph-intelligence/src/index.ts@@ -52,6 +52,31 @@ export {type StreamingUpdate,} from './application/streaming-bridge.js';+// Federation protocol (Phase 8 β beyond-SOTA)+export {+ PrArtifactRequestSchema,+ PrArtifactResponseSchema,+ PrArtifactDeltaSchema,+ PrArtifactStaleSchema,+ FederationMessageSchema,+ type PrArtifactRequest,+ type PrArtifactResponse,+ type PrArtifactDelta,+ type PrArtifactStale,+ type FederationMessage,+ type FederationTransport,+} from './domain/federation-protocol.js';+export {+ FederationServer,+ type FederationServerOptions,+} from './application/federation-server.js';+export {+ FederationClient,+ inProcessTransport,+ type FederationClientOptions,+ type FetchPrResult,+} from './application/federation-client.js';+// Signed PR artifacts (Phase 7 β beyond-SOTA)export {ARTIFACT_ENVELOPE_VERSION,diff --git a/plugins/ruflo-graph-intelligence/tests/phase8-federation.test.ts b/plugins/ruflo-graph-intelligence/tests/phase8-federation.test.tsnew file mode 100644index 0000000000..9bf82cc826--- /dev/null+++ b/plugins/ruflo-graph-intelligence/tests/phase8-federation.test.ts@@ -0,0 +1,194 @@+/**+ * Phase 8 Tests β Federation Distribution of Signed PR Vectors (beyond-SOTA)+ */++import { describe, it, expect, beforeEach } from 'vitest';+import { FederationServer } from '../src/application/federation-server.js';+import {+ FederationClient,+ inProcessTransport,+} from '../src/application/federation-client.js';+import { generateWitnessKey } from '../src/infrastructure/witness-signer.js';+import { resetRegistry, getRegistry, type SublinearAdapter } from '../src/domain/adapter.js';+import type { SparseMatrix } from '../src/domain/types.js';+import { createHash } from 'node:crypto';++function ddAdapter(graphId: string, n = 6): SublinearAdapter {+ const entries = [];+ const nodeIndex: Record<string, number> = {};+ const indexNode: string[] = [];+ for (let i = 0; i < n; i++) {+ nodeIndex[`n${i}`] = i;+ indexNode.push(`n${i}`);+ entries.push({ row: i, col: i, value: 5 });+ if (i > 0) entries.push({ row: i, col: i - 1, value: -1 });+ if (i < n - 1) entries.push({ row: i, col: i + 1, value: -1 });+ }+ const contentHash = createHash('sha256')+ .update(JSON.stringify({ graphId, n }))+ .digest('hex');+ const matrix: SparseMatrix = {+ graphId,+ size: n,+ entries,+ nodeIndex,+ indexNode,+ capturedAt: '2026-05-19T00:00:00Z',+ contentHash,+ };+ return {+ graphId,+ ownerPlugin: 'test',+ async exportAsSparseMatrix() {+ return matrix;+ },+ };+}++describe('Federation round-trip', () => {+ beforeEach(() => resetRegistry());++ it('client receives a verifiable peer artifact', async () => {+ const adapter = ddAdapter('fed:test', 6);+ getRegistry().register(adapter);+ const key = generateWitnessKey();+ const server = new FederationServer({+ installationId: 'inst-A',+ witnessKey: key,+ witnessKeyId: 'key-v1',+ transport: { async send() { return null; }, onMessage() { return () => {}; } },+ });+ const client = new FederationClient({+ installationId: 'inst-B',+ transport: inProcessTransport(server),+ trustedPublicKeys: [key.publicKeyHex],+ });+ const result = await client.fetchPageRank({+ peer: 'inst-A',+ graphId: 'fed:test',+ nodeId: 'n2',+ });+ expect(result.origin).toBe('peer');+ expect(result.verification?.valid).toBe(true);+ expect(result.result.score).toBeGreaterThanOrEqual(0);+ });++ it('client falls back to local on untrusted signer', async () => {+ const adapter = ddAdapter('fed:test', 6);+ getRegistry().register(adapter);+ const strangerKey = generateWitnessKey();+ const server = new FederationServer({+ installationId: 'inst-A',+ witnessKey: strangerKey,+ witnessKeyId: 'key-v1',+ transport: { async send() { return null; }, onMessage() { return () => {}; } },+ });+ const client = new FederationClient({+ installationId: 'inst-B',+ transport: inProcessTransport(server),+ trustedPublicKeys: ['0'.repeat(64)], // stranger NOT in trust list+ });+ const result = await client.fetchPageRank({+ peer: 'inst-A',+ graphId: 'fed:test',+ nodeId: 'n2',+ });+ expect(result.origin).toBe('untrusted-fallback');+ expect(result.fallbackReason).toMatch(/trusted list/i);+ expect(result.result.score).toBeGreaterThanOrEqual(0);+ });++ it('server sends pr_artifact_stale when graphHash differs', async () => {+ const adapter = ddAdapter('fed:test', 6);+ getRegistry().register(adapter);+ const key = generateWitnessKey();+ const server = new FederationServer({+ installationId: 'inst-A',+ witnessKey: key,+ witnessKeyId: 'key-v1',+ transport: { async send() { return null; }, onMessage() { return () => {}; } },+ });+ const client = new FederationClient({+ installationId: 'inst-B',+ transport: inProcessTransport(server),+ trustedPublicKeys: [key.publicKeyHex],+ });+ const result = await client.fetchPageRank({+ peer: 'inst-A',+ graphId: 'fed:test',+ nodeId: 'n2',+ lastKnownGraphHash: '0'.repeat(64), // doesn't match what server has+ });+ expect(result.origin).toBe('stale-fallback');+ expect(result.fallbackReason).toMatch(/changed/);+ });++ it('server returns stale-reject for an unknown graphId', async () => {+ const key = generateWitnessKey();+ const server = new FederationServer({+ installationId: 'inst-A',+ witnessKey: key,+ witnessKeyId: 'key-v1',+ transport: { async send() { return null; }, onMessage() { return () => {}; } },+ });+ const client = new FederationClient({+ installationId: 'inst-B',+ transport: inProcessTransport(server),+ });+ // No adapter registered on client OR server side+ try {+ await client.fetchPageRank({+ peer: 'inst-A',+ graphId: 'fed:nonexistent',+ nodeId: 'n2',+ });+ throw new Error('expected localCompute to throw');+ } catch (err) {+ expect((err as Error).message).toMatch(/no adapter/);+ }+ });++ it('server rate-limits per peer', async () => {+ const adapter = ddAdapter('fed:test', 6);+ getRegistry().register(adapter);+ const key = generateWitnessKey();+ const server = new FederationServer({+ installationId: 'inst-A',+ witnessKey: key,+ witnessKeyId: 'key-v1',+ transport: { async send() { return null; }, onMessage() { return () => {}; } },+ rateLimitPerPeerPerMinute: 2,+ });+ const client = new FederationClient({+ installationId: 'inst-B',+ transport: inProcessTransport(server),+ trustedPublicKeys: [key.publicKeyHex],+ });+ const r1 = await client.fetchPageRank({ peer: 'inst-A', graphId: 'fed:test', nodeId: 'n2' });+ const r2 = await client.fetchPageRank({ peer: 'inst-A', graphId: 'fed:test', nodeId: 'n3' });+ const r3 = await client.fetchPageRank({ peer: 'inst-A', graphId: 'fed:test', nodeId: 'n4' });+ expect(r1.origin).toBe('peer');+ expect(r2.origin).toBe('peer');+ expect(r3.origin).toBe('stale-fallback');+ expect(r3.fallbackReason).toMatch(/rate limit/i);+ });++ it('client falls back to local compute when no usable response', async () => {+ const adapter = ddAdapter('fed:test', 6);+ getRegistry().register(adapter);+ const client = new FederationClient({+ installationId: 'inst-B',+ transport: {+ async send() { return null; }, // server unreachable+ onMessage() { return () => {}; },+ },+ });+ const result = await client.fetchPageRank({+ peer: 'inst-A',+ graphId: 'fed:test',+ nodeId: 'n2',+ });+ expect(result.origin).toBe('local-fallback');+ expect(result.result.score).toBeGreaterThanOrEqual(0);+ });+});