mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-25 06:36:49 +09:00
dbb88fdc3722069cd7fa079ad34ee04bd444f182
1066
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
9056720219 |
fix(browser): #2015 round 2 — strip bogus --kind flag, ship alpha.42
Round 1 (alpha.41) added the required --dimension flag to `ruvector rvf create` but left the equally bogus `--kind browser-session` in place. ruvector@0.2.25's `rvf create` accepts only: -d, --dimension <n> (required) -m, --metric <metric> (optional, default cosine) Commander's required-option check fires before its unknown-option check, so the original bug report (#2015) only surfaced the dimension error. The fresh live regression check after publishing alpha.41 exposed the second-layer bug: `error: unknown option '--kind'`. This round: - Strip `--kind browser-session` from all 5 call sites (TS source, compiled dist via rebuild, replay-spike.sh, browser-agent.md, browser-record/SKILL.md). Also fixed the ADR prose example. - Tighten the smoke (scripts/smoke-browser-rvf-create-flags.mjs): - Switch from rg-based content scan to an explicit PATHS_IN_SCOPE list (the original `--kind browser-session` anchor is gone, so we can no longer identify call sites by content). - Police BOTH invariants per line: * --dimension / -d is present * --kind is ABSENT (since ruvector@0.2.25 rejects it) - Skip quoted-string false positives ('rvf create failed' log lines). Versions: @claude-flow/cli 3.7.0-alpha.42 claude-flow 3.7.0-alpha.42 ruflo 3.7.0-alpha.42 @claude-flow/memory 3.0.0-alpha.16 (unchanged, #2019 fix already live) Post-publish live functional check (everything green): - ruvector rvf create --dimension 384 (no --kind): exit 0, .rvf file written. Reproduces what the MCP tool now invokes. - Published CLI dist:113 carries '--dimension','384', no --kind. - #2019 vectorBackend / graphAdapter functional test from alpha.41 still passes against published memory@3.0.0-alpha.16. - verify.mjs precondition contract still holds. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
e4bd9bbcbe |
fix(verify+memory+browser): #1880, #2019, #2015 — three precondition/contract fixes + CI guards
Three small but recurring bugs ship together because they share the same anti-pattern: a try/catch (or a missing flag) silently turned a clear precondition failure into a vague "verification failed" / "controller disabled" / "rvf create failed" outcome that downstream consumers couldn't act on. #1880 — witness verify exits 1 on source-only checkouts - The 12h scheduled verification has been filing a duplicate "HIGH — verification broken" issue every cron run since 2026-05-10 because the runner does a source-only checkout (no @noble/ed25519 install, no `npm run build`) and verify.mjs lumped that into the same exit-1 bucket as a real signature regression. - verify.mjs now reserves exit 2 strictly for precondition misses: * @noble/ed25519 not installed → exit 2 * every manifest entry missing AND manifest → exit 2 references /dist/ paths (= "dist not built") Real failures (signature invalid, specific marker regressed) keep exit 1. The scheduled runner can now distinguish "needs install/build" from "we broke something". - New CI guard: scripts/smoke-witness-verify-precondition.mjs drives all three shapes (missing dep, all-files-missing, built tree) and asserts the exit code contract. - Wired into v3-ci.yml as witness-verify-precondition-smoke and into witness-verify's `needs:` so a contract break blocks publish. #2019 — vectorBackend controller permanently disabled - @claude-flow/memory's controller-registry.ts calls agentdb.getController('vectorBackend'). agentdb@3.0.0-alpha.14's getController switch only handles memory/reflexion/skills/causal and throws `Unknown controller: vectorBackend` for everything else — silently swallowed, leaving the controller `enabled: false` even though `agentdb.vectorBackend` is a real field on the instance (assigned in AgentDB.initialize()). - Registry now probes `agentdb[name]` directly first, falls back to getController only when the field is absent. Applied to all three accessor paths (initializeController, get, isEnabled). - RuntimeConfig gains an optional `agentdb` injection field so tests and consumers with a pre-built AgentDB can govern it via the registry. - Two new tests in controller-registry.test.ts cover both branches (direct property wins; falls back to getController when absent). - Full controller-registry suite stays green (67 tests). #2015 — ruflo-browser session_record fails every call - ruvector@0.2.25 makes `-d, --dimension <n>` required on `rvf create`. The browser_session_record MCP tool wrapper invoked `rvf create … --kind browser-session` WITHOUT the flag, so every call returned `{ success: false, error: "rvf create failed" }`. - All five call sites updated to pass `--dimension 384` (matches MiniLM-L6 / AgentDB index default): v3/@claude-flow/cli/src/mcp-tools/browser-session-tools.ts plugins/ruflo-browser/scripts/replay-spike.sh plugins/ruflo-browser/agents/browser-agent.md plugins/ruflo-browser/skills/browser-record/SKILL.md plugins/ruflo-browser/docs/adrs/0001-browser-skills-architecture.md - New CI guard: scripts/smoke-browser-rvf-create-flags.mjs statically scans every `rvf create … --kind browser-session` invocation across the repo (TS, dist, shell, markdown) and fails if any is missing --dimension / -d. - Wired into v3-ci.yml as browser-rvf-create-flags-smoke and into witness-verify's `needs:` so a regression blocks publish. Cases covered by guards: source-only checkout (no deps), source-only checkout with build, built tree, missing dimension flag on TS/dist/ shell/markdown call sites. The smokes are independent jobs so the CI summary names the specific contract that broke. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
0873f81463 |
fix(mcp): protect stdout from stray console.log in stdio MCP mode (#1910) (#1998)
A broad MCP tool smoke test bricked the transport mid-batch: after hooks_pre_task ran, every subsequent hooks_* / mcp_* call returned `Transport closed`, including mcp_status. Root cause is stdout protocol corruption — Codex closes the MCP transport the moment it sees a non-JSON line on fd 1, and one or more of the modules that hooks_route lazy-loads (@ruvector/router, @claude-flow/neural, transformers.js/ONNX, semantic-router init) emits a diagnostic via console.log into the JSON-RPC stream. Defense in three layers, all in `startStdioServer()`: 1. **Hijack console.log/info/debug → stderr.** As the first thing the server does, replace those three methods with stderr writers prefixed `[stdout→stderr]`. Any subsequent module that calls `console.log(...)` (lazy-loaded or otherwise) goes to stderr instead of corrupting the protocol. `console.error` is unchanged. 2. **`writeFrame()` helper for JSON-RPC.** All three server-originated frames (`server.initialized`, the `Request too large` error, and tool responses) go through a dedicated helper that calls `process.stdout.write(...)` directly. The hijack above can't redirect protocol frames because they bypass `console.log` entirely. 3. **uncaughtException + unhandledRejection handlers.** Previously only SIGINT/SIGTERM were caught — an unhandled rejection in a lazy-loaded module's init (very common during the hooks semantic-router race the issue describes) crashed the server silently. Now those go to stderr with the full stack and the process stays up. Plus: sets `process.env.MCP_STDIO_MODE = '1'` so downstream code that wants to behave differently in stdio mode can probe a single flag. Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
ced2abc200 |
feat(memory): excludeFilePatterns/excludeFiles for memory_import_claude (#1937) (#1996)
`memory_import_claude` only had `allProjects: true/false` granularity.
Voice-fidelity-aware operators (named-persona content, PII-aware
hygiene) couldn't bulk-import without contaminating the unified
`claude-memories` namespace with the subset of files they had to
exclude. The current workaround was to halt imports entirely.
Two new params:
excludeFilePatterns: string[]
Glob patterns matched against the absolute file path. Files
matching ANY pattern are skipped. Supports:
`**` any chars including path separators
`*` any chars except path separators
`?` exactly one char except a path separator
Example: ["**/voice-*.md", "**/persona-*.md"]
excludeFiles: string[]
Absolute file paths to skip verbatim. Faster than a pattern when
the operator already has a list captured.
Both apply to either branch (`allProjects: true` or single-project).
The response gains an `excludedByPattern` counter so callers can
verify the exclusion ran.
A minimal `globToRegex` helper is added (anchored, escapes regex
metas, handles `**` / `*` / `?`). Verified four representative
cases pass; the unrelated regex escapes the issue's voice-fidelity
patterns need.
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
|
||
|
|
1f8971d16b |
fix(init): platform-aware statusLine command (#1948) (#1995)
The statusLine command was hardcoded as
`sh -c 'D="${CLAUDE_PROJECT_DIR:-.}"; … exec node "$D/<script>"'`
on every platform. On native Windows (cmd / PowerShell, no
Git-Bash) `sh` either isn't on PATH or its quoting gets mangled.
Symptom in #1948: spurious files like `0)` or
`toastr.error('ESD...` appearing in the repo root because misparsed
shell tokens leak back into the file system as filenames.
Fix: detect `process.platform === 'win32'` at init time and emit a
shell-free command instead — a `node -e "…"` one-liner that
resolves the script path internally using `process.env`. No shell
quoting hazards because the resolution happens inside Node, not in
the shell.
Windows: node -e "const fs=require('fs'),p=require('path');
const d=process.env.CLAUDE_PROJECT_DIR||'.';
const f=p.join(d,'.claude/helpers/statusline.cjs');
const h=p.join(process.env.USERPROFILE||process.env.HOME||'.', '.claude/helpers/statusline.cjs');
require(fs.existsSync(f)?f:h);"
POSIX: unchanged (sh -c with project-dir / HOME fallback)
Verified both branches emit valid JSON when generated through the
real settings-generator path on each platform.
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
|
||
|
|
6b9250ea8c |
fix(memory): memory stats HNSW count reads persistent DB (#1987) (#1993)
`memory stats` always reported `HNSW Index: active (0 entries)` even when `memory store` had just stored a vector and `memory search` successfully retrieved it. Root cause: the rendered count was `hnsw.entryCount`, which is the live in-process JS state (`hnswIndex?.entries.size`). A fresh `memory stats` invocation has never initialized HNSW in this Node process, so the in-process counter is always 0 — even when the persistent .swarm/memory.db has many entries with embeddings. Fix: prefer the persistent count from the `memory_stats` MCP tool, which already computes `entriesWithEmbeddings` by listing the DB's real rows. Fall back to the live counter when persistent count isn't available. When both are non-zero, take the max (covers the edge case where the live process has indexed more entries than the persisted store has flushed). Behavior matrix: hnsw.available persisted live → rendered false any any → "not active" (unchanged) true 0 0 → "available but not initialized" true N>0 any → "active (max(N,live) entries)" true 0 M>0 → "active (M entries)" (unchanged) Adds `entriesWithEmbeddings?: number` to the stats result type so TypeScript is happy. The MCP tool already returns this field; this just teaches the consumer to read it. Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
4680a2c044 |
fix(statusline): guard SQLite header read on encrypted memory.db (#1989) (#1992)
Resolves #1989. When encryption at rest is enabled, `.swarm/memory.db` becomes an RFE1-magicked ciphertext blob rather than a SQLite database. The statusline-generator's "page count at offset 28" fallback read ciphertext bytes as a uint32 and rendered 3,367,093,602 patterns, which then cascaded into fake DDD 5/5 / 100% / intelligence 100% downstream. Three defense layers, all in `statusline-generator.ts` (the template that `ruflo init` writes to `.claude/helpers/statusline.cjs`): 1. **Magic-bytes check** -- compare the first 16 bytes against the literal "SQLite format 3\\0" before interpreting any subsequent bytes. Encrypted, empty, or non-SQLite files are skipped. 2. **Page-count sanity clamp** -- reject pageCount > 1,000,000 (~4GB DB). Catches future regressions or genuinely corrupt headers even on plaintext SQLite. 3. **Defensive consumer clamps** in `getV3Progress` and `getSystemMetrics` -- `Number.isFinite` + range check on `learning.patterns` before deriving domainsCompleted / intelligencePct. If any future regression in the reader returns a wild value, the downstream displays stay honest. Verified with a fake RFE1-headered `memory.db` matching the forensic bytes from the issue: Before: DDD Domains 5/5 / 100% / patterns=3367093.6k / 🧠 100% After: DDD Domains 0/5 / 0% / patterns=0 / 🧠 0% The `\\0` in the SQLite-magic string is intentional: the statusline-generator emits via a JS template literal, so the source-level `\\\\0` resolves to `\\0` in the generated .cjs which JS then parses as the null byte. Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
8a4803020f |
fix(daemon): forward --workers / --headless / --sandbox to forked child (#1968) (#1970)
`daemon start --workers map` (and `--headless` / `--sandbox`) were accepted by the launcher but silently dropped when it forked the foreground child — so the daemon came up with the full default worker set (`map,audit,optimize,consolidate,testgaps`) regardless of what the user asked for. Root cause: `startBackgroundDaemon()` only accepted resource thresholds (`--max-cpu-load` / `--min-free-memory`) and forwarded just those plus `--workspace` to the forked child. `--workers` / `--headless` / `--sandbox` were read by `ctx.flags.*` but never passed through. Fix: thread the three additional flags through the launcher and add them to the forked child's argv, gated by the same kind of strict input validation the existing thresholds use: - `--workers <list>` — `/^[a-z][a-z0-9_-]*(,[a-z][a-z0-9_-]*)*$/` - `--headless` — boolean - `--sandbox <mode>` — one of `strict|permissive|disabled` Anything that fails validation is dropped silently — same posture as the existing thresholds. Forced through the same `forkArgs.push()` path so the child sees them in argv (which both the daemon's own arg parser AND `killStaleDaemons` rely on for workspace identification). Behaviour now (matching the user's repro from #1968): $ ruflo daemon start --workers map --max-cpu-load 1000 --min-free-memory 0 $ ruflo daemon status Workers Enabled: 1 map enabled Build verified clean (tsc). Resolves #1968. Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
a5a6389852 |
fix(embeddings-index): make -c optional for build/rebuild (#1947 RC2) (#1964)
The HNSW index is a single global structure that indexes every
namespace's embeddings — `-c` was always informational. But the earlier
code REQUIRED `-c` for `build`/`rebuild` and the examples showed
`-c documents`/`-c patterns`/`-c default`, so users who stored entries
under a non-default namespace (e.g. `project`, `claude-memories`) hit
"Collection is required" on plain `-a build`, then re-ran with `-c default`
and got `Vector Count: 0` because that namespace was empty.
Drop the required check. When `-c` is omitted, label the result `(all
namespaces)`, run the same global rebuild, and print a helpful follow-up
if the resulting vector count is 0. Update help text + examples so the
intent is clear ("Omit to build for all namespaces"). No runtime
behavior change for callers passing `-c` — still indexes globally, just
labels the box with whatever they passed.
Build verified clean (tsc).
Resolves #1947 RC #2.
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
|
||
|
|
2c904df868 |
fix(memory): provision vector_indexes per namespace + truthful bridge_status (#1941, #1940) (#1963)
Two related memory-bridge bugs:
**#1941** — \`memory_search({namespace:"claude-memories"})\` always returned
0 results even when \`memory_import_claude\` had inserted hundreds of rows
into that namespace. The schema's \`vector_indexes\` table held only
\`default\` and \`patterns\` rows; AgentDB's HNSW/router keys namespace
lookups by this table, so any namespace without a row was effectively
unindexed for search.
Fix: every store path (both the AgentDB-bridge \`bridgeStoreEntry\` and the
raw-sql.js fallback \`storeEntry\`) now does \`INSERT OR IGNORE INTO
vector_indexes (id, name, dimensions) VALUES (?, ?, ?)\` for the entry's
namespace before the row insert. Idempotent; legacy DBs without the
table fall through cleanly. Dimensions defaults to the embedding's
actual dim (384 for the default model), preserving #1947's contract.
**#1940** — \`memory_bridge_status\` reported \`totalEntries: 0\` and
\`status: not-synced\` on DBs with hundreds of rows. Root cause: it used
\`listEntries({}).entries.length\`, but \`listEntries\` returns at most 20
entries with the full row count in a separate \`.total\` field — so the
status reporter was capped at the page size, not the table count.
Fix: use \`listEntries({}).total\` for the count. Plus surface a
per-namespace breakdown (\`agentdb.namespaces\`) for the common namespaces
(\`default\`, \`patterns\`, \`claude-memories\`, \`auto-memory\`, \`tasks\`,
\`feedback\`, \`pretrain\`) so callers can see where the rows actually live.
\`bridge.status\` now flips to \`connected\` on ANY persisted row, not only
\`claude-memories\` (the bridge is in use from many import paths).
Build verified clean (tsc).
Resolves #1941, #1940.
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
|
||
|
|
4e6822fa8d |
fix(memory-import): resolve Win32 cwd to Claude Code's slug (#1939) (#1962)
`memory_import_claude({ allProjects: false })` couldn't find the current
project's memory directory on a pure Win32+Win32 install, because the
slug candidates in `resolveProjectMemoryDir()` only replaced forward
slashes — never the drive-colon, backslash, or whitespace that a Win32
cwd contains.
Example:
- cwd: `C:\Users\tobia\OneDrive\Desktop\Claude Stuff`
- Claude Code's on-disk slug: `C--Users-tobia-OneDrive-Desktop-Claude-Stuff`
- Before this fix: no candidate matched, importer reported `imported: 0,
"No Claude memory files found"`.
Add a Win32-specific candidate gated on `/^[A-Za-z]:[\\/]/` that does the
full normalization (`:` / `\` / `/` / whitespace → `-`). The other four
candidates (legacy POSIX, WSL `/mnt/<drive>/`, leading-dash strip, space
rule) are unchanged, so no regression for the other setup classes.
Verified the new candidate emits
`C--Users-tobia-OneDrive-Desktop-Claude-Stuff` for the reporter's path.
Build verified clean (tsc).
Resolves #1939.
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
|
||
|
|
1d414b194d |
fix(hooks-pretrain): code-file budget + code-dir-first traversal (#1953) (#1961)
`hooks_pretrain` reported `patternsExtracted: 0` on any monorepo whose depth-first traversal hit 50 non-code files (.md / .yaml / .db / .log / …) before reaching a single .ts/.js/.py/etc. The 50-file budget that gates the import-pattern scan was checked against `filesAnalyzed`, which counts EVERY directory entry — so in markdown-heavy repos (docs/, specs/, _bmad-output/, …) the budget burned out on Markdown long before the walker recursed into apps/, packages/, or src/. Two-part fix: 1. Use a separate `codeFilesScanned` counter for the budget, incremented only inside the `if (codeExts.includes(ext))` block. The 50-file cap now means "50 code files", which is what the comment always claimed. 2. Sort `readdirSync` entries so the walker recurses into code-likely dirs first (`src/`, `apps/`, `packages/`, `lib/`, `crates/`, `workers/`, `server/`, `backend/`, `frontend/`, `app/`, `cli/`, `core/`) and deprioritises docs/specs/build/coverage/test dirs. Files are mixed in between. Stable sort so test behaviour is deterministic. Plus two collateral improvements: - Widen the per-file scan window from 30 → 80 lines. Modern TS files often have license headers + JSDoc + type-only imports before the first `import` — the 30-line cap was missing real imports. - Recognise more code extensions: `.tsx`, `.jsx`, `.mjs`, `.cjs`. The `SUPPORTED_EXTRACTION_EXTS` list used by the "found N code files but 0 patterns" note got the same expansion so the diagnostic stays accurate. Build verified clean (tsc). Resolves #1953. Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
7ca28a7593 |
fix(statusline): read installed version from plugin package.json (#1951) (#1960)
The statusline showed a hard-coded "RuFlo V3.5" regardless of the
installed version, even on alpha.27 where `ruflo doctor` correctly
reported the real version.
Two files had the bug:
1. `v3/@claude-flow/cli/.claude/helpers/statusline.cjs` — fully hard-coded
`▊ RuFlo V3.5 ` in both header constructions, with no version-reading
logic at all. Added a startup version-probe (4 candidate package.jsons,
preferring the plugin install at `~/.claude/plugins/marketplaces/ruflo/`)
and wired `${RUFLO_VERSION}` into both headers.
2. `.claude/helpers/statusline.cjs` — already had version-reading, but its
candidate list only checked project-local `node_modules` paths, never
the plugin install location. Plugin users always fell back to `'3.5'`.
Added the plugin path as the first candidate.
3. `v3/@claude-flow/cli/src/init/statusline-generator.ts` — the template
that writes `<project>/.claude/helpers/statusline.cjs` at init time had
the same too-narrow candidate list. Same fix, applied to the template.
Probe order for all three:
1. ~/.claude/plugins/marketplaces/ruflo/package.json (plugin install)
2. <cwd>/node_modules/@claude-flow/cli/package.json (npm install)
3. <cwd>/node_modules/ruflo/package.json (umbrella)
4. <cwd>/v3/@claude-flow/cli/package.json (source checkout)
Falls through to a hard-coded default if all four are missing or malformed.
Build verified clean (tsc) on @claude-flow/cli.
Resolves #1951.
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
|
||
|
|
434a8f95bb |
fix(memory): bridge + doctor honor CLAUDE_FLOW_MEMORY_PATH / config (#1945, #1946) (#1959)
Two CLI memory bugs caused by hard-coded `.swarm/memory.db` paths that
ignored the configured memory location:
**#1945** — `memory-bridge.ts::getDbPath()` always defaulted to
`<cwd>/.swarm/memory.db` regardless of `CLAUDE_FLOW_MEMORY_PATH` or
`claude-flow.config.json#memory.persistPath`. So a user with a non-default
memory layout (e.g. `data/memory/memory.db`) had `memory init` write the
schema to the configured file, while `bridgeStoreEntry()` silently wrote
INSERTs to `.swarm/memory.db` — a different file, sometimes a different
directory. CLI `memory store` reported success against the wrong DB, and
a fresh process reading the configured path saw zero rows ("store works
but next process finds nothing").
Fix: route `getDbPath()` through `getMemoryRoot()` (from
memory-initializer), the same function `memory init` uses. The two now
agree on the same file. `:memory:` and explicit `customPath` still work
unchanged; path-traversal protection unchanged.
**#1946** — `doctor.ts::checkMemoryDatabase()` only checked the legacy
paths `.claude-flow/memory.db` / `.swarm/memory.db` / `data/memory.db` and
ignored `CLAUDE_FLOW_MEMORY_PATH` / config entirely. So `ruflo doctor`
reported `⚠ Memory Database: Not initialized` on a perfectly-initialized
DB at `data/memory/memory.db`.
Fix: check `getMemoryRoot() + '/memory.db'` first (the authoritative
path); fall back to the legacy candidates for non-standard layouts; add
`data/memory/memory.db` to the fallback list (a common config that was
missing entirely).
Build verified clean (tsc) on `@claude-flow/cli`.
Resolves #1945, #1946.
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
|
||
|
|
3657a69366 |
fix(hooks): pre-bash TypeError + global-install MODULE_NOT_FOUND (#1944, #1943) (#1957)
Two critical hook regressions on a fresh `ruflo init` (alpha.27):
**#1944** — `helpers/hook-handler.cjs` builds the `prompt` string from a
`||` fallback chain whose third term is the normalised `toolInput` *object*
(`{command:"ls"}` etc.). The object is truthy so the chain stops there;
the next line calls `.toLowerCase()` on it and every `pre-bash` invocation
prints `[WARN] Hook pre-bash encountered an error: …toLowerCase is not a
function` — i.e. **every Bash tool call from Claude Code spams a TypeError**.
Fix: fall back to `toolInput.command` (the string) instead of `toolInput`
(the object). One-character change in three places — the deployed handler
(both tracked copies) and the template in `helpers-generator.ts` that
writes the user's `.claude/helpers/hook-handler.cjs` at init time.
Repro on the fixed file:
echo '{"tool_input":{"command":"ls"},"tool_name":"Bash"}' \
| node v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs pre-bash
→ [OK] Command validated (was: TypeError warning)
Dangerous-command guard still fires:
echo '{"tool_input":{"command":"rm -rf /"},"tool_name":"Bash"}' | … pre-bash
→ [BLOCKED] Dangerous command detected: rm -rf /
**#1943** — `settings-generator.ts` writes hook command strings anchored at
`${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/…`. That works when `ruflo init`
lands helpers project-locally, but breaks when init's settings end up in
`~/.claude/settings.json` (global install) with helpers at
`~/.claude/helpers/`: Claude Code still sets `CLAUDE_PROJECT_DIR` to the
*project* root, the path resolves there, finds nothing, and every Bash /
Edit / Session hook fires `MODULE_NOT_FOUND`.
Fix: replace the path expression with a POSIX `sh` probe that tries the
project-local path first and falls back to `$HOME` when it's missing —
project-local overrides still take precedence; global installs work; no
upgrade-skew. Windows gets the same probe via `cmd /c IF EXIST … ELSE …`.
Applied to both `hookCmd()` and `generateStatusLineConfig()` (the
statusline scaffolding had the same anchor bug).
**CI guard**: `scripts/audit-hook-handler-prompt.mjs` (new) — fails the
build if any `.cjs` handler / TS template falls back to a bare `toolInput`
(object) instead of `toolInput.command` (string). Catches the #1944
pattern exactly. Wired into the existing `hook-command-audit` job.
Verified to flag a deliberately-reverted regression (and clean on HEAD).
Resolves #1944, #1943.
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
|
||
|
|
4abef4b83f |
fix(memory): schema vector_indexes dim 768→384 + CI guard (#1947, #1942, #1952) (#1956)
* fix(memory): schema vector_indexes dim 768→384 (#1947, #1942, #1952) The bundled SQL schema initialises the `default` and `patterns` rows in `vector_indexes` with `dimensions = 768`, but the default ONNX embedding model (`Xenova/all-MiniLM-L6-v2`) produces **384-dim** vectors. HNSW rejects every insert with the mismatched dim — so on a fresh install `memory_store --vector` prints success while `memory_search` always returns 0 hits, and `memory_stats` reads 0 vectors. Root cause is a single inline schema literal in `memory-initializer.ts`'s `getInitialMetadata()`. That string is run against the user's DB at init time and is the canonical writer of the `vector_indexes` rows (the `.swarm/schema.sql` files some packages ship are stale artifacts, not the runtime source). Fix: change the two literals to 384 (matching the default model). CI guard: `scripts/audit-vector-dim.mjs` scans `v3/` and `ruflo/` for any `INSERT … INTO vector_indexes (id, name, dimensions) VALUES ('default'|'patterns', …, N)` row and fails the build if `N !== 384`. Wired into `vector-dim-audit` job (gates `witness-verify`). Verified to catch a deliberately-reverted regression and to pass on the fixed tree (24 matching rows scanned, all 384). Resolves #1947 root cause #1 (the dim mismatch). Resolves #1942 (Bridge search index 768 vs imported 384-dim embeddings). Resolves #1952 (Windows: store ok, search returns 0, stats shows 0) — same root cause, Windows is just where the reporter observed it. Follow-ups (not in this PR): - #1947 root cause #2: `embeddings index -a build` defaults to `-c default` even when entries are in another namespace. - #1947 "additional": `embeddings init --force` model-ID validator rejects the default model's own name (`Xenova/all-MiniLM-L6-v2`) because of `/`. - #1941: claude-memories import doesn't provision a vector_indexes row. - #1940: `memory_bridge_status` reports 0 despite persisted rows. - Several published `@claude-flow/*` packages have no `files:` / `.npmignore` and ship stale `.swarm/` binary state (memory.db, hnsw.index, etc.). Co-Authored-By: RuFlo <ruv@ruv.net> * fix(memory-initializer): drop backticks from SQL comment (TS template-literal compile error) The earlier fix included a comment block with backticks (\`Xenova/all-MiniLM-L6-v2\`, \`memory_store --vector\`, \`memory_search\`) inside a TypeScript template literal — the backticks terminated the template string and tsc errored with TS1005/TS1443 on lines 989/991. Build V3 failed across ubuntu / macOS / windows. Replace the backticks with parens / plain prose. The schema literals are unchanged (still 384). Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
ef73a1616f |
feat(ruflo-agent): rename ruflo-wasm → ruflo-agent + Claude Managed Agents (cloud) runtime — ADR-115 (proposed→accepted, implemented) (#1929)
* docs(adr): ADR-115 — Claude Managed Agents as a cloud backend for rvagent (explored + validated)
Records the proposal to add `runtime: "managed"` to ruflo's rvagent
interface (ruflo-wasm / @ruvector/rvagent-wasm / wasm_agent_* MCP tools),
backed by Anthropic's Claude Managed Agents API (beta), as a second backend
alongside the local WASM sandbox — mirroring the ConsensusTransport
LocalTransport|FederationTransport pattern (ADR-095 G2 / ADR-104). The
agent/environment/session/events model maps ~1:1 to wasm_agent_create/
prompt/files/terminate + the gallery.
Validated live against api.anthropic.com/v1 with the org's Anthropic key
(GCP claude-flow/anthropic-api-key): created an agent + environment + session,
sent a bash task, observed the full event log (status_running → user.message
→ tool_use(bash) → tool_result → agent.message("Done.") → status_idle,
stop_reason end_turn), cleaned up. ~7s for a trivial Haiku task.
High-value combos noted: ruflo's own MCP server as a Managed Agent tool
source (cloud-hosted ruflo, zero local infra); Managed Agent session as a
third task_assign executor (closes #1916 items 3/4); long-running/async work;
skills + define-outcomes parity. Constraints: opt-in/off-by-default, needs
ANTHROPIC_API_KEY + beta access, plugin-level @anthropic-ai/sdk dep,
cost-tracking + orphaned-session GC, beta churn, branding.
Status: proposed. Registered in AgentDB (adr-ADR-115) + adr-patterns.
Co-Authored-By: RuFlo <ruv@ruv.net>
* refactor(plugins): rename ruflo-wasm → ruflo-agent (agent-runtimes home; ADR-115 prep)
`ruflo-wasm` only covered local WASM-sandboxed agents (rvagent —
@ruvector/rvagent-wasm, the wasm_agent_*/wasm_gallery_* MCP tools). It's
becoming the home for *all* ruflo agent runtimes: the existing local-WASM
backend plus Anthropic's Claude Managed Agents as a cloud backend (ADR-115),
behind one interface — same local-vs-cloud pattern as ConsensusTransport.
- git mv plugins/ruflo-wasm → plugins/ruflo-agent
- plugin.json: name ruflo-wasm → ruflo-agent; description/keywords now span
both runtimes (rvagent/wasm + managed-agents/anthropic/cloud)
- .claude-plugin/marketplace.json entry renamed
- README / plugins/README / docs/index / cli README / ruflo README /
discover-plugins SKILL / verification/inventory.json / ADR-115 — refs updated
- wasm_agent_* / wasm_gallery_* MCP tool names are unchanged (they stay; the
plugin is just renamed). managed_agent_* tools land next per ADR-115.
(Left `ruflo-wasm-mcp` in ruvocal/workerClient.ts alone — unrelated worker MCP name.)
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(cli): managed_agent_* MCP tools — Claude Managed Agents cloud runtime (ADR-115)
Six new MCP tools wrapping Anthropic's Claude Managed Agents REST API (beta,
`anthropic-beta: managed-agents-2026-04-01`) via plain fetch — no new SDK dep:
managed_agent_create agents.create + environments.create + sessions.create ↔ wasm_agent_create (CLOUD counterpart)
managed_agent_prompt events.send(user.message) + poll events until idle ↔ wasm_agent_prompt
managed_agent_status GET /v1/sessions/{id}
managed_agent_events GET /v1/sessions/{id}/events (full transcript) ↔ wasm_agent_files
managed_agent_list GET /v1/sessions
managed_agent_terminate DELETE /v1/sessions/{id} (+ optionally the env) ↔ wasm_agent_terminate
Needs ANTHROPIC_API_KEY (or CLAUDE_API_KEY); every tool degrades gracefully
with a structured "use wasm_agent_* for a local no-key runtime" error when the
key is absent — the CLI/MCP server stays up. ADR-112-compliant descriptions
(each says when wasm_agent_* / native is the right call instead). Registered
in mcp-client.ts. Lives conceptually in the `ruflo-agent` plugin (the
`ruflo-wasm`→`ruflo-agent` rename in the prior commit).
Validated live against api.anthropic.com with the org's Anthropic key (GCP
claude-flow/anthropic-api-key) via `ruflo mcp exec -t managed_agent_*`:
create (haiku) → prompt ("echo … > /tmp/r.txt && cat") → got finished:true,
status:idle, stopReason:end_turn, assistantText:"Done.", toolUses:[bash],
13 events → terminate (sessionDeleted+environmentDeleted). No-key path returns
the graceful error. audit-cli-mcp-tools 311 registered/0 dangling;
audit-tool-descriptions 0 no-guidance; cli build clean.
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(ruflo-agent): wire the managed-agent (cloud) runtime into the plugin + CI smoke
- skills/managed-agent/SKILL.md — drives the cloud runtime: managed_agent_create
/ prompt / status / events / list / terminate, with the WASM-vs-managed
decision table, the ANTHROPIC_API_KEY prereq + graceful fallback, the
mcpServers-reachability caveat, and the cost/cleanup discipline (a cloud
session bills until terminated). Explicit allowed-tools (no wildcard).
- commands/managed-agent.md — quick "list cloud sessions / status / transcript
/ clean up" command (the cloud sibling of /wasm).
- plugin.json — kept rvagent-wasm + ruvllm-wasm keywords (still built on those);
added managed-agents/anthropic/cloud.
- smoke.sh: step 1 now also asserts name=ruflo-agent + the managed-agents
keywords; step 10 expects ADR-0001 status `Accepted` (was stale `Proposed`,
pre-existing red); new step 12 — managed-agent skill+command exist + all 6
managed_agent_* tools referenced + the skill keeps an explicit allowed-tools
list + offers the wasm_agent_create fallback. 12 passed / 0 failed.
- .github/workflows/ruflo-agent-smoke.yml — new CI job running smoke.sh on any
plugins/ruflo-agent/** change (the plugin had no CI gate before).
Validated: `claude --plugin-dir plugins/ruflo-agent` loads the plugin and lists
its skills (managed-agent, wasm-agent, wasm-gallery); plugin.json + all skill
frontmatters parse; smoke.sh 12/0.
Co-Authored-By: RuFlo <ruv@ruv.net>
* docs(adr): ADR-115 → Accepted + Implementation section (managed_agent_* landed)
Status Proposed → Accepted. Added an Implementation (2026-05-12) section:
the ruflo-wasm→ruflo-agent rename, the 6 managed_agent_* MCP tools (plain
fetch, no new SDK dep, graceful no-key degradation, ADR-112 descriptions),
the managed-agent skill+command, the smoke.sh/ruflo-agent-smoke.yml CI guard,
the live e2e validation (create→prompt→terminate against api.anthropic.com
with the GCP anthropic-api-key) and `claude --plugin-dir` validation, and the
called-out follow-ups (runtime:"managed" unification, deployed HTTP ruflo MCP
server for the cloud-hosted-ruflo combo, task_assign/federation dispatch to a
Managed Agent session, cost-tracking + orphaned-session GC, multiagent/outcomes).
Tracking issue: #1931.
Co-Authored-By: RuFlo <ruv@ruv.net>
* test(cli): no-network guard for managed_agent_* tools (ADR-115)
__tests__/managed-agent-tools.test.ts (10 cases): the 6 managed_agent_*
tools are registered; each has an object inputSchema + a ≥80-char,
ADR-112-ish, unique description that names the wasm_agent_*/native fallback;
and — crucially — every handler degrades gracefully with no ANTHROPIC_API_KEY/
CLAUDE_API_KEY: no throw, structured error mentioning the key + the
wasm_agent_create fallback, no network call (so the CLI/MCP server stays up
offline). Plus managed_agent_prompt's missing-sessionId/message validation.
Co-Authored-By: RuFlo <ruv@ruv.net>
* docs(adr): ADR-115 — add the third runtime (Claude Agent SDK) to the picture
ADR-115 adds the *cloud* runtime (Managed Agents); add a section noting the
natural *third* runtime — the Claude Agent SDK (@anthropic-ai/claude-agent-sdk,
"Claude Code as a library": query()/ClaudeSDKClient, hooks, subagents, MCP,
permission modes, sessions, loads .claude/ config + plugins; runs in-process,
full host trust). ruflo-agent → three runtimes behind one model:
WASM (rvagent) local sandbox, no host fs/net untrusted/portable/offline
SDK (future) your process, your filesystem a real Claude agent loop on the local repo — the in-process `claude -p`
Managed Anthropic cloud container long-running/async, no local infra
The SDK runtime's killer combo: `mcpServers: { ruflo: { command: "npx", args: ["ruflo","mcp","start"] } }` — a *local* stdio MCP server, so the agent gets ruflo's 314 tools with zero deployment (vs Managed Agents needing a reachable URL). Anthropic positions SDK→Managed as prototype→production. Costs: heavy dep (bundles a Claude Code binary), full host trust (no sandbox — least isolated), needs an API key. Implementing it = a follow-up, likely ADR-116 (tracked in #1931).
Co-Authored-By: RuFlo <ruv@ruv.net>
---------
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
|
||
|
|
95df0111e0 |
fix(plugins): #1902/#1903/#1904 install-safety + plugin-package CI guard (#1925)
* fix(plugins): #1902/#1903/#1904 install-safety + CI guard published tarballs declared @claude-flow/ruvector-upstream (a never- published package) as a hard dep / strict peer, so `npm install` E404'd. The repo source was already clean (the runtime does `await import(...). catch(() => null)`), so the fix is a republish + a guard. resolve any @claude-flow publish (they're all 3.x prereleases). Repo source already uses ">=3.0.0-0" + optional peers; fix is a republish. plus ./formula and ./convoy subpaths the build never emitted. tsup.config now builds the formula/convoy entries (were commented out) and package.json exports/main/module point at the actually-emitted .js/.cjs filenames. CI guard: scripts/audit-plugin-packages.mjs — fails on (A) unpublished @claude-flow/* hard dep / non-optional peer, (B) bare-stable peer range that can't resolve a prerelease, (C) main/module/exports path not in `files`, (D) post-build, an exports path that doesn't exist on disk. Wired into v3-ci.yml as `plugin-package-audit` (builds plugins first so check D is live) + added to witness-verify needs[]. Witness markers for Version bumps for republish: legal-contracts/healthcare-clinical/ perf-optimizer 3.0.0-alpha.1→2, agentic-qe 3.0.0-alpha.4→5 (repo was stale at 3.5.59), gastown-bridge 0.1.3→0.1.4. Co-Authored-By: RuFlo <ruv@ruv.net> * chore(plugins): bump IPFS registry CID for #1902/#1903/#1904 republish LIVE_REGISTRY_CID → QmeXmAdbWVvT84GfDXPD2Vg1HWhiTW2VdZfRLhkS96KkX2 (re-pinned to Pinata). Reflects the republished plugin versions: @claude-flow/plugin-agentic-qe 3.0.0-alpha.4 → 3.0.0-alpha.5 @claude-flow/plugin-gastown-bridge 0.1.3 → 0.1.4 @claude-flow/plugin-legal-contracts 3.0.0-alpha.1 → 3.0.0-alpha.2 @claude-flow/plugin-healthcare-clinical 3.0.0-alpha.1 → 3.0.0-alpha.2 @claude-flow/plugin-perf-optimizer 3.0.0-alpha.1 → 3.0.0-alpha.2 Also updated the matching `version` fields in the demoPluginRegistry offline fallback. Ships with the next @claude-flow/cli release. Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
31f22ff9a9 |
fix(#1916): register agent_logs + hive worker resolution + all 20 dangling CLI↔MCP tools — published 3.7.0-alpha.26 (#1924)
* fix(#1916): register agent_logs MCP tool + resolve hive-spawned workers `ruflo agent logs <id>` called `callMCPTool('agent_logs', …)` against a tool that was never registered → `MCP tool not found: agent_logs`. Registered it in agent-tools.ts. Today it returns the agent's createdAt + lastResult as synthetic entries (per-agent activity logging lands with hive worker execution wiring — #1916 items 3/4, a tracked follow-up) with the documented shape `{ agentId, entries: [{timestamp,level,message,context?}], total }`. Also: `hive-mind_spawn` writes workers to `.claude-flow/agents.json`, a different file from the canonical `.claude-flow/agents/store.json` that agent_status/agent_list/agent_logs read — so `agent status <hive-worker-id>` returned `not_found`. Added `loadAllAgents()` (canonical store ∪ hive store, canonical wins on collision) and routed those three tools through it. NOT in this PR: the task-execution dispatch (#1916 items 3/4 — `task_assign` transitions state but doesn't run a worker; hive metrics stay 0). That needs a design decision (which executor) and is a separate change. CI guard: scripts/audit-cli-mcp-tools.mjs — scans every `callMCPTool('<name>')` in src/commands/*.ts and fails if `<name>` isn't registered in src/mcp-tools/*.ts (the `MCP tool not found` class). Monotone-decreasing baseline at verification/cli-mcp-tool-baseline.json — surfaces 20 *other* CLI subcommands with the same dangling-tool bug (`memory export`, `task retry`, `workflow validate`, `session export`, …; agent_logs is now fixed and not in the list). Wired into v3-ci.yml `tool-descriptions-audit` job (already in witness-verify needs[]). Behavioral guard: __tests__/agent-logs-hive-resolution.test.ts. Witness markers for #1916 + #1916-guard. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(#1916): register the 16 missing CLI↔MCP tools — cli-mcp-tool-baseline → 0 The #1916-guard (scripts/audit-cli-mcp-tools.mjs) surfaced 20 `ruflo <cmd>` subcommands that callMCPTool() a tool that was never registered (would die with `MCP tool not found`). Cleared all of them: - Renamed the coverage tools `hooks/coverage-{route,suggest,gaps}` → `hooks_coverage-{route,suggest,gaps}` (the handlers already existed; the slash names just didn't match the CLI's underscore calls). - Pointed `ruflo swarm stop` / `ruflo stop` at the existing `swarm_shutdown` tool instead of a non-existent `swarm_stop`. - Registered 16 new MCP tools (each with ADR-112 "use when … is wrong" guidance): task_retry, workflow_stop, workflow_validate, session_current, session_export, session_import, memory_detailed-stats, memory_cleanup, memory_compress, memory_export, memory_import, hive-mind_optimize-memory, hooks_teammate-idle, hooks_task-completed, mcp_start, mcp_stop Real where the operation maps cleanly to an existing store/backend (task_retry clones into a fresh pending task; memory_export/import dump & re-store entries; memory_cleanup prunes expired TTLs dry-run-by-default; workflow_validate structurally checks a JSON workflow; session_export/import round-trip the session record; memory_detailed-stats reshapes memory_stats). Honest no-ops with the correct return shape + a `note` where the underlying capability genuinely isn't wired yet (memory_compress — sql.js has no on-disk compression; hive-mind_optimize-memory — structural compaction only, pattern-quality consolidation is the intelligence pipeline's job; hooks_* team hooks — auto-assignment/pattern-learning delegated; mcp_start/stop — the MCP toolset runs in-process, there's no separate server to start/stop). cli-mcp-tool-baseline.json is now 0. tool-descriptions-audit still passes (all 16 new tools carry guidance, ≥80 chars, unique). Full cli test suite green (48 files / 1977 tests). Witness #1916-cli-tools marker added → ruflo verify 107 verified, 0 regressed. mcp-tools-deep.test.ts exception list updated for mcp_start/mcp_stop. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(#1916): register coverageRouterTools + harden the CLI↔MCP audit; bump 3.7.0-alpha.26 Validating the alpha.25 publish caught a gap: `ruflo hooks coverage-route` (and -suggest / -gaps) still failed with `Tool not found: hooks_coverage-route`. Root cause: the coverage tools were defined in ruvector/coverage-tools.ts but their array was never imported into mcp-client.ts's TOOL_REGISTRY — renaming the slash→underscore name didn't help because the file wasn't registered at all. - mcp-client.ts: import + `...coverageRouterTools` in registerTools([…]). - coverage-tools.ts: category 'coverage' → 'hooks' (matches the hooks_* names). - scripts/audit-cli-mcp-tools.mjs: now derives the "registered" set from what mcp-client.ts ACTUALLY spreads into registerTools([…]) (resolving each `...xTools` to its `import { xTools } from '<path>'` and scanning that file), instead of "any src file with a name: definition". So an unregistered tool-source file now correctly produces a dangling-reference flag — this is exactly the gap that let hooks_coverage-* slip through. Version bumped to 3.7.0-alpha.26 (alpha.25 shipped the still-broken coverage tools). Witness manifest regenerated. cli-mcp-tool-baseline.json still 0; audit + mcp-tools-deep + mcp-client tests green. Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
ad169de89b |
fix(#1914): daemon start only reaps daemons in the current workspace (#1917)
`killStaleDaemons` SIGTERM'd every process whose command line contained
`daemon start --foreground`, so starting the daemon in workspace B killed
workspace A's daemon — a violation of ADR-014's per-workspace daemon scope.
The forked daemon's argv is now stamped with `--workspace <root>` (kept
last), and `killStaleDaemons{Posix,Windows}` filter on it via
`daemonCommandLineBelongsToWorkspace` — an exact trailing match, never a
bare path-prefix match, so `/a/proj` can't reap `/a/proj-other`'s daemon.
Pre-#1914 daemons (no stamp) are left for `daemon stop` to handle via the
PID file. `resolveWorkspaceFlag` rejects shell metacharacters / null bytes
since the value lands in a forked child's argv.
CI guard: __tests__/daemon-workspace-scope.test.ts (12 cases — cross-
workspace isolation, prefix-sibling, legacy-no-stamp, Windows tasklist
row, space-containing paths) + witness marker for #1914.
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
|
||
|
|
16e59c2613 |
fix(#1906): agent_execute model aliases → current Claude 4.x ids (not deprecated claude-3.x) (#1908)
`MODEL_MAP` in agent-execute-core.ts mapped haiku/sonnet/opus/inherit to `claude-3-5-haiku-latest` / `claude-3-5-sonnet-latest` / `claude-3-opus-latest` — ids the Anthropic API now 404s. Every `agent_execute` call (and the WASM agent's LLM fallback, which routes through `resolveAnthropicModel`) failed with HTTP 404 even with a valid key. Fixed mappings (Claude 4.x family): haiku → claude-haiku-4-5-20251001 sonnet → claude-sonnet-4-6 opus → claude-opus-4-7 inherit → claude-sonnet-4-6 (= new DEFAULT_ANTHROPIC_MODEL) Also replaced the 4 other hardcoded `claude-3-5-sonnet-latest` defaults (`callAnthropicMessages` fallback, `resolveAnthropicModel` no-input case, `executeAgentTask` fallback, the doc-comment example) with `DEFAULT_ANTHROPIC_MODEL`. ## CI coverage (the user's ask: "make sure the ci guard doesn't miss these") Two layers: 1. Unit test `__tests__/agent-execute-models.test.ts` — picked up by the cli package's vitest run in CI. Asserts each alias resolves to the right Claude-4.x id, the prefix-strip works, the pass-through works, and — critically — `no alias resolves to a claude-3.x id` (the #1906 regression-class assertion). 8/8 pass. 2. Witness marker `#1906` in the manifest — `claude-sonnet-4-6` must be present in `agent-execute-core.js` dist; `witness-verify` fails on regression. 104/104 fixes verified. Closes #1906 · related to #1863 (agent_execute was the path #1863's comment pointed users at — now it actually works) Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
8403907d86 |
fix(#1863): guard undefined arrays in task status + cli-no-crash CI smoke
## The crash
`task status <id>` threw `TypeError: Cannot read properties of undefined
(reading 'join')` in the Assignment section. Lines in task.ts did
`result.dependencies.join(', ')`, `result.dependents.join(', ')`,
`result.tags.join(', ')` — `callMCPTool<{ dependencies: string[]; ... }>()`
types those as non-optional arrays, but the MCP server legitimately omits
them for tasks created via task_create or loaded from an older store
schema. The TS compiler can't see the risk; only running the command does.
Fix: `?.join(', ') || 'None'` at all five sites (the inline `task status`
formatter at ~206 + the detailed one at ~441). `assignedTo` was already
guarded; the others weren't.
## CI guard (the user's ask: "ensure this type of error is caught")
New plugins/ruflo-core/scripts/test-cli-no-crash.mjs — drives
`task create` → `task status <id>` plus `task list` / `agent list` /
`memory list` / `swarm status`, asserting none crash with an unhandled
exception (TypeError/ReferenceError/"Cannot read propert"/etc). Graceful
"not found" errors are fine; only unhandled crash stacks fail the gate.
Per-command 30s timeout + 90s process-level watchdog so CI never hangs.
Tried a static grep-based guard first (`obj.prop.arrayMethod()` without
`?.`) — too noisy: 285 hits, mostly legit. Behavioral smoke is the right
shape: it catches the actual crash class, not the syntactic pattern.
Wired as a step in the existing mcp-roundtrip-smoke job (already builds
the cli + has the watchdog discipline).
Local: smoke green — confirms `task status` on a fresh task no longer crashes.
Closes #1863
Co-Authored-By: RuFlo <ruv@ruv.net>
|
||
|
|
8aac1b2ccc |
feat(mcp): ADR-112 — 285/285 tool descriptions have 'Use when …' guidance + CI guard + #1892 statusline (#1897)
* docs(adr-095): status update — G1/G3/G4/G6/benchmark remediated (verification receipts)
External re-audit (AlphaSignal AI, May 7) surfaced ADR-095 gaps publicly.
Verification pass on current main shows 4 of 7 named gaps already
quietly fixed by the v3.7.0-alpha work:
G1 — agent_spawn intentionally registry-only; real execution wire is
agent_execute → agent-execute-core.ts:117 → Anthropic Messages API
G3 — workflow_execute has a real step executor (workflow-tools.ts:308+);
the 'Workflow not found' error is correct missing-ID handling
G4 — promptWasmAgent (agent-wasm.ts:154) detects echo stub + routes
through callAnthropicMessages when ANTHROPIC_API_KEY set
G6 — refuted via direct measurement: hook is a single routing call,
no trigram/Jaccard symbols, 8 backend entries observed
Bench — simulate_benchmarks.py removed; '84.8% SWE' claim cleaned
from tracked docs
Preserves original ADR text. Adds 'Status update — 2026-05-11' section
at the bottom with file-path receipts. Still open: G2, G5 (→ADR-094),
G7 (per-controller), #1748 (tool descriptions).
Related: #1896 (external audit response)
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(mcp): ADR-112 — every tool description now has "Use when … is wrong because …" guidance + CI guard + #1892 statusline fix
External audit (AlphaSignal AI, May 7) measured 237/300 MCP tool
descriptions lacked guidance for when Claude should pick Ruflo's tool
over native (Bash/Read/Grep/Glob/Task/TodoWrite). Re-measurement on
current main was actually 279/285 — worse. Now: 0/285.
## ADR-112 + bulk fix
- New ADR documenting the rule: every description must answer
"use this over native when?" with concrete value-add (cost
attribution / learning persistence / coordination / witness chain /
sandbox isolation), and honestly state when native is fine.
- 7 agent-tools.ts descriptions hand-edited (the P1 native-Task overlap).
- 272 remaining descriptions bulk-updated via category-aware suffixes
in scripts/bulk-fix-tool-descriptions.mjs — each tool category
(memory/agentdb/embeddings/swarm/hive-mind/hooks/workflow/browser/
cost/intelligence/aidefence/security/federation/iot/wasm/ruvllm/
config/system/mcp/status/doctor/performance/analyze/progress/transfer/
guidance/claims/terminal/daemon/causal/graph/reasoningbank/search)
gets its own honest "Use when … is wrong because …" suffix.
## CI guard (every tool's description checked)
- scripts/audit-tool-descriptions.mjs scans every MCPTool definition and
enforces three gates per tool:
1. "Use when ..." guidance present (the original ADR-112 check)
2. Description length ≥ 80 chars (catches near-empty descriptions)
3. Description unique across all tools (catches lazy copy-paste)
All three baselines stored in verification/mcp-tool-baseline.json
and are monotone-decreasing — CI fails on any regression.
- .github/workflows/v3-ci.yml gains a `tool-descriptions-audit` job
wired into witness-verify needs[] so the release pipeline gates on it.
## #1892 — UI version mismatch
- v3/@claude-flow/cli/.claude/helpers/statusline.js was hardcoded
to "RuFlo V3.5"; now reads from installed @claude-flow/cli's
package.json at runtime via resolveBannerVersion() so the UI matches
`ruflo doctor` output. Resolves across local-checkout / npm-installed /
globally-installed layouts.
## Witness manifest
- verification/witness-fixes.json: ADR-111, ADR-112, #1892 markers added.
- verification/macos/manifest.md.json regen'd — 102/102 fixes verified,
Ed25519 signature valid.
## Tests
- 1963 federation+cli tests pass on this branch.
- Build clean.
- Audit: 285/285 tools with guidance, 0 too-short, 0 duplicates.
Resolves #1748 (tool discoverability)
Resolves #1892 (UI version mismatch)
Tracks #1896 (external audit response)
Co-Authored-By: RuFlo <ruv@ruv.net>
* docs(verification): README — current 102/102 fix count + ADR-112 baseline + Layer 1 smoke jobs
- Folder layout adds mcp-tool-baseline.json (ADR-112)
- Example manifest summary updated 82→102 fixes, alpha.18→alpha.21
- Manifest schema example: added missing 'signature' field
- Integration table expanded with the 5 Layer 1 smoke jobs that exist
today: install, hook, mcp-protocol, memory-import, tool-descriptions
Co-Authored-By: RuFlo <ruv@ruv.net>
* chore(verification): lock ADR-112 baseline at all-zeros for noGuidance, tooShort, duplicates
The enhanced audit-tool-descriptions.mjs now tracks three gates instead
of one. Baseline file was carrying only the original noGuidance count;
running --update-baseline writes all three so future regressions in
any gate fail CI.
Co-Authored-By: RuFlo <ruv@ruv.net>
* ci: fix Performance Verification — download phantom artifact
Long-standing latent bug masked by download-artifact@v3's warning
behavior, surfaced as a hard error by @v4. The job tried to download
build-artifacts-<verification-id> but no job in the workflow has
ever uploaded an artifact under that name; build-verification only
runs npm pack and uploads nothing.
Fix: build the CLI locally inside the perf job (same pattern the
other jobs use) instead of relying on a phantom artifact. Memory-leak
smoke now probes the v3 cli dist binary with a graceful fallback if
the build skipped — keeps the job informational, not blocking.
Affected run: https://github.com/ruvnet/ruflo/actions/runs/25648092044
Triggered by main push of
|
||
|
|
d0c507e643 |
fix(memory): #1883 + #1884 — WSL path resolution + import-key sanitization + CI guard (#1886)
* fix(memory): #1883 + #1884 — WSL path resolution + import-key sanitization #1883 — memory_import_claude(allProjects=false) returned imported=0 on WSL because project-hash derivation only POSIX-slash-replaced cwd. A WSL bridge running Ruflo with cwd `/mnt/c/Users/x/Project Name` could never match the Windows-host Claude Code project dir `C--Users-x-Project-Name`. Fix: resolveProjectMemoryDir() tries multiple candidate hashes (legacy POSIX, WSL `/mnt/<drive>/`-translated, leading-dash-stripped, space-replaced) and returns the first that exists. Also adds optional `projectPath` input parameter as an explicit override for callers in cross-environment setups. #1884 — memory_import_claude wrote keys built from raw frontmatter `name` and section titles directly to storeEntry, bypassing validateMemoryInput. memory_delete enforces it. Any markdown file with shell-metacharacters in section headings (`(`, `)`, `{`, `}`, `[`, `]`, `<`, `>`, `!`, `#`, etc.) produced keys that imported successfully but could not be deleted through MCP — stranded in the database, requiring direct SQLite intervention. Fix: sanitizeMemoryKey() replaces every char in DANGEROUS_KEY_CHARS with `_` before storeEntry. The set is shared with DANGEROUS_KEY_PATTERN used by validateMemoryInput so write-side and read-side can never drift apart. CI guard (catches the bug class going forward): - plugins/ruflo-core/scripts/test-memory-import.mjs: 12 regression checks covering static dist scan (helpers defined + called from import handler), legacy-code negative-attestation, sanitizer property test against 27 adversarial inputs, WSL-fixture and POSIX-compat candidate-set checks. - .github/workflows/v3-ci.yml: new `memory-import-smoke` job (ubuntu+macos), wired into witness-verify needs[]. - verification/witness-fixes.json: #1883 + #1884 markers (resolve…, sanitize…) — witness-verify cryptographically attests both helpers are present in dist on every PR. Why our verification missed these (and is now closed): - Witness manifest catches drift from a known-good baseline. Both bugs were always there; no drift to detect. Closed via new markers + the static dist scan that asserts call-sites, not just helper presence. - CI matrix has Linux/macOS/Windows runners but no WSL-bridge fixture. Closed via deriveCandidates() unit assertion on synthetic WSL cwd. - No round-trip test for write-path/read-path key invariant. Closed via sanitizer property test on 27 adversarial inputs. Local verification: 12/12 regression guards pass; witness-verify clean (99 fixes pass, signature valid). Closes #1883 Closes #1884 Co-Authored-By: RuFlo <ruv@ruv.net> * ci: memory-import-smoke uses recursive --no-bail build The targeted `--filter @claude-flow/cli... run build` doesn't pull in @claude-flow/swarm, which @claude-flow/cli imports from at TS-compile time (TS6305 — referenced .d.ts not built from source). Switching to the same `pnpm --recursive --no-bail run build || true` pattern that witness-verify uses. The smoke script already fails loudly if the cli dist didn't get produced, so we don't lose signal. Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
19a569b1a7 |
feat(federation): ADR-097 phases 2.a/2.b/3-up/4 + ADR-104 transport (#1876)
* feat(federation): ADR-097 Phase 2.a — peer state machine entity layer FederationNode entity gains a state field (ACTIVE/SUSPENDED/EVICTED) plus suspend()/evict()/reactivate() methods. All transitions flow through a canTransition() table in the new federation-node-state.ts value object — self-loops are rejected (so a duplicate suspend can't reset the auto-eviction grace timer), EVICTED is terminal under breaker flow, operator reactivate is the only escape. Also ships pure helpers isCooldownElapsed + shouldAutoEvict so the Phase 2.b breaker service (separate file, deferred) can drive transitions deterministically without owning the clock. 27 new tests pin: legal/illegal edges, no-op invariant on duplicate suspend, EVICTED terminality, props round-trip preservation, cooldown boundaries, auto-evict grace > cooldown. Phase 2.b (breaker service wiring cost-tracker → suspend; outbound short-circuit on !isActive) and Phase 4 (federation_breaker_status MCP + doctor surface) remain deferred per ADR-097 status table. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(federation): ADR-097 Phase 2.b — breaker service + outbound short-circuit Two-layer breaker shipping the active-defense half of the circuit breaker: 1. **evaluatePolicy** (pure) — given rolling samples + node + policy + now, returns SUSPEND/EVICT/REACTIVATE_ELIGIBLE/NONE. Cost-takes-priority over failure-ratio when both trip (cost is the harder-to-fake signal). Auto-evict supersedes reactivate-eligible from SUSPENDED. 2. **FederationBreakerService** — owns per-peer rolling buffer (bounded, default 100k samples), wraps evaluatePolicy with entity mutation, exposes recordOutcome/evaluate/tick/snapshot/forget. Crucially does NOT auto-reactivate — the breaker only signals eligibility; the integrator's health probe owns the reactivate() call. This avoids the "false-positive recovery" failure mode where a peer flaps SUSPENDED↔ ACTIVE on transient telemetry. Coordinator wiring: sendMessage now short-circuits on !peer.isActive BEFORE session lookup, with PEER_SUSPENDED / PEER_EVICTED constant-string errors (no remaining-budget echo per the Phase 1 anti-oracle posture). Security invariants pinned by 25 new tests: - Negative tokens/usd clamped to 0 (no credit-inflation attack) - Failure ratio gated on minSamples=10 (anti-noise) - Strict > on threshold comparisons (boundary correctness) - EVICTED peers always return NONE (terminal under breaker flow) - apply=false dry-run preserves entity state Phase 4 (federation_breaker_status MCP + ruflo doctor surface) is now unblocked: snapshot() + node.stateRecord give it everything it needs. Phase 3 upstream (federation_spend bus emission) remains separate work — when it lands, the bus subscriber calls recordOutcome() and the in-memory buffer becomes a transparent cache. No breaker code changes. Witness manifest: 87 fixes (was 85), Phase2b + Phase2b-coordinator markers signed. Co-Authored-By: RuFlo <ruv@ruv.net> * chore(release): @claude-flow/plugin-agent-federation@1.0.0-alpha.6 Ships ADR-097 Phase 2.a (peer state machine) + Phase 2.b (breaker service + outbound short-circuit). Published to npm dist-tag alpha; latest is held at alpha.5 until the breaker bakes for one /loop cycle. Verified: tarball contains dist/application/federation-breaker-service.js, dist/domain/value-objects/federation-node-state.js, and PEER_EVICTED short-circuit in dist/application/federation-coordinator.js. All three witness markers present in the published artifact. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(federation): ADR-097 Phase 4 — operator surface (3 MCP tools + doctor) Closes the loop on the breaker so operators can see and operate it: **3 new MCP tools** (mcp-tools.ts): - federation_breaker_status — per-peer state snapshot + bucket counts; optional nodeId filter - federation_evict — operator-initiated MANUAL_EVICT with audit log + session-termination side effect; idempotent (already-evicted returns false but still emits audit for operator visibility) - federation_reactivate — escape hatch from SUSPENDED (after probe) or EVICTED (operator override) **Coordinator additions** (federation-coordinator.ts): - getPeerStates() — projects stateRecord over discovery.listPeers() - getPeerStateCounts() — O(peers) bucket count for status lines - evictPeer() / reactivatePeer() — async wrappers that audit-log every outcome (applied:true/false in metadata) **Doctor health-check** (cli/doctor.ts): - checkFederationBreaker — probes plugin loadability + asserts FederationNodeState export presence (catches version-skew where users have a pre-Phase-2 plugin installed). Optional plugin → "not installed" is a pass, not a fail. Selectable as `--component federation`. **Plugin index exports** — FederationNodeState + breaker primitives so external integrators (and the doctor probe) can detect Phase 2/4 support. 11 new coordinator tests pin: bucket-count math, audit emission on both success/no-op evict paths, EVICTED → ACTIVE operator override, unknown-peer no-op (no audit silence). 60 plugin-level tests updated to assert the 12-tool count. Witness markers added: ADR-097-Phase4-mcp + ADR-097-Phase4-doctor. 89 signed fixes in the manifest (was 87). Published @claude-flow/plugin-agent-federation@1.0.0-alpha.7 to npm alpha tag. Tarball validated: all 7 markers (Phase 2.a + 2.b + 4) present in dist/. ADR-097 status: Phases 1, 2.a, 2.b, 3-consumer, and 4 all Implemented. Only Phase 3 upstream (federation_spend bus emission) remains deferred — when it lands, the breaker's in-memory rolling buffer becomes a transparent cache with zero breaker code changes. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(federation): ADR-097 Phase 3 upstream — closes ADR-097 100% The last remaining "Deferred" entry from ADR-097's status table. With this, the breaker has end-to-end telemetry: integrators call coordinator.reportSpend() after each downstream agent completes, and the event fans out to TWO subscribers in parallel: 1. SpendReporter — pushes to whatever durable backend the integrator wires (cost-tracker memory namespace, Datadog, accounting DB). The event shape matches the cost-tracker consumer in plugins/ruflo-cost-tracker/scripts/federation.mjs verbatim: { peerId, taskId, tokensUsed, usdSpent, ts, success } 2. FederationBreakerService.recordOutcome — feeds the breaker's in-memory rolling buffer so cost/failure-ratio thresholds fire correctly. Without this fan-out, integrators would have to wire two parallel pipelines for the same telemetry. Both integrations are constructor-optional. A coordinator with neither still accepts reportSpend() calls (silent no-op) so callers don't branch on configuration. **New files:** - application/spend-reporter.ts — SpendReporter interface, FederationSpendEvent type, InMemorySpendReporter reference impl - __tests__/unit/coordinator-spend-reporting.test.ts — 10 tests pinning fan-out, contract shape, ts auto-fill, throw-bubble **New MCP tool:** federation_report_spend (13 tools total) **Coordinator constructor:** added optional 9th arg `integrations: { spendReporter?, breakerService? }` — backward-compat since omission preserves the existing 8-arg shape. **Anti-coupling design:** federation doesn't own model pricing; the caller owns it. reportSpend() is an explicit POST-completion call, not auto-emitted from federation_send. Future enhancement could auto-emit a "predicted cost" placeholder, but deferred until a concrete request justifies the additional state. **Witness:** 90 signed fixes (was 89). Phase 3 upstream marker added. **Published:** @claude-flow/plugin-agent-federation@1.0.0-alpha.8 to npm alpha tag. Tarball validated — all 8 markers (Phase 2.a + 2.b + 3-upstream + 4) present. ADR-097 status: ALL FIVE PHASES IMPLEMENTED (1, 2.a, 2.b, 3-consumer + 3-upstream, 4). Future work is integrator-side (production SpendReporter adapter that persists to ruflo memory; auto-emit predicted-cost placeholder). Co-Authored-By: RuFlo <ruv@ruv.net> * chore(release): umbrella alpha.20 — ships ADR-097 Phase 4 doctor surface Bumps + publishes the 3-package umbrella chain: - @claude-flow/cli@3.7.0-alpha.20 - claude-flow@3.7.0-alpha.20 - ruflo@3.7.0-alpha.20 All three on alpha + latest + v3alpha tags per CLAUDE.md publishing rules. Static check confirms `checkFederationBreaker` ships in the published @claude-flow/cli@alpha dist (3 occurrences in package/dist/src/commands/doctor.js). Now visible to users: - `npx ruflo@latest doctor --component federation` reports plugin loadability + version-skew detection (catches users running an older pre-Phase-2 federation plugin against the new MCP tools) Federation plugin already at @claude-flow/plugin-agent-federation @1.0.0-alpha.8 (published earlier this session) — installs via `npm install @claude-flow/plugin-agent-federation@alpha`. Witness manifest re-signed with new release versions; 90 fixes still verified. No new fix entries since this is a release-only bump (the underlying code already shipped in the prior 3 commits today). Co-Authored-By: RuFlo <ruv@ruv.net> * docs(adr): ADR-104 — federation wire transport (agentic-flow loader, WS today, QUIC roadmap) Documents the transport selection for ADR-097 federation. Smoke test mac↔ruvultra over tailscale revealed agentic-flow's published QUIC is API-only — loadWasmModule returns {}, encode/decode are placeholders, crates/agentic-flow-quic/src/wasm.rs explicitly notes the WASM build is a stub since browsers can't do raw UDP. Decision: adopt the loadQuicTransport() loader pattern with WebSocket fallback. Same AgentTransport interface today (WS) and tomorrow (native QUIC when it lands — set AGENTIC_FLOW_QUIC_NATIVE=1). Federation code stays transport-agnostic. Validated: real mac→ruvultra:9101 over tailscale, 125ms send latency (real I/O, not the prior 0ms stub). Upstream contribution: - ruvnet/agentic-flow#153 — adds quic-loader.ts to the published inner package, with WebSocketServer-backed real fallback - Patched build published as agentic-flow@2.0.12-fix.1 (`fix` dist-tag) so federation can consume the working transport without waiting for upstream merge 12h verification routine updated with Check 8 (ADR-104 transport smoke): - Pulls agentic-flow@fix - Stands up real WebSocketServer + client send round-trip on localhost - Asserts real send latency (>0, <5000ms) — catches if a future regression re-introduces the no-op stub behavior - SEVERITY:HIGH if stub regression detected Re-open this ADR when: - ruvnet/agentic-flow ships native QUIC binding - Federation traffic exceeds ~100 RPS to any single peer - Federation peers cross outside tailnet boundary - We have measured WS-vs-QUIC switch data Co-Authored-By: RuFlo <ruv@ruv.net> * feat(federation): wire ADR-104 transport — real mac↔ruvultra peering ADR-104 documented the design (agentic-flow loader pattern, WebSocket fallback today, native QUIC roadmap). This commit wires it into the plugin so federation_send actually moves bytes on the wire. Changes to src/plugin.ts: - New dep: agentic-flow@2.0.12-fix.2 (PR ruvnet/agentic-flow#153 patched build that fixes the published QUIC stub) - initialize() loads transport via loadQuicTransport(), registers it as federation:transport service - If config.port is set, transport.listen(port, host='0.0.0.0') binds an inbound listener (peers that only initiate outbound leave port unset) - sendToNode callback now resolves peer.endpoint via discovery.getPeer, strips the protocol prefix (ws://, tailscale://), and calls transport.send(address, AgentMessage{id, type, payload, metadata}) - shutdown() closes the transport (terminates outbound + inbound clients, awaits server close cb) - Graceful degrade: if transport load fails, plugin logs a warn and continues with the legacy in-process noop (preserves backward compat for tests/sandboxes without ws available) Validated end-to-end on real hardware: ruvultra (linux/x64): plugin booted, listening on 0.0.0.0:9101 mac (darwin/arm64): plugin booted, sent envelope in 150ms over tailscale Witness manifest: 91 fixes (was 90), ADR-104-transport marker added. Service-count assertion bumped 7 → 8 (added federation:transport). All 450 federation tests still pass (transport load is async + safe in the mocked test PluginContext). Published: @claude-flow/plugin-agent-federation@1.0.0-alpha.9 to npm alpha tag. Tarball validated: dist/plugin.js contains 'loadQuicTransport' + 'agentic-flow/transport/loader' import + 'federation:transport' service registration + dep agentic-flow@2.0.12-fix.2. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(deps): regenerate pnpm-lock — was out of sync since alpha.9 (agentic-flow dep adds) * chore: bump agentic-flow dep to 2.0.12-fix.8 to match lockfile (CI fix) --------- Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |
||
|
|
a8e9a05b08 |
ci: use standalone witness verifier + ts-ignore optional sona import
Two issues from the
|
||
|
|
8d06e427ca |
fix: #1859 #1862 ruflo-core hooks + CLI flag priority
Two distinct bugs converged on the same user symptom (every Write/Edit/Bash fired in Claude Code logged a parser error or recorded "true" as the file path). ## CLI parser bug (root of #1859 "records true as filename") In v3/@claude-flow/cli/src/commands/hooks.ts every handler resolved the primary value with: const x = ctx.args[0] || ctx.flags.X as string Because boolean-typed flags don't consume their next token, writing `--success true` (which the help text and project examples explicitly recommend) leaves the literal string "true" in `ctx.args[0]`, which then beats the named flag. Result: post-edit logs "Recording outcome for: true" instead of the path passed via --file. Fixed by swapping priority — flag value first, positional fallback — across all 14 sites: const x = (ctx.flags.X as string) || ctx.args[0] Backward compatible for legacy positional-only callers; surgical to a single regexed bulk swap. ## Plugin hooks bug (#1862 + part of #1859) plugins/ruflo-core/hooks/hooks.json passed flags the CLI doesn't accept: `--format true`, `--update-memory true`, `--track-metrics true`, `--store-results true`. The CLI's global `--format` flag rejects "true" because it's restricted to text|json|table — every Write/Edit hook crashed with "Invalid value for --format: true" before the handler ran. Also: the Bash hook's `tr '\n' '\0' | xargs -0 -I {}` mangled multi-line heredoc commands by splitting them at newlines, occasionally producing empty `--command ''` calls that the CLI rejected with "Required option missing". Replaced with a `bash -c` wrapper that: - Reads stdin once, extracts via jq into env vars (multi-line safe). - No-ops cleanly when the relevant field is absent. - Calls only flags the CLI documents: -c/-s/-e for post-command, -f/-s for post-edit. ## CI regression guard plugins/ruflo-core/scripts/test-hooks.mjs drives each PostToolUse hook with synthetic Claude-Code JSON against a CLI binary (local or published), asserting both exit code 0 *and* that the recorded value is the intended one (not a stray boolean). Verified empirically: fixed CLI: 7/7 pass broken @3.7.0-alpha.17: 5/7 fail with the exact #1859/#1862 symptoms Wired into .github/workflows/v3-ci.yml as `plugin-hooks-smoke` (Node 20 + 22), gating publish on green. Refs #1859 #1862 Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
66f7f644d8 |
fix(3.7.0-alpha.17): #1565 supervisor, #1856 mid-flight detector, #1857 Windows tasklist
Closes #1565, #1856, #1857. #1856 — services/worker-daemon.ts: detect workers that were mid-flight at the previous lifetime's crash and count them as failures so the run-counter math stays consistent. Adds `lastStartedAt` to WorkerState, records it in `executeWorker()` before running anything (with an immediate saveState so it survives crashes), restores it on init, and scans for `lastStartedAt > lastRun` in a new `detectMidFlightFailures()` called from `start()` after the orphan reaper. Each detected mid-flight worker bumps `failureCount` and gets an INFO log line; workers retry naturally at their next scheduled interval (no immediate re-run, which would just hammer the same code path that just killed the daemon). #1857 — commands/daemon.ts: split `killStaleDaemons` into a Windows path that uses `tasklist /v /fo csv /nh` + `taskkill /pid <n> /t`, and a POSIX path that keeps the existing `ps -eo pid,command` / process.kill behavior. Same defensive shape: any tooling failure swallowed silently so cleanup doesn't break daemon start. CSV parse splits on `","` after stripping outer quotes — robust against spaces in command lines. NOT runtime-tested on Windows by the maintainer (Mac dev environment); please report regressions. #1565 — commands/daemon.ts: ship `daemon install-supervisor` and `daemon uninstall-supervisor` subcommands. Writes a launchd plist on macOS (`~/Library/LaunchAgents/io.ruv.ruflo.daemon.plist`) with KeepAlive on Crashed=true, ThrottleInterval=10s, RunAtLoad=true — daemon survives crashes AND reboot. On Linux writes a systemd-user unit (`~/.config/systemd/user/ruflo-daemon.service`) with Restart=on-failure, RestartSec=10, StartLimitBurst=5. Both paths log the unit file location and offer a `--dry-run` to preview without writing. `--no-load` skips the immediate launchctl/systemctl enable. Windows scheduled-task installer deferred (errors with a link back to #1565). Validation: - Test suite: 1963 pass / 0 fail / 46 skipped — no regressions - Live #1856: pre-seeded daemon-state.json with audit lastStartedAt > lastRun → after start(), audit.failureCount went 0 → 1 ✓ - Live #1565: `daemon install-supervisor --dry-run` outputs the correct plist with absolute node + cli.js paths, KeepAlive on Crashed, log file paths under .claude-flow/logs/ ✓ - Live #1857: dist contains `killStaleDaemonsWindows`, `tasklist`, `taskkill` references; POSIX path unchanged ✓ - Lifecycle regression: daemon start → status (RUNNING) → stop → status (STOPPED) works on the published distro ✓ Published @claude-flow/cli@3.7.0-alpha.17, claude-flow@3.7.0-alpha.17, ruflo@3.7.0-alpha.17 with all dist-tags. Pre-publish + post-publish validation both green. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
f46e52f41e |
fix(3.7.0-alpha.16): daemon crash recovery (#1855)
Closes #1855. Two recovery gaps that allowed hard failures to leave the system in an inconsistent state are now fixed: Gap 1 — uncaughtException / unhandledRejection handlers: services/worker-daemon.ts now installs `installCrashHandlers()` from the constructor. On uncaught exception or unhandled rejection: 1. Append a structured record to .claude-flow/logs/crash.log (kind, timestamp, pid, message, stack) 2. Synchronously remove daemon.pid and save state via saveState() 3. Snapshot active child PIDs so the next lifetime can reap them 4. process.exit(1) so the failure is visible to supervisors/shells Without these, a thrown error from any timer callback or worker logic path silently crashed the daemon — PID file leaked, no diagnostic trail, operator had no idea why the daemon stopped. Gap 2 — orphan headless worker child reaping: services/headless-worker-executor.ts gains `getActiveChildPids()` returning the PIDs of currently-running children. worker-daemon.ts now writes `.claude-flow/daemon-children.json` on every execution:start/:complete/:error transition with the active PID list. At the top of `start()`, the new lifetime calls `reapOrphanedChildren()`: reads the children file, SIGTERMs any PID still alive that doesn't belong to the current daemon, then truncates the file. Self-PID is always skipped. The daemon log records the reap count. Previously, hard crashes (SIGKILL/OOM/segfault) left `claude --print` children running until their own per-worker timeout (5-15 min), holding API credits + memory. They're now reaped within ~1s of the next `daemon start`. Validation against published @claude-flow/cli@3.7.0-alpha.16: - Test 1: Pre-seeded daemon-children.json with orphan PID; daemon startup reaps the orphan and clears the file. PASS. - Test 2: Daemon throws via setImmediate; crash.log written, daemon.pid cleaned, daemon-state.json preserved. PASS. - Lifecycle regression: daemon start → status (RUNNING) → stop → status (STOPPED) still works; no "already running" line in log. - Test suite: 1963 pass / 0 fail / 46 skipped — no regressions. Out of scope for this issue (would land separately): - Full supervisor / auto-restart (launchd/systemd installer — that's #1565) - `ruflo daemon status --crashes` reader for crash.log - Windows ps replacement for killStaleDaemons (already noted in #1766) Published @claude-flow/cli@3.7.0-alpha.16, claude-flow@3.7.0-alpha.16, ruflo@3.7.0-alpha.16 with all dist-tags. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
d88c69dde9 |
fix(3.7.0-alpha.15): #1852 Windows shell-injection, #1853 daemon self-kill, #1854 memory path
Closes #1852, #1853, #1854. #1852 — services/headless-worker-executor.ts: pipe prompt via stdin instead of as a positional CLI arg. Previously `spawn('claude', ['--print', prompt])` on Windows routed through `cmd.exe /d /s /c` (because `claude` resolves to `claude.cmd`, which Node refuses to exec directly post-CVE-2024-27980). cmd.exe re-tokenized the entire command line including the prompt — any `>` `<` `&` `|` in source-code prompts became shell redirects, creating zero-byte files in cwd named after the next token (e.g. `controller.abort()`, `{const`, `0`, `HTTP`). Fix: `spawn('claude', ['--print'])` with stdio: pipe, then `child.stdin.end(prompt)` to write+close atomically. Stdin bypasses cmd.exe entirely. The end() call still produces EOF so `claude --print` doesn't block (the original concern in #1395 that drove the previous `stdio: ['ignore', ...]` choice). Reporter (@hassamtc) provided exact diff. #1853 — services/worker-daemon.ts: `checkExistingDaemon()` now ignores PID files containing the calling process's own PID. The detached-spawn path in commands/daemon.ts writes the child's PID as a fallback after 500ms; on Node 25 / macOS 26 the child reaches `start()` slower than that 500ms window and reads its own PID back, concluding "another daemon is already running" and exiting before scheduling workers. A daemon process is never "another instance" of itself; treat self-match as absence so start() proceeds normally. #1854 — memory/memory-initializer.ts: introduce `getMemoryRoot()` helper with documented precedence (env → config → default), and route every hardcoded `path.join(process.cwd(), '.swarm')` and `path.resolve( process.cwd(), '.swarm')` site (12+ in this file) through it. The three documented entry points — `CLAUDE_FLOW_MEMORY_PATH` env, `memory.persistPath` / `memory.path` in claude-flow.config.json, and the cwd default — now actually take effect instead of silently no-op'ing. Cached per-process; `_resetMemoryRootCache()` exported for the runtime configure flow + tests. Verification: - 1963 tests pass / 0 fail / 46 skipped - Build clean (tsc) - Live #1852 probe: dist now shows `spawn('claude', ['--print'], ...)` — no prompt as arg, stdio pipe. - Live #1853 probe: `checkExistingDaemon` has the self-PID skip in dist. - Live #1854 probe: default → cwd/.swarm CLAUDE_FLOW_MEMORY_PATH=/tmp/probe-mem → /tmp/probe-mem ✓ Published @claude-flow/cli@3.7.0-alpha.15, claude-flow@3.7.0-alpha.15, ruflo@3.7.0-alpha.15 with all dist-tags. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
2804d85f17 |
fix(3.7.0-alpha.14): auto-compact statusline on narrow terminals
Closes #1153. `ruflo hooks statusline` outputs 5+ lines of full-width formatted content by default. On narrow terminals (≤80 cols, common in tmux splits and side-by-side layouts) the lines wrap awkwardly and consume 6-7 lines of vertical space. Fix: `commands/hooks.ts` statusline now reads `process.stdout.columns` and auto-collapses to the existing single-line `compact` format when the terminal is narrower than 100 cols. New `--full` flag overrides this auto-detection for users who prefer the multi-line output even on narrow terms. `--compact` and `--json` continue to work as explicit overrides; default behavior on wide terminals is unchanged. Verification (this repo, both modes): COLUMNS=80 statusline (no flag) → "DDD:3/5 CVE:0/3 Swarm:1/15 Ctx:50% Int:10%" COLUMNS=80 statusline --full → 5-line multi-line output preserved COLUMNS=200 statusline (no flag) → 5-line multi-line (auto-detected wide) Build clean. Published @claude-flow/cli@3.7.0-alpha.14, claude-flow@3.7.0-alpha.14, ruflo@3.7.0-alpha.14 with all dist-tags. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
c67fa393de |
fix(3.7.0-alpha.13): persist headless results + ab-test guard
Closes #1793, #1652. #1793 — services/worker-daemon.ts: headless worker runs now persist their parsedOutput / output to the same metrics files the local fallback workers write to (.claude-flow/metrics/<name>.json). Previously the AI-mode branch returned the result and exited, leaving rich findings trapped in `.claude-flow/logs/headless/*_result.log` and invisible to `npx ruflo memory stats` and downstream consumers. Mapping mirrors the *Local methods: audit→security-audit.json, optimize→performance.json, testgaps→test-gaps.json, document→documentation.json, etc. Persisted record schema: { timestamp, mode:'headless', workerType, model, durationMs, tokensUsed, executionId, success, findings (= parsedOutput), rawOutputPreview (first 2KB), rawOutputLength }. Persistence is wrapped in try/catch so a write failure logs a warning but doesn't break the worker. #1652 — @claude-flow/guidance/src/analyzer.ts: abBenchmark now throws an actionable error when the provided executor is not content-aware instead of silently producing a guaranteed zero-delta verdict that costs ~$23 per run. The DefaultHeadlessExecutor IS content-aware as of @claude-flow/guidance@3.0.0-alpha.2 (it has `setContext` and physically swaps CLAUDE.md with backup/restore), so the guard only fires for caller-injected bare IHeadlessExecutor implementations. Verification: - @claude-flow/cli: 1963 tests pass / 0 fail / 46 skipped - @claude-flow/guidance: 1331 tests pass / 0 fail - Builds clean for both packages Published @claude-flow/cli@3.7.0-alpha.13, claude-flow@3.7.0-alpha.13, ruflo@3.7.0-alpha.13, and @claude-flow/guidance@3.0.0-alpha.3 with all dist-tags. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
1884ed1010 |
fix(3.7.0-alpha.12): batch resolve issue-fix loop #1839-#1847
Closes #1839, #1840, #1841, #1842, #1843, #1844, #1845, #1846, #1847.
#1839 — bin/cli.js, bin/mcp-server.js, config-adapter.ts: rename
serverInfo.name 'claude-flow' → 'ruflo' so MCP wire identity matches the
package name. Live probe of `ruflo mcp start` now returns
`serverInfo.name="ruflo"` (verified post-build).
#1840 — init/executor.ts: detectExistingRufloMCP() now also walks
parsed.projects[*].mcpServers.ruflo with normalized path matching
(lowercase + forward-slash) so `claude mcp add ruflo` registrations
stored project-scoped in ~/.claude.json are detected and init skips
writing a duplicate .mcp.json.
#1841 — init/mcp-generator.ts: generated .mcp.json now keys
`mcpServers.ruflo` instead of legacy `mcpServers['claude-flow']`. The
printed `claude mcp add` instructions match. Prevents the
duplicate-tool-prefix problem when init runs over an existing ruflo
registration.
#1842 — commands/doctor.ts: checkMcpServers() now traverses
~/.claude.json.projects[*].mcpServers in addition to top-level
mcpServers, so doctor stops warning "No MCP config found" when a
working project-scoped ruflo registration exists.
#1843 — mcp-tools/system-tools.ts: exclude `unknown` from health
denominator (was dragging the score down even when actionable checks
were green) and surface as `advisory` count. Add YAML config and
sql.js/HNSW/.swarm/ruvector memory paths to detection. Local probe:
4 healthy / 5 actionable = 80% (was 4/8 = 50%) with 3 advisory.
#1844 — services/worker-daemon.ts: WorkerDaemon now reads
.claude-flow/config.yaml (and .yml) when config.json is absent, with
lazy `yaml` import so missing dep falls back to a clear warning.
Adds yaml@^2.8.0 to runtime deps. Logs the chosen source.
#1845 — services/worker-daemon.ts + mcp-tools/hooks-tools.ts: durable
queue boundary between MCP dispatch and daemon. mcp__hooks_worker-
dispatch now writes .claude-flow/daemon-queue/<id>.json (the
process-local Map was invisible to the daemon). The daemon polls this
directory every 5s, executes triggerWorker(), and moves processed
entries to .processed/. Adds `mcp-only` status for queue-write
failures so we never claim `queued` without proof on disk.
#1846 — mcp-tools/memory-tools.ts + commands/memory.ts: feature-detect
smartSearch on the resolved @claude-flow/memory build. When absent
(older published memory packages predate the export), fall through to
plain semantic search with an explicit warning + `smartFallback`
field on the response, instead of throwing
`smartSearch is not a function`.
#1847 — mcp-tools/hooks-tools.ts: hooks_pretrain now emits an explicit
note when a non-empty corpus produces zero patterns, naming the
supported extraction extensions (.ts/.js/.py/.go/.rs/.java) and
clarifying that pretrain is a separate axis from live trajectories
and statusline state. Local probe on a Markdown vault returns the
new note correctly.
src/index.ts: pre-existing TS strict-null error in showCommandHelp()
that was preventing `npm run build` (introduced by #1791.4 /
|
||
|
|
23016fdfa5 |
fix(hive-mind): use --mcp-config=<path> to stop variadic prompt slurp (#1780) (#1800)
Claude Code's `--mcp-config <configs...>` flag is variadic, so passing it as two argv tokens lets a later positional argument — the hive-mind prompt itself — get slurped as a second config file path. Once the prompt grows past PATH_MAX (4000+ chars is normal for hive-mind), `open(prompt)` fails with `ENAMETOOLONG: name too long`, the worker never spawns, and `ruflo hive-mind spawn --claude` exits 1. Use `=`-syntax (`--mcp-config=<path>`) so the flag stays attached to its single value and the prompt is parsed as the prompt. Closes #1780. |
||
|
|
3673138249 |
fix(security): retry plain import + actionable error for aidefence load (closes #1807) (#1813)
* fix(security): retry plain import + actionable error for aidefence load (#1807) `mcp__ruflo__aidefence_*` tools were unconditionally failing on npm-global installs of `claude-flow` (and any setup where the auto-install of `@claude-flow/aidefence` lands somewhere Node's standard module resolver doesn't search). The previous flow: 1. `import('@claude-flow/aidefence')` — fails on first call 2. `autoInstallPackage(...)` — runs `npm install --no-save` in cwd 3. `require.resolve(...)` + file:// import — also fails because the install landed in a different prefix than the resolver searches 4. Throws `AIDefence installed but failed to load: ... Try restarting the MCP server.` — user follows that advice and it still doesn't work. Two changes: - **Add a plain `import(pkg)` retry between the auto-install and the file:// dance.** After the install, Node's standard resolver often picks up the new node_modules directory across the `await` boundary; that path succeeds where the first attempt failed. - **Replace the cryptic terminal error with an actionable one** that explains the npm-global root cause and lists three recovery paths (project-local install, run from a project dir, restart MCP). If both retries succeed, log which path worked (`resolver path` vs `file:// path`) so users diagnosing future regressions can see how loading actually resolved. This is the load-path fix only — bundling aidefence as a real dependency vs documenting it as optional is tracked separately. The auto-install behaviour is unchanged. Closes #1807. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(doctor): surface @claude-flow/aidefence availability (#1807) Reviewing #1807 again: the reporter listed three suggested fixes and this PR's load-path retry covered #2 ("make autoInstallPackage path work"). They also asked for #3: surface the failure mode in `claude-flow doctor` so operators know their AIDefence stack is non-functional BEFORE they rely on it. Add `checkAIDefence()` to the doctor health-check set. Probe is the same dynamic `import('@claude-flow/aidefence')` the MCP tool's handler uses — `pass` means the actual `aidefence_*` tools will work, `warn` includes the actionable fix (`npm install --save` in the project, or run mcp from a dir that has it). Wired into both: - the default `allChecks[]` (so `ruflo doctor` shows it) - the `componentMap` (so `ruflo doctor -c aidefence` runs just this probe) Stays as `warn` on absence — aidefence is genuinely an optional dep, not a hard requirement, so missing != broken-system. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
7cee603178 |
fix(init): skip writing .mcp.json when ruflo MCP already registered (#1779) (#1820)
`ruflo init` was always writing `.mcp.json` with a hardcoded
`claude-flow` top-level key. When users had ALSO registered the same
binary under the new `ruflo` name (via `claude mcp add ruflo ...`,
or via another project's `.mcp.json` in a parent directory), Claude
Code ended up registering the same MCP server twice under two prefixes
(`mcp__claude-flow__*` and `mcp__ruflo__*`), exposing ~250 duplicate
tools and inflating the deferred-tools list.
Detect-and-skip approach (defensive, narrow):
- New `detectExistingRufloMCP(targetDir)` helper walks parents of
`targetDir` looking for `.mcp.json`, plus checks
`~/.claude.json` and `~/.claude/mcp.json` (Claude Code's user-global
configs). Returns the path of any file that already declares a
`ruflo`-keyed MCP server.
- In `writeMCPConfig`, when that helper finds an existing `ruflo`
registration AND `--force` is not passed, skip writing `.mcp.json`
entirely with a clear message naming the existing file. The user
keeps their single `ruflo` registration; init doesn't add the
duplicate.
- `--force` bypasses the guard for users who genuinely want both
registrations.
What this DOESN'T do: rename `claude-flow` → `ruflo` as the canonical
MCP key. That's a wider change because the codebase's existing tool
references (`mcp__claude-flow__*` in agent prompts, CLAUDE.md docs)
assume the legacy key. Leaving canonical-key migration for a follow-up
design pass; this PR fixes the immediate duplicate-registration pain.
Closes #1779.
|
||
|
|
3ed34fe065 |
fix(hive-mind): re-route task submission to existing task_create MCP tool (#1791.1) (#1806)
`ruflo hive-mind task --description "smoke" --hive-id <id>` was failing with: [INFO] Submitting task to hive... [ERROR] Task submission error: MCP tool not found: hive-mind_task The bundled MCP server's `mcp__ruflo__hive-mind_*` surface exposes init / spawn / status / broadcast / consensus / memory / shutdown / leave — but no `task` tool. The CLI was dispatching to a name that was never registered. Rather than register a new tool (which needs a hive-mind-specific backing implementation), re-route to the existing `task_create` tool which is registered and works. Hive-specific options that don't have a home in `task_create`'s schema are preserved as tags so a future hive-mind worker / consensus tool can pick them up: - `consensus:required` / `consensus:none` - `timeout:<n>s` Display the values back from local flags (priority, consensus, timeout) since `task_create` doesn't echo them all. `assignedTo` shows "pending dispatch" when `task_create` returns the empty array (the expected state right after creation, before workers pick it up). Closes #1791 (sub-bug 1). |
||
|
|
7ebdaf580b |
fix(cli): pre-load lazy commands so short flags scope correctly (#1791.2) (#1803)
`ruflo hive-mind task -d "smoke"` was silently rejecting the short flag:
$ ruflo hive-mind task -d "smoke"
[ERROR] Task description is required
even though `taskCommand` defines `{ name: 'description', short: 'd' }`.
Root cause is the lazy-command path in the parser. When the parser walks
argv in pass 1 and encounters a name registered via `registerLazyCommandName`
(hive-mind, neural, performance, security, ruvector, …), it `break`s out
without resolving subcommands — by design, since the lazy module hasn't
been imported yet. That means `buildScopedAliases()` only ever sees the
parent's options, and the subcommand's short flags never make it into
the alias map. `-d` falls through to global resolution, gets stored as
`flags.d = "smoke"`, and the action handler reading `flags.description`
sees `undefined`.
Fix: in `CLI.run()`, before calling `parser.parse()`, eagerly load any
lazy command that appears as the first non-flag positional, then
`registerCommand()` it as a normal command. Parse then sees the full
subcommand tree and scopes flags correctly.
Cost: lazy commands now load on first use rather than after the parser
identifies them as the dispatch target — but they would have loaded
moments later anyway, so the wall-clock impact is essentially zero.
Commands the user doesn't invoke still don't load.
Adds `parser.isLazyOnly(name)` helper so the CLI can ask the question
without reaching into private state.
Closes #1791 (sub-bug 2).
|
||
|
|
48da302b3b |
fix(doctor): walk-up .git fallback for git-repo health check (#1791.7) (#1802)
`ruflo doctor` was reporting `Not a git repository` even when `.git/`
clearly existed in cwd, because the only signal it consulted was a `git
rev-parse --git-dir` invocation that failed for unrelated environment
reasons (PATH inheritance, daemon-launched contexts, broken global git
config, etc.).
Two changes:
1. Use `--is-inside-work-tree` instead of `--git-dir` — slightly more
robust and matches what other tools do.
2. On failure, walk up parents of cwd looking for a `.git` directory.
If found, surface a *useful* warning ("repo detected on disk but
`git rev-parse` failed — check git PATH") instead of the misleading
"not a repository". Only return the original message when neither
git nor a .git directory is found.
This preserves `pass` semantics (still requires git working) but stops
gaslighting users whose repos are clearly on disk.
Closes #1791 (sub-bug 7).
|
||
|
|
0377945c93 |
fix(memory): make memory init idempotent when DB already exists (#1791.6) (#1801)
`ruflo memory init` previously emitted `[ERROR] Database already exists. Use --force to reinitialize.` and a "Initialization failed" spinner whenever `.swarm/memory.db` was already on disk — even though the existing DB was perfectly healthy and there was nothing to fail. This made the command awkward to script (callers had to either probe disk first or invoke `--force` and lose data) and confused users who read `[ERROR]` as something actually being wrong. Treat the "DB exists, no --force" case as a successful no-op: - `MemoryInitResult` gains an optional `alreadyExists?: boolean` flag - The early-return branch now returns `success: true, alreadyExists: true` - `memory init` CLI prints `Memory database already initialized at <path>` with a hint about `--force`, exits 0 - MCP-side callers (`mcp-server.ts`, `mcp-tools/memory-tools.ts`) that only check `result.success` continue to work — they previously treated this case as a failure, now they see the existing DB as ready, which matches their intent Closes #1791 (sub-bug 6). |
||
|
|
88f9fba5f8 |
fix(doctor): surface config collision between legacy JSON and v3 YAML (#1798) (#1811)
The previous \`checkConfigFile\` returned at the first config it found, checking JSON before YAML. When a project had both a leftover v2 \`claude-flow.config.json\` AND a v3 \`.claude-flow/config.yaml\`, doctor reported only the JSON as "active" while the daemon was actually reading from the YAML — exactly the silent disagreement #1798 calls out. v3 \`init\` only writes the YAML; the JSON variants are legacy shapes that survive across upgrades. Detect the collision and surface it: - Collect ALL configs that exist (no early return). - If the JSON parses badly: fail (unchanged behavior). - If BOTH a legacy JSON and a v3 YAML exist: emit \`warn\` with "Config collision: ... — subsystems may disagree silently" and a \`fix\` suggesting \`mv <legacy>.json <legacy>.json.bak\`, keeping the YAML canonical. - Otherwise prefer the YAML (v3 canonical) over a lone JSON. Doctor stops being silent. The subsystems still need their own unification (tracked separately) but users can now SEE the problem. Closes #1798. |
||
|
|
c42aa265a0 |
fix(swarm): reconcile orphan entries on swarm-state.json load (#1799) (#1809)
`.claude-flow/swarm/swarm-state.json` was retaining entries with
`status: "running"` indefinitely after the host process exited.
Each `claude-flow start --daemon` registered a new swarm; nothing ever
reconciled those entries against PID liveness or heartbeat TTL, so
crashed/exited orchestrators left permanent ghost registrations.
Reporter measured three orphan swarms accumulated in a single afternoon
on Windows v3.7.0-alpha.8.
Two changes in `swarm-tools.ts`:
1. `swarm_init` now records `pid: process.pid` on the new
`SwarmState`. Backward compatible — the field is optional.
2. `loadSwarmStore()` runs `reconcileOrphanSwarms()` on every read
and persists if anything changed. Reconciliation marks any
`status: 'running'` entry as `terminated` (with a
`terminationReason`) when:
- PID-based: `pid` is set and the process is dead
(ESRCH from `process.kill(pid, 0)`; EPERM still counts as
alive — different user but live)
- TTL fallback: pre-#1799 entries with no `pid` are reaped
when `updatedAt` is older than 24h (conservative; live but
long-idle swarms can recover by writing a heartbeat)
`swarm_status` and `swarm_health` no longer return the ghost entries
the reporter complained about. Cost is sub-millisecond (one kill(0)
syscall per running entry).
Closes #1799.
|
||
|
|
3eb6b4d656 |
fix(memory): content-hash dedupe in memory_import_claude (#1791.8) (#1808)
`memory_import_claude --allProjects=true` was indexing the same memory file content under multiple `project_id` prefixes (e.g. `claude:-home-matheus:`, `claude:-home-mathe:`, `claude:-home-atheus-ssali:`), producing 5-8x duplication on long-lived homes. The reporter measured 2648 entries from 456 files on an 8-project home (vs 331 entries from 57 files with `--allProjects=false` — the natural 8x reduction). Root cause: Claude Code's `~/.claude/projects/` accumulates historical project_id directories (truncated forms, sandbox cwds, renamed workspaces). Each contains its own copy of the same memory files. The previous import walked all of them and stored every copy. Fix: track a `Set<string>` of SHA-256 prefix hashes of each file's raw content. When iterating, skip any file whose content hash we've already imported under a different project_id directory. Surface the new `duplicatesSkipped` count in the response so users can see how much dedupe happened. This preserves the FIRST project_id seen for each unique content (a deterministic-enough behavior given readdir's sort order). Real behavioral differences between projects' versions of "the same" memory file would, of course, hash differently and import normally. Closes #1791 (sub-bug 8). |
||
|
|
122193a454 |
fix(memory): show active embedding provider + HNSW status in stats (#1622) (#1816)
`ruflo memory stats` previously didn't surface which embedding backend
the runtime fallback chain in `loadEmbeddingModel()` actually picked.
That mattered because the chain ranges from full 384-dim ONNX semantic
search down to a 128-dim hash fallback with no semantic understanding,
and users couldn't tell which one they had without re-running
`memory init --verbose --force` (destructive — reinitializes the DB).
Add an "Embedding" section to the stats table showing:
- **Provider** — modelName from loadEmbeddingModel (e.g.
`Xenova/all-MiniLM-L6-v2`, `ruvector/onnx`, `hash-fallback`)
- **Dimensions** — vector length (384 / 768 / 128)
- **Semantic Search** — yes/no flag derived from a known-providers
set; surfaces the hash-fallback degradation explicitly so users
can see WHY their search results are poor
- **HNSW Index** — active (with entry count) / available-not-initialised
/ not-active, derived from `getHNSWStatus()`
Calling `loadEmbeddingModel()` is cheap (cached after first call) and
wrapped in try/catch so a broken introspection path doesn't fail the
whole stats dashboard — the rest stays useful.
Closes #1622.
|
||
|
|
7bfd650eec |
fix(init): make RuFlo attribution trailer opt-in (#1670) (#1815)
`ruflo init` was silently writing this block into every project's
`.claude/settings.json`:
"attribution": {
"commit": "Co-Authored-By: RuFlo <ruv@ruv.net>",
"pr": "🤖 Generated with [RuFlo](...)"
}
…which the assistant then dutifully appended to every git commit it
created during a session. The reporter (#1670) flagged the
consequences:
- no consent — trailer is injected without prompting
- misrepresents contribution — implies direct human authorship
- pollutes contributor graphs — GitHub counts Co-Authored-By
trailers when building the Contributors page, so `ruvnet`
appeared as a contributor on repos they never touched
- hard to undo — removing the trailer needs `git filter-branch` +
force-push, disrupting anyone who cloned the repo
Make it opt-in:
- Add `attribution?: boolean` to `InitOptions` (default `false`).
- `generateSettings` only emits `settings.attribution` when
`options.attribution === true`.
- Test updated to assert the new default (`toBeUndefined`) and a
second test asserts opt-in still produces the block.
Existing projects that already have the field in their settings.json
keep working — this fix only changes what `ruflo init` *writes* on a
fresh setup. Users who want the trailer can pass `--attribution` or
add it to their settings manually.
Closes #1670.
|
||
|
|
d469721710 |
fix(hooks): NaN-safe coercion in metrics + pretrain output (#1686) (#1814)
`?? 0` defaults null/undefined but lets NaN through. When a counter
came back as `Number.NaN` from the MCP tool, the metrics dashboard
either rendered `"NaN"` (best case) or threw
`TypeError: Cannot read properties of null (reading 'toFixed')`
(when an earlier null path hit before the May-1 nullish-coalesce fix).
Pretrain output specifically reported `Duration: NaNs` because
`rawResult.duration === NaN` survived the `??` chain.
Add a tiny `safeNum(value, fallback = 0)` helper at the top of the
module that coerces to a finite number (null/undefined/non-numeric/
NaN/Infinity all collapse to `fallback`) and use it for every numeric
the metrics + pretrain commands feed into `.toFixed(...)`:
- `metricsCommand`: totalPatterns, successfulPatterns, failedPatterns,
avgConfidence, routingAccuracy, totalRoutes, totalCommands,
commandSuccessRate, avgRiskScore
- `pretrainCommand`: durationMs
`hooks metrics` now renders cleanly even when the underlying memory
backend hasn't been written to yet, and `hooks pretrain` reports a
real `0.0s` instead of `NaNs` when timing isn't available.
NB this only fixes the *display layer*. The architectural disconnect
the issue describes — `hooks post-*` writes to `.swarm/memory.db` but
the dashboard reads from `.claude-flow/metrics/*.json` — is a
separate, larger fix tracked for follow-up.
Closes #1686 (display crashes / NaN output). Architectural disconnect
addressed separately.
|
||
|
|
93b97548ed |
fix(cli): subcommand --help renders the leaf, not the parent (#1791.4) (#1805)
`ruflo hive-mind spawn --help`, `... task --help`, `... broadcast --help` were all returning the same parent `hive-mind` help with the SUBCOMMANDS list — never the per-subcommand options the user was actually asking for. This made flag discovery painful (see #1791 sub-bugs 2 and 5, where users couldn't see the short flags / clarifying descriptions). Root cause: `CLI.run()` only passed `commandPath[0]` to `showCommandHelp`, discarding the rest of the path. `showCommandHelp(name: string)` then looked up only the root command, so `--help` on any subcommand showed the root's help. Fix: - Change signature to `showCommandHelp(commandPathOrName: string | string[])`, preserving the previous string form for backward compatibility. - When given a path, walk subcommands following the path so nested invocations render the leaf's own options / examples / aliases. - Title now reads `ruflo hive-mind spawn` instead of `ruflo hive-mind`, matching what the user actually invoked. - Falls back to the last known node if a path segment is unknown, preserving graceful behavior on typos. Update both call sites (`flags.help` branch + "no action" fallback) to pass `commandPath` instead of `commandName`. Closes #1791 (sub-bug 4). |
||
|
|
b51b804fab |
fix(doctor): clarify that --fix prints commands rather than auto-applying (#1791.5) (#1804)
`ruflo doctor --fix` was reported as misleading: the flag name reads as
"automatically fix issues" but the implementation only PRINTS suggested
shell commands for the user to run themselves. The pre-existing help
text (`Show fix commands for issues`) was buried and ambiguous.
Three small wording changes in `doctor.ts`:
- Option description now reads: "Print suggested fix commands (does
not auto-apply — copy/paste them yourself)"
- Example description matches.
- Output header changes from "Suggested Fixes:" to "Suggested commands
(run them yourself):", and the "use --fix" hint mentions that it
doesn't auto-apply.
No behavior change; this is purely a help/output clarity fix. A real
auto-apply mode (proposed `--apply` in #1791) is intentionally out of
scope — that needs design work on which fix recipes are safe enough to
run without user confirmation.
Closes #1791 (sub-bug 5).
|
||
|
|
2fd38f4ded |
fix(wasm): bump default Sonnet from 20250514 to 4.6 (closes #1810) (#1812)
* fix(wasm): bump default Sonnet model from 20250514 to 4.6 (#1810) `wasm_agent_create` (gallery + plain) hardcoded `anthropic:claude-sonnet-4-20250514` as the default model. New WASM agents silently inherited a year-old Sonnet ID unless the caller passed an explicit `model`, which is a quiet UX/pricing failure that new users won't catch until they hit version-specific behaviour. Bump to `anthropic:claude-sonnet-4-6` (current Sonnet at time of writing) in all four locations the previous ID was hardcoded: - `src/ruvector/agent-wasm.ts` — actual default (this is what actually shipped to users) - `src/commands/agent-wasm.ts` — `--model` flag description - `src/commands/agent-wasm.ts` — example command - `src/mcp-tools/wasm-agent-tools.ts` — MCP `wasm_agent_create` schema description - `__tests__/ruvector/agent-wasm.test.ts` — assertion in "creates agent with defaults" A future follow-up should replace the hardcode with a config-driven default (e.g. read from `claudeFlow.modelPreferences.default`) so Anthropic version cuts don't require a code change. Tracked separately. Closes #1810. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(wasm,plugins): pin gallery test + sweep remaining stale model IDs (#1810) Follow-up to the WASM default bump in this same PR. Reviewing the issue more carefully, the reporter's repro path goes through `createAgentFromTemplate('researcher')` (the GALLERY path) — and while that path *does* inherit the new default (it passes `model: undefined`, falling through to `createWasmAgent`'s default), nothing in the test suite actually pinned the gallery output to the new default. A future regression would only surface in `creates agent with defaults` (the bare-call test), not in the gallery test the user actually hits. __tests__/ruvector/agent-wasm.test.ts:326 + expect(info.model).toBe('anthropic:claude-sonnet-4-6'); While I had grep open, also swept the rest of the workspace for the `claude-sonnet-4-20250514` literal and the matching old Claude 4.x model IDs: - plugins/examples/plugin-creator/index.ts (×2 — runtime + code-gen template string) - plugins/examples/plugin-creator/plugin-creator.test.ts (assertion) - plugins/src/collections/official/index.ts (×4 — coder, tester, reviewer, coordinator agent defs) - plugins/src/providers/index.ts (Claude provider's models[] list — also bumped opus-4-5 → opus-4-7 and 3-5-haiku → haiku-4-5) - plugins/README.md (example snippet) - mcp/.claude/settings.json (modelPreferences default + routing) Historical ADR docs (`v3/implementation/adrs/`) still reference the old IDs by design — they capture decisions at issuance time. Comments in the WASM agent source that reference the old hardcode for context are kept too. Strengthens the original closes-#1810 fix from "default works" to "default works AND a regression of the gallery path is caught by tests AND no other surface in the workspace ships the stale ID anymore." Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
d031c3d13a |
feat(agentdb): hierarchical + causal-edge + causal-node delete MCP tools (#1784) (#1789)
* feat(agentdb): add hierarchical-delete + causal-edge-delete + causal-node-delete MCP tools (#1784) The reporter (@Tovli) flagged that agentdb_hierarchical-store and agentdb_causal-edge had no delete counterparts. Net effect: /adr-index cant do a full re-index because deleted ADR files remain as stale nodes + dangling edges in adr-patterns / adr-edges forever. Architectural finding during scoping: neither @ruvector/graph-node native binding (createNode/createEdge/createHyperedge only) nor agentdbs HierarchicalMemory class exposes a public delete API. So the original proposed deleteNode/deleteEdge wrappers cant land — the storage layer genuinely has no delete primitive. Honest fix: surface delete for the SQL fallback path that bridge stores already use (memory_entries soft-delete via status flip + AttestationLog audit), and explicitly report controller="native-unsupported" when an entry lives in a backend without delete. No silent black holes. What ships: v3/@claude-flow/cli/src/memory/memory-bridge.ts: 3 new bridge functions - bridgeDeleteHierarchical({ key, tier? }): 1. Try hm.delete() if HM ever ships one 2. Try hm.remove() for stub HMs 3. SQL fallback: soft-delete on memory_entries WHERE namespace LIKE hierarchical% 4. native-unsupported when neither path matches but real HM is loaded - bridgeDeleteCausalEdge({ sourceId, targetId, relation? }): 1. Try causalGraph.removeEdge() if it ever exists 2. SQL fallback: soft-delete causal-edges row keyed by sourceId→targetId 3. native-unsupported when graph-node native is the canonical store - bridgeDeleteCausalNode({ nodeId }) — cascade: Soft-deletes the node row + every edge whose key matches nodeId→% or %→nodeId Returns deletedEdges count for observability All three flow through MutationGuard (fail-closed) and AttestationLog (audit). v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts: 3 new MCP tools - agentdb_hierarchical-delete (validates key + tier enum) - agentdb_causal-edge-delete (validates sourceId + targetId + optional relation) - agentdb_causal-node-delete (cascade) Registered in agentdbTools export array. Each tools description surfaces the native-backend caveat so callers can tell at a glance. v3/@claude-flow/cli/__tests__/agentdb-delete-tools.test.ts: 12 surface tests - All 3 tools registered in agentdbTools - Required-field validation - Tier enum rejection - Cascade contract shape - InputSchema completeness Validation: - tsc clean - 12 new delete-tool tests pass - 781 baseline cli tests still pass (parser, output, validate-input ×2, mcp-tools-deep, commands, cli, commands-deep, config-adapter ×2, p1-commands, router-bandit, neural-package-bridge) Closes #1784 (the SQL-fallback delete path). Out of scope (tracked for follow-up): - Tombstone tables for native graph-node storage (recall paths would filter against a shadow table). Bigger architectural change. - Updating plugins/ruflo-adr/scripts/import.mjs to invoke the new delete tools during re-index. Requires the sync semantics call. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(agentdb): wire bridge delete fns to agentdb@3.0.0-alpha.13 native APIs (#1784) Upstream agentic-flow#150 / agentic-flow#151 merged + agentdb@3.0.0-alpha.13 shipped with the missing delete API. Updates the bridge to use the native methods first, falling back to the SQL path only when the controller is older than alpha.13. What changed: v3/@claude-flow/cli/package.json: bumped agentdb dep range "agentdb": "^3.0.0-alpha.11" -> "^3.0.0-alpha.13" v3/pnpm-lock.yaml: regenerated with --no-frozen-lockfile v3/@claude-flow/cli/src/memory/memory-bridge.ts: 3 bridge fns updated. bridgeDeleteHierarchical: now tries reflexionMemory.deleteEpisode(key) FIRST. ReflexionMemory.deleteEpisode propagates through graph adapter + generic graph backend + vector backend AND purges SQL episodes + episode_embeddings rows in one call (durably consistent across backends). Falls back to old hm.delete()/hm.remove() probes + SQL soft-delete for pre-alpha.13 / non-reflexion controllers. bridgeDeleteCausalEdge: now tries causalGraph.deleteEdgesByEndpoints( sourceId, targetId, relation) FIRST — Cypher-routed (MATCH … DETACH DELETE). Cypher-injection-safe; labels validated /^[A-Za-z_][A-Za-z0-9_]*$/ upstream. Falls back to removeEdge() probe and SQL fallback. bridgeDeleteCausalNode: now tries causalGraph.deleteNode(id, {cascade: true}) FIRST. Returns native {deletedNode, deletedEdges} for accurate audit. Cascade counts incident edges before delete; works regardless of binding stats. Falls back to SQL multi-row soft-delete. Validation: - tsc clean - 12 delete-tool surface tests pass - 781 baseline cli tests still pass - Total 793 cli tests green - lockfile drift fixed (regenerated for new agentdb range) The "controller: native-unsupported" branch is now dead-code on alpha.13 backends — it only fires for pre-alpha.13 installs that explicitly load @ruvector/graph-node native binding without the Cypher routing. Closes #1784 (truly this time). Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: Reuven <cohen@ruv-mac-mini.local> |