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

fix(ADR-058): address deep review findings across Phase 3-4 modules

rUv808a34af3dc9
diff --git a/v3/@claude-flow/cli/src/appliance/gguf-engine.ts b/v3/@claude-flow/cli/src/appliance/gguf-engine.ts
index 4a2268339b..c025d0b106 100644
--- a/v3/@claude-flow/cli/src/appliance/gguf-engine.ts
+++ b/v3/@claude-flow/cli/src/appliance/gguf-engine.ts
@@ -88,6 +88,7 @@ class BufferReader {
readF64(): number { const v = this.buf.readDoubleLE(this.offset); this.offset += 8; return v; }
readU64(): bigint { const v = this.buf.readBigUInt64LE(this.offset); this.offset += 8; return v; }
readI64(): bigint { const v = this.buf.readBigInt64LE(this.offset); this.offset += 8; return v; }
+ /** Safe for values up to 2^53. Real GGUF files never exceed this for tensor/kv counts. */
readU64AsNumber(): number { return Number(this.readU64()); }
readBool(): boolean { return this.readU8() !== 0; }
@@ -299,8 +300,16 @@ export class GgufEngine {
? request.stopSequences.map((s: string) => new this.llamaCpp.LlamaText([s]))
: undefined,
});
+ // Use llama.cpp tokenizer for accurate count when available, else estimate
+ let tokensUsed: number;
+ try {
+ const seq = this.llamaContext.getSequence();
+ tokensUsed = seq.tokenCount ?? Math.ceil(text.length / 4);
+ } catch {
+ tokensUsed = Math.ceil(text.length / 4); // ~4 chars per token heuristic
+ }
return {
- text, model: modelName, tokensUsed: text.split(/\s+/).length,
+ text, model: modelName, tokensUsed,
latencyMs: performance.now() - start, metadataOnly: false,
};
} catch (err) {
@@ -398,12 +407,13 @@ export class GgufEngine {
offset += keyLen + valLen;
}
- // Verify footer hash
- if (offset + 32 <= data.length) {
- const stored = data.subarray(offset, offset + 32);
- const computed = createHash('sha256').update(data.subarray(44, offset)).digest();
- if (!stored.equals(computed)) throw new Error('KV cache integrity check failed: hash mismatch');
+ // Verify footer hash (mandatory)
+ if (offset + 32 > data.length) {
+ throw new Error('KV cache file missing SHA256 footer');
}
+ const stored = data.subarray(offset, offset + 32);
+ const computed = createHash('sha256').update(data.subarray(44, offset)).digest();
+ if (!stored.equals(computed)) throw new Error('KV cache integrity check failed: hash mismatch');
this.kvCache = entries;
if (this.config.verbose) console.log(`[gguf-engine] KV cache loaded: ${entries.size} entries`);
diff --git a/v3/@claude-flow/cli/src/appliance/ruvllm-bridge.ts b/v3/@claude-flow/cli/src/appliance/ruvllm-bridge.ts
index befaa25d64..e892563135 100644
--- a/v3/@claude-flow/cli/src/appliance/ruvllm-bridge.ts
+++ b/v3/@claude-flow/cli/src/appliance/ruvllm-bridge.ts
@@ -15,7 +15,7 @@
import { readdir, stat } from 'node:fs/promises';
import { join, extname, basename } from 'node:path';
-import type { GgufEngine as GgufEngineType, GgufMetadata } from './gguf-engine.js';
+import type { GgufEngine as GgufEngineType } from './gguf-engine.js';
// ── Configuration ───────────────────────────────────────────
diff --git a/v3/@claude-flow/cli/src/appliance/rvfa-distribution.ts b/v3/@claude-flow/cli/src/appliance/rvfa-distribution.ts
index 87b0c13ffa..8e61f9c215 100644
--- a/v3/@claude-flow/cli/src/appliance/rvfa-distribution.ts
+++ b/v3/@claude-flow/cli/src/appliance/rvfa-distribution.ts
@@ -50,12 +50,23 @@ export interface PublishedItem { cid: string; name: string; size: number; date:
function sha256(d: Buffer): string { return createHash('sha256').update(d).digest('hex'); }
function sha256B(d: Buffer): Buffer { return createHash('sha256').update(d).digest(); }
+function detectKeyFormat(key: Buffer): { format: 'pem' | 'der'; type: string } {
+ const str = key.toString('utf-8');
+ if (str.includes('BEGIN PRIVATE KEY')) return { format: 'pem', type: 'pkcs8' };
+ if (str.includes('BEGIN PUBLIC KEY')) return { format: 'pem', type: 'spki' };
+ // Heuristic: DER-encoded keys are raw binary, never valid UTF-8 "BEGIN"
+ return { format: 'der', type: 'pkcs8' }; // caller must override type for public keys
+}
+
function edSign(data: Buffer, key: Buffer): string {
- return sign(null, data, { key, format: 'der', type: 'pkcs8' }).toString('hex');
+ const det = detectKeyFormat(key);
+ return sign(null, data, { key, format: det.format, type: det.type } as any).toString('hex');
}
function edCheck(data: Buffer, sig: string, key: Buffer): boolean {
try {
- return edVerify(null, data, { key, format: 'der', type: 'spki' }, Buffer.from(sig, 'hex'));
+ const det = detectKeyFormat(key);
+ const type = det.format === 'pem' ? det.type : 'spki'; // public key for verify
+ return edVerify(null, data, { key, format: det.format, type } as any, Buffer.from(sig, 'hex'));
} catch { return false; }
}
@@ -81,23 +92,28 @@ function pinataReq(
});
},
);
+ req.setTimeout(30_000, () => { req.destroy(new Error('Request timed out after 30s')); });
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
-function httpGet(url: string): Promise<Buffer> {
+function httpGet(url: string, maxRedirects = 5): Promise<Buffer> {
return new Promise((resolve, reject) => {
+ if (maxRedirects <= 0) return reject(new Error('Too many redirects'));
const u = new URL(url);
- httpsRequest({ hostname: u.hostname, path: u.pathname + u.search, method: 'GET' }, (res) => {
+ const req = httpsRequest({ hostname: u.hostname, path: u.pathname + u.search, method: 'GET' }, (res) => {
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
- return void httpGet(res.headers.location).then(resolve, reject);
+ return void httpGet(res.headers.location, maxRedirects - 1).then(resolve, reject);
}
const ch: Buffer[] = [];
res.on('data', (c: Buffer) => ch.push(c));
res.on('end', () => resolve(Buffer.concat(ch)));
- }).on('error', reject).end();
+ });
+ req.setTimeout(30_000, () => { req.destroy(new Error('Request timed out after 30s')); });
+ req.on('error', reject);
+ req.end();
});
}
@@ -128,6 +144,20 @@ function patchData(buf: Buffer): { start: number; end: number; section: Buffer }
return { start, end, section: buf.subarray(start, end) };
}
+/** Canonical JSON: recursive key-sorting for deterministic serialization. */
+function canonicalJson(value: unknown): string {
+ return JSON.stringify(value, (_key, val) => {
+ if (val !== null && typeof val === 'object' && !Array.isArray(val) && !Buffer.isBuffer(val)) {
+ const sorted: Record<string, unknown> = {};
+ for (const k of Object.keys(val as Record<string, unknown>).sort()) {
+ sorted[k] = (val as Record<string, unknown>)[k];
+ }
+ return sorted;
+ }
+ return val;
+ });
+}
+
/** Build a failed ApplyResult. */
function failResult(sec: string, errs: string[], extra?: Partial<ApplyResult>): ApplyResult {
return { success: false, newSize: 0, patchedSection: sec, errors: errs, ...extra };
@@ -146,7 +176,7 @@ export class RvfaPatcher {
newSectionSha256: sha256(payload), compression: comp,
};
if (opts.privateKey && opts.signedBy) {
- const signable = Buffer.concat([Buffer.from(JSON.stringify(header), 'utf-8'), payload]);
+ const signable = Buffer.concat([Buffer.from(canonicalJson(header), 'utf-8'), payload]);
header.signature = edSign(signable, opts.privateKey);
header.signedBy = opts.signedBy;
}
@@ -213,7 +243,7 @@ export class RvfaPatcher {
const { section } = patchData(patchBuf);
const unsigned = { ...header } as Record<string, unknown>;
delete unsigned.signature; delete unsigned.signedBy;
- const signable = Buffer.concat([Buffer.from(JSON.stringify(unsigned), 'utf-8'), section]);
+ const signable = Buffer.concat([Buffer.from(canonicalJson(unsigned), 'utf-8'), section]);
if (!edCheck(signable, header.signature, opts.publicKey))
return failResult(sec, ['Patch signature verification failed']);
}
diff --git a/v3/@claude-flow/cli/src/appliance/rvfa-signing.ts b/v3/@claude-flow/cli/src/appliance/rvfa-signing.ts
index 46cc2c88ff..37c7730152 100644
--- a/v3/@claude-flow/cli/src/appliance/rvfa-signing.ts
+++ b/v3/@claude-flow/cli/src/appliance/rvfa-signing.ts
@@ -12,7 +12,8 @@ import {
createPublicKey, createPrivateKey,
type KeyObject,
} from 'node:crypto';
-import { readFile, writeFile, stat, chmod } from 'node:fs/promises';
+import { readFile, writeFile, stat, chmod, mkdir } from 'node:fs/promises';
+import { dirname } from 'node:path';
// ── Constants ────────────────────────────────────────────────
@@ -84,6 +85,8 @@ export async function saveKeyPair(
dir: string,
name = 'rvfa-signing',
): Promise<{ publicKeyPath: string; privateKeyPath: string }> {
+ await mkdir(dir, { recursive: true });
+
const pubPath = `${dir}/${name}.pub`;
const privPath = `${dir}/${name}.key`;
diff --git a/v3/@claude-flow/cli/src/commands/appliance-advanced.ts b/v3/@claude-flow/cli/src/commands/appliance-advanced.ts
index b7ceaf2d9e..2be0051d67 100644
--- a/v3/@claude-flow/cli/src/commands/appliance-advanced.ts
+++ b/v3/@claude-flow/cli/src/commands/appliance-advanced.ts
@@ -84,7 +84,7 @@ export const signCommand: Command = {
}
const s = new signing.RvfaSigner(privateKey);
- const meta = await s.signAppliance(file);
+ const meta = await s.signAppliance(file, signer);
output.printSuccess('Appliance signed successfully');
output.printInfo(`Algorithm: ${meta.algorithm}`);
output.printInfo(`Fingerprint: ${meta.publicKeyFingerprint}`);