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): fail closed when verification cannot read a complete graph

Rudy Celekli4f673fda7086
diff --git a/plugins/ruflo-adr/scripts/__tests__/verify-read-safety-3147.test.mjs b/plugins/ruflo-adr/scripts/__tests__/verify-read-safety-3147.test.mjs
new file mode 100644
index 0000000000..dfc1b91eb5
--- /dev/null
+++ b/plugins/ruflo-adr/scripts/__tests__/verify-read-safety-3147.test.mjs
@@ -0,0 +1,132 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import test from 'node:test';
+
+const verify = resolve(dirname(fileURLToPath(import.meta.url)), '../verify.mjs');
+
+function runVerifier(mode, format = 'json', extraEnv = {}) {
+ const root = mkdtempSync(join(tmpdir(), 'ruflo-adr-verify-'));
+ const bin = join(root, 'bin');
+ const project = join(root, 'project');
+ const calls = join(root, 'calls.jsonl');
+ mkdirSync(bin);
+ mkdirSync(project);
+ if (mode !== 'spawn-error') {
+ const fake = join(bin, 'npx');
+ writeFileSync(fake, `#!${process.execPath}
+const { appendFileSync } = require('node:fs');
+const args = process.argv.slice(2);
+const ns = args.find((a) => a.startsWith('--namespace='))?.split('=')[1];
+const limit = Number(args.find((a) => a.startsWith('--limit='))?.split('=')[1] || 20);
+appendFileSync(process.env.FAKE_CALLS, JSON.stringify({ args, cwd: process.cwd() }) + '\\n');
+if (process.env.FAKE_MODE === 'nonzero' && ns === 'adr-patterns') {
+ console.error('database unreadable'); process.exit(7);
+}
+if (process.env.FAKE_MODE === 'malformed' && ns === 'adr-patterns') {
+ console.log('warning\\n[]'); process.exit(0);
+}
+if (process.env.FAKE_MODE === 'nonarray' && ns === 'adr-patterns') {
+ console.log('{}'); process.exit(0);
+}
+if (process.env.FAKE_MODE === 'badrow' && ns === 'adr-patterns') {
+ console.log('[{}]'); process.exit(0);
+}
+if (process.env.FAKE_MODE === 'wrongns' && ns === 'adr-patterns') {
+ console.log(JSON.stringify([{ key: 'ADR-001', namespace: 'other' }])); process.exit(0);
+}
+if (process.env.FAKE_MODE === 'signal' && ns === 'adr-patterns') process.kill(process.pid, 'SIGTERM');
+if (process.env.FAKE_MODE === 'timeout' && ns === 'adr-patterns') {
+ setTimeout(() => {}, 10_000);
+}
+let rows = [];
+if (process.env.FAKE_MODE === 'late-cycle') {
+ rows = ns === 'adr-patterns'
+ ? Array.from({ length: 30 }, (_, i) => ({ key: 'ADR-' + String(i + 1).padStart(3, '0'), namespace: ns }))
+ : [
+ ...Array.from({ length: 25 }, (_, i) => ({ key: 'related:ADR-001->ADR-' + String(i + 2).padStart(3, '0'), namespace: ns })),
+ { key: 'supersedes:ADR-025->ADR-026', namespace: ns },
+ { key: 'supersedes:ADR-026->ADR-025', namespace: ns },
+ ];
+}
+if (process.env.FAKE_MODE === 'over-cap' && ns === 'adr-patterns') {
+ rows = Array.from({ length: 10_001 }, (_, i) => ({ key: 'ADR-' + i, namespace: ns }));
+}
+if (process.env.FAKE_MODE === 'bad-edge' && ns === 'adr-edges') {
+ rows = [{ key: 'broken edge', namespace: ns }];
+}
+console.log(JSON.stringify(rows.slice(0, limit)));
+`);
+ chmodSync(fake, 0o755);
+ }
+ const result = spawnSync(process.execPath, [verify], {
+ cwd: root,
+ env: {
+ ...process.env,
+ PATH: mode === 'spawn-error' ? bin : `${bin}:${process.env.PATH || ''}`,
+ ADR_ROOT: project,
+ VERIFY_FORMAT: format,
+ FAKE_MODE: mode,
+ FAKE_CALLS: calls,
+ ...extraEnv,
+ },
+ encoding: 'utf8',
+ timeout: 10_000,
+ });
+ const callLog = existsSync(calls) ? readFileSync(calls, 'utf8').trim().split('\n').map(JSON.parse) : [];
+ const canonicalProject = realpathSync(project);
+ rmSync(root, { recursive: true, force: true });
+ assert.equal(result.error, undefined);
+ return { ...result, calls: callLog, project: canonicalProject };
+}
+
+test('a successful, complete empty graph remains valid and uses the writer CLI and ADR_ROOT', () => {
+ const result = runVerifier('empty', 'json', { CLI_CORE: '1' });
+ assert.equal(result.status, 0);
+ const report = JSON.parse(result.stdout);
+ assert.equal(report.adrCount, 0);
+ assert.equal(report.edgeCount, 0);
+ assert.equal(result.calls.length, 2);
+ for (const call of result.calls) {
+ assert.equal(call.cwd, result.project);
+ assert.equal(call.args[0], '@claude-flow/cli@latest');
+ assert.ok(call.args.includes('--limit=10001'));
+ }
+});
+
+for (const format of ['json', 'markdown']) {
+ test(`${format}: a failed read cannot certify an empty graph`, () => {
+ const result = runVerifier('nonzero', format);
+ assert.equal(result.status, 1);
+ assert.match(result.stdout, /adr-patterns/);
+ assert.match(result.stdout, /database unreadable/);
+ assert.doesNotMatch(result.stdout, /ADRs in adr-patterns/);
+ if (format === 'json') {
+ const report = JSON.parse(result.stdout);
+ assert.equal(report.readErrors[0].namespace, 'adr-patterns');
+ assert.equal(report.adrCount, undefined);
+ }
+ });
+}
+
+for (const mode of ['spawn-error', 'signal', 'timeout', 'malformed', 'nonarray', 'badrow', 'wrongns', 'over-cap', 'bad-edge']) {
+ test(`${mode} is an incomplete or invalid read, never a healthy graph`, () => {
+ const result = runVerifier(mode, 'json', mode === 'timeout' ? { ADR_VERIFY_TIMEOUT_MS: '100' } : {});
+ assert.equal(result.status, 1);
+ const report = JSON.parse(result.stdout);
+ assert.ok(report.readErrors.length > 0);
+ assert.equal(report.adrCount, undefined);
+ });
+}
+
+test('a supersede cycle beyond the CLI default 20 rows is detected', () => {
+ const result = runVerifier('late-cycle');
+ assert.equal(result.status, 1);
+ const report = JSON.parse(result.stdout);
+ assert.equal(report.adrCount, 30);
+ assert.equal(report.edgeCount, 27);
+ assert.ok(report.cycles.length >= 1);
+});
diff --git a/plugins/ruflo-adr/scripts/verify.mjs b/plugins/ruflo-adr/scripts/verify.mjs
index bf173ac4cc..6ebed33845 100755
--- a/plugins/ruflo-adr/scripts/verify.mjs
+++ b/plugins/ruflo-adr/scripts/verify.mjs
@@ -13,43 +13,87 @@
// ADR_ROOT=/path/to/repo node scripts/verify.mjs # same root import.mjs was run with
import { spawnSync } from 'node:child_process';
-import { parseEdgeKey } from './lib/index-records.mjs';
+import { CLI_PKG, parseEdgeKey } from './lib/index-records.mjs';
-// ADR-100 / #1748 Issue 3 — CLI_CORE=1 routes to lite cli-core (~2s cold-cache).
-// verify only does list+retrieve across adr-patterns and adr-edges namespaces;
-// no semantic search needed. JSON backend is sufficient.
-const CLI_PKG = process.env.CLI_CORE === '1'
- ? '@claude-flow/cli-core@alpha'
- : '@claude-flow/cli@latest';
+// Import/reindex always use the default CLI's SQLite store (#2781). Reading
+// cli-core's separate JSON store would verify a different graph.
+if (process.env.CLI_CORE === '1') {
+ console.warn('[ruflo-adr] warning: CLI_CORE=1 is ignored for verification (#2781).');
+}
// #2666 point 2: must match whatever ADR_ROOT import.mjs/reindex.mjs were
// run with — the CLI resolves `.swarm/memory.db` relative to this
// subprocess's cwd, so a mismatched root silently reads the wrong db.
const ROOT = process.env.ADR_ROOT || process.cwd();
+// The CLI has no cursor/offset flag. Request one more than our maximum and
+// refuse a full response, since its default --limit=20 cannot prove a graph.
+const MAX_ROWS = 10_000;
+const READ_LIMIT = MAX_ROWS + 1;
+const READ_TIMEOUT_MS = Math.min(120_000, Math.max(100,
+ Number(process.env.ADR_VERIFY_TIMEOUT_MS) || 60_000));
+const MAX_BUFFER = 32 * 1024 * 1024;
function memoryListJson(namespace) {
const r = spawnSync('npx', [
CLI_PKG, 'memory', 'list',
- '--namespace', namespace, '--format', 'json',
- ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: ROOT });
- if (r.status !== 0) return [];
- const m = /\[[\s\S]*\]/.exec(r.stdout || '');
- if (!m) return [];
- try { return JSON.parse(m[0]); } catch { return []; }
+ `--namespace=${namespace}`, '--format=json', `--limit=${READ_LIMIT}`,
+ ], {
+ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: ROOT,
+ timeout: READ_TIMEOUT_MS, maxBuffer: MAX_BUFFER,
+ });
+ const fail = (error) => ({ ok: false, namespace, error });
+ if (r.error) return fail(`memory list failed: ${r.error.message}`);
+ if (r.signal) return fail(`memory list terminated by ${r.signal}`);
+ if (r.status !== 0) {
+ const detail = (r.stderr || r.stdout || '').trim().slice(0, 300);
+ return fail(`memory list exited ${r.status}${detail ? `: ${detail}` : ''}`);
+ }
+ let entries;
+ try {
+ entries = JSON.parse((r.stdout || '').trim());
+ } catch (error) {
+ return fail(`memory list returned invalid JSON: ${error.message}`);
+ }
+ if (!Array.isArray(entries)) return fail('memory list returned JSON other than an array');
+ if (entries.length >= READ_LIMIT) {
+ return fail(`memory list reached ${READ_LIMIT} rows; completeness cannot be proven`);
+ }
+ for (const [index, entry] of entries.entries()) {
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry) ||
+ typeof entry.key !== 'string' || !entry.key.trim()) {
+ return fail(`memory list row ${index} has no valid key`);
+ }
+ if (entry.namespace !== undefined && entry.namespace !== namespace) {
+ return fail(`memory list row ${index} belongs to ${entry.namespace}, not ${namespace}`);
+ }
+ }
+ return { ok: true, entries };
}
-function memoryRetrieve(namespace, key) {
- const r = spawnSync('npx', [
- CLI_PKG, 'memory', 'retrieve',
- '--namespace', namespace, '--key', key,
- ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: ROOT });
- if (r.status !== 0) return null;
- // Strip ANSI / box-drawing
- const txt = (r.stdout || '').replace(/\x1b\[[0-9;]*m/g, '');
- return txt;
+
+const patternRead = memoryListJson('adr-patterns');
+const edgeRead = memoryListJson('adr-edges');
+const readErrors = [patternRead, edgeRead].filter((read) => !read.ok)
+ .map(({ namespace, error }) => ({ namespace, error }));
+if (readErrors.length === 0) {
+ for (const [index, entry] of edgeRead.entries.entries()) {
+ if (!parseEdgeKey(entry.key)) {
+ readErrors.push({ namespace: 'adr-edges', error: `row ${index} has an invalid edge key: ${entry.key}` });
+ }
+ }
+}
+if (readErrors.length) {
+ if (process.env.VERIFY_FORMAT === 'json') {
+ console.log(JSON.stringify({ scannedRoot: ROOT, readErrors }, null, 2));
+ } else {
+ console.log('## ADR Graph Verification FAILED');
+ console.log('');
+ for (const { namespace, error } of readErrors) console.log(`- ${namespace}: ${error}`);
+ }
+ process.exit(1);
}
-const patternEntries = memoryListJson('adr-patterns');
-const edgeEntries = memoryListJson('adr-edges');
+const patternEntries = patternRead.entries;
+const edgeEntries = edgeRead.entries;
const adrIds = new Set(
patternEntries.map((e) => (e.key || '').split('::')[0]).filter(Boolean)