π 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(adr): reconcile deleted ADRs β hard-delete primitive + drop-and-rebuild reindex (#2668)
rUvdc015986dc7c
diff --git a/plugins/ruflo-adr/.claude-plugin/plugin.json b/plugins/ruflo-adr/.claude-plugin/plugin.jsonindex 5619bfcfa2..079eb1b19c 100644--- a/plugins/ruflo-adr/.claude-plugin/plugin.json+++ b/plugins/ruflo-adr/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-adr",- "description": "ADR lifecycle management \u2014 create, index, supersede, check compliance, and link Architecture Decision Records to code via AgentDB hierarchical store + causal edges (supersedes/amends/depends-on/related)",- "version": "0.3.0",+ "description": "ADR lifecycle management \u2014 create, index, reconcile, supersede, check compliance, and link Architecture Decision Records to code via AgentDB hierarchical store + causal edges (supersedes/amends/depends-on/related)",+ "version": "0.4.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"diff --git a/plugins/ruflo-adr/README.md b/plugins/ruflo-adr/README.mdindex e77b8f72eb..e96c1aff9e 100644--- a/plugins/ruflo-adr/README.md+++ b/plugins/ruflo-adr/README.md@@ -1,10 +1,10 @@# ruflo-adr-ADR lifecycle management -- create, index, supersede, and link Architecture Decision Records to code.+ADR lifecycle management -- create, index, reconcile, supersede, and link Architecture Decision Records to code.## Overview-Manages Architecture Decision Records through their full lifecycle (proposed, accepted, deprecated, superseded). ADRs are stored as markdown files in `docs/adr/` and indexed in AgentDB with causal edges tracking supersedes/amends/depends-on relationships. Includes compliance checking that scans git diffs for ADR violations.+Manages Architecture Decision Records through their full lifecycle (proposed, accepted, deprecated, superseded). ADRs are stored as markdown files in `docs/adr/` and indexed in AgentDB with causal edges tracking supersedes/amends/depends-on relationships. Includes compliance checking that scans git diffs for ADR violations, and reconciliation (`adr-reindex`) for ADRs deleted from disk (#2666).## Installation@@ -23,9 +23,10 @@ claude --plugin-dir plugins/ruflo-adr| Skill | Usage | Description ||-------|-------|-------------|| `adr-create` | `/adr-create <title>` | Create a new ADR with sequential numbering and AgentDB registration |-| `adr-index` | `/adr-index` | Build or rebuild the ADR index and dependency graph in AgentDB |+| `adr-index` | `/adr-index` | Build or rebuild the ADR index and dependency graph in AgentDB (add/update only β never removes) || `adr-review` | `/adr-review [--branch BRANCH]` | Review code changes against accepted ADRs for compliance violations || `adr-verify` | `/adr-verify` | Read back adr-patterns + adr-edges namespaces, surface dangling refs / supersede cycles / status mismatches; exits 1 on cycles |+| `adr-reindex` | `/adr-reindex` | Reconcile a **deleted** ADR file: drop-and-rebuild adr-patterns + adr-edges from what's on disk right now |## Commands (7 subcommands)@@ -66,12 +67,13 @@ This plugin owns the `adr-patterns` AgentDB namespace. It defers to [ruflo-agent```bashbash plugins/ruflo-adr/scripts/smoke.sh-# Expected: "15 passed, 0 failed"+# Expected: "21 passed, 0 failed"```## Architecture Decisions- [`ADR-0001` β ruflo-adr plugin contract (pinning, namespace coordination, smoke as contract)](./docs/adrs/0001-adr-plugin-pattern.md)+- [`ADR-0002` β Reconcile deleted ADRs (hard-delete primitive + drop-and-rebuild reindex)](./docs/adrs/0002-reconcile-deleted-adrs.md)## Related Pluginsdiff --git a/plugins/ruflo-adr/docs/adrs/0002-reconcile-deleted-adrs.md b/plugins/ruflo-adr/docs/adrs/0002-reconcile-deleted-adrs.mdnew file mode 100644index 0000000000..86ac473ed6--- /dev/null+++ b/plugins/ruflo-adr/docs/adrs/0002-reconcile-deleted-adrs.md@@ -0,0 +1,89 @@+---+id: ADR-0002+title: Reconcile deleted ADRs β a real hard-delete primitive and a drop-and-rebuild reindex skill+status: Accepted+date: 2026-07-14+authors:+ - claude (Claude Code)+tags: [plugin, adr, agentdb, reconcile, memory, hard-delete]+---++## Context++Issue #2666: `adr-index` can add and (once #2660 is fixed) update an ADR in the `adr-patterns`/`adr-edges` namespaces, but has no way to **remove** one. Delete an ADR file, or delete a single relation line from a surviving one, and the row `adr-index` wrote for it survives every future import. `adr-verify` then certifies the resulting graph as healthy β an orphan row has no dangling ref and forms no cycle, so it's invisible to both of `adr-verify`'s checks.++Root cause traced to the underlying `@claude-flow/cli` `memory` command surface, not this plugin's own logic:++- `memory delete` (and the `deleteEntry`/`bridgeDeleteEntry` functions behind it) only ever does `UPDATE memory_entries SET status='deleted'` β a soft tombstone. The row keeps occupying its `UNIQUE(namespace, key)` slot, so a later non-upsert `memory store` for the same key still fails (#2652).+- `memory cleanup` reaps by age/TTL/quality, not by "does the source still exist" β it has no orphan concept.+- Neither the AgentDB v3 bridge (`memory-bridge.ts`) nor the sql.js fallback (`memory-initializer.ts`) exposed any hard, namespace-scoped delete.+- Separately, `import.mjs`'s and `verify.mjs`'s `spawnSync('npx', [...])` calls never passed `cwd`, so `ADR_ROOT=/other/repo node import.mjs` scanned the right files but wrote to whichever `.swarm/memory.db` happened to be under the *caller's* cwd, not `ADR_ROOT` β `getMemoryRoot()` resolves `.swarm/` relative to the CLI subprocess's cwd, confirmed in `v3/@claude-flow/cli/src/memory/memory-initializer.ts:87`.+- No lock exists anywhere around `memory.db` writes (issue #2621 is real and, before this change, completely unaddressed in the codebase).++The only reliable reconcile is therefore a **drop-and-rebuild of both namespaces**, and that requires a genuine hard delete β which didn't exist anywhere in the public CLI/MCP surface.++## Decision++### 1. New CLI primitive: `memory purge --namespace <ns> --force`++Added to `@claude-flow/cli`:+- `bridgePurgeNamespace()` (`memory-bridge.ts`) β a real `DELETE FROM memory_entries WHERE namespace = ?` against the live AgentDB v3 bridge's SQLite handle, routed through the existing `MutationGuard`/`AttestationLog` hooks (`guardValidate`/`logAttestation`, operation `'purge'`).+- `purgeNamespace()` (`memory-initializer.ts`) β tries the bridge first, falls back to the same sql.js whole-file read/mutate/rewrite shape `deleteEntry` already uses (same encryption handling via `readFileMaybeEncrypted`/`writeFileRestricted`), for parity with every other memory operation's bridge-then-fallback structure.+- `withMemoryDbLock()` β a new `<dbPath>.lock` O_EXCL advisory lock, same stale-takeover pattern as `services/global-ai-budget.ts`. Wraps `purgeNamespace`'s body. This protects against a second concurrent purge/delete on the same file; it does **not** close #2621 (a writer that doesn't call this helper β the general `memory store` path, a daemon's own write cycle β is still unprotected). That is a larger, separate change (every writer would need to adopt the same lock) and out of scope here.+- `memory purge` CLI command (`commands/memory.ts`) β requires `--namespace` explicitly (no default, to prevent an accidental blanket wipe), confirms interactively unless `--force`, supports `--dry-run`.++No new MCP tool was added deliberately β a hard, irreversible, whole-namespace delete callable by any agent without a human in the loop is a larger safety-surface increase than this issue needs; the CLI command (invoked by a script the user runs, or with explicit `--force`) is the right trust boundary for now.++### 2. `plugins/ruflo-adr/scripts/reindex.mjs`++New script, paired with the new `/adr-reindex` skill:+1. Purge `adr-patterns` and `adr-edges` via `memory purge --force`.+2. Re-scan every ADR currently on disk (same dual-format parser `import.mjs` uses) and store fresh.+3. Re-list `adr-patterns` and assert the count equals the number of files just scanned β a `storedRecords != 0` tally cannot see the failure this exists to prevent (issue's point 3): if the purge got clobbered by a concurrent writer (#2621) between step 1 and step 2, every store in step 2 still reports "ok", landing on top of resurrected rows. Only a fresh recount catches it. Exits non-zero on failure.++Full-namespace wipe rather than a selective orphan diff, deliberately: `adr-edges` keys always carry a fresh `timestamp-rand` suffix (`import.mjs`), so edges are never deduplicated across repeated imports β a selective "only remove orphans" pass would still leave duplicate edge rows accumulating for ADRs that *do* still exist. A full rebuild is simpler, avoids that accumulation as a side effect, and β as a bonus, not the goal β incidentally fixes the separate staleness problem (#2660) where a changed-but-still-present ADR's stored content never refreshes, since a fresh insert after a full purge has nothing to conflict with.++### 3. `import.mjs`/`verify.mjs` cwd fix++Every `spawnSync('npx', [...])` call in both scripts now passes `cwd: ROOT`, so `ADR_ROOT` genuinely controls which `.swarm/memory.db` gets read/written, not just which files get scanned.++### 4. Shared parser extraction++`findAdrs`/`parseAdr` (and their frontmatter/body sub-parsers) moved from `import.mjs` into `scripts/lib/parse-adrs.mjs`, imported by both `import.mjs` and `reindex.mjs`. Avoided duplicating ~150 lines of dual-format parsing a second time; `import.mjs` shrank from 322 to 156 lines with no behavior change (verified: dry-run scan of this repo still reports the same 530 ADRs / same status and relation breakdown before and after the refactor).++## Consequences++### Positive+- The repro in the issue (`rm` an ADR, re-run `adr-index`, `adr-verify` reports healthy) is now closeable: `adr-reindex` removes the orphan and the post-condition check proves it.+- `memory purge` is a general primitive, not ADR-specific β any other plugin/skill that owns a namespace and needs the same reconcile shape can reuse it directly.+- `ADR_ROOT` now does what its own doc comment always claimed.++### Negative+- One more CLI subcommand to maintain, and one more way to lose data if misused outside the reindex flow (`--namespace` is required with no default specifically to raise the bar against that).+- Doesn't fully close #2621 β documented as a known residual risk in the skill, the ADR, and the reindex script's own post-condition messaging, rather than silently claimed as fixed.++### Neutral+- `plugin.json` bumps `0.3.0 β 0.4.0` (new skill + script, backward compatible β nothing existing changed behavior except the cwd fix, which only changes behavior when `ADR_ROOT` differs from cwd, previously a latent bug).++## Verification++```bash+bash plugins/ruflo-adr/scripts/smoke.sh+# Expected: "N passed, 0 failed"++# End-to-end repro + fix, against a scratch repo with a local CLI build:+# 1. Two ADRs, adr-index β adr-patterns has 2.+# 2. rm one ADR file, adr-index again β adr-patterns still has 2 (bug reproduced).+# 3. adr-reindex β adr-patterns has 1, post-condition OK, exit 0.+```++Also see: `v3/@claude-flow/cli/__tests__/memory-purge-namespace-2666.test.ts` β unit coverage for `purgeNamespace`/`withMemoryDbLock`, including the specific #2652 regression (non-upsert re-store of a purged key must succeed, proving it's a real delete and not a tombstone).++## Related++- Issue #2666 β the bug this ADR resolves+- Issue #2652 β the UNIQUE(namespace, key) tombstone-blocks-restore bug this ADR's hard-delete works around (not itself fixed β `memory delete`'s soft-delete semantics are unchanged; `memory purge` is a new, separate, namespace-scoped primitive)+- Issue #2621 β the general memory.db concurrent-write race; partially, not fully, mitigated here+- Issue #2660 β convergence (update-in-place staleness); not this ADR's target, incidentally improved by the full-rebuild approach+- `plugins/ruflo-adr/docs/adrs/0001-adr-plugin-pattern.md` β namespace ownership + smoke-as-contract this ADR continues+- `v3/implementation/adrs/` β `services/global-ai-budget.ts`'s O_EXCL lock pattern, reused for `withMemoryDbLock`diff --git a/plugins/ruflo-adr/scripts/import.mjs b/plugins/ruflo-adr/scripts/import.mjsindex 3253c67cc0..86578eac43 100755--- a/plugins/ruflo-adr/scripts/import.mjs+++ b/plugins/ruflo-adr/scripts/import.mjs@@ -20,9 +20,9 @@// is hundreds of MCP round-trips. spawnSync over the CLI is materially faster// and avoids shell-quoting pitfalls in the ADR titles.-import { readFileSync, readdirSync, statSync } from 'node:fs';-import { join, basename } from 'node:path';+import { basename } from 'node:path';import { spawnSync } from 'node:child_process';+import { findAdrs, parseAdr } from './lib/parse-adrs.mjs';// ADR-100 / #1748 Issue 3 β CLI_CORE=1 routes to lite cli-core (~2s cold-cache).// Note: cli-core's JsonMemoryBackend overwrites by default, so the@@ -35,178 +35,6 @@ const CLI_PKG = process.env.CLI_CORE === '1': '@claude-flow/cli@latest';const ROOT = process.env.ADR_ROOT || process.cwd();-// #2474 bonus: \`.claude/worktrees/*\` mirrors the repo so every ADR was-// indexed 2-3x. Skip the whole \`.claude\` tree β it's all ruflo runtime-// state (worktrees, scheduled tasks, etc.), never authored content.-const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'v2', '.next', '.turbo', 'build', '.claude']);--// #2474 Bug 4: parseId padded ADR numbers, but extractAdrRefs's-// padStart-then-strip pipeline produced different results for the same-// numeric value. A repo mixing `0001-foo.md` (parseId β ADR-0001) with-// a body line `Supersedes: ADR-0001` (extractAdrRefs β ADR-001) drops-// every edge as dangling. Single normalizer keeps both paths in lockstep.-function normalizeAdrId(raw) {- const digits = String(raw).replace(/^ADR-?/i, '').trim();- if (!/^\d+$/.test(digits)) return `ADR-${raw}`;- // Canonical form: β€3 digits β zero-pad to 3 (legacy default);- // β₯4 digits β keep as-is. Either way, the same numeric input from- // a filename and from a body reference now produce the same key.- return digits.length >= 4 ? `ADR-${digits}` : `ADR-${digits.padStart(3, '0')}`;-}--function findAdrs(dir, out = []) {- let entries;- try { entries = readdirSync(dir); } catch { return out; }- for (const e of entries) {- if (SKIP_DIRS.has(e)) continue;- const p = join(dir, e);- let st;- try { st = statSync(p); } catch { continue; }- if (st.isDirectory()) {- findAdrs(p, out);- } else if (e.endsWith('.md') && (p.includes('/docs/adr/') || p.includes('/docs/adrs/'))) {- out.push(p);- }- }- return out;-}--function parseAdr(path) {- const text = readFileSync(path, 'utf-8');- const id = parseId(path, text);- const title = parseTitle(text);- const status = parseStatus(text);- const date = parseDate(text);- const tags = parseTags(text);- const context = parseContextFirstParagraph(text);- const links = parseLinks(text, id);- return { id, title, status, date, tags, context, links, file: path.replace(ROOT + '/', '') };-}--function parseId(path, text) {- const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);- if (fm) {- const m = /^id:\s*(\S+)/m.exec(fm[1]);- if (m) return normalizeAdrId(m[1]);- }- const fname = basename(path, '.md');- const m = /^(ADR-?\d+|\d{3,4})/i.exec(fname);- if (m) return normalizeAdrId(m[1]);- return fname;-}--function parseTitle(text) {- const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);- if (fm) {- const m = /^title:\s*(.+)$/m.exec(fm[1]);- if (m) return m[1].trim();- }- const m = /^#\s*(?:ADR-?\d+:?\s*)?(.+?)$/m.exec(text);- return m ? m[1].trim() : '(untitled)';-}--function parseStatus(text) {- const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);- if (fm) {- const m = /^status:\s*(.+)$/im.exec(fm[1]);- if (m) return m[1].trim();- }- // #2474 Bug 2: also accept `**Status:**` (colon inside the bold span),- // the widely-used Nygard / MADR style. Previous regex only matched- // `**Status**:` (colon outside) and dropped every Nygard-style ADR- // to status=Unknown. Now the colon can sit on either side of the `**`.- // Strip parenthetical qualifiers like "Proposed (v3.6.x)" -> "Proposed".- let m = /^\*\*Status:?\*\*:?\s*([A-Za-z][A-Za-z\- ]*?)(?:\s*\(.*?\))?\s*$/m.exec(text);- if (m) return m[1].trim();- // Also handle full-bold MADR style: **Status: Value** (entire phrase bolded)- m = /^\*\*Status:\s*([A-Za-z][A-Za-z\- ]*?)(?:\s*\([^)]*\))?\*\*\s*$/m.exec(text);- return m ? m[1].trim() : 'Unknown';-}--function parseDate(text) {- const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);- if (fm) {- const m = /^date:\s*(\S+)/m.exec(fm[1]);- if (m) return m[1];- }- const m = /^\*\*Date\*\*:\s*(\S+)/m.exec(text);- return m ? m[1] : '';-}--function parseTags(text) {- const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);- if (fm) {- const m = /^tags:\s*\[([^\]]+)\]/m.exec(fm[1]);- if (m) return m[1].split(',').map((s) => s.trim()).filter(Boolean);- }- const m = /^\*\*Tags\*\*:\s*(.+)$/m.exec(text);- return m ? m[1].split(',').map((s) => s.trim()).filter(Boolean) : [];-}--function parseContextFirstParagraph(text) {- const m = /^##\s*Context\s*$\s*([\s\S]+?)(?=^##\s|\Z)/m.exec(text);- if (!m) return '';- return m[1].trim().split(/\n\s*\n/)[0].replace(/\s+/g, ' ').slice(0, 400);-}--// Extract ADR-NNN references from a link line. CRITICAL: must distinguish ADR-// references from GitHub issue numbers (#1697 etc.) which the prior version-// false-positively captured as "ADR-1697". We only recognize bare numbers as-// ADR refs when they appear in a known ADR-link section AND they don't look-// like GitHub issues (no leading #, no leading "issue").-function parseLinks(text, selfId) {- const out = [];- // Frontmatter relationships- const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);- if (fm) {- for (const [field, relation] of [- ['supersedes', 'supersedes'],- ['amended-by', 'amends'],- ['amends', 'amends'],- ['related', 'related'],- ['depends-on', 'depends-on'],- ]) {- const re = new RegExp(`^${field}:\\s*\\[?([^\\]\\n]+)\\]?$`, 'mi');- const m = re.exec(fm[1]);- if (m) for (const ref of extractAdrRefs(m[1])) {- if (relation === 'supersedes') out.push({ from: ref, to: selfId, relation });- else out.push({ from: selfId, to: ref, relation });- }- }- }- // Body relationship lines. #2474 Bug 3: loosened to accept both colon- // placements (`**Supersedes:**` and `**Supersedes**:`) and an optional- // parenthetical qualifier like `**Supersedes (partial):**` β same- // tolerance as parseStatus.- const REL = (label) => new RegExp(`^\\*\\*${label}(?:\\s*\\([^)]*\\))?:?\\*\\*:?\\s*(.+)$`, 'mi');- const supersedes = REL('Supersedes').exec(text);- if (supersedes) for (const ref of extractAdrRefs(supersedes[1])) out.push({ from: ref, to: selfId, relation: 'supersedes' });- const amended = REL('(?:Amended[ -]by|Amends)').exec(text);- if (amended) for (const ref of extractAdrRefs(amended[1])) out.push({ from: selfId, to: ref, relation: 'amends' });- const related = REL('Related').exec(text);- if (related) for (const ref of extractAdrRefs(related[1])) out.push({ from: selfId, to: ref, relation: 'related' });- const dependsOn = REL('Depends[ -]on').exec(text);- if (dependsOn) for (const ref of extractAdrRefs(dependsOn[1])) out.push({ from: selfId, to: ref, relation: 'depends-on' });- return out;-}--function extractAdrRefs(s) {- const refs = new Set();- // Strip GitHub issue / commit references first to prevent false positives.- const cleaned = s- .replace(/#\d+/g, '') // #1697- .replace(/issue[s]?\s*\d+/gi, '') // issue 1697- .replace(/PR\s*\d+/gi, '') // PR 1234- .replace(/commit\s*[`a-f0-9]+/gi, '') // commit `abc123`- .replace(/`[^`]*`/g, ''); // any backtick-quoted span- const re = /\bADR-?(\d+)\b/gi;- let m;- // #2474 Bug 4: route every ADR ref through the same normalizer parseId- // uses, so a Supersedes: ADR-0001 line lands on the same node key as- // the file ADR-0001.md (was: padStart-then-strip produced ADR-001).- while ((m = re.exec(cleaned))) refs.add(normalizeAdrId(m[1]));- return [...refs];-}function memoryStore(namespace, key, value) {const valueStr = typeof value === 'string' ? value : JSON.stringify(value);@@ -221,12 +49,18 @@ function memoryStore(namespace, key, value) {// and doesn't try to interpret the leading character of the value.// This works on both legacy and current npm; the underlying CLI accepts// \`--flag=value\` and \`--flag value\` equivalently.+ // #2666 point 2: without `cwd: ROOT`, this subprocess inherits THIS+ // process's own cwd, so `ADR_ROOT=/other/repo node import.mjs` run from+ // anywhere else scans the right files but writes to the wrong+ // `.swarm/memory.db` (the CLI resolves the db path relative to the+ // subprocess's cwd, not ADR_ROOT). Every memory subprocess call in this+ // plugin must pass `cwd: ROOT` so the scan root and the db root agree.const r = spawnSync('npx', [CLI_PKG, 'memory', 'store',`--namespace=${namespace}`,`--key=${key}`,`--value=${valueStr}`,- ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: ROOT });if (r.status !== 0) {if (/UNIQUE constraint/i.test(r.stderr || r.stdout || '')) return 'exists';return 'error: ' + (r.stderr || '').slice(0, 100);@@ -238,7 +72,7 @@ const dryRun = process.env.IMPORT_DRY_RUN === '1';const fmt = process.env.IMPORT_FORMAT || 'markdown';const files = findAdrs(ROOT);-const adrs = files.map(parseAdr);+const adrs = files.map((f) => parseAdr(f, ROOT));const byId = new Map();const allEdges = [];for (const a of adrs) {diff --git a/plugins/ruflo-adr/scripts/lib/parse-adrs.mjs b/plugins/ruflo-adr/scripts/lib/parse-adrs.mjsnew file mode 100644index 0000000000..21404cca83--- /dev/null+++ b/plugins/ruflo-adr/scripts/lib/parse-adrs.mjs@@ -0,0 +1,183 @@+// Shared ADR file-scan + parse logic for the ruflo-adr plugin scripts+// (import.mjs, reindex.mjs). Extracted from import.mjs (#2666) so a+// full reconcile (reindex.mjs) doesn't duplicate ~150 lines of dual-format+// (v3-style / plugin-style frontmatter) parsing and drift out of sync with it.+//+// Pure functions only β no memory_store / subprocess calls live here. Callers+// own persistence.++import { readFileSync, readdirSync, statSync } from 'node:fs';+import { join, basename } from 'node:path';++// #2474 bonus: `.claude/worktrees/*` mirrors the repo so every ADR was+// indexed 2-3x. Skip the whole `.claude` tree β it's all ruflo runtime+// state (worktrees, scheduled tasks, etc.), never authored content.+export const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'v2', '.next', '.turbo', 'build', '.claude']);++// #2474 Bug 4: parseId padded ADR numbers, but extractAdrRefs's+// padStart-then-strip pipeline produced different results for the same+// numeric value. A repo mixing `0001-foo.md` (parseId β ADR-0001) with+// a body line `Supersedes: ADR-0001` (extractAdrRefs β ADR-001) drops+// every edge as dangling. Single normalizer keeps both paths in lockstep.+export function normalizeAdrId(raw) {+ const digits = String(raw).replace(/^ADR-?/i, '').trim();+ if (!/^\d+$/.test(digits)) return `ADR-${raw}`;+ // Canonical form: β€3 digits β zero-pad to 3 (legacy default);+ // β₯4 digits β keep as-is. Either way, the same numeric input from+ // a filename and from a body reference now produce the same key.+ return digits.length >= 4 ? `ADR-${digits}` : `ADR-${digits.padStart(3, '0')}`;+}++export function findAdrs(dir, out = []) {+ let entries;+ try { entries = readdirSync(dir); } catch { return out; }+ for (const e of entries) {+ if (SKIP_DIRS.has(e)) continue;+ const p = join(dir, e);+ let st;+ try { st = statSync(p); } catch { continue; }+ if (st.isDirectory()) {+ findAdrs(p, out);+ } else if (e.endsWith('.md') && (p.includes('/docs/adr/') || p.includes('/docs/adrs/'))) {+ out.push(p);+ }+ }+ return out;+}++export function parseAdr(path, root) {+ const text = readFileSync(path, 'utf-8');+ const id = parseId(path, text);+ const title = parseTitle(text);+ const status = parseStatus(text);+ const date = parseDate(text);+ const tags = parseTags(text);+ const context = parseContextFirstParagraph(text);+ const links = parseLinks(text, id);+ return { id, title, status, date, tags, context, links, file: path.replace(root + '/', '') };+}++function parseId(path, text) {+ const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);+ if (fm) {+ const m = /^id:\s*(\S+)/m.exec(fm[1]);+ if (m) return normalizeAdrId(m[1]);+ }+ const fname = basename(path, '.md');+ const m = /^(ADR-?\d+|\d{3,4})/i.exec(fname);+ if (m) return normalizeAdrId(m[1]);+ return fname;+}++function parseTitle(text) {+ const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);+ if (fm) {+ const m = /^title:\s*(.+)$/m.exec(fm[1]);+ if (m) return m[1].trim();+ }+ const m = /^#\s*(?:ADR-?\d+:?\s*)?(.+?)$/m.exec(text);+ return m ? m[1].trim() : '(untitled)';+}++function parseStatus(text) {+ const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);+ if (fm) {+ const m = /^status:\s*(.+)$/im.exec(fm[1]);+ if (m) return m[1].trim();+ }+ // #2474 Bug 2: also accept `**Status:**` (colon inside the bold span),+ // the widely-used Nygard / MADR style. Previous regex only matched+ // `**Status**:` (colon outside) and dropped every Nygard-style ADR+ // to status=Unknown. Now the colon can sit on either side of the `**`.+ // Strip parenthetical qualifiers like "Proposed (v3.6.x)" -> "Proposed".+ let m = /^\*\*Status:?\*\*:?\s*([A-Za-z][A-Za-z\- ]*?)(?:\s*\(.*?\))?\s*$/m.exec(text);+ if (m) return m[1].trim();+ // Also handle full-bold MADR style: **Status: Value** (entire phrase bolded)+ m = /^\*\*Status:\s*([A-Za-z][A-Za-z\- ]*?)(?:\s*\([^)]*\))?\*\*\s*$/m.exec(text);+ return m ? m[1].trim() : 'Unknown';+}++function parseDate(text) {+ const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);+ if (fm) {+ const m = /^date:\s*(\S+)/m.exec(fm[1]);+ if (m) return m[1];+ }+ const m = /^\*\*Date\*\*:\s*(\S+)/m.exec(text);+ return m ? m[1] : '';+}++function parseTags(text) {+ const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);+ if (fm) {+ const m = /^tags:\s*\[([^\]]+)\]/m.exec(fm[1]);+ if (m) return m[1].split(',').map((s) => s.trim()).filter(Boolean);+ }+ const m = /^\*\*Tags\*\*:\s*(.+)$/m.exec(text);+ return m ? m[1].split(',').map((s) => s.trim()).filter(Boolean) : [];+}++function parseContextFirstParagraph(text) {+ const m = /^##\s*Context\s*$\s*([\s\S]+?)(?=^##\s|\Z)/m.exec(text);+ if (!m) return '';+ return m[1].trim().split(/\n\s*\n/)[0].replace(/\s+/g, ' ').slice(0, 400);+}++// Extract ADR-NNN references from a link line. CRITICAL: must distinguish ADR+// references from GitHub issue numbers (#1697 etc.) which the prior version+// false-positively captured as "ADR-1697". We only recognize bare numbers as+// ADR refs when they appear in a known ADR-link section AND they don't look+// like GitHub issues (no leading #, no leading "issue").+function parseLinks(text, selfId) {+ const out = [];+ // Frontmatter relationships+ const fm = /^---\s*$([\s\S]*?)^---\s*$/m.exec(text);+ if (fm) {+ for (const [field, relation] of [+ ['supersedes', 'supersedes'],+ ['amended-by', 'amends'],+ ['amends', 'amends'],+ ['related', 'related'],+ ['depends-on', 'depends-on'],+ ]) {+ const re = new RegExp(`^${field}:\\s*\\[?([^\\]\\n]+)\\]?$`, 'mi');+ const m = re.exec(fm[1]);+ if (m) for (const ref of extractAdrRefs(m[1])) {+ if (relation === 'supersedes') out.push({ from: ref, to: selfId, relation });+ else out.push({ from: selfId, to: ref, relation });+ }+ }+ }+ // Body relationship lines. #2474 Bug 3: loosened to accept both colon+ // placements (`**Supersedes:**` and `**Supersedes**:`) and an optional+ // parenthetical qualifier like `**Supersedes (partial):**` β same+ // tolerance as parseStatus.+ const REL = (label) => new RegExp(`^\\*\\*${label}(?:\\s*\\([^)]*\\))?:?\\*\\*:?\\s*(.+)$`, 'mi');+ const supersedes = REL('Supersedes').exec(text);+ if (supersedes) for (const ref of extractAdrRefs(supersedes[1])) out.push({ from: ref, to: selfId, relation: 'supersedes' });+ const amended = REL('(?:Amended[ -]by|Amends)').exec(text);+ if (amended) for (const ref of extractAdrRefs(amended[1])) out.push({ from: selfId, to: ref, relation: 'amends' });+ const related = REL('Related').exec(text);+ if (related) for (const ref of extractAdrRefs(related[1])) out.push({ from: selfId, to: ref, relation: 'related' });+ const dependsOn = REL('Depends[ -]on').exec(text);+ if (dependsOn) for (const ref of extractAdrRefs(dependsOn[1])) out.push({ from: selfId, to: ref, relation: 'depends-on' });+ return out;+}++export function extractAdrRefs(s) {+ const refs = new Set();+ // Strip GitHub issue / commit references first to prevent false positives.+ const cleaned = s+ .replace(/#\d+/g, '') // #1697+ .replace(/issue[s]?\s*\d+/gi, '') // issue 1697+ .replace(/PR\s*\d+/gi, '') // PR 1234+ .replace(/commit\s*[`a-f0-9]+/gi, '') // commit `abc123`+ .replace(/`[^`]*`/g, ''); // any backtick-quoted span+ const re = /\bADR-?(\d+)\b/gi;+ let m;+ // #2474 Bug 4: route every ADR ref through the same normalizer parseId+ // uses, so a Supersedes: ADR-0001 line lands on the same node key as+ // the file ADR-0001.md (was: padStart-then-strip produced ADR-001).+ while ((m = re.exec(cleaned))) refs.add(normalizeAdrId(m[1]));+ return [...refs];+}diff --git a/plugins/ruflo-adr/scripts/reindex.mjs b/plugins/ruflo-adr/scripts/reindex.mjsnew file mode 100755index 0000000000..d396c2a1d8--- /dev/null+++ b/plugins/ruflo-adr/scripts/reindex.mjs@@ -0,0 +1,191 @@+#!/usr/bin/env node+// ADR index reconciler for the ruflo-adr plugin (#2666).+//+// import.mjs is convergence-only: it upserts what's on disk into+// `adr-patterns`/`adr-edges`, but has no way to remove a row whose source+// ADR file was deleted (or an edge line that was deleted from a surviving+// file) β that row survives every future import, and adr-verify.mjs+// certifies the resulting graph as "healthy" because an orphan row has no+// dangling ref and forms no cycle. See issue #2666 for the full analysis.+//+// This is reaping, not convergence, and the only reliable way to reap is a+// full drop-and-rebuild of BOTH namespaces:+// 1. Hard-purge `adr-patterns` and `adr-edges` (via the new+// `memory purge --namespace <ns> --force` CLI command, #2666 β a real+// DELETE, not `memory delete`'s soft tombstone that still trips the+// UNIQUE(namespace, key) constraint on re-store, #2652).+// 2. Re-scan every ADR currently on disk and store fresh.+// 3. Re-list the namespace and assert the count equals the number of ADR+// files scanned β a `storedRecords != 0` tally (what import.mjs prints)+// cannot see this failure mode: if step 1 got silently clobbered by a+// concurrent writer resurrecting old rows (#2621), step 2's upserts+// still report "ok", and only a fresh re-count catches the drift.+//+// This also incidentally fixes the separate staleness problem where+// `memory store` (no --upsert) leaves a changed-but-still-present ADR's+// content stale forever (#2660) β after a full purge there's nothing to+// conflict with, so every store is a clean insert of current content.+//+// Usage:+// node scripts/reindex.mjs # purge + rebuild, markdown summary+// REINDEX_FORMAT=json node scripts/reindex.mjs # JSON summary+// REINDEX_DRY_RUN=1 node scripts/reindex.mjs # report only, no purge/store+// ADR_ROOT=/path/to/repo node scripts/reindex.mjs # override scan + db root (default: cwd)+//+// #2621 caveat: the purge step is lock-protected against a second concurrent+// purge/delete on the same memory.db, but NOT against every possible+// concurrent writer (a daemon or MCP server mid a sql.js-fallback+// read-modify-write cycle can still flush an older image afterward and+// resurrect what this just purged) β that requires every memory.db writer+// to respect the same lock, which is a larger change than this reconcile+// primitive. Re-run this script if that ever happens; the post-condition+// check below will tell you.++import { basename } from 'node:path';+import { spawnSync } from 'node:child_process';+import { findAdrs, parseAdr } from './lib/parse-adrs.mjs';++const CLI_PKG = process.env.CLI_CORE === '1'+ ? '@claude-flow/cli-core@alpha'+ : '@claude-flow/cli@latest';++const ROOT = process.env.ADR_ROOT || process.cwd();+const dryRun = process.env.REINDEX_DRY_RUN === '1';+const fmt = process.env.REINDEX_FORMAT || 'markdown';++const NAMESPACES = ['adr-patterns', 'adr-edges'];++function purgeNamespace(namespace) {+ const r = spawnSync('npx', [+ CLI_PKG, 'memory', 'purge',+ `--namespace=${namespace}`,+ '--force',+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: ROOT });+ if (r.status !== 0) {+ return { success: false, error: (r.stderr || r.stdout || '').slice(0, 300) };+ }+ return { success: true };+}++function memoryStore(namespace, key, value) {+ const valueStr = typeof value === 'string' ? value : JSON.stringify(value);+ // Same argv-encoding note as import.mjs: `--flag=value` avoids npm's+ // non-ASCII-leading-dash argv rejection on em-dash titles (#2474 Bug 1).+ const r = spawnSync('npx', [+ CLI_PKG, 'memory', 'store',+ `--namespace=${namespace}`,+ `--key=${key}`,+ `--value=${valueStr}`,+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: ROOT });+ if (r.status !== 0) return 'error: ' + (r.stderr || r.stdout || '').slice(0, 100);+ return 'ok';+}++function memoryListCount(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 null;+ const m = /\[[\s\S]*\]/.exec(r.stdout || '');+ if (!m) return null;+ try { return JSON.parse(m[0]).length; } catch { return null; }+}++const files = findAdrs(ROOT);+const adrs = files.map((f) => parseAdr(f, ROOT));+const byId = new Map();+const allEdges = [];+for (const a of adrs) {+ byId.set(a.id, a);+ allEdges.push(...a.links);+}++const result = {+ scannedRoot: ROOT,+ total: adrs.length,+ edges: allEdges.length,+ dryRun,+ purge: {},+ storedRecords: 0,+ storedEdges: 0,+ errors: [],+ postCondition: null,+};++if (dryRun) {+ if (fmt === 'json') {+ console.log(JSON.stringify(result, null, 2));+ process.exit(0);+ }+ console.log('## ADR Reindex (dry run β nothing purged or written)');+ console.log('');+ console.log(`Would purge + rebuild \`adr-patterns\` and \`adr-edges\` from ${result.total} ADR file(s) under ${ROOT}.`);+ process.exit(0);+}++// Step 1: hard-purge both namespaces (drop).+for (const ns of NAMESPACES) {+ result.purge[ns] = purgeNamespace(ns);+ if (!result.purge[ns].success) {+ result.errors.push(`purge ${ns}: ${result.purge[ns].error}`);+ }+}++// Step 2: rebuild from the current on-disk scan.+for (const a of adrs) {+ const r = memoryStore('adr-patterns', `${a.id}::${basename(a.file, '.md')}`,+ `${a.title} β ${a.context || '(no context)'}\n\nfile: ${a.file}\nstatus: ${a.status}\ndate: ${a.date}\ntags: ${a.tags.join(',')}`);+ if (r === 'ok') result.storedRecords++;+ else result.errors.push(`${a.id} ${a.file}: ${r}`);+}+for (const e of allEdges) {+ const key = `${e.relation}:${e.from}->${e.to}:${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+ const r = memoryStore('adr-edges', key, JSON.stringify({ ...e, capturedAt: new Date().toISOString() }));+ if (r === 'ok') result.storedEdges++;+}++// Step 3: post-condition β re-count from a fresh `memory list`, not the+// store-loop's own "ok" tally. This is the check the issue's point 3 calls+// for: a tally of successful store calls cannot see a concurrent-writer+// clobber of the purge; a fresh recount can.+const recount = memoryListCount('adr-patterns');+result.postCondition = {+ expected: adrs.length,+ actual: recount,+ ok: recount === adrs.length,+};+if (!result.postCondition.ok) {+ result.errors.push(+ `post-condition failed: expected ${adrs.length} adr-patterns record(s) after reindex, found ${recount === null ? 'unreadable' : recount}. ` ++ `Likely cause: a concurrent memory.db writer (daemon/MCP server) raced the purge (#2621). Re-run reindex.mjs.`+ );+}++if (fmt === 'json') {+ console.log(JSON.stringify(result, null, 2));+} else {+ console.log('## ADR Reindex Summary');+ console.log('');+ console.log(`Scanned root: ${ROOT}`);+ console.log(`ADR files on disk: **${result.total}**`);+ console.log('');+ console.log('### Purge');+ for (const ns of NAMESPACES) {+ console.log(`- ${ns}: ${result.purge[ns].success ? 'purged' : `FAILED β ${result.purge[ns].error}`}`);+ }+ console.log('');+ console.log('### Rebuild');+ console.log(`- Records stored to \`adr-patterns\`: ${result.storedRecords}/${result.total}`);+ console.log(`- Edges stored to \`adr-edges\`: ${result.storedEdges}/${result.edges}`);+ console.log('');+ console.log('### Post-condition (records == ADR files on disk)');+ console.log(`- Expected: ${result.postCondition.expected}, Actual: ${result.postCondition.actual}, ${result.postCondition.ok ? 'OK' : 'FAILED'}`);+ if (result.errors.length) {+ console.log('');+ console.log('### Errors');+ for (const e of result.errors.slice(0, 10)) console.log(`- ${e}`);+ }+}++process.exit(result.postCondition.ok && result.errors.length === 0 ? 0 : 1);diff --git a/plugins/ruflo-adr/scripts/smoke.sh b/plugins/ruflo-adr/scripts/smoke.shindex c44541c98c..2f355899d1 100755--- a/plugins/ruflo-adr/scripts/smoke.sh+++ b/plugins/ruflo-adr/scripts/smoke.sh@@ -1,5 +1,5 @@#!/usr/bin/env bash-# Structural smoke test for ruflo-adr v0.2.0 (ADR-0001).+# Structural smoke test for ruflo-adr v0.4.0 (ADR-0001, ADR-0002).set -uROOT="$(cd "$(dirname "$0")/.." && pwd)"PASS=0@@ -9,10 +9,10 @@ ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }# 1. plugin.json bump + new keywords-step "1. plugin.json declares 0.3.0 with new keywords"+step "1. plugin.json declares 0.4.0 with new keywords"v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)-if [[ "$v" != "0.3.0" ]]; then- bad "expected 0.3.0, got '$v'"+if [[ "$v" != "0.4.0" ]]; then+ bad "expected 0.4.0, got '$v'"elsemiss=""for k in lifecycle compliance causal-graph mcp; do@@ -21,10 +21,10 @@ else[[ -z "$miss" ]] && ok || bad "missing keywords:$miss"fi-# 2. All 4 skills present with valid frontmatter-step "2. skills (adr-create, adr-index, adr-review, adr-verify) present with name/description/allowed-tools"+# 2. All 5 skills present with valid frontmatter+step "2. skills (adr-create, adr-index, adr-review, adr-verify, adr-reindex) present with name/description/allowed-tools"miss=""-for s in adr-create adr-index adr-review adr-verify; do+for s in adr-create adr-index adr-review adr-verify adr-reindex; dof="$ROOT/skills/$s/SKILL.md"[[ -f "$f" ]] || { miss="$miss missing-$s"; continue; }for k in 'name:' 'description:' 'allowed-tools:'; do@@ -95,14 +95,17 @@ for s in import.mjs verify.mjs; dodone[[ -z "$miss" ]] && ok || bad "$miss"-# 12. import.mjs handles both ADR formats + has issue-number false-positive guard-step "12. import.mjs supports v3 + plugin formats and strips issue numbers"-F="$ROOT/scripts/import.mjs"+# 12. shared parser lib handles both ADR formats + has issue-number false-positive+# guard (#2666: moved from import.mjs into lib/parse-adrs.mjs so reindex.mjs+# doesn't duplicate it β check the lib, and that import.mjs imports from it).+step "12. lib/parse-adrs.mjs supports v3 + plugin formats and strips issue numbers"+F="$ROOT/scripts/lib/parse-adrs.mjs"miss=""grep -q "extractAdrRefs" "$F" || miss="$miss no-extractAdrRefs"grep -q "frontmatter\|YAML\|^---" "$F" || miss="$miss no-frontmatter-handling"grep -q "#\\\\d+\|issue\|PR\\\\s*\\\\d" "$F" || miss="$miss no-issue-strip"grep -q '\*\*Status\*\*' "$F" || miss="$miss no-v3-status-pattern"+grep -q "extractAdrRefs\|parseAdr" "$ROOT/scripts/import.mjs" || miss="$miss import.mjs-not-importing-lib"[[ -z "$miss" ]] && ok || bad "$miss"# 13. verify.mjs reports cycles + dangling refs and exits 1 on cycles@@ -126,5 +129,53 @@ F="$ROOT/skills/adr-verify/SKILL.md"grep -q "scripts/verify\.mjs\|verify\.mjs" "$F" \&& ok || bad "skill does not invoke verify.mjs"+# 16. reindex.mjs present, executable, syntax-clean (#2666)+step "16. scripts/reindex.mjs executable + syntax-clean"+F="$ROOT/scripts/reindex.mjs"+miss=""+[[ -x "$F" ]] || miss="$miss not-executable"+node --check "$F" 2>/dev/null || miss="$miss syntax-error"+[[ -z "$miss" ]] && ok || bad "$miss"++# 17. reindex.mjs purges via `memory purge`, rebuilds, and asserts a post-condition+step "17. reindex.mjs purges + rebuilds + checks a post-condition"+F="$ROOT/scripts/reindex.mjs"+miss=""+grep -q "memory', 'purge'" "$F" || miss="$miss no-purge-call"+grep -q "postCondition" "$F" || miss="$miss no-post-condition"+grep -q "process.exit(result.postCondition" "$F" || miss="$miss no-fail-exit"+[[ -z "$miss" ]] && ok || bad "$miss"++# 18. adr-reindex skill references reindex.mjs+step "18. adr-reindex skill calls scripts/reindex.mjs"+F="$ROOT/skills/adr-reindex/SKILL.md"+grep -q "scripts/reindex\.mjs\|reindex\.mjs" "$F" \+ && ok || bad "skill does not invoke reindex.mjs"++# 19. shared parser lib exists and both import.mjs + reindex.mjs use it (no duplicated parsing)+step "19. import.mjs and reindex.mjs share scripts/lib/parse-adrs.mjs"+miss=""+[[ -s "$ROOT/scripts/lib/parse-adrs.mjs" ]] || miss="$miss lib-missing"+grep -q "from './lib/parse-adrs.mjs'" "$ROOT/scripts/import.mjs" || miss="$miss import.mjs-not-using-lib"+grep -q "from './lib/parse-adrs.mjs'" "$ROOT/scripts/reindex.mjs" || miss="$miss reindex.mjs-not-using-lib"+[[ -z "$miss" ]] && ok || bad "$miss"++# 20. import.mjs and verify.mjs pass cwd to every memory subprocess call (#2666 point 2)+step "20. import.mjs + verify.mjs pass cwd: ROOT to every npx memory subprocess"+miss=""+imp_calls=$(grep -c "spawnSync('npx'" "$ROOT/scripts/import.mjs")+imp_cwd=$(grep -c "cwd: ROOT" "$ROOT/scripts/import.mjs")+[[ "$imp_calls" -gt 0 && "$imp_cwd" -ge "$imp_calls" ]] || miss="$miss import.mjs($imp_cwd/$imp_calls)"+ver_calls=$(grep -c "spawnSync('npx'" "$ROOT/scripts/verify.mjs")+ver_cwd=$(grep -c "cwd: ROOT" "$ROOT/scripts/verify.mjs")+[[ "$ver_calls" -gt 0 && "$ver_cwd" -ge "$ver_calls" ]] || miss="$miss verify.mjs($ver_cwd/$ver_calls)"+[[ -z "$miss" ]] && ok || bad "$miss"++# 21. ADR-0002 exists with status Accepted+step "21. ADR-0002 (reconcile deleted ADRs) exists with status Accepted"+ADR="$ROOT/docs/adrs/0002-reconcile-deleted-adrs.md"+[[ -f "$ADR" ]] && grep -qE "^status:[[:space:]]*Accepted" "$ADR" \+ && ok || bad "ADR-0002 missing or status != Accepted"+printf "\n%s passed, %s failed\n" "$PASS" "$FAIL"[[ $FAIL -eq 0 ]] || exit 1diff --git a/plugins/ruflo-adr/scripts/verify.mjs b/plugins/ruflo-adr/scripts/verify.mjsindex ad4de58da4..3a8fbb5fdd 100755--- a/plugins/ruflo-adr/scripts/verify.mjs+++ b/plugins/ruflo-adr/scripts/verify.mjs@@ -10,6 +10,7 @@// 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 withimport { spawnSync } from 'node:child_process';@@ -20,11 +21,16 @@ 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' });+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: ROOT });if (r.status !== 0) return [];const m = /\[[\s\S]*\]/.exec(r.stdout || '');if (!m) return [];@@ -34,7 +40,7 @@ function memoryRetrieve(namespace, key) {const r = spawnSync('npx', [CLI_PKG, 'memory', 'retrieve','--namespace', namespace, '--key', key,- ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: ROOT });if (r.status !== 0) return null;// Strip ANSI / box-drawingconst txt = (r.stdout || '').replace(/\x1b\[[0-9;]*m/g, '');diff --git a/plugins/ruflo-adr/skills/adr-index/SKILL.md b/plugins/ruflo-adr/skills/adr-index/SKILL.mdindex a4a42b0f62..2296acee46 100644--- a/plugins/ruflo-adr/skills/adr-index/SKILL.md+++ b/plugins/ruflo-adr/skills/adr-index/SKILL.md@@ -66,8 +66,13 @@ tags: <comma-separated>`#1697` / `commit abc123` / `PR 1234` references inside ADR bodies are stripped before regex extraction so they don't get misread as `ADR-1697` etc. See `extractAdrRefs()` in `scripts/import.mjs`.+## What this skill cannot do++`adr-index` only ever adds/upserts. If an ADR file was deleted (or a relation line removed from a surviving file), the row it wrote stays forever β `adr-verify` won't catch it either, since an orphan has no dangling ref and forms no cycle. Use the sibling `adr-reindex` skill to reconcile a deletion (issue #2666).+## Cross-references- `adr-create` β produces the ADR files this skill consumes- `adr-review` β runs over `adr-patterns` for compliance checks- `adr-verify` (sibling skill) β runs `scripts/verify.mjs` for graph-integrity gating+- `adr-reindex` (sibling skill) β drop-and-rebuild reconcile for a deleted ADR file (this skill can only add, never remove)diff --git a/plugins/ruflo-adr/skills/adr-reindex/SKILL.md b/plugins/ruflo-adr/skills/adr-reindex/SKILL.mdnew file mode 100644index 0000000000..c12d16b49b--- /dev/null+++ b/plugins/ruflo-adr/skills/adr-reindex/SKILL.md@@ -0,0 +1,54 @@+---+name: adr-reindex+description: Reconcile the ADR index against a DELETED ADR file or relation line by dropping and rebuilding adr-patterns + adr-edges from scratch (scripts/reindex.mjs). Use when adr-index alone leaves stale rows behind.+argument-hint: ""+allowed-tools: Bash mcp__claude-flow__memory_list+---++# ADR Reindex++`adr-index` only ever **adds** or upserts rows β it has no way to remove one. Delete an ADR file (or a single relation line from a surviving file) and the row `adr-index` wrote for it survives every future `adr-index` run, forever, with no dangling-ref or cycle ever pointing at it. `adr-verify` then certifies the resulting graph as healthy, because an orphan row with zero edges in or out is invisible to both its checks. See issue #2666.++This is a different failure mode from staleness (an ADR that changed but whose stored record didn't) β that's convergence, `adr-index`'s job. This is **reaping** β the source of truth (the ADR file) is gone, so the derived cache row for it must be gone too. The only reliable way to reap is to drop both namespaces and rebuild from what's actually on disk right now.++## When to use++- After deleting an ADR file (or removing a relation line from one)+- Periodically, as a scheduled reconcile (`adr-verify` can't catch what `adr-reindex` catches β see below)+- If `adr-verify`'s ADR count looks higher than `find docs/adr -name '*.md' | wc -l`++## Steps++```bash+node plugins/ruflo-adr/scripts/reindex.mjs+```++Optional env:+- `REINDEX_FORMAT=json` β JSON instead of markdown+- `REINDEX_DRY_RUN=1` β report what would happen, purge/write nothing+- `ADR_ROOT=/path` β scan root **and** the root the underlying `memory purge`/`memory store` subprocesses run from (must match whatever root `adr-index` was last run with, or you'll reconcile the wrong repo's namespace)++## What it does++1. **Purge** β hard-deletes every row in `adr-patterns` and `adr-edges` via `memory purge --namespace <ns> --force` (the CLI's real `DELETE FROM memory_entries`, not `memory delete`'s soft tombstone that still blocks a same-key re-store β see "Why not `adr-index` + `memory delete`" below).+2. **Rebuild** β re-scans every ADR currently on disk (same dual-format parser `adr-index` uses) and stores it fresh.+3. **Post-condition** β re-lists `adr-patterns` and asserts the count equals the number of ADR files just scanned. This is stronger than `adr-index`'s "N stored, 0 errors" tally: if a concurrent memory.db writer clobbered the purge (see Caveats), the store loop would still report success on every call β only a fresh recount catches that.++Exits non-zero if the post-condition fails.++## Why not `adr-index` + `memory delete`++`memory delete` is a **soft** delete (`UPDATE ... SET status='deleted'`) β the row keeps occupying its `UNIQUE(namespace, key)` slot, so a later non-upsert `memory store` for that same key still fails. `memory cleanup` only reaps entries by age/TTL/quality, not by "does its source file still exist" β it has no orphan concept. Neither gets you back to a clean graph; only a real namespace-scoped `DELETE FROM` does, which is what `memory purge` (and this skill) uses.++## Caveats++- **Irreversible.** This purges the *entire* namespace, not a diff β always safe here because step 2 immediately rebuilds from the current on-disk truth, but don't call `memory purge` directly against `adr-patterns`/`adr-edges` outside this flow.+- **#2621 (unaddressed):** the purge is lock-protected against a second concurrent purge/delete on the same `memory.db`, but not against every writer β a daemon or MCP server mid a read-modify-write cycle on the sql.js fallback path can still flush an older image afterward and resurrect what this just purged. The post-condition check exists specifically to surface this; re-run the skill if it fails.+- Cross-repo `related`/`depends-on` edges pointing at an ADR that was never scanned in *this* root (a legitimate sibling-repo reference, not an orphan) are dropped by the rebuild the same as everything else in `adr-edges` β they only come back if the sibling repo's ADRs are indexed in the same run. This matches `adr-verify`'s own documented "dangling ref, common cause: sibling repo" caveat; it isn't new drift introduced by this skill.++## Cross-references++- `adr-index` β convergence (add/upsert); this skill is reaping (remove what's gone)+- `adr-verify` β read-back integrity check; run after reindex to confirm `adrCount` matches disk+- `scripts/reindex.mjs` β implementation+- ADR-0002 (`docs/adrs/`) β the decision record for this skilldiff --git a/plugins/ruflo-adr/skills/adr-verify/SKILL.md b/plugins/ruflo-adr/skills/adr-verify/SKILL.mdindex 40b6afeea1..0ef5e4709c 100644--- a/plugins/ruflo-adr/skills/adr-verify/SKILL.md+++ b/plugins/ruflo-adr/skills/adr-verify/SKILL.md@@ -13,6 +13,8 @@ Companion to `adr-index`. After import, reads the persisted graph and surfaces i- **Supersede cycles** β `ADR-A supersedes ADR-B` and `ADR-B supersedes ADR-A` (or longer cycles). Always data corruption.- **Status mismatches** β an ADR is the source of a `supersedes` edge but its own status isn't `Superseded`. Usually a missed status update during a successor ADR's promotion.+**What this skill cannot catch:** an `adr-patterns` row for an ADR that was deleted from disk and has zero edges referencing it or from it β invisible to every check above (issue #2666). If the reported ADR count looks higher than what's actually on disk, run `adr-reindex`, not `adr-verify` again.+## When to use- Right after `adr-index` to confirm the graph is healthy@@ -40,3 +42,4 @@ Optional env:- `adr-index` β populates the data this skill verifies- `scripts/import.mjs` β has its own dry-run validation; this skill is the read-back companion+- `adr-reindex` β reconciles a deleted ADR that `adr-verify` cannot detectdiff --git a/v3/@claude-flow/cli/__tests__/memory-purge-namespace-2666.test.ts b/v3/@claude-flow/cli/__tests__/memory-purge-namespace-2666.test.tsnew file mode 100644index 0000000000..4338ee08df--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/memory-purge-namespace-2666.test.ts@@ -0,0 +1,150 @@+/**+ * Regression guard for issue #2666 β reconciling a deleted source (e.g. an+ * ADR file removed from disk) needs a *hard* delete, not the soft+ * tombstone `memory delete`/`deleteEntry` leaves behind.+ *+ * `deleteEntry` only ever does `UPDATE memory_entries SET status='deleted'`+ * β the row keeps occupying its `UNIQUE(namespace, key)` slot, so a+ * subsequent non-upsert `storeEntry` for the same (namespace, key) still+ * fails (#2652). `purgeNamespace` must do a real+ * `DELETE FROM memory_entries WHERE namespace = ?` so that slot is+ * genuinely free again β this is the concrete, observable difference this+ * suite asserts, not just "the row doesn't show up in a list anymore".+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {+ initializeMemoryDatabase,+ storeEntry,+ listEntries,+ purgeNamespace,+ withMemoryDbLock,+} from '../src/memory/memory-initializer.js';++let tmp: string;+let dbPath: string;++beforeEach(async () => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'purge-namespace-2666-'));+ dbPath = path.join(tmp, 'memory.db');+ const init = await initializeMemoryDatabase({ dbPath, force: true, migrate: false });+ expect(init.success).toBe(true);+});++afterEach(() => {+ try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* */ }+});++describe('purgeNamespace (#2666)', () => {+ it('hard-deletes every entry in the target namespace, leaving other namespaces untouched', async () => {+ await storeEntry({ key: 'ADR-001::adr-001-foo', value: 'foo', namespace: 'adr-patterns', dbPath, generateEmbeddingFlag: false });+ await storeEntry({ key: 'ADR-002::adr-002-bar', value: 'bar', namespace: 'adr-patterns', dbPath, generateEmbeddingFlag: false });+ await storeEntry({ key: 'keep-me', value: 'unrelated', namespace: 'other-namespace', dbPath, generateEmbeddingFlag: false });++ const before = await listEntries({ namespace: 'adr-patterns', dbPath });+ expect(before.total).toBe(2);++ const result = await purgeNamespace({ namespace: 'adr-patterns', dbPath });+ expect(result.success).toBe(true);+ expect(result.deletedCount).toBe(2);++ const after = await listEntries({ namespace: 'adr-patterns', dbPath });+ expect(after.total).toBe(0);++ const other = await listEntries({ namespace: 'other-namespace', dbPath });+ expect(other.total).toBe(1);+ });++ it('is a genuine hard delete β a non-upsert re-store of a purged key does not hit the UNIQUE(namespace, key) constraint (#2652)', async () => {+ const key = 'ADR-002::adr-002-bar';+ const namespace = 'adr-patterns';++ await storeEntry({ key, value: 'original', namespace, dbPath, generateEmbeddingFlag: false, upsert: false });+ await purgeNamespace({ namespace, dbPath });++ // If the row were merely tombstoned (status='deleted'), this non-upsert+ // insert would fail the UNIQUE(namespace, key) constraint (#2652).+ const restore = await storeEntry({ key, value: 'rebuilt after reindex', namespace, dbPath, generateEmbeddingFlag: false, upsert: false });+ expect(restore.success).toBe(true);++ const after = await listEntries({ namespace, dbPath, includeContent: true });+ expect(after.total).toBe(1);+ expect(after.entries[0]?.content).toBe('rebuilt after reindex');+ });++ it('rejects an invalid namespace rather than silently no-op-ing', async () => {+ const result = await purgeNamespace({ namespace: 'not; a valid namespace', dbPath });+ expect(result.success).toBe(false);+ expect(result.error).toMatch(/invalid namespace/i);+ });++ it('is a no-op (0 deleted) on an empty/absent namespace, not an error', async () => {+ const result = await purgeNamespace({ namespace: 'never-used', dbPath });+ expect(result.success).toBe(true);+ expect(result.deletedCount).toBe(0);+ });+});++describe('withMemoryDbLock (#2666)', () => {+ it('creates and removes the lock file around the guarded operation', async () => {+ const lockFile = `${dbPath}.lock`;+ let sawLockDuringCall = false;++ await withMemoryDbLock(dbPath, () => {+ sawLockDuringCall = fs.existsSync(lockFile);+ });++ expect(sawLockDuringCall).toBe(true);+ expect(fs.existsSync(lockFile)).toBe(false);+ });++ it('releases the lock even when the guarded function throws', async () => {+ const lockFile = `${dbPath}.lock`;+ await expect(withMemoryDbLock(dbPath, () => {+ throw new Error('boom');+ })).rejects.toThrow('boom');++ expect(fs.existsSync(lockFile)).toBe(false);+ });++ it('takes over a stale lock left by a crashed process instead of hanging', async () => {+ const lockFile = `${dbPath}.lock`;+ fs.writeFileSync(lockFile, '999999999'); // a pid that cannot be this test+ const staleTime = Date.now() / 1000 - 60; // 60s old β well past the stale threshold+ fs.utimesSync(lockFile, staleTime, staleTime);++ let ran = false;+ await withMemoryDbLock(dbPath, () => { ran = true; });++ expect(ran).toBe(true);+ expect(fs.existsSync(lockFile)).toBe(false);+ });++ it('serializes two concurrent purges on the same db so they do not interleave', async () => {+ await storeEntry({ key: 'a', value: '1', namespace: 'race-ns', dbPath, generateEmbeddingFlag: false });++ const order: string[] = [];+ const slow = withMemoryDbLock(dbPath, async () => {+ order.push('slow-start');+ await new Promise((r) => setTimeout(r, 50));+ order.push('slow-end');+ });+ const fast = withMemoryDbLock(dbPath, async () => {+ order.push('fast-start');+ order.push('fast-end');+ });++ await Promise.all([slow, fast]);++ // Whichever ran first, its start+end must be contiguous β the second+ // caller cannot start until the first fully released the lock.+ const firstIsSlow = order[0] === 'slow-start';+ if (firstIsSlow) {+ expect(order).toEqual(['slow-start', 'slow-end', 'fast-start', 'fast-end']);+ } else {+ expect(order).toEqual(['fast-start', 'fast-end', 'slow-start', 'slow-end']);+ }+ });+});diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex 9f032d620f..798ad8a5fa 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -106,6 +106,7 @@"@noble/ed25519": "2.3.0","@ruvector/rabitq-wasm": "0.1.0","semver": "7.7.3",+ "sql.js": "^1.13.0","yaml": "^2.8.0"},"optionalDependencies": {diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.tsindex b0dcdbdfae..bfe836669c 100644--- a/v3/@claude-flow/cli/src/commands/memory.ts+++ b/v3/@claude-flow/cli/src/commands/memory.ts@@ -706,6 +706,97 @@ const deleteCommand: Command = {}};+// #2666 β Hard, namespace-scoped purge. `delete` above only ever+// soft-deletes a single key (status='deleted', row stays and still occupies+// the UNIQUE(namespace, key) slot β #2652). Reconciling an entire namespace+// after its source-of-truth changed (e.g. a plugin's index after a source+// file was removed) needs the row to actually be gone, not tombstoned.+// Irreversible β always requires --namespace explicitly (no default) and+// either interactive confirmation or --force.+const purgeCommand: Command = {+ name: 'purge',+ description: 'Permanently delete every entry in a namespace (hard delete β not the soft delete/tombstone that `memory delete` uses)',+ options: [+ {+ name: 'namespace',+ short: 'n',+ description: 'Namespace to purge (required β no default, to avoid an accidental whole-namespace wipe)',+ type: 'string'+ },+ {+ name: 'dry-run',+ short: 'd',+ description: 'Report how many entries would be deleted, without deleting them',+ type: 'boolean',+ default: false+ },+ {+ name: 'force',+ short: 'f',+ description: 'Skip confirmation',+ type: 'boolean',+ default: false+ },+ DB_PATH_OPTION+ ],+ examples: [+ { command: 'claude-flow memory purge --namespace stale-cache --dry-run', description: 'Preview a purge' },+ { command: 'claude-flow memory purge --namespace stale-cache --force', description: 'Purge without confirmation (e.g. in a script)' }+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const namespace = ctx.flags.namespace as string;+ const dryRun = ctx.flags.dryRun as boolean;+ const force = ctx.flags.force as boolean;+ const dbPath = ctx.flags.path as string | undefined;++ if (!namespace) {+ output.printError('Namespace is required. Use: memory purge -n "namespace" [--dry-run | --force]');+ return { success: false, exitCode: 1 };+ }++ try {+ const { listEntries, purgeNamespace, resolveDbPath: _rdbPurge } = await import('../memory/memory-initializer.js');+ const resolvedDbPath = _rdbPurge(dbPath);++ const preview = await listEntries({ namespace, limit: 1, dbPath: resolvedDbPath });+ const previewCount = preview.total ?? preview.entries?.length ?? 0;++ if (dryRun) {+ output.printInfo(`Would permanently delete ${previewCount} entr${previewCount === 1 ? 'y' : 'ies'} from namespace "${namespace}" (dry run β nothing deleted)`);+ return { success: true, data: { namespace, wouldDelete: previewCount } };+ }++ if (!force && ctx.interactive) {+ const confirmed = await confirm({+ message: `Permanently delete ${previewCount} entr${previewCount === 1 ? 'y' : 'ies'} from namespace "${namespace}"? This is a hard delete β not reversible with \`memory delete\`'s soft-undo.`,+ default: false+ });+ if (!confirmed) {+ output.printInfo('Operation cancelled');+ return { success: true };+ }+ } else if (!force) {+ output.printError(`Refusing to purge namespace "${namespace}" without --force in non-interactive mode`);+ return { success: false, exitCode: 1 };+ }++ const result = await purgeNamespace({ namespace, dbPath: resolvedDbPath });++ if (!result.success) {+ output.printError(result.error || 'Failed to purge');+ return { success: false, exitCode: 1 };+ }++ output.printSuccess(`Purged ${result.deletedCount} entr${result.deletedCount === 1 ? 'y' : 'ies'} from namespace "${namespace}"`);+ output.printInfo(`Remaining entries (all namespaces): ${result.remainingEntries}`);+ return { success: true, data: result };+ } catch (error) {+ output.printError(`Failed to purge: ${error instanceof Error ? error.message : 'Unknown error'}`);+ return { success: false, exitCode: 1 };+ }+ }+};+// Stats commandconst statsCommand: Command = {name: 'stats',@@ -1688,7 +1779,7 @@ const initMemoryCommand: Command = {export const memoryCommand: Command = {name: 'memory',description: 'Memory management commands',- subcommands: [initMemoryCommand, storeCommand, retrieveCommand, searchCommand, listCommand, deleteCommand, statsCommand, configureCommand, cleanupCommand, compressCommand, exportCommand, importCommand, distillCommand, backupCommand],+ subcommands: [initMemoryCommand, storeCommand, retrieveCommand, searchCommand, listCommand, deleteCommand, purgeCommand, statsCommand, configureCommand, cleanupCommand, compressCommand, exportCommand, importCommand, distillCommand, backupCommand],options: [],examples: [{ command: 'claude-flow memory store -k "key" -v "value"', description: 'Store data' },diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.tsindex e370e13507..025451be4a 100644--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts@@ -1239,6 +1239,70 @@ export async function bridgeDeleteEntry(options: {}}+// #2666 β Hard, namespace-scoped purge. bridgeDeleteEntry above only ever+// soft-deletes a single (namespace, key); this is a real+// `DELETE FROM memory_entries WHERE namespace = ?` against the live+// better-sqlite3-style handle, for callers (e.g. a plugin's index-reconcile+// step) that need a namespace to be genuinely empty rather than tombstoned.+// Irreversible β callers must gate this behind an explicit confirmation.+export async function bridgePurgeNamespace(options: {+ namespace: string;+ dbPath?: string;+}): Promise<{+ success: boolean;+ deletedCount: number;+ remainingEntries: number;+ guarded?: boolean;+ error?: string;+} | null> {+ const registry = await getRegistry(options.dbPath);+ if (!registry) return null;++ const ctx = getDb(registry);+ if (!ctx) return null;++ try {+ const { namespace } = options;++ const guardResult = await guardValidate(registry, 'purge', { namespace });+ if (!guardResult.allowed) {+ return { success: false, deletedCount: 0, remainingEntries: 0, error: `MutationGuard rejected: ${guardResult.reason}` };+ }++ let deletedCount = 0;+ try {+ const result = ctx.db.prepare(`DELETE FROM memory_entries WHERE namespace = ?`).run(namespace);+ deletedCount = result?.changes ?? 0;+ } catch (e) {+ return { success: false, deletedCount: 0, remainingEntries: 0, error: e instanceof Error ? e.message : String(e) };+ }++ const safeNs = String(namespace).replace(/:/g, '_');+ await cacheInvalidate(registry, `namespace:${safeNs}`);++ if (deletedCount > 0) {+ await logAttestation(registry, 'purge', namespace, { namespace, deletedCount });+ }++ let remaining = 0;+ try {+ const row = ctx.db.prepare(`SELECT COUNT(*) as cnt FROM memory_entries WHERE status = 'active'`).get();+ remaining = row?.cnt ?? 0;+ } catch {+ // Non-fatal+ }++ return {+ success: true,+ deletedCount,+ remainingEntries: remaining,+ guarded: true,+ };+ } catch {+ return null;+ }+}+// ===== Phase 2: Embedding bridge =====/**diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.tsindex 1fb75d5238..fb5490bea0 100644--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts@@ -3416,6 +3416,153 @@ export async function deleteEntry(options: {}}+// #2666 β Namespace reconciliation ("reaping"). `deleteEntry` above only ever+// soft-deletes (UPDATE ... SET status='deleted'), and the row's (namespace,+// key) stays occupied against the UNIQUE(namespace, key) constraint β a+// caller that needs a namespace to be genuinely empty (e.g. a plugin+// rebuilding its whole index after a source file was deleted, so a stale+// row would otherwise survive forever with no dangling-ref/cycle signal to+// ever catch it) has no way to get there through the public CLI/MCP surface.+// `purgeNamespace` is a real `DELETE FROM memory_entries WHERE namespace = ?`+// β irreversible, namespace-scoped, and lock-protected against a second+// concurrent purge/delete on the same db file (see withMemoryDbLock below).+//+// This does NOT fully close #2621 (a concurrent daemon/MCP server already+// mid read-modify-write on the sql.js fallback path can still flush an+// older in-memory image after this purge commits, resurrecting rows) β that+// requires every memory.db writer to respect the same lock, which is a+// larger change than this namespace-reconcile primitive. The lock here+// bounds the race to "another purge/delete running at the same instant",+// which is the concrete case this feature needs to be safe against.++const MEMORY_DB_LOCK_STALE_MS = 10_000;++function delayMs(ms: number): Promise<void> {+ return new Promise((r) => setTimeout(r, ms));+}++/**+ * Advisory O_EXCL lock scoped to a single memory.db file (`<dbPath>.lock`),+ * same stale-takeover pattern as services/global-ai-budget.ts. Only+ * meaningful between callers that opt into it (purgeNamespace does); it+ * cannot coordinate against writers that don't call this helper.+ */+export async function withMemoryDbLock<T>(dbPath: string, fn: () => Promise<T> | T): Promise<T> {+ const lockFile = `${dbPath}.lock`;+ const deadline = Date.now() + 5000;+ for (;;) {+ try {+ const fd = fs.openSync(lockFile, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);+ fs.writeSync(fd, String(process.pid));+ fs.closeSync(fd);+ try {+ return await fn();+ } finally {+ try { fs.unlinkSync(lockFile); } catch { /* already gone */ }+ }+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;+ try {+ const st = fs.lstatSync(lockFile);+ if (Date.now() - st.mtimeMs > MEMORY_DB_LOCK_STALE_MS) {+ fs.unlinkSync(lockFile);+ continue;+ }+ } catch { /* raced β retry */ }+ if (Date.now() > deadline) {+ throw new Error(`timed out acquiring memory.db lock: ${lockFile}`);+ }+ await delayMs(25);+ }+ }+}++const NAMESPACE_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;++export async function purgeNamespace(options: {+ namespace: string;+ dbPath?: string;+}): Promise<{+ success: boolean;+ deletedCount: number;+ remainingEntries: number;+ error?: string;+}> {+ const { namespace, dbPath: customPath } = options;++ if (!NAMESPACE_PATTERN.test(namespace)) {+ return { success: false, deletedCount: 0, remainingEntries: 0, error: `Invalid namespace: ${namespace}` };+ }++ const swarmDir = getMemoryRoot();+ const dbPath = customPath ? path.resolve(customPath) : path.join(swarmDir, 'memory.db');++ return withMemoryDbLock(dbPath, async () => {+ // ADR-053: try the AgentDB v3 bridge first β a real SQLite handle, so+ // the DELETE is a genuine transactional statement, not a whole-file+ // read/mutate/rewrite.+ const bridge = await getBridge();+ if (bridge) {+ const bridgeResult = await bridge.bridgePurgeNamespace({ namespace, dbPath });+ if (bridgeResult) {+ if (bridgeResult.deletedCount > 0 && hnswIndex?.entries) {+ for (const [id, entry] of hnswIndex.entries) {+ if (((entry as any)?.namespace ?? 'default') === namespace) hnswIndex.entries.delete(id);+ }+ saveHNSWMetadata();+ rebuildSearchIndex();+ }+ return bridgeResult;+ }+ }++ // Fallback: raw sql.js, same whole-file read/mutate/rewrite shape as+ // deleteEntry's fallback path above (and the same encryption handling).+ try {+ if (!fs.existsSync(dbPath)) {+ return { success: false, deletedCount: 0, remainingEntries: 0, error: 'Database not found' };+ }++ await ensureSchemaColumns(dbPath);++ const initSqlJs = (await import('sql.js')).default;+ const SQL = await initSqlJs();++ const fileBuffer = readFileMaybeEncrypted(dbPath, null);+ const db = new SQL.Database(fileBuffer);++ const beforeResult = db.exec(`SELECT COUNT(*) FROM memory_entries WHERE namespace = ?`, [namespace]);+ const deletedCount = (beforeResult[0]?.values?.[0]?.[0] as number) || 0;++ db.run(`DELETE FROM memory_entries WHERE namespace = ?`, [namespace]);++ const countResult = db.exec(`SELECT COUNT(*) FROM memory_entries WHERE status = 'active'`);+ const remainingEntries = (countResult[0]?.values?.[0]?.[0] as number) || 0;++ const data = db.export();+ writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });+ db.close();++ if (deletedCount > 0 && hnswIndex?.entries) {+ for (const [id, entry] of hnswIndex.entries) {+ if (((entry as any)?.namespace ?? 'default') === namespace) hnswIndex.entries.delete(id);+ }+ saveHNSWMetadata();+ rebuildSearchIndex();+ }++ return { success: true, deletedCount, remainingEntries };+ } catch (error) {+ return {+ success: false,+ deletedCount: 0,+ remainingEntries: 0,+ error: error instanceof Error ? error.message : String(error),+ };+ }+ });+}+export default {initializeMemoryDatabase,checkMemoryInitialization,@@ -3430,6 +3577,8 @@ export default {listEntries,getEntry,deleteEntry,+ purgeNamespace,+ withMemoryDbLock,rebuildSearchIndex,MEMORY_SCHEMA_V3,getInitialMetadatadiff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex 218e3e03d3..5375b4be9e 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -43,7 +43,7 @@ importers:version: 5.9.3vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/aidefence':dependencies:@@ -109,7 +109,7 @@ importers:version: 5.9.3vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/cli':dependencies:@@ -134,6 +134,9 @@ importers:semver:specifier: 7.7.3version: 7.7.3+ sql.js:+ specifier: ^1.13.0+ version: 1.14.1yaml:specifier: ^2.8.0version: 2.8.2@@ -204,7 +207,7 @@ importers:version: 5.9.3vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/deployment':dependencies:@@ -217,7 +220,7 @@ importers:version: 25.0.2([email protected])vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/embeddings':dependencies:@@ -267,7 +270,7 @@ importers:version: 5.9.3vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/hooks':dependencies:@@ -299,7 +302,7 @@ importers:version: 5.9.3vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/integration':dependencies:@@ -344,7 +347,7 @@ importers:version: 8.18.1vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/memory':dependencies:@@ -393,7 +396,7 @@ importers:devDependencies:vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/plugin-agent-federation':dependencies:@@ -443,7 +446,7 @@ importers:version: 5.9.3vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/plugins':dependencies:@@ -471,7 +474,7 @@ importers:version: 5.9.3vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/providers':dependencies:@@ -496,7 +499,7 @@ importers:version: 5.9.3vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/security':dependencies:@@ -512,7 +515,7 @@ importers:devDependencies:vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/shared':dependencies:@@ -546,7 +549,7 @@ importers:version: 7.2.0vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])ws:specifier: ^8.16.0version: 8.19.0@@ -558,7 +561,7 @@ importers:devDependencies:vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])'@claude-flow/testing':devDependencies:@@ -576,7 +579,7 @@ importers:version: 5.9.3vitest:specifier: '>=4.1.0'- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])packages:@@ -6327,7 +6330,7 @@ packages:obug: 2.1.1std-env: 4.1.0tinyrainbow: 3.1.0- vitest: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])+ vitest: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])dev: true/@vitest/[email protected]:@@ -6355,7 +6358,7 @@ packages:'@vitest/spy': 4.1.8estree-walker: 3.0.3magic-string: 0.30.21- vite: 7.3.0(@types/[email protected])([email protected])+ vite: 7.3.0(@types/[email protected])([email protected])dev: true/@vitest/[email protected]:@@ -6556,7 +6559,7 @@ packages:ora: 7.0.1ruvector: 0.1.95([email protected])ruvector-attention-wasm: 0.1.0- sql.js: 1.13.0+ sql.js: 1.14.1zod: 3.25.76optionalDependencies:'@opentelemetry/auto-instrumentations-node': 0.47.1(@opentelemetry/[email protected])@@ -7005,7 +7008,7 @@ packages:express: 5.2.1fastmcp: 3.26.7http-proxy-middleware: 3.0.5- sql.js: 1.14.0+ sql.js: 1.14.1tiktoken: 1.0.22ulid: 3.0.2validator: 13.15.26@@ -11782,12 +11785,6 @@ packages:resolution: {integrity: sha512-RJbVP1HRDlUUXahJ7VMTcu9Rm1Nzw+EBpoPr94vnbD4LwR715F3CcxE2G2k45PewcaZ57pjetYa+LoSJLAASgA==}dev: false- resolution: {integrity: sha512-NXYh+kFqLiYRCNAaHD0PcbjFgXyjuolEKLMk5vRt2DgPENtF1kkNzzMlg42dUk5wIsH8MhUzsRhaUxIisoSlZQ==}- requiresBuild: true- dev: false- optional: true-resolution: {integrity: sha512-gcj8zBWU5cFsi9WUP+4bFNXAyF1iRpA3LLyS/DP5xlrNzGmPIizUeBggKa8DbDwdqaKwUcTEnChtd2grWo/x/A==}requiresBuild: true@@ -12571,7 +12568,6 @@ packages:yaml: 2.8.2optionalDependencies:fsevents: 2.3.3- dev: false/[email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected]):resolution: {integrity: sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==}@@ -12703,7 +12699,7 @@ packages:tinyexec: 1.0.2tinyglobby: 0.2.15tinyrainbow: 3.1.0- vite: 7.3.0(@types/[email protected])([email protected])+ vite: 7.3.0(@types/[email protected])([email protected])why-is-node-running: 2.3.0transitivePeerDependencies:- msw