Skip to content

Community patches for @claude-flow/cli v3.1.0-alpha.39 — 18 bug fixes across headless workers, daemon, config, embeddings, namespaces, and HNSW

Notifications You must be signed in to change notification settings

sparkling/claude-flow-patch

Repository files navigation

@sparkleideas/claude-flow-patch

Contents


Community patches for @claude-flow/cli v3.1.0-alpha.41, ruvector, and ruv-swarm v1.0.20.

These patches fix 60 defects across 15 categories. They are applied at runtime via idempotent Python scripts that perform targeted string replacements on the npx-cached source files.

Quick Start

Patch before init. Several patches fix the init/generator scripts. If you run claude-flow init before patching, the generated .claude/helpers/ files will be stubs with no learning, no PageRank, and no-op feedback. Always patch first:

# 1. Patch first -- fixes the init generators
npx --yes @sparkleideas/claude-flow-patch --global

# 2. Then init (or re-init if already initialized)
npx @claude-flow/cli@latest init            # fresh project
npx @claude-flow/cli@latest init upgrade    # existing project

# 3. Verify
npx --yes @sparkleideas/claude-flow-patch check

If you already initialized before patching:

npx --yes @sparkleideas/claude-flow-patch repair --target /path/to/project

Target Options

npx --yes @sparkleideas/claude-flow-patch                                  # global npx cache (default)
npx --yes @sparkleideas/claude-flow-patch --global                         # explicit global
npx --yes @sparkleideas/claude-flow-patch --target ~/my-project            # project's node_modules
npx --yes @sparkleideas/claude-flow-patch --global --target ~/my-project   # both

npx @claude-flow/cli uses local node_modules if present, otherwise the global npx cache. Use --target to patch a project's local install.

CLI Commands

Command Purpose
claude-flow-patch [--global] [--target <dir>] Apply all patches (default: --global)
claude-flow-patch apply <ID> Apply a single patch by defect ID (e.g. SG-002)
claude-flow-patch check Verify patch sentinels and auto-detect drift
claude-flow-patch repair --target <dir> [--source auto|local|global] [--dry-run] Rehydrate .claude/helpers in projects initialized before patching

How It Works

  1. patch-all.sh locates the @claude-flow/cli dist files in the npm/npx cache
  2. Globs patch/*/fix.py (numeric prefixes on directories ensure correct execution order)
  3. Concatenates lib/common.py with each fix.py and runs as a single Python process
  4. Each patch is idempotent: skips if already applied, warns if source changed

The check-patches.sh sentinel runs on session start to detect npx cache wipes and auto-reapply. It reads sentinel files from each patch directory — no hardcoded patch list.

Sentinel Files

Each patch directory contains a sentinel file that declares how to verify the patch is applied:

grep "pattern to find" relative/path/to/file.js
absent "pattern that should NOT exist" relative/path.js
none
package: ruvector
Directive Meaning
grep "..." file Pass if pattern is found in file (standard check)
absent "..." file Pass if pattern is not found (removal check)
none No sentinel — skip verification
package: X Target package (default: @claude-flow/cli). Skipped if package not installed

check-patches.sh and lib/discover.mjs both read these files dynamically. Adding a new patch requires no edits to any script — just create the sentinel file in the new patch directory.

Target Packages

Package Version Location Env var
@claude-flow/cli 3.1.0-alpha.41 ~/.npm/_npx/*/node_modules/@claude-flow/cli/dist/src/ BASE
ruvector (bundled) ~/.npm/_npx/*/node_modules/ruvector/bin/cli.js RUVECTOR_CLI
ruv-swarm 1.0.20 ~/.npm/_npx/*/node_modules/ruv-swarm/ (found via glob)

BASE is set by patch-all.sh. All path variables in lib/common.py derive from it. RUVECTOR_CLI is set by patch-all.sh to the ruvector CLI entry point. RS-001 locates its own target via find.

Dependency Order

Execution order is controlled by 3-digit numeric prefixes on directory names (e.g. 010-CF-001-*, 170-IN-001-*). patch-all.sh globs patch/*/fix.py, which sorts lexicographically — numeric prefixes guarantee correct order.

Two dependency chains exist:

Chain Directories Reason
IN-001 -> SG-003 170-IN-001-* before 270-SG-003-* SG-003's patch targets code introduced by IN-001
NS-001 -> NS-002 -> NS-003 190-NS-001-* before 200-NS-002-* before 210-NS-003-* Sequential namespace fixes

All other patches are independent.

Key Design Decisions

  • Zero-maintenance discovery: patch-all.sh, check-patches.sh, and doc generation all discover patches dynamically — no hardcoded lists.
  • Idempotent: patch() checks if new string is already present before replacing.
  • Non-destructive: patches only modify the npx cache, never the npm registry package.
  • Platform-aware: DM-003 is macOS-only (auto-skipped on Linux).
  • Sentinel-guarded: check-patches.sh reads sentinel files from each patch directory to detect cache wipes and auto-reapply.

Repository Structure

claude-flow-patch/
  README.md              # This file
  CLAUDE.md              # Claude Code instructions (defect workflow, policies)
  AGENTS.md              # Codex agent configuration
  patch-all.sh           # Apply all patches (globs patch/*/fix.py dynamically)
  check-patches.sh       # Sentinel: reads patch/*/sentinel files dynamically
  repair-post-init.sh    # Post-init helper repair
  lib/
    common.py            # Shared patch()/patch_all() helpers + path variables
    discover.mjs         # Dynamic patch discovery — single source of truth
    categories.json      # Prefix-to-label mapping (e.g. HW → Headless Worker)
  scripts/
    preflight.mjs        # Pre-commit sync: doc tables, versions, config
  patch/
    {NNN}-{PREFIX}-{NNN}-{slug}/    # NNN = 3-digit execution order
      README.md          # Defect report: title, severity, root cause, fix
      fix.py             # Idempotent patch script
      fix.sh             # Shell-based patch script (EM-002 only)
      sentinel           # Verification directives for check-patches.sh
    (29 defect directories total)

Memory System

The patched CLI runs a dual-write memory backend (SQLite + AgentDB v3) with three learning subsystems:

Layer What It Does Key Patch
HybridBackend Dual-writes entries to SQLite (structured) + AgentDB RVF (vector search) WM-001
AutoMemoryBridge Syncs ~/.claude/memory/*.json into the backend at session start/end WM-003
Intelligence.cjs PageRank graph + trigram matching + confidence decay/boost IN-001
AgentDB self-learning Records search feedback to improve future vector search relevance WM-009
Witness chain SHAKE-256 tamper detection on the memory database at session start WM-010
ReasoningBank Stores and retrieves successful reasoning patterns across sessions WM-011

Database files live in .swarm/:

.swarm/
  hybrid-memory.db         # SQLite (structured queries, WAL mode)
  agentdb-memory.rvf       # AgentDB v3 (HNSW vectors, learning state, witness chain)

All memory config is in .claude-flow/config.json under memory.*. Key settings:

{
  "memory": {
    "backend": "hybrid",
    "agentdb": { "enableLearning": true, "vectorBackend": "rvf" },
    "learningBridge": { "enabled": true, "sonaMode": "balanced" },
    "memoryGraph": { "enabled": true, "pageRankDamping": 0.85 }
  }
}

Full documentation: docs/memory-system.md

Defect Index

61 defects across 15 categories.

CF -- Config & Doctor

ID Description Severity GitHub Issue
CF‑001 Doctor ignores YAML config files Low #1141
CF‑002 Config export shows hardcoded defaults Medium #1142
CF‑003 Doctor --install native dependency resolution Medium #1186
CF‑004 config get/export uses hand-rolled YAML parser instead of config.json Medium #1193
CF‑006 config.yaml -> config.json migration in start.js, status.js, init.js Medium #1197
CF‑009 Upgrade MINIMAL init preset to v3 runtime defaults High #1203

DM -- Daemon & Workers

ID Description Severity GitHub Issue
DM‑001 daemon.log always 0 bytes Medium #1116
DM‑002 maxCpuLoad=2.0 blocks all workers on multi-core Critical #1138
DM‑003 macOS freemem() always ~0% — workers blocked Critical #1077
DM‑004 Worker stubs — preload + consolidation Enhancement #1139
DM‑006 No log rotation — logs grow unbounded Medium #1114

EM -- Embeddings & HNSW

ID Description Severity GitHub Issue
EM‑001 Embedding system ignores project config (model + HNSW dims) High #1143
EM‑002 @xenova/transformers cache EACCES Medium #1144

GV -- Ghost Vectors

ID Description Severity GitHub Issue
GV‑001 HNSW ghost vectors persist after memory delete Medium #1122

HK -- Hooks

ID Description Severity GitHub Issue
HK‑001 post-edit hook records file_path as "unknown" Medium #1155
HK‑002 MCP hook handlers are stubs that don't persist data High #1058
HK‑003 hooks_metrics MCP handler returns hardcoded fake data High #1158
HK‑004 hooks_session-start ignores daemon.autoStart from settings.json High #1175
HK‑005 Multiple MCP servers start independent in-process daemons Critical #1171

HW -- Headless Worker

ID Description Severity GitHub Issue
HW‑001 Headless workers hang — stdin pipe never closed Critical #1111
HW‑002 Headless failures silently swallowed as success High #1112
HW‑003 Worker scheduling intervals too aggressive + settings ignored High #1113
HW‑004 runWithTimeout rejects but does not kill child process Medium #1117

IN -- Intelligence

ID Description Severity GitHub Issue
IN‑001 intelligence.cjs is a stub that doesn't actually learn Critical #1154

MM -- Memory Management

ID Description Severity GitHub Issue
MM‑001 Remove dead persistPath config option Low #1152

NS -- Memory Namespace

ID Description Severity GitHub Issue
NS‑001 Discovery ops default to wrong namespace Critical #1123
NS‑002 Store/delete/retrieve fall back to 'default' + accept 'all' Critical #581
NS‑003 Namespace typo 'pattern' vs 'patterns' Medium #1136

RS -- ruv-swarm

ID Description Severity GitHub Issue
RS‑001 ruv-swarm MCP fails on Node 24 — better-sqlite3 missing native bindings Critical ruv-FANN#185

RV -- RuVector Intelligence

ID Description Severity GitHub Issue
RV‑001 force-learn command calls intel.tick() which doesn't exist Medium #1156
RV‑002 activeTrajectories not loaded from saved file High #1157
RV‑003 trajectory-end does not update stats counters Medium ruv-FANN#186

SG -- Settings Generator

ID Description Severity GitHub Issue
SG‑001 Init generates invalid settings High #1150
SG‑003 Init missing helpers for --dual, --minimal, hooks, and upgrade paths Critical #1169
SG‑004 init wizard lacks parity with init High #1181
SG‑005 add 'start all' subcommand to start everything at once Enhancement #1177
SG‑006 Wizard captures permissionRequest hook but never assigns it + topology hardcoded Medium #1184
SG‑007 --skip-claude / --only-claude mutate shared init options via shallow copy Medium #1188
SG‑008 init should generate .claude-flow/config.json (not config.yaml) Enhancement #1195
SG‑009 Remove --v3-mode from swarm init, make v3 the default High #1202
SG‑010 Add CLI options to init for all config.json settings Enhancement #1205
SG‑011 Fix stale --topology hierarchical references Medium #1206

UI -- Display & Cosmetic

ID Description Severity GitHub Issue
UI‑001 intelligence stats crashes on .toFixed() Critical #1145
UI‑002 neural status shows "Not loaded" Low #1146

WM -- Wiring / Memory Integration

ID Description Severity GitHub Issue
WM‑001 Wire @claude-flow/memory HybridBackend into CLI Critical #829
WM‑002 Neural config gating (neural.enabled not consumed at runtime) Medium #1185
WM‑003 Activate AutoMemoryBridge in auto-memory-hook.mjs High #1102
WM‑004 Source hook silently falls back to JsonFileBackend High #1190
WM‑007 Wire dead config.json keys into runtime consumers High #1204
WM‑008 Upgrade AgentDB v2 to v3 (RVF backend, self-learning, witness chain) High #1207
WM‑009 Wire AgentDB learning loop (recordFeedback) High #1209
WM‑010 Wire witness chain verification at session start High #1208
WM‑011 Instantiate ReasoningBank controller High #1210
WM‑012 HybridBackend proxy methods for learning + witness chain High #1212

DOC -- Documentation

ID Description Severity GitHub Issue
DOC‑001 Update upstream README.md to match patched CLI behavior Enhancement #1201

Init-Script Patches (Local Project Action Required)

Five patches target the init/generator scripts (executor.js, settings-generator.js, helpers-generator.js). These fix the code that generates your .claude/ project files -- but applying patches does not update files already generated in your project. You must take one additional step.

Affected Defects

ID Generator patched Local file affected Problem if not refreshed
IN-001 init/executor.js .claude/helpers/intelligence.cjs 197-line stub: no PageRank, no graph, feedback() is a no-op, no learning
HK-001 init/helpers-generator.js .claude/helpers/hook-handler.cjs Reads env vars instead of stdin JSON; post-edit logs file: "unknown"
SG-001 init/settings-generator.js .claude/settings.json May contain invalid hook events, broad permissions, relative paths
SG-002 init/executor.js .claude/helpers/*.js / *.cjs Missing .js/.cjs compat copies; hook-handler.cjs require() calls fail silently
MM-001 init/executor.js .claude-flow/config.yaml Misleading persistPath setting that nothing reads

How to Fix

Option A: Run repair (recommended)

npx --yes @sparkleideas/claude-flow-patch --global
npx --yes @sparkleideas/claude-flow-patch repair --target .
npx --yes @sparkleideas/claude-flow-patch apply SG-002       # apply a single patch

This copies patched helper files into your project and creates any missing .js/.cjs compat copies.

Option B: Copy full helpers from the package manually

npx --yes @sparkleideas/claude-flow-patch --global
SRC=$(find ~/.npm/_npx -path '*/@claude-flow/cli/.claude/helpers' -type d 2>/dev/null | head -1)
for f in intelligence.cjs hook-handler.cjs session.js learning-service.mjs metrics-db.mjs statusline.cjs; do
  [ -f "$SRC/$f" ] && cp "$SRC/$f" .claude/helpers/ && echo "Copied: $f"
done

Option C: Re-run init upgrade (regenerates from patched scripts)

npx --yes @sparkleideas/claude-flow-patch --global
npx @claude-flow/cli@latest init upgrade --force

Caution: Option C may overwrite other customizations in .claude/.

Why This Happens

These patches fix the generator functions inside the npm package (e.g., generateIntelligenceStub() in executor.js). When the generator runs via claude-flow init, it produces the project files in .claude/helpers/. If your project was initialized before patches were applied, the stubs are already on disk. Patches only modify the npm package source -- they do not touch files already generated in your project.

Additionally, init upgrade only force-overwrites 3 "critical" helpers (auto-memory-hook.mjs, hook-handler.cjs, intelligence.cjs). The other 30+ helper files (shell scripts for daemon management, health monitoring, security scanning, swarm hooks, etc.) are only copied on fresh init, not on upgrade. If these are missing, use Option A above.

Auto-Reapply on Update

When npx fetches a new version of @claude-flow/cli, ruvector, or ruv-swarm, it replaces the cached files and wipes all patches. Use one of these approaches to detect this and auto-reapply.

Option A: Claude Code Hook (Recommended for AI Agents)

Add a session_start hook to your project's .claude/settings.json. This runs check-patches.sh every time Claude starts a session — it detects missing patches and reapplies automatically:

// .claude/settings.json
{
  "hooks": {
    "session_start": [
      {
        "command": "bash /path/to/claude-flow-patch/check-patches.sh --global",
        "timeout": 30000
      }
    ]
  }
}

Replace /path/to/claude-flow-patch with the absolute path to your clone. If your project also has a local install, use --global --target . instead.

check-patches.sh is fast and idempotent — if patches are intact it prints OK and exits. If any sentinel fails, it runs patch-all.sh, restarts the daemon, and reports what happened.

Option B: Cron / systemd Timer

Poll every 5 minutes with cron:

# crontab -e
*/5 * * * * bash /path/to/claude-flow-patch/check-patches.sh --global >> /tmp/patch-sentinel.log 2>&1

Or with a systemd user timer:

# ~/.config/systemd/user/patch-sentinel.timer
[Timer]
OnBootSec=60
OnUnitActiveSec=300

[Install]
WantedBy=timers.target
# ~/.config/systemd/user/patch-sentinel.service
[Service]
Type=oneshot
ExecStart=/bin/bash /path/to/claude-flow-patch/check-patches.sh --global
systemctl --user enable --now patch-sentinel.timer

Option C: npm postinstall Hook

If you install @claude-flow/cli as a project dependency, add a postinstall script that reapplies patches whenever npm install refreshes it:

// package.json
{
  "scripts": {
    "postinstall": "npx --yes @sparkleideas/claude-flow-patch --target ."
  }
}

How the Sentinel Works

check-patches.sh reads the sentinel file in each patch/*/ directory and checks whether the patched strings are present in the target files. If any check fails:

  1. Prints a warning identifying the likely cause (npx cache update)
  2. Runs patch-all.sh to reapply all patches
  3. Stops and restarts the claude-flow daemon so it picks up the patched code

The entire check takes under 2 seconds when patches are intact. Reapplication takes 5-10 seconds.

Compatibility

  • Tested against @claude-flow/cli@3.1.0-alpha.41 and ruv-swarm@1.0.20
  • Requires Python 3.6+ and Bash
  • Works on Linux and macOS (DM-003 is macOS-only, auto-skipped on Linux)

Links

License

MIT

About

Community patches for @claude-flow/cli v3.1.0-alpha.39 — 18 bug fixes across headless workers, daemon, config, embeddings, namespaces, and HNSW

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors