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(graph-intelligence): #2044 ADR-123 Phases 6.5+7 β€” streaming bridge + signed PR artifacts (beyond-SOTA)

ruved81567cdbb3
diff --git a/plugins/ruflo-graph-intelligence/src/application/streaming-bridge.ts b/plugins/ruflo-graph-intelligence/src/application/streaming-bridge.ts
new file mode 100644
index 0000000000..0bd28ebe4b
--- /dev/null
+++ b/plugins/ruflo-graph-intelligence/src/application/streaming-bridge.ts
@@ -0,0 +1,137 @@
+/**
+ * Streaming Bridge β€” Wedge 12 (ADR-123 Phase 6.5)
+ *
+ * Couples a registered SublinearAdapter with `solve_on_change` so event-driven
+ * graphs (federation trust deltas, span streams, append-only causal breaks,
+ * cost spend events, AIDefence flag updates) pay only `O(nnz(delta) Β· log N)`
+ * per event rather than recomputing the full vector each tick.
+ *
+ * The bridge maintains the *previous solution* in memory; every push call
+ * applies the delta and returns the updated solution. It also exposes a
+ * `crossoverHeuristic()` that decides whether the cheap delta path is
+ * actually cheaper than a full re-solve given the current density.
+ */
+
+import type { SublinearAdapter } from '../domain/adapter.js';
+import type { ComplexityClass, SparseDelta, SparseMatrix } from '../domain/types.js';
+import { runSolveOnChange, runSolve } from '../infrastructure/solver-bridge.js';
+
+export interface StreamingBridgeOptions {
+ adapter: SublinearAdapter;
+ /** Initial b vector for the base full-solve. */
+ initialRhs: number[];
+ algorithm?: 'cg' | 'neumann';
+ maxComplexityClass?: ComplexityClass;
+ /**
+ * Crossover threshold: prefer `solve_on_change` when
+ * `nnz(delta) / nnz(matrix) < deltaRatioThreshold`. Default 0.05.
+ */
+ deltaRatioThreshold?: number;
+ /** Force full re-solve after N delta updates regardless. Default 50. */
+ refreshEvery?: number;
+}
+
+export interface StreamingUpdate {
+ x: number[];
+ residualNorm: number;
+ iterations: number;
+ /** How this update was computed β€” informational. */
+ mode: 'delta' | 'full-resolve' | 'cold-start';
+ deltaNnz?: number;
+ appliedAt: string;
+}
+
+export class StreamingBridge {
+ private readonly adapter: SublinearAdapter;
+ private readonly initialRhs: number[];
+ private readonly algorithm: 'cg' | 'neumann';
+ private readonly maxComplexityClass: ComplexityClass;
+ private readonly deltaRatioThreshold: number;
+ private readonly refreshEvery: number;
+
+ private prevSolution: number[] | undefined;
+ private deltaCount = 0;
+ private cachedMatrix: SparseMatrix | undefined;
+
+ constructor(options: StreamingBridgeOptions) {
+ this.adapter = options.adapter;
+ this.initialRhs = options.initialRhs;
+ this.algorithm = options.algorithm ?? 'cg';
+ this.maxComplexityClass = options.maxComplexityClass ?? 'polynomial';
+ this.deltaRatioThreshold = options.deltaRatioThreshold ?? 0.05;
+ this.refreshEvery = options.refreshEvery ?? 50;
+ }
+
+ /** Force a fresh full re-solve and reset the streaming state. */
+ async coldStart(): Promise<StreamingUpdate> {
+ const matrix = await this.adapter.exportAsSparseMatrix();
+ this.cachedMatrix = matrix;
+ const result = runSolve(matrix, {
+ graphId: matrix.graphId,
+ rhs: this.initialRhs,
+ algorithm: this.algorithm,
+ maxComplexityClass: this.maxComplexityClass,
+ coherenceThreshold: 0,
+ });
+ this.prevSolution = result.x;
+ this.deltaCount = 0;
+ return {
+ x: result.x,
+ residualNorm: result.residualNorm,
+ iterations: result.iterations,
+ mode: 'cold-start',
+ appliedAt: new Date().toISOString(),
+ };
+ }
+
+ /**
+ * Apply a delta event. The bridge picks `solve_on_change` if the delta is
+ * sparse enough; otherwise it falls back to a full re-solve.
+ */
+ async pushDelta(delta: SparseDelta): Promise<StreamingUpdate> {
+ if (!this.prevSolution || !this.cachedMatrix) {
+ await this.coldStart();
+ }
+ // Refresh-cap forces a clean re-solve to bound drift error
+ if (this.deltaCount >= this.refreshEvery) {
+ return this.coldStart().then((u) => ({ ...u, mode: 'full-resolve' as const }));
+ }
+
+ const matrix = this.cachedMatrix!;
+ const deltaRatio = delta.indices.length / Math.max(1, matrix.entries.length);
+ if (deltaRatio >= this.deltaRatioThreshold) {
+ // Too dense β€” full re-solve is cheaper than delta-and-correct
+ return this.coldStart().then((u) => ({ ...u, mode: 'full-resolve' as const }));
+ }
+
+ const result = runSolveOnChange(matrix, {
+ graphId: matrix.graphId,
+ prevSolution: this.prevSolution!,
+ delta,
+ algorithm: this.algorithm,
+ maxComplexityClass: this.maxComplexityClass,
+ });
+ this.prevSolution = result.x;
+ this.deltaCount++;
+ return {
+ x: result.x,
+ residualNorm: result.residualNorm,
+ iterations: result.iterations,
+ mode: 'delta',
+ deltaNnz: delta.indices.length,
+ appliedAt: new Date().toISOString(),
+ };
+ }
+
+ /** Best-effort current solution snapshot. */
+ getCurrentSolution(): readonly number[] | undefined {
+ return this.prevSolution;
+ }
+
+ /** Reset cached state (e.g. after the underlying graph re-grew). */
+ reset(): void {
+ this.prevSolution = undefined;
+ this.cachedMatrix = undefined;
+ this.deltaCount = 0;
+ }
+}
diff --git a/plugins/ruflo-graph-intelligence/src/domain/signed-artifact.ts b/plugins/ruflo-graph-intelligence/src/domain/signed-artifact.ts
new file mode 100644
index 0000000000..5a9727c3be
--- /dev/null
+++ b/plugins/ruflo-graph-intelligence/src/domain/signed-artifact.ts
@@ -0,0 +1,80 @@
+/**
+ * Signed PageRank Artifact (Phase 7 β€” beyond-SOTA, ADR-123)
+ *
+ * RuFlo gains a primitive no competing memory framework can ship: a portable,
+ * Ed25519-signed PageRank result that carries enough metadata for a remote
+ * peer to verify provenance + budget compliance + input stability without
+ * trusting the producer. Federation peers exchange these instead of
+ * re-walking graphs.
+ *
+ * Schema mirrors the ADR-123 Architecture diagram with the upstream 1.7.0
+ * additions: `complexity_class` (budget compliance) + `coherence_score`
+ * (DD-margin at compute time).
+ */
+
+import { z } from 'zod';
+import {
+ ComplexityClassSchema,
+ PageRankResultSchema,
+ type PageRankResult,
+} from './types.js';
+
+export const ARTIFACT_ENVELOPE_VERSION = '1.0.0';
+export const ARTIFACT_ENVELOPE_KIND = 'pagerank';
+
+export const SignedPageRankPayloadSchema = z.object({
+ envelopeVersion: z.literal(ARTIFACT_ENVELOPE_VERSION),
+ kind: z.literal(ARTIFACT_ENVELOPE_KIND),
+ installationId: z.string().min(1),
+ /** Witness key ID (key version, not key identity per ADR-103). */
+ witnessKeyId: z.string().min(1),
+ /** Ed25519 public key (hex, 32 bytes). */
+ publicKey: z.string().regex(/^[0-9a-f]{64}$/),
+ /** Adapter graph id (e.g. `ruflo-federation:trust-mesh`). */
+ graphId: z.string().min(1),
+ /** SHA-256 of the input matrix's `contentHash`. */
+ graphHash: z.string().regex(/^[0-9a-f]{64}$/),
+ /** Wall-clock at compute time. */
+ graphTimestamp: z.string(),
+ algorithm: z.enum(['forward-push', 'backward-push', 'bidirectional', 'cg', 'neumann']),
+ alpha: z.number().positive().lt(1),
+ epsilon: z.number().positive(),
+ /** Query node β€” None for full-vector artifacts. */
+ queryNode: z.string().optional(),
+ /** Seed nodes (PPR). Empty for plain PR. */
+ seedNodes: z.array(z.string()),
+ /** Result (single-entry or full-vector). */
+ result: PageRankResultSchema,
+ /** Class the solver actually achieved (echoes result.complexityClass). */
+ complexityClass: ComplexityClassSchema,
+ /** Coherence margin at compute time (echoes result.coherence.score). */
+ coherenceScore: z.number(),
+ /** Hash of `result` (echoes result.resultHash). */
+ resultHash: z.string().regex(/^[0-9a-f]{64}$/),
+ /** When the envelope was sealed. */
+ sealedAt: z.string(),
+ /** Solver version used. */
+ solverVersion: z.string().default('[email protected]'),
+});
+export type SignedPageRankPayload = z.infer<typeof SignedPageRankPayloadSchema>;
+
+export const SignedPageRankEnvelopeSchema = z.object({
+ payload: SignedPageRankPayloadSchema,
+ signature: z.string().regex(/^[0-9a-f]{128}$/),
+ algorithm: z.literal('ed25519'),
+});
+export type SignedPageRankEnvelope = z.infer<typeof SignedPageRankEnvelopeSchema>;
+
+export interface ArtifactVerificationResult {
+ valid: boolean;
+ signatureValid: boolean;
+ schemaValid: boolean;
+ /** True iff graphHash + resultHash + signature all check out. */
+ integrityValid: boolean;
+ publicKey?: string;
+ /** Complexity class echo β€” callers can budget against this. */
+ complexityClass?: PageRankResult['complexityClass'];
+ /** Coherence margin echo β€” callers can sanity-check input stability. */
+ coherenceScore?: number;
+ reason?: string;
+}
diff --git a/plugins/ruflo-graph-intelligence/src/index.ts b/plugins/ruflo-graph-intelligence/src/index.ts
index 1e48b66ad9..b08a948a0d 100644
--- a/plugins/ruflo-graph-intelligence/src/index.ts
+++ b/plugins/ruflo-graph-intelligence/src/index.ts
@@ -45,6 +45,35 @@ export * from './adapters/index.js';
// JL embedding (ADR-121 follow-up)
export { jlEmbed, computeTargetDim, type JLEmbedOptions, type JLEmbedResult } from './infrastructure/jl-embed.js';
+// Streaming bridge (Wedge 12)
+export {
+ StreamingBridge,
+ type StreamingBridgeOptions,
+ type StreamingUpdate,
+} from './application/streaming-bridge.js';
+
+// Signed PR artifacts (Phase 7 β€” beyond-SOTA)
+export {
+ ARTIFACT_ENVELOPE_VERSION,
+ ARTIFACT_ENVELOPE_KIND,
+ SignedPageRankEnvelopeSchema,
+ SignedPageRankPayloadSchema,
+ type SignedPageRankEnvelope,
+ type SignedPageRankPayload,
+ type ArtifactVerificationResult,
+} from './domain/signed-artifact.js';
+export {
+ generateWitnessKey,
+ loadWitnessKey,
+ resolveWitnessKey,
+ sealArtifact,
+ verifyArtifact,
+ canonicalJSON,
+ sha256Hex,
+ type WitnessKey,
+ type SealArtifactInput,
+} from './infrastructure/witness-signer.js';
+
// Default export
import { graphIntelligenceTools } from './mcp-tools/index.js';
import { getRegistry } from './domain/adapter.js';
diff --git a/plugins/ruflo-graph-intelligence/src/infrastructure/witness-signer.ts b/plugins/ruflo-graph-intelligence/src/infrastructure/witness-signer.ts
new file mode 100644
index 0000000000..d099685965
--- /dev/null
+++ b/plugins/ruflo-graph-intelligence/src/infrastructure/witness-signer.ts
@@ -0,0 +1,209 @@
+/**
+ * Witness Signer for PR Artifacts (Phase 7, ADR-123)
+ *
+ * Ed25519 sign / verify via node:crypto. Mirrors @claude-flow/browser's
+ * ADR-122 Phase 1 witness signer β€” same canonical-JSON approach so a single
+ * upstream-ADR-103 schema change cascades cleanly.
+ */
+
+import {
+ createPrivateKey,
+ createPublicKey,
+ sign,
+ verify,
+ generateKeyPairSync,
+ createHash,
+ type KeyObject,
+} from 'node:crypto';
+import {
+ ARTIFACT_ENVELOPE_KIND,
+ ARTIFACT_ENVELOPE_VERSION,
+ SignedPageRankEnvelopeSchema,
+ SignedPageRankPayloadSchema,
+ type SignedPageRankEnvelope,
+ type SignedPageRankPayload,
+ type ArtifactVerificationResult,
+} from '../domain/signed-artifact.js';
+import type { PageRankResult } from '../domain/types.js';
+
+export interface WitnessKey {
+ privateKey: KeyObject;
+ publicKey: KeyObject;
+ publicKeyHex: string;
+}
+
+/** Canonical-JSON for deterministic signing β€” omits undefined keys, sorts. */
+export function canonicalJSON(value: unknown): string {
+ if (value === undefined) return 'null';
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
+ if (Array.isArray(value)) return '[' + value.map(canonicalJSON).join(',') + ']';
+ const obj = value as Record<string, unknown>;
+ const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort();
+ return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalJSON(obj[k])).join(',') + '}';
+}
+
+export function sha256Hex(input: Buffer | string): string {
+ return createHash('sha256').update(input).digest('hex');
+}
+
+export function generateWitnessKey(): WitnessKey {
+ const { privateKey, publicKey } = generateKeyPairSync('ed25519');
+ return { privateKey, publicKey, publicKeyHex: extractPubkeyHex(publicKey) };
+}
+
+export function loadWitnessKey(privateKeyPem: string): WitnessKey {
+ const privateKey = createPrivateKey(privateKeyPem);
+ const publicKey = createPublicKey(privateKey);
+ return { privateKey, publicKey, publicKeyHex: extractPubkeyHex(publicKey) };
+}
+
+function extractPubkeyHex(publicKey: KeyObject): string {
+ const der = publicKey.export({ format: 'der', type: 'spki' });
+ return der.subarray(der.length - 32).toString('hex');
+}
+
+export function resolveWitnessKey(): WitnessKey {
+ const envKey = process.env.RUFLO_GRAPH_INTELLIGENCE_WITNESS_KEY;
+ if (envKey) return loadWitnessKey(envKey);
+ return generateWitnessKey();
+}
+
+export interface SealArtifactInput {
+ installationId: string;
+ witnessKeyId: string;
+ graphId: string;
+ graphHash: string;
+ graphTimestamp: string;
+ algorithm: SignedPageRankPayload['algorithm'];
+ alpha: number;
+ epsilon: number;
+ queryNode?: string;
+ seedNodes: readonly string[];
+ result: PageRankResult;
+ witnessKey?: WitnessKey;
+ sealedAt?: string;
+}
+
+export function sealArtifact(input: SealArtifactInput): {
+ envelope: SignedPageRankEnvelope;
+ publicKeyHex: string;
+} {
+ const key = input.witnessKey ?? resolveWitnessKey();
+ const payload: SignedPageRankPayload = SignedPageRankPayloadSchema.parse({
+ envelopeVersion: ARTIFACT_ENVELOPE_VERSION,
+ kind: ARTIFACT_ENVELOPE_KIND,
+ installationId: input.installationId,
+ witnessKeyId: input.witnessKeyId,
+ publicKey: key.publicKeyHex,
+ graphId: input.graphId,
+ graphHash: input.graphHash,
+ graphTimestamp: input.graphTimestamp,
+ algorithm: input.algorithm,
+ alpha: input.alpha,
+ epsilon: input.epsilon,
+ queryNode: input.queryNode,
+ seedNodes: [...input.seedNodes],
+ result: input.result,
+ complexityClass: input.result.complexityClass,
+ coherenceScore: input.result.coherence.score,
+ resultHash: input.result.resultHash,
+ sealedAt: input.sealedAt ?? new Date().toISOString(),
+ solverVersion: '[email protected]',
+ });
+ const canonical = canonicalJSON(payload);
+ const sigBuf = sign(null, Buffer.from(canonical, 'utf8'), key.privateKey);
+ return {
+ envelope: { payload, signature: sigBuf.toString('hex'), algorithm: 'ed25519' },
+ publicKeyHex: key.publicKeyHex,
+ };
+}
+
+export function verifyArtifact(
+ envelope: unknown,
+ options: { trustedPublicKeys?: string[] } = {},
+): ArtifactVerificationResult {
+ const parsed = SignedPageRankEnvelopeSchema.safeParse(envelope);
+ if (!parsed.success) {
+ return {
+ valid: false,
+ signatureValid: false,
+ schemaValid: false,
+ integrityValid: false,
+ reason: 'schema: ' + parsed.error.issues.map((i) => i.path.join('.') + ' ' + i.message).join('; '),
+ };
+ }
+ const { payload, signature } = parsed.data;
+
+ if (options.trustedPublicKeys && !options.trustedPublicKeys.includes(payload.publicKey)) {
+ return {
+ valid: false,
+ signatureValid: false,
+ schemaValid: true,
+ integrityValid: false,
+ publicKey: payload.publicKey,
+ reason: 'signer not in trusted list',
+ };
+ }
+
+ // Integrity: result.resultHash must match payload.resultHash
+ if (payload.result.resultHash !== payload.resultHash) {
+ return {
+ valid: false,
+ signatureValid: false,
+ schemaValid: true,
+ integrityValid: false,
+ publicKey: payload.publicKey,
+ reason: 'result.resultHash != payload.resultHash (tampered)',
+ };
+ }
+ // Coherence echo must match
+ if (Math.abs(payload.result.coherence.score - payload.coherenceScore) > 1e-9) {
+ return {
+ valid: false,
+ signatureValid: false,
+ schemaValid: true,
+ integrityValid: false,
+ publicKey: payload.publicKey,
+ reason: 'coherenceScore echo mismatch (tampered)',
+ };
+ }
+ // Complexity-class echo must match
+ if (payload.result.complexityClass !== payload.complexityClass) {
+ return {
+ valid: false,
+ signatureValid: false,
+ schemaValid: true,
+ integrityValid: false,
+ publicKey: payload.publicKey,
+ reason: 'complexityClass echo mismatch (tampered)',
+ };
+ }
+
+ // Signature
+ try {
+ const spkiPrefix = Buffer.from('302a300506032b6570032100', 'hex');
+ const der = Buffer.concat([spkiPrefix, Buffer.from(payload.publicKey, 'hex')]);
+ const pk = createPublicKey({ key: der, format: 'der', type: 'spki' });
+ const canonical = canonicalJSON(payload);
+ const sigValid = verify(null, Buffer.from(canonical, 'utf8'), pk, Buffer.from(signature, 'hex'));
+ return {
+ valid: sigValid,
+ signatureValid: sigValid,
+ schemaValid: true,
+ integrityValid: true,
+ publicKey: payload.publicKey,
+ complexityClass: payload.complexityClass,
+ coherenceScore: payload.coherenceScore,
+ reason: sigValid ? undefined : 'signature verification failed (envelope tampered)',
+ };
+ } catch (err) {
+ return {
+ valid: false,
+ signatureValid: false,
+ schemaValid: true,
+ integrityValid: false,
+ publicKey: payload.publicKey,
+ reason: 'verify threw: ' + (err instanceof Error ? err.message : String(err)),
+ };
+ }
+}
diff --git a/plugins/ruflo-graph-intelligence/tests/phase6_5-streaming.test.ts b/plugins/ruflo-graph-intelligence/tests/phase6_5-streaming.test.ts
new file mode 100644
index 0000000000..9a7b8082fb
--- /dev/null
+++ b/plugins/ruflo-graph-intelligence/tests/phase6_5-streaming.test.ts
@@ -0,0 +1,135 @@
+/**
+ * Phase 6.5 Tests β€” Streaming Bridge (Wedge 12)
+ */
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import { StreamingBridge } from '../src/application/streaming-bridge.js';
+import { resetRegistry, getRegistry, type SublinearAdapter } from '../src/domain/adapter.js';
+import type { SparseEntry, SparseMatrix } from '../src/domain/types.js';
+
+function staticDdAdapter(n: number, graphId = 'streaming:test'): SublinearAdapter {
+ const entries: SparseEntry[] = [];
+ 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 matrix: SparseMatrix = {
+ graphId,
+ size: n,
+ entries,
+ nodeIndex,
+ indexNode,
+ capturedAt: '2026-05-19T00:00:00Z',
+ };
+ return {
+ graphId,
+ ownerPlugin: 'test',
+ async exportAsSparseMatrix() {
+ return matrix;
+ },
+ };
+}
+
+describe('StreamingBridge', () => {
+ beforeEach(() => resetRegistry());
+
+ it('cold-start produces a full-solve baseline', async () => {
+ const adapter = staticDdAdapter(8);
+ const bridge = new StreamingBridge({
+ adapter,
+ initialRhs: Array.from({ length: 8 }, () => 1),
+ algorithm: 'cg',
+ maxComplexityClass: 'polynomial',
+ });
+ const u = await bridge.coldStart();
+ expect(u.mode).toBe('cold-start');
+ expect(u.x).toHaveLength(8);
+ expect(u.residualNorm).toBeLessThan(1e-3);
+ });
+
+ it('applies a sparse delta via solve_on_change', async () => {
+ const adapter = staticDdAdapter(8);
+ const bridge = new StreamingBridge({
+ adapter,
+ initialRhs: Array.from({ length: 8 }, () => 1),
+ algorithm: 'cg',
+ maxComplexityClass: 'polynomial',
+ deltaRatioThreshold: 0.5, // generous so single-element delta uses solve_on_change
+ });
+ await bridge.coldStart();
+ const u = await bridge.pushDelta({ indices: [3], values: [0.5] });
+ expect(u.mode).toBe('delta');
+ expect(u.deltaNnz).toBe(1);
+ expect(u.x).toHaveLength(8);
+ });
+
+ it('falls back to full re-solve when delta ratio exceeds threshold', async () => {
+ const adapter = staticDdAdapter(4);
+ const bridge = new StreamingBridge({
+ adapter,
+ initialRhs: [1, 1, 1, 1],
+ algorithm: 'cg',
+ maxComplexityClass: 'polynomial',
+ deltaRatioThreshold: 0.1, // very strict
+ });
+ await bridge.coldStart();
+ const u = await bridge.pushDelta({
+ indices: [0, 1, 2, 3],
+ values: [0.1, 0.1, 0.1, 0.1],
+ });
+ expect(u.mode).toBe('full-resolve');
+ });
+
+ it('refresh-cap forces full re-solve after N deltas', async () => {
+ const adapter = staticDdAdapter(8);
+ const bridge = new StreamingBridge({
+ adapter,
+ initialRhs: Array.from({ length: 8 }, () => 1),
+ algorithm: 'cg',
+ maxComplexityClass: 'polynomial',
+ deltaRatioThreshold: 0.5,
+ refreshEvery: 3,
+ });
+ await bridge.coldStart();
+ // 3 deltas β†’ 4th should be full-resolve via refresh cap
+ for (let i = 0; i < 3; i++) {
+ await bridge.pushDelta({ indices: [i], values: [0.1] });
+ }
+ const u = await bridge.pushDelta({ indices: [4], values: [0.1] });
+ expect(u.mode).toBe('full-resolve');
+ });
+
+ it('getCurrentSolution returns the latest known x', async () => {
+ const adapter = staticDdAdapter(8);
+ const bridge = new StreamingBridge({
+ adapter,
+ initialRhs: Array.from({ length: 8 }, () => 1),
+ algorithm: 'cg',
+ maxComplexityClass: 'polynomial',
+ });
+ await bridge.coldStart();
+ expect(bridge.getCurrentSolution()).toBeDefined();
+ expect(bridge.getCurrentSolution()).toHaveLength(8);
+ });
+
+ it('reset clears cached state', async () => {
+ const adapter = staticDdAdapter(8);
+ const bridge = new StreamingBridge({
+ adapter,
+ initialRhs: Array.from({ length: 8 }, () => 1),
+ algorithm: 'cg',
+ maxComplexityClass: 'polynomial',
+ });
+ await bridge.coldStart();
+ bridge.reset();
+ expect(bridge.getCurrentSolution()).toBeUndefined();
+ // After reset, a delta push should cold-start first
+ const u = await bridge.pushDelta({ indices: [3], values: [0.5] });
+ expect(u).toBeDefined();
+ });
+});
diff --git a/plugins/ruflo-graph-intelligence/tests/phase7-signed-artifact.test.ts b/plugins/ruflo-graph-intelligence/tests/phase7-signed-artifact.test.ts
new file mode 100644
index 0000000000..919f7ee78b
--- /dev/null
+++ b/plugins/ruflo-graph-intelligence/tests/phase7-signed-artifact.test.ts
@@ -0,0 +1,238 @@
+/**
+ * Phase 7 Tests β€” Witness-Signed PageRank Artifact (beyond-SOTA wedge)
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ generateWitnessKey,
+ sealArtifact,
+ verifyArtifact,
+ canonicalJSON,
+ sha256Hex,
+} from '../src/infrastructure/witness-signer.js';
+import type { PageRankResult } from '../src/domain/types.js';
+import type { SignedPageRankEnvelope } from '../src/domain/signed-artifact.js';
+
+const SAMPLE_RESULT: PageRankResult = {
+ graphId: 'test:dd',
+ nodeId: 'n3',
+ score: 0.123456,
+ alpha: 0.85,
+ epsilon: 1e-3,
+ iterations: 4,
+ complexityClass: 'logarithmic',
+ coherence: { score: 0.42, passed: true, threshold: 0 },
+ computedAt: '2026-05-19T01:00:00.000Z',
+ resultHash: 'f'.repeat(64),
+};
+
+describe('canonicalJSON', () => {
+ it('produces identical output for structurally-equal objects', () => {
+ expect(canonicalJSON({ a: 1, b: 2 })).toBe(canonicalJSON({ b: 2, a: 1 }));
+ });
+ it('skips undefined keys', () => {
+ expect(canonicalJSON({ a: 1, b: undefined })).toBe('{"a":1}');
+ });
+});
+
+describe('sealArtifact + verifyArtifact', () => {
+ it('round-trips on the happy path', () => {
+ const key = generateWitnessKey();
+ const { envelope } = sealArtifact({
+ installationId: 'inst-A',
+ witnessKeyId: 'key-v1',
+ graphId: 'test:dd',
+ graphHash: 'a'.repeat(64),
+ graphTimestamp: '2026-05-19T00:00:00.000Z',
+ algorithm: 'forward-push',
+ alpha: 0.85,
+ epsilon: 1e-3,
+ queryNode: 'n3',
+ seedNodes: [],
+ result: SAMPLE_RESULT,
+ witnessKey: key,
+ });
+ const r = verifyArtifact(envelope);
+ expect(r.valid).toBe(true);
+ expect(r.signatureValid).toBe(true);
+ expect(r.integrityValid).toBe(true);
+ expect(r.publicKey).toBe(key.publicKeyHex);
+ expect(r.complexityClass).toBe('logarithmic');
+ expect(r.coherenceScore).toBe(0.42);
+ });
+
+ it('rejects tampering with the score (signature breaks)', () => {
+ const key = generateWitnessKey();
+ const { envelope } = sealArtifact({
+ installationId: 'inst-A',
+ witnessKeyId: 'key-v1',
+ graphId: 'test:dd',
+ graphHash: 'a'.repeat(64),
+ graphTimestamp: '2026-05-19T00:00:00.000Z',
+ algorithm: 'forward-push',
+ alpha: 0.85,
+ epsilon: 1e-3,
+ seedNodes: [],
+ result: SAMPLE_RESULT,
+ witnessKey: key,
+ });
+ const forged: SignedPageRankEnvelope = JSON.parse(JSON.stringify(envelope));
+ forged.payload.result.score = 0.99;
+ const r = verifyArtifact(forged);
+ expect(r.valid).toBe(false);
+ });
+
+ it('rejects an artifact where complexityClass echo was changed', () => {
+ const key = generateWitnessKey();
+ const { envelope } = sealArtifact({
+ installationId: 'inst-A',
+ witnessKeyId: 'key-v1',
+ graphId: 'test:dd',
+ graphHash: 'a'.repeat(64),
+ graphTimestamp: '2026-05-19T00:00:00.000Z',
+ algorithm: 'forward-push',
+ alpha: 0.85,
+ epsilon: 1e-3,
+ seedNodes: [],
+ result: SAMPLE_RESULT,
+ witnessKey: key,
+ });
+ const forged: SignedPageRankEnvelope = JSON.parse(JSON.stringify(envelope));
+ forged.payload.complexityClass = 'constant';
+ const r = verifyArtifact(forged);
+ expect(r.valid).toBe(false);
+ expect(r.reason).toMatch(/complexityClass echo mismatch/);
+ });
+
+ it('rejects an artifact where coherenceScore echo was changed', () => {
+ const key = generateWitnessKey();
+ const { envelope } = sealArtifact({
+ installationId: 'inst-A',
+ witnessKeyId: 'key-v1',
+ graphId: 'test:dd',
+ graphHash: 'a'.repeat(64),
+ graphTimestamp: '2026-05-19T00:00:00.000Z',
+ algorithm: 'forward-push',
+ alpha: 0.85,
+ epsilon: 1e-3,
+ seedNodes: [],
+ result: SAMPLE_RESULT,
+ witnessKey: key,
+ });
+ const forged: SignedPageRankEnvelope = JSON.parse(JSON.stringify(envelope));
+ forged.payload.coherenceScore = 0.99;
+ expect(verifyArtifact(forged).reason).toMatch(/coherenceScore echo mismatch/);
+ });
+
+ it('rejects an artifact where resultHash echo was changed', () => {
+ const key = generateWitnessKey();
+ const { envelope } = sealArtifact({
+ installationId: 'inst-A',
+ witnessKeyId: 'key-v1',
+ graphId: 'test:dd',
+ graphHash: 'a'.repeat(64),
+ graphTimestamp: '2026-05-19T00:00:00.000Z',
+ algorithm: 'forward-push',
+ alpha: 0.85,
+ epsilon: 1e-3,
+ seedNodes: [],
+ result: SAMPLE_RESULT,
+ witnessKey: key,
+ });
+ const forged: SignedPageRankEnvelope = JSON.parse(JSON.stringify(envelope));
+ forged.payload.resultHash = '0'.repeat(64);
+ const r = verifyArtifact(forged);
+ expect(r.valid).toBe(false);
+ expect(r.reason).toMatch(/resultHash/);
+ });
+
+ it('rejects an envelope signed by an untrusted key when trust-list is set', () => {
+ const stranger = generateWitnessKey();
+ const { envelope } = sealArtifact({
+ installationId: 'inst-A',
+ witnessKeyId: 'key-v1',
+ graphId: 'test:dd',
+ graphHash: 'a'.repeat(64),
+ graphTimestamp: '2026-05-19T00:00:00.000Z',
+ algorithm: 'forward-push',
+ alpha: 0.85,
+ epsilon: 1e-3,
+ seedNodes: [],
+ result: SAMPLE_RESULT,
+ witnessKey: stranger,
+ });
+ const r = verifyArtifact(envelope, { trustedPublicKeys: ['00'.repeat(32)] });
+ expect(r.valid).toBe(false);
+ expect(r.reason).toMatch(/not in trusted list/);
+ });
+
+ it('accepts an envelope signed by a trusted key', () => {
+ const friend = generateWitnessKey();
+ const { envelope } = sealArtifact({
+ installationId: 'inst-A',
+ witnessKeyId: 'key-v1',
+ graphId: 'test:dd',
+ graphHash: 'a'.repeat(64),
+ graphTimestamp: '2026-05-19T00:00:00.000Z',
+ algorithm: 'forward-push',
+ alpha: 0.85,
+ epsilon: 1e-3,
+ seedNodes: [],
+ result: SAMPLE_RESULT,
+ witnessKey: friend,
+ });
+ const r = verifyArtifact(envelope, { trustedPublicKeys: [friend.publicKeyHex] });
+ expect(r.valid).toBe(true);
+ });
+
+ it('is byte-deterministic for identical inputs + same key + same sealedAt', () => {
+ const key = generateWitnessKey();
+ const sealedAt = '2026-05-19T01:23:45.678Z';
+ const inputs = {
+ installationId: 'inst-A',
+ witnessKeyId: 'key-v1',
+ graphId: 'test:dd',
+ graphHash: 'a'.repeat(64),
+ graphTimestamp: '2026-05-19T00:00:00.000Z',
+ algorithm: 'forward-push' as const,
+ alpha: 0.85,
+ epsilon: 1e-3,
+ seedNodes: [] as string[],
+ result: SAMPLE_RESULT,
+ witnessKey: key,
+ sealedAt,
+ };
+ const a = sealArtifact(inputs).envelope;
+ const b = sealArtifact(inputs).envelope;
+ expect(a.signature).toBe(b.signature);
+ });
+
+ it('produces a different signature when score changes', () => {
+ const key = generateWitnessKey();
+ const sealedAt = '2026-05-19T01:23:45.678Z';
+ const base = {
+ installationId: 'inst-A',
+ witnessKeyId: 'key-v1',
+ graphId: 'test:dd',
+ graphHash: 'a'.repeat(64),
+ graphTimestamp: '2026-05-19T00:00:00.000Z',
+ algorithm: 'forward-push' as const,
+ alpha: 0.85,
+ epsilon: 1e-3,
+ seedNodes: [] as string[],
+ witnessKey: key,
+ sealedAt,
+ };
+ const a = sealArtifact({ ...base, result: SAMPLE_RESULT }).envelope;
+ const altered: PageRankResult = { ...SAMPLE_RESULT, score: 0.5 };
+ const b = sealArtifact({ ...base, result: altered }).envelope;
+ expect(a.signature).not.toBe(b.signature);
+ });
+});
+
+describe('sha256Hex', () => {
+ it('hashes consistently', () => {
+ expect(sha256Hex('hello')).toBe(sha256Hex('hello'));
+ expect(sha256Hex('hello')).not.toBe(sha256Hex('world'));
+ });
+});