mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 14:16:34 +09:00
* feat(adr): reconcile deleted ADRs — hard-delete primitive + drop-and-rebuild reindex Closes #2666. `adr-index` can only add/upsert; deleting an ADR file (or a relation line from a surviving one) left an orphan row in `adr-patterns`/ `adr-edges` forever, and `adr-verify` certified the result as healthy since an orphan has no dangling ref and forms no cycle. Root cause traced into @claude-flow/cli itself, not just this plugin: `memory delete` only ever soft-deletes (status='deleted'), so the row keeps occupying its UNIQUE(namespace, key) slot and blocks a later non-upsert re-store (#2652). `memory cleanup` reaps by age/TTL/quality, not by "does the source still exist". Neither the AgentDB v3 bridge nor the sql.js fallback exposed any hard, namespace-scoped delete anywhere in the CLI/MCP surface. Separately, import.mjs/verify.mjs's spawnSync calls never passed `cwd`, so ADR_ROOT scanned the right files but could write to the wrong `.swarm/memory.db`. CLI (@claude-flow/cli): - memory-bridge.ts: bridgePurgeNamespace() — real DELETE FROM memory_entries WHERE namespace = ? against the live bridge SQLite handle, routed through the existing MutationGuard/AttestationLog hooks. - memory-initializer.ts: purgeNamespace() (bridge-then-sql.js-fallback, same shape as deleteEntry) + withMemoryDbLock() (new <dbPath>.lock O_EXCL advisory lock, same stale-takeover pattern as global-ai-budget.ts — protects against a second concurrent purge/delete on the same file; does not close #2621, which needs every writer to adopt the same lock). - commands/memory.ts: `memory purge --namespace <ns> --force [--dry-run]` — requires --namespace explicitly (no default), confirms unless --force. - package.json: sql.js was already imported directly by memory-initializer.ts's fallback path but never declared as a dependency — worked by accident under npm's loose hoisting, silently broken under this repo's strict pnpm workspace (confirmed: unmodified deleteEntry/ storeEntry fail identically). Declared explicitly. Plugin (ruflo-adr): - scripts/reindex.mjs (new) — purge both namespaces via `memory purge`, rescan every ADR currently on disk, store fresh, then re-list and assert the count equals files-on-disk (a storedRecords tally can't see a concurrent-writer clobber of the purge; a fresh recount can). Exits non-zero on failure. Full-namespace wipe rather than a selective orphan diff, since adr-edges keys always carry a fresh timestamp-rand suffix and are never deduplicated across imports — a selective pass would still leave duplicate edges accumulating for ADRs that do still exist. - scripts/lib/parse-adrs.mjs (new) — findAdrs/parseAdr and sub-parsers extracted from import.mjs so reindex.mjs doesn't duplicate ~150 lines of dual-format parsing; import.mjs shrank 322 -> 156 lines, same dry-run output verified before/after (530 ADRs, same status/relation counts). - import.mjs/verify.mjs: every npx subprocess call now passes `cwd: ROOT`. - New `/adr-reindex` skill; adr-index/adr-verify SKILL.md cross-link it. - ADR-0002 records the decision. plugin.json 0.3.0 -> 0.4.0. Verified end-to-end against a scratch repo + local CLI build: 2 ADRs indexed, one deleted from disk, re-run adr-index -> orphan survives (bug reproduced exactly as filed), run adr-reindex -> orphan gone, post-condition OK, exit 0. New tests: __tests__/memory-purge-namespace-2666.test.ts (8 cases) — namespace-scoped hard delete, cross-namespace isolation, the specific #2652 regression (non-upsert re-store of a purged key must succeed), invalid-namespace rejection, lock acquire/release/stale-takeover/ serialization. smoke.sh: 15 -> 21 checks. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(ci): restore sql.js lockfile entry lost during local drift verification A `git stash` + reinstall done while investigating unrelated pre-existing pnpm-lock.yaml drift (verifying it wasn't caused by this branch) ran with @claude-flow/cli/package.json temporarily reverted, regenerating v3/pnpm-lock.yaml without the sql.js entry the prior commit added. `git stash pop` restored package.json but not the lockfile state written while the stash was active, so the previous commit's lockfile silently lost that entry — CI's `pnpm install --frozen-lockfile` correctly caught the drift (ERR_PNPM_OUTDATED_LOCKFILE). Re-ran `pnpm install` with package.json in its correct state; frozen-lockfile install now passes clean locally, matching CI's exact step. Co-Authored-By: RuFlo <ruv@ruv.net>
129 lines
4.9 KiB
JavaScript
Executable File
129 lines
4.9 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
// adr-verify — read the persisted adr-patterns + adr-edges namespaces, surface
|
|
// dangling refs, supersede cycles, and status mismatches.
|
|
//
|
|
// Companion to scripts/import.mjs. Run after import to validate graph integrity.
|
|
// Useful in CI: exits with code 1 on supersede cycles by default, or on ANY
|
|
// issue (dangling refs, status mismatches) when VERIFY_STRICT=1 is set.
|
|
//
|
|
// Usage:
|
|
// node scripts/verify.mjs # markdown report
|
|
// VERIFY_FORMAT=json node scripts/verify.mjs # JSON for chaining
|
|
// VERIFY_STRICT=1 node scripts/verify.mjs # exit 1 on ANY issue (default: only on cycles)
|
|
// ADR_ROOT=/path/to/repo node scripts/verify.mjs # same root import.mjs was run with
|
|
|
|
import { spawnSync } from 'node:child_process';
|
|
|
|
// 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';
|
|
|
|
// #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();
|
|
|
|
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 []; }
|
|
}
|
|
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 patternEntries = memoryListJson('adr-patterns');
|
|
const edgeEntries = memoryListJson('adr-edges');
|
|
|
|
const adrIds = new Set(
|
|
patternEntries.map((e) => (e.key || '').split('::')[0]).filter(Boolean)
|
|
);
|
|
|
|
// Parse edge values to recover {from, to, relation}
|
|
const edges = [];
|
|
for (const e of edgeEntries) {
|
|
const k = e.key || '';
|
|
// key format: relation:FROM->TO:timestamp-rand
|
|
const m = /^(\w[\w-]*?):(\S+?)->(\S+?):/.exec(k);
|
|
if (m) edges.push({ relation: m[1], from: m[2], to: m[3], key: k });
|
|
}
|
|
|
|
const danglingRefs = edges.filter((e) => !adrIds.has(e.to));
|
|
const danglingFroms = edges.filter((e) => !adrIds.has(e.from));
|
|
|
|
// Cycle detection on supersedes (cycle = data corruption — ADR can't supersede itself transitively)
|
|
const supersedesGraph = new Map();
|
|
for (const e of edges.filter((e) => e.relation === 'supersedes')) {
|
|
if (!supersedesGraph.has(e.from)) supersedesGraph.set(e.from, []);
|
|
supersedesGraph.get(e.from).push(e.to);
|
|
}
|
|
const cycles = [];
|
|
function findCycle(node, visited, stack) {
|
|
if (stack.has(node)) {
|
|
cycles.push([...stack, node].join(' → '));
|
|
return;
|
|
}
|
|
if (visited.has(node)) return;
|
|
visited.add(node);
|
|
stack.add(node);
|
|
for (const next of supersedesGraph.get(node) || []) {
|
|
findCycle(next, visited, stack);
|
|
}
|
|
stack.delete(node);
|
|
}
|
|
for (const n of supersedesGraph.keys()) findCycle(n, new Set(), new Set());
|
|
|
|
const result = {
|
|
adrCount: adrIds.size,
|
|
edgeCount: edges.length,
|
|
byRelation: edges.reduce((acc, e) => { acc[e.relation] = (acc[e.relation] || 0) + 1; return acc; }, {}),
|
|
danglingRefs,
|
|
danglingFroms,
|
|
cycles: [...new Set(cycles)],
|
|
};
|
|
|
|
if (process.env.VERIFY_FORMAT === 'json') {
|
|
console.log(JSON.stringify(result, null, 2));
|
|
} else {
|
|
console.log('## ADR Graph Verification');
|
|
console.log('');
|
|
console.log(`| Metric | Value |`);
|
|
console.log(`|---|---:|`);
|
|
console.log(`| ADRs in adr-patterns | ${result.adrCount} |`);
|
|
console.log(`| Edges in adr-edges | ${result.edgeCount} |`);
|
|
for (const [k, n] of Object.entries(result.byRelation).sort((a, b) => b[1] - a[1])) {
|
|
console.log(`| edges (${k}) | ${n} |`);
|
|
}
|
|
console.log(`| Dangling 'to' refs | ${result.danglingRefs.length} |`);
|
|
console.log(`| Dangling 'from' refs | ${result.danglingFroms.length} |`);
|
|
console.log(`| Supersede cycles | ${result.cycles.length} |`);
|
|
if (result.danglingRefs.length) {
|
|
console.log('\n### Sample dangling refs');
|
|
for (const d of result.danglingRefs.slice(0, 8)) console.log(`- ${d.relation} ${d.from} → ${d.to} (missing)`);
|
|
}
|
|
if (result.cycles.length) {
|
|
console.log('\n### Cycles (DATA CORRUPTION — fix immediately)');
|
|
for (const c of result.cycles) console.log(`- ${c}`);
|
|
}
|
|
}
|
|
|
|
const strict = process.env.VERIFY_STRICT === '1';
|
|
if (result.cycles.length || (strict && (result.danglingRefs.length || result.danglingFroms.length))) {
|
|
process.exit(1);
|
|
}
|