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

10.4 KB
Raw Blame
// 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, realpathSync } from 'node:fs';
import { join, basename, relative, sep } 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.
//
// #2911: `.brain` is ruvnet-brain's own tree, holding shallow clones of
// ~50 external repos under `.brain/repo/clones/` — many carrying their
// own `docs/adr/`. Left unskipped, a walk from the project root picks up
// every foreign ADR (measured: 1,415 foreign vs 19 belonging to the
// project) and, because `.brain` sorts before `docs`, the project's own
// ADRs land dead last in the walk order — an interrupted run can index
// hundreds of foreign ADRs and zero of the project's.
export const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'v2', '.next', '.turbo', 'build', '.claude', '.brain']);

// #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')}`;
}

// #4126: an index table (README.md, index.md) or a template (template*.md) in docs/adr is not an ADR.
const NON_ADR_FILE = /^(?:readme|index|template[^/]*)\.md$/i;
// #2413: `join()` yields backslashes on Windows; match either separator so a
// Windows scan does not silently return zero ADRs.
const ADR_PATH = /(?:^|[\\/])docs[\\/]adrs?[\\/]/;

export function isAdrPath(filePath) {
  return ADR_PATH.test(filePath);
}

export function findAdrs(dir, out = [], visited = new Set()) {
  let canonical;
  try { canonical = realpathSync(dir); } catch { return out; }
  if (visited.has(canonical)) return out;
  visited.add(canonical);
  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, visited);
    } else if (e.endsWith('.md') && !NON_ADR_FILE.test(e) && isAdrPath(p)) {
      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,
    // #2413: keep the reported path repo-relative and POSIX-shaped on Windows.
    file: relative(root, path).split(sep).join('/'),
  };
}

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".
  //
  // #2781 (Jordi-Izquierdo-DDS): tolerate an optional Markdown list-item
  // prefix (`- **Status**: proposed`) — that's exactly what adr-create's
  // own template emits, and the column-0-anchored regex dropped every
  // freshly-scaffolded ADR to status=Unknown, making adr-review a no-op.
  let m = /^[-*+]?\s*\*\*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 = /^[-*+]?\s*\*\*Status:\s*([A-Za-z][A-Za-z\- ]*?)(?:\s*\([^)]*\))?\*\*\s*$/m.exec(text);
  if (m) return m[1].trim();
  // #4126: real status lines carry more than one parenthetical: a link ("superseded by
  // [ADR-025](...) (2026-07-02)"), a date plus a note ("accepted (2026-07-02) — spike
  // closed"), an amendment marker. The leading keyword is the status; ignore the rest.
  m = /^[-*+]?\s*\*\*Status:?\*\*:?[ \t]*\**[ \t]*([A-Za-z][A-Za-z-]*)\b/m.exec(text);
  return m ? m[1] : '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];
  }
  // #2659: adr-create emits metadata as Markdown list items. Accept the
  // optional list marker and both common colon placements, matching Status.
  const m = /^[-*+]?\s*\*\*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 = /^[-*+]?\s*\*\*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|(?![\s\S]))/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 });
      }
    }
  }
  // Accept qualified labels, either colon placement, and repeated fields.
  // Wrapped reference lists (#2781) remain supported, but narrative prose is
  // not a continuation: incidental ADR mentions must not invent edges (#3096).
  const values = (label) => {
    const re = new RegExp(
      `^[ \\t]*(?:[-*+]\\s+)?\\*\\*${label}(?=\\s|:|\\*\\*|/|\\()[^*\\r\\n]*\\*\\*:?[^\\S\\r\\n]*(.*)$`, 'gmi',
    );
    return [...text.matchAll(re)].map((match) => {
      let value = match[1];
      const rest = text.slice(match.index + match[0].length).split(/\r?\n/).slice(1);
      for (const line of rest) {
        const plain = line.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1');
        if (!/\bADR-?\d+\b/i.test(plain) || !/^[\s,+;&]*$/.test(plain.replace(/\bADR-?\d+\b/gi, ''))) break;
        value += `\n${line}`;
      }
      return value;
    });
  };
  for (const value of values('Supersedes')) for (const ref of extractAdrRefs(value)) out.push({ from: ref, to: selfId, relation: 'supersedes' });
  for (const value of values('(?:Amended[ -]by|Amends)')) for (const ref of extractAdrRefs(value)) out.push({ from: selfId, to: ref, relation: 'amends' });
  for (const value of values('(?:Related|Relates)')) for (const ref of extractAdrRefs(value)) out.push({ from: selfId, to: ref, relation: 'related' });
  for (const value of values('Depends[ -]on')) for (const ref of extractAdrRefs(value)) out.push({ from: selfId, to: ref, relation: 'depends-on' });
  // #4126: "Status: superseded by ADR-025" names the superseding ADR; the edge runs
  // old -> new, the same direction a "Supersedes:" line in the newer ADR produces.
  const sb = /^[-*+]?\s*\*\*Status:?\*\*:?[ \t]*\**[ \t]*superseded[ \t]+by\b(.*)$/im.exec(text);
  if (sb) {
    const [ref] = extractAdrRefs(sb[1].replace(/\[([^\]]*)\]\([^)]*\)/g, '$1'));
    if (ref && ref !== selfId) out.push({ from: selfId, to: ref, relation: 'supersedes' });
  }
  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];
}