Files
ruflo/plugins/ruflo-adr/scripts/lib/parse-adrs.mjs
T
rUv 810b13dcd6 fix: tracker-sweep 2026-07-26 (v3.32.10) — 9 bugs + promo seed + follow-ups (#2788)
* fix: tracker sweep 2026-07-26 — 9 bug fixes + promo seed

Closes: #2770 #2774 #2776 #2777 #2781 #2782 #2785 #2786 (Codex follow-up)
Refs:   #2775 (memory upsert semantics)

- Statusline promo row blank on new installs — restored cold-start local
  seed pool that ADR-311 had emptied. Remote Cognitum-served pool
  (funnel.ruv.io/v1/messages) remains authoritative via
  eligibleMessagesFromPools (remote wins by id); seed only fills the
  ≤ 60s cold-start window before first successful remote fetch.
- #2777 — ruflo init no longer imports the entire ruvnet/ruflo repo
  (97 MB, 384 SKILL.md) into .agents/skills/ruflo/. Materializes single
  platform SKILL.md; detects "bloated" prior install and re-materializes.
- #2781 — ruflo-adr adr-index no longer silently drops ADR data: status
  regex accepts "- **Status**: proposed"; single-line and wrapped
  relation lines parse fully; CLI_CORE=1 warns and unifies namespace.
- #2770 — Windows: browser-session MCP tools + two init execFileSync npx
  sites now set shell: process.platform === 'win32' so cmd.exe resolves
  npx.cmd. POSIX behavior unchanged.
- #2782 — WorkerDaemon.saveState + autopilot-state.saveState + appendLog
  no longer race on shared .tmp filename; all three call writeFileAtomic
  (pid + timestamp + random-suffixed temp).
- #2785 — ruflo hooks post-task accepts --task/-t and --store-results
  flags matching CLAUDE.md-documented usage; routing outcomes finally
  persist to the namespace hooks_metrics reads.
- #2786 — AgentDB no longer silently fails to initialize under
  CLAUDE_FLOW_ENCRYPT_AT_REST=1. New getAgentDbPath() returns
  agentdb-memory.db in the same directory as memory.db, so the
  ControllerRegistry native better-sqlite3 opens a distinct file from
  the sql.js CRUD writer's encrypted memory.db.
- #2776 — Statusline security STALE/IN_PROGRESS branches reachable via
  local overlay recomputing freshness on every render from
  .claude/security-scans/scan-*.json. Env: RUFLO_SCAN_STALE_HOURS (24),
  RUFLO_SCAN_PENDING_CAP_MIN (30). STALE renders dim gray.
- #2774 — Codex MCP generator registers dedicated stdio server binary
  claude-flow-mcp instead of the management CLI ruflo mcp start that
  never answers initialize. All 7 wrong-command sites fixed
  (initializer.ts + 6 template sites in generators/config-toml.ts + 2
  in migrations/index.ts + generators.test.ts:653 assertion).
- #2775 — Memory store to existing key no longer dead-ends:
  bridgeStoreEntry uses INSERT ... ON CONFLICT with tombstone
  auto-resurrect; UNIQUE returns typed error instead of null (no more
  misleading demotion into #2735 guard); bridgeDeleteEntry runs
  wal_checkpoint(PASSIVE); CLI memory store --upsert default
  materialized locally (parser.applyDefaults bug).
- Stale ruflo-rebrand assertion in codex/tests/generators.test.ts:192
  updated Co-Authored-By: claude-flow → ruflo-bot.

- #2786 fix-2/3 (hooks_metrics reads dead .claude-flow/memory/store.json;
  bridgeRecordFeedback calls non-existent agentdb API) — architectural
  rewire, needs separate PR.
- #2775 defect #3 root cause (parser.ts applyDefaults doesn't apply
  subcommand-declared defaults) — flagged by agent, other subcommands
  affected too.
- #2775 memory-tools.ts MCP tool schema still defaults upsert:false
  (parity fix flagged).

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(parser): applyDefaults now walks subcommand + command options (#2775 follow-up)

Previously only `this.globalOptions` were walked. Any subcommand-declared
`default: <value>` silently dropped and the action handler received
`undefined`. The immediate victim was `memory store --upsert` (per #2775),
but the bug is generic — every subcommand that relies on a per-flag
default was affected.

Fix: applyDefaults now accepts optional command + subcommand, walks all
three layers narrow-to-broad (subcommand > command > global), and the
first layer to supply a value wins (because it only writes when the flag
is `undefined`, so earlier writers stick).

Parser tests: 52/52 pass. Build: tsc exit 0.

Refs: #2775 (root cause behind the CLI --upsert workaround already in
`commands/memory.ts`; the workaround is now redundant but harmless).

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(mcp): memory_store defaults upsert=true for CLI parity (#2775 follow-up)

The CLI `memory store` command defaults `--upsert=true` (issue #2594, fix
c36cb4d66) so `store → delete → store` on the same (namespace, key)
doesn't trip the `UNIQUE(namespace, key)` constraint against a
soft-deleted row. The `memory_store` MCP tool schema still defaulted
`upsert: false`, so every agent-facing store-to-existing-key hit the
strict-insert path unless the caller explicitly passed `upsert: true` —
different behavior than the CLI documented.

Fix: schema description now states default true, handler reads
`input.upsert !== false` (only explicit `upsert: false` opts out).
Symmetric with the CLI-side workaround in `commands/memory.ts`.

Refs: #2775 (MCP parity follow-up flagged by the sweep agent).

Co-Authored-By: RuFlo <ruv@ruv.net>

* docs(changelog): re-scope tracker sweep to 3.32.10 + reflect final commit set

- Rename header 3.28.1 → 3.32.10 (patch on the actual current 3.32.9;
  the original 3.28.1 heading was left over from the stale-base draft
  before the rebase onto origin/main).
- Remove the #2774 bullet from the "Fixed" list — that fix was reverted
  during rebase (upstream d20f1323b superseded it and the reporter's
  diagnosis appears incorrect). Move #2774 to a new "Investigated"
  subsection with the analysis and a note recommending closure.
- Fold the #2775 parser follow-up (parser.ts:applyDefaults walks
  subcommand + command options) and the MCP parity follow-up
  (memory_store default upsert=true) into the #2775 bullet, since
  they're the same defect surfacing at three layers.
- Drop the "stale rebrand test assertion" bullet — that assertion is
  now on origin/main already; no notable delta in this PR.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(hooks): dual-write routing decisions to JSON store for metrics reader (#2786 fix-2)

Previously `hooks_post-task --store-results` wrote routing outcomes to
AgentDB namespace `patterns` via `storeFn`, but the sync reader
`getIntelligenceStatsFromMemory()` only reads
`.claude-flow/memory/store.json`. Result: the "Pattern Learning" and
"Agent Routing" numbers in `hooks_metrics` stayed at zero even when
routing decisions were being recorded.

Fix: after the AgentDB write, mirror the same entry into the JSON store
with `metadata.type = 'routing-decision'` so the reader's filter
picks it up. AgentDB stays authoritative for cross-session retrieval;
the JSON store is the counter surface the sync reader depends on. Both
writes are wrapped in try/catch so a failure at either layer doesn't
break `hooks_post-task`.

Same shape as the existing dual-write pattern for `hooks_post-command`
at line 910-931. Keeps `getIntelligenceStatsFromMemory` synchronous
(would require async ripple through 3 callers otherwise).

Refs: #2786 fix-2 (flagged as architectural by the sweep agent — turns
out to be one bounded additive write, not a rewire).

Co-Authored-By: RuFlo <ruv@ruv.net>

* test(parser): regression coverage for command + subcommand defaults (#2775)

Three new tests in the existing `defaults` describe block:
- command-level `option.default` applies to a flagless invocation
- subcommand-level `option.default` applies to a subcommand invocation
  (this is the exact shape that trapped `memory store --upsert`)
- explicit `--no-upsert` still overrides the default:true

Guards against a re-regression of parser.ts:applyDefaults collapsing
back to only walking `globalOptions`.

52/52 → 55/55 parser tests pass.

Co-Authored-By: RuFlo <ruv@ruv.net>

* test(hooks): regression guard for #2786 fix-2 JSON dual-write

New test file `hooks-post-task-routing-dual-write-2786.test.ts` runs
`hooksPostTask.handler` in a temp cwd and asserts that when called with
`storeDecisions=true`:

  - `.claude-flow/memory/store.json` is created
  - It contains a `routing-decision:<taskId>` entry
  - The entry's shape matches what `getIntelligenceStatsFromMemory()`
    filters on (`key.includes('routing') || metadata.type === 'routing-decision'`)
  - `metadata.confidence` maps from `quality` (used to compute avgConfidence)
  - `namespace` is `patterns` (parity with the AgentDB write)

Second test guards backwards compat: when `storeDecisions` is omitted,
no routing-decision entry appears in the JSON store.

Bridge is mocked (the AgentDB path's real behavior is covered elsewhere).

2/2 pass.

Co-Authored-By: RuFlo <ruv@ruv.net>

* test(funnel): regression coverage for cold-start seed pool

New test file `funnel-messages-seed-pool.test.ts` asserts the seven
invariants of the 2026-07-26 cold-start pool restoration:
  - MESSAGES is non-empty
  - contains ≥1 disclosure so the disclosure gate can unlock cold
  - every disclosure carries the exact ' · manage: ruflo settings' tail
    (ADR-301 invariant)
  - every seed message passes isValidMessage() (schema / host allowlist
    / control-char strip / 80-col cap)
  - every URL is on the exact-host allowlist (no third-party leaks)
  - contains ≥1 educational (4-in-5 rotation slots)
  - all ids are unique (rotation dedups on id)

7/7 pass. Guards against a re-empty of MESSAGES that would blank the
statusline promo row again on new installs.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(funnel): disclosure gate now consults local seed pool (E2E follow-up)

E2E validation of the 2026-07-26 sweep exposed a gap: on true cold
start (no remote cache, no network), the promo row stayed blank
because `selectDisclosureMessage` only read `getRemoteMessages()` —
my local seed disclosure in messages.ts never reached the disclosure
gate, so the gate stayed `never_seen` forever.

Fix: `getDisclosureMessagePool` now merges local `MESSAGES` with the
remote pool via the same `eligibleMessagesFromPools` helper rotation
uses (remote wins by id). This mirrors the design of the rotation
selector — the seed is a cold-start bootstrap, remote takes over as
soon as its cache populates.

Verified end-to-end: cleared funnel cache + pointed
`RUFLO_FUNNEL_MESSAGES_ENDPOINT` at an unreachable host; statusline
render emits the local disclosure ("Ruflo shows occasional tips and
sponsor notes here · manage: ruflo settings") — exactly the string
seeded in messages.ts (`local.disclosure.v1`).

Refs: 2026-07-26 tracker sweep, promo row cold-start.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-07-26 15:05:33 -07:00

202 lines
8.5 KiB
JavaScript

// 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".
//
// #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);
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.
//
// #2781 (Jordi-Izquierdo-DDS): a wrapped relation like
// **Related**: ADR-124,
// ADR-125
// silently dropped ADR-125 because `(.+)$` under /m only captures one
// physical line. Now capture the first line plus any continuation lines
// that don't look like the start of a new field (bold **Label**:), a
// heading (`##`), a horizontal rule (`---`), or a new list bullet.
// Safe because extractAdrRefs strips anything that isn't an ADR-NNN
// token, so over-capture into a plain-text continuation is harmless.
const REL = (label) => new RegExp(
`^\\*\\*${label}(?:\\s*\\([^)]*\\))?:?\\*\\*:?\\s*(.+(?:\\n(?!\\s*(?:\\*\\*[A-Za-z]|##|---|[-*+]\\s|\\d+\\.\\s))[^\\n]+)*)`,
'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];
}