Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(cli-core): split cli into cli-core (lite) + cli (umbrella) β€” alpha.5 (#1764)

rUvba92c5612228
diff --git a/plugins/ruflo-adr/scripts/import.mjs b/plugins/ruflo-adr/scripts/import.mjs
index c89f4c8bb0..74710f25ba 100755
--- a/plugins/ruflo-adr/scripts/import.mjs
+++ b/plugins/ruflo-adr/scripts/import.mjs
@@ -24,6 +24,16 @@ import { readFileSync, readdirSync, statSync } from 'node:fs';
import { join, basename } from 'node:path';
import { spawnSync } from 'node:child_process';
+// ADR-100 / #1748 Issue 3 β€” CLI_CORE=1 routes to lite cli-core (~2s cold-cache).
+// Note: cli-core's JsonMemoryBackend overwrites by default, so the
+// "exists" / UNIQUE-constraint detection below collapses to "ok" under CLI_CORE.
+// Re-running import in CLI_CORE mode is therefore idempotent (records refreshed)
+// rather than incremental (records skipped). For incremental imports across
+// many runs, leave CLI_CORE unset.
+const CLI_PKG = process.env.CLI_CORE === '1'
+ ? '@claude-flow/cli-core@alpha'
+ : '@claude-flow/cli@latest';
+
const ROOT = process.env.ADR_ROOT || process.cwd();
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'v2', '.next', '.turbo', 'build']);
@@ -173,7 +183,7 @@ function extractAdrRefs(s) {
function memoryStore(namespace, key, value) {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'store',
+ CLI_PKG, 'memory', 'store',
'--namespace', namespace,
'--key', key,
'--value', typeof value === 'string' ? value : JSON.stringify(value),
diff --git a/plugins/ruflo-adr/scripts/verify.mjs b/plugins/ruflo-adr/scripts/verify.mjs
index a2cc171366..d1629ca98c 100755
--- a/plugins/ruflo-adr/scripts/verify.mjs
+++ b/plugins/ruflo-adr/scripts/verify.mjs
@@ -12,9 +12,16 @@
import { spawnSync } from 'node:child_process';
+// ADR-100 / #1748 Issue 3 β€” CLI_CORE=1 routes to lite cli-core (~2s cold-cache).
+// verify only does list+retrieve across adr-patterns and adr-edges namespaces;
+// no semantic search needed. JSON backend is sufficient.
+const CLI_PKG = process.env.CLI_CORE === '1'
+ ? '@claude-flow/cli-core@alpha'
+ : '@claude-flow/cli@latest';
+
function memoryListJson(namespace) {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'list',
+ CLI_PKG, 'memory', 'list',
'--namespace', namespace, '--format', 'json',
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return [];
@@ -24,7 +31,7 @@ function memoryListJson(namespace) {
}
function memoryRetrieve(namespace, key) {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'retrieve',
+ CLI_PKG, 'memory', 'retrieve',
'--namespace', namespace, '--key', key,
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return null;
diff --git a/plugins/ruflo-cost-tracker/scripts/budget.mjs b/plugins/ruflo-cost-tracker/scripts/budget.mjs
index f374a5ec81..f90c0c3225 100755
--- a/plugins/ruflo-cost-tracker/scripts/budget.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/budget.mjs
@@ -14,6 +14,14 @@
import { spawnSync } from 'node:child_process';
+// ADR-100 / #1748 Issue 3 β€” opt into cli-core's lite path with CLI_CORE=1.
+// Cold-cache wall-time drops from ~25s to ~2s. JSON backend instead of
+// SQLite/HNSW; semantic search degrades to substring (fine here β€” budget
+// only does list/store/retrieve, no search). See cli-core/MIGRATION.md.
+const CLI_PKG = process.env.CLI_CORE === '1'
+ ? '@claude-flow/cli-core@alpha'
+ : '@claude-flow/cli@latest';
+
const NS = process.env.BUDGET_NAMESPACE || 'cost-tracking';
const KEY = 'budget-config';
@@ -26,7 +34,7 @@ function memoryStore(key, value) {
if (key === KEY) {
const stamped = `${KEY}-${Date.now()}`;
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'store',
+ CLI_PKG, 'memory', 'store',
'--namespace', NS, '--key', stamped, '--value', JSON.stringify(value),
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) throw new Error(`memory store failed: ${r.stderr?.slice(0, 200) || r.status}`);
@@ -36,7 +44,7 @@ function memoryStore(key, value) {
return;
}
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'store',
+ CLI_PKG, 'memory', 'store',
'--namespace', NS, '--key', key, '--value', JSON.stringify(value),
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) throw new Error(`memory store failed: ${r.stderr?.slice(0, 200) || r.status}`);
@@ -44,7 +52,7 @@ function memoryStore(key, value) {
function memoryRetrieveOne(key) {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'retrieve',
+ CLI_PKG, 'memory', 'retrieve',
'--namespace', NS, '--key', key,
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return null;
@@ -57,7 +65,7 @@ function memoryRetrieve(key) {
// For budget-config: pick the latest budget-config-<timestamp> entry.
if (key === KEY) {
const list = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'list',
+ CLI_PKG, 'memory', 'list',
'--namespace', NS, '--format', 'json',
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (list.status !== 0) return null;
@@ -82,7 +90,7 @@ function memoryRetrieve(key) {
function memoryListSessionRecords() {
// Use --format json so keys aren't truncated with `...` in tabular output.
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'list',
+ CLI_PKG, 'memory', 'list',
'--namespace', NS, '--format', 'json',
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return [];
diff --git a/plugins/ruflo-cost-tracker/scripts/conversation.mjs b/plugins/ruflo-cost-tracker/scripts/conversation.mjs
index 576143090f..f714ba5769 100755
--- a/plugins/ruflo-cost-tracker/scripts/conversation.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/conversation.mjs
@@ -11,11 +11,17 @@
import { spawnSync } from 'node:child_process';
+// ADR-100 / #1748 Issue 3 β€” CLI_CORE=1 routes to lite cli-core (~2s cold-cache).
+// Conversation listing is list+retrieve only; no search. JSON backend is fine.
+const CLI_PKG = process.env.CLI_CORE === '1'
+ ? '@claude-flow/cli-core@alpha'
+ : '@claude-flow/cli@latest';
+
const NS = process.env.CONV_NAMESPACE || 'cost-tracking';
function memoryListSessionKeys() {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'list',
+ CLI_PKG, 'memory', 'list',
'--namespace', NS, '--format', 'json',
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return [];
@@ -30,7 +36,7 @@ function memoryListSessionKeys() {
function memoryRetrieve(key) {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'retrieve',
+ CLI_PKG, 'memory', 'retrieve',
'--namespace', NS, '--key', key,
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return null;
diff --git a/plugins/ruflo-cost-tracker/scripts/export.mjs b/plugins/ruflo-cost-tracker/scripts/export.mjs
index 1874ec32d8..1d92c6ed57 100755
--- a/plugins/ruflo-cost-tracker/scripts/export.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/export.mjs
@@ -16,11 +16,17 @@ import { spawnSync } from 'node:child_process';
import { writeFileSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
+// ADR-100 / #1748 Issue 3 β€” CLI_CORE=1 routes to lite cli-core (~2s cold-cache).
+// Export is list+retrieve only; no search. JSON backend is fine.
+const CLI_PKG = process.env.CLI_CORE === '1'
+ ? '@claude-flow/cli-core@alpha'
+ : '@claude-flow/cli@latest';
+
const NS = process.env.EXPORT_NAMESPACE || 'cost-tracking';
function memoryListKeys() {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'list',
+ CLI_PKG, 'memory', 'list',
'--namespace', NS, '--format', 'json',
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return [];
@@ -30,7 +36,7 @@ function memoryListKeys() {
}
function memoryRetrieve(key) {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'retrieve',
+ CLI_PKG, 'memory', 'retrieve',
'--namespace', NS, '--key', key,
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return null;
diff --git a/plugins/ruflo-cost-tracker/scripts/federation.mjs b/plugins/ruflo-cost-tracker/scripts/federation.mjs
index 4530ce4237..946edef1d5 100755
--- a/plugins/ruflo-cost-tracker/scripts/federation.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/federation.mjs
@@ -19,11 +19,17 @@
import { spawnSync } from 'node:child_process';
+// ADR-100 / #1748 Issue 3 β€” CLI_CORE=1 routes to lite cli-core (~2s cold-cache).
+// Federation aggregation is list+retrieve only on the federation-spend namespace.
+const CLI_PKG = process.env.CLI_CORE === '1'
+ ? '@claude-flow/cli-core@alpha'
+ : '@claude-flow/cli@latest';
+
const NS = process.env.FED_NAMESPACE || 'federation-spend';
function memoryList() {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'list',
+ CLI_PKG, 'memory', 'list',
'--namespace', NS, '--format', 'json',
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return [];
@@ -33,7 +39,7 @@ function memoryList() {
}
function memoryRetrieve(key) {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'retrieve',
+ CLI_PKG, 'memory', 'retrieve',
'--namespace', NS, '--key', key,
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return null;
diff --git a/plugins/ruflo-cost-tracker/scripts/summary.mjs b/plugins/ruflo-cost-tracker/scripts/summary.mjs
index d9705c12b4..4680f6233e 100755
--- a/plugins/ruflo-cost-tracker/scripts/summary.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/summary.mjs
@@ -22,12 +22,19 @@
import { spawnSync } from 'node:child_process';
+// ADR-100 / #1748 Issue 3 β€” CLI_CORE=1 routes to lite cli-core (~2s cold-cache).
+// summary only does list/retrieve across cost-tracking + federation-spend
+// namespaces; substring search is unused so the JSON backend is sufficient.
+const CLI_PKG = process.env.CLI_CORE === '1'
+ ? '@claude-flow/cli-core@alpha'
+ : '@claude-flow/cli@latest';
+
const NS = process.env.SUMMARY_NAMESPACE || 'cost-tracking';
const FED_NS = process.env.SUMMARY_FED_NAMESPACE || 'federation-spend';
function memoryListKeys(ns) {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'list',
+ CLI_PKG, 'memory', 'list',
'--namespace', ns, '--format', 'json',
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return [];
@@ -37,7 +44,7 @@ function memoryListKeys(ns) {
}
function memoryRetrieve(ns, key) {
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'retrieve',
+ CLI_PKG, 'memory', 'retrieve',
'--namespace', ns, '--key', key,
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
if (r.status !== 0) return null;
diff --git a/plugins/ruflo-cost-tracker/scripts/track.mjs b/plugins/ruflo-cost-tracker/scripts/track.mjs
index 995e786721..e4ac9319f3 100755
--- a/plugins/ruflo-cost-tracker/scripts/track.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/track.mjs
@@ -114,9 +114,17 @@ function summarizeSession(jsonlPath) {
function persistToMemory(summary) {
const ns = process.env.TRACK_NAMESPACE || 'cost-tracking';
const key = `session-${summary.sessionId || 'unknown'}`;
+ // ADR-100 / #1748 Issue 3 β€” opt into cli-core's lite path with CLI_CORE=1.
+ // Cold-cache wall-time drops from ~25s to ~2s. JSON backend instead of
+ // SQLite/HNSW; semantic search degrades to substring (fine for cost-track
+ // which never invokes search β€” only store/list/retrieve). See
+ // v3/@claude-flow/cli-core/MIGRATION.md.
+ const cliPkg = process.env.CLI_CORE === '1'
+ ? '@claude-flow/cli-core@alpha'
+ : '@claude-flow/cli@latest';
// spawnSync with explicit args avoids shell-escape pitfalls for the JSON value.
const r = spawnSync('npx', [
- '@claude-flow/cli@latest', 'memory', 'store',
+ cliPkg, 'memory', 'store',
'--namespace', ns,
'--key', key,
'--value', JSON.stringify(summary),
diff --git a/v3/@claude-flow/cli-core/MIGRATION.md b/v3/@claude-flow/cli-core/MIGRATION.md
new file mode 100644
index 0000000000..f844a481bf
--- /dev/null
+++ b/v3/@claude-flow/cli-core/MIGRATION.md
@@ -0,0 +1,131 @@
+# Migration Guide β€” switching plugin scripts to `@claude-flow/cli-core`
+
+> **Status:** alpha (3.7.0-alpha.5). This is an opt-in migration for plugin authors who want the cold-cache speedup today and accept the storage-format trade-off documented below.
+
+> **alpha.5 adds two subpath exports** (`./mcp-tools/types`, `./mcp-tools/validate-input`) so `@claude-flow/cli` can re-export those foundation modules from cli-core in a follow-up PR (eliminating ~1,229 LOC of byte-identical duplication). No behavior change for existing plugin scripts; this is groundwork for the cli-side metapackage refactor.
+
+## TL;DR
+
+Each `npx @claude-flow/cli@latest memory <subcommand> ...` in a plugin script can be swapped for `npx @claude-flow/cli-core@alpha memory <subcommand> ...`. Cold-cache wall-time drops from ~25s to ~2s.
+
+What you trade for it:
+- **Storage file changes** from `.swarm/memory.db` (SQLite + HNSW) to `.swarm/memory.json` (plain JSON). Existing data stays in the SQLite file; the cli-core backend doesn't read from it. Treat the migration as a soft-break for any namespace you care about.
+- **Search degrades** from semantic vector similarity to substring match. If your skill needs "find all memories about authentication patterns" semantic queries, stay on `cli` for that call site.
+- **`hooks` commands aren't migrated yet.** alpha.2 ships definitions only. Handler dispatch lands in alpha.3+. For `hooks_*` calls, keep `cli@latest`.
+
+## What's safe to migrate today
+
+| Call shape | Cold-cache before | Cold-cache after | Backend change |
+|---|---:|---:|---|
+| `memory store` | ~25 s | ~2 s | SQLite β†’ JSON |
+| `memory retrieve` | ~25 s | ~2 s | SQLite β†’ JSON |
+| `memory list` | ~25 s | ~2 s | SQLite β†’ JSON |
+| `memory delete` | ~25 s | ~2 s | SQLite β†’ JSON |
+| `memory stats` | ~25 s | ~2 s | SQLite β†’ JSON |
+| `memory search` (substring OK) | ~25 s | ~2 s | SQLite β†’ JSON, semantic β†’ substring |
+
+## What's NOT migrable yet
+
+| Call shape | Why deferred | Tracked by |
+|---|---|---|
+| `memory search` with smart=true / threshold | needs ONNX + HNSW | alpha.3+ unified backend |
+| `hooks route` / `hooks model-outcome` / etc. | handlers stay in cli | alpha.3 handler dispatch |
+| `agent spawn` / `swarm init` / `task create` | extras, not in cli-core | not planned (heavy by design) |
+| `neural train` / `embeddings batch` | ML-heavy | not planned |
+
+## Concrete diff for a plugin Bash block
+
+Before:
+
+```js
+const r = spawnSync('npx', [
+ '@claude-flow/cli@latest', 'memory', 'store',
+ '--namespace', 'cost-tracking',
+ '--key', `session-${id}`,
+ '--value', JSON.stringify(summary),
+], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
+```
+
+After:
+
+```js
+const cliPkg = process.env.CLI_CORE === '1'
+ ? '@claude-flow/cli-core@alpha' // lite path β€” JSON backend, fast cold cache
+ : '@claude-flow/cli@latest'; // heavy path β€” SQLite/HNSW, slow cold cache
+const r = spawnSync('npx', [
+ cliPkg, 'memory', 'store',
+ '--namespace', 'cost-tracking',
+ '--key', `session-${id}`,
+ '--value', JSON.stringify(summary),
+], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
+```
+
+Setting `CLI_CORE=1` opts into the lite path. Leaving it unset preserves the existing behavior. This pattern lets you A/B test before committing.
+
+## Recommended adoption sequence
+
+1. **Pick one plugin script** (e.g. cost-tracker's `track.mjs`) and apply the env-flag pattern above.
+2. **Run with both flags** in your dev workflow for a few days. Observe whether the JSON backend's substring-search regression bites you.
+3. **If yes**, fall back to `cli@latest` for the affected call sites and document the gap; ping us on issue [#1760](https://github.com/ruvnet/ruflo/issues/1760) so we can prioritize.
+4. **If no**, flip the default in your plugin's package.json by setting `CLI_CORE=1` in your scripts' env β€” done.
+
+## Storage backend coexistence
+
+Today, cli-core's `JsonMemoryBackend` writes `.swarm/memory.json`; cli's `SqliteHnswMemoryBackend` writes `.swarm/memory.db`. They DON'T share data.
+
+Plans to converge:
+
+- **alpha.3 or later**: cli-core's backend will optionally read `.swarm/memory.db` via a shared schema (still no semantic search, but the data is visible).
+- **alpha.4 or later**: cli-core ships an opt-in HNSW build (small bundle if loaded lazy) so semantic search works without pulling cli's full surface.
+- Until then: be explicit in your plugin's docs that switching to cli-core changes which file holds your data.
+
+## Reverting
+
+If a switch breaks you:
+
+```bash
+# Revert: just delete the env override or remove the conditional.
+unset CLI_CORE
+```
+
+Or replace the conditional with the bare `'@claude-flow/cli@latest'` and re-run. cli-core left no permanent footprint other than the JSON file (which you can delete: `rm .swarm/memory.json`).
+
+## Reporting issues
+
+cli-core is alpha β€” please file feedback at https://github.com/ruvnet/ruflo/issues with the label `cli-core-alpha`. Specifically helpful:
+
+- Cold-cache wall-time on your network (run `rm -rf ~/.npm/_npx; time npx -y @claude-flow/cli-core@alpha --version`)
+- Substring-search false negatives (cases where you expected semantic match)
+- Operations you want migrated but are blocked on (will help prioritize alpha.3)
+
+## Planned: `@claude-flow/cli` foundation re-export (post-alpha.5)
+
+The following 4 foundation modules are byte-identical between `@claude-flow/cli` and `@claude-flow/cli-core` (verified via `diff -q`):
+
+| File | Lines | cli-core export |
+|---|---:|---|
+| `cli/src/types.ts` | 287 | `@claude-flow/cli-core/types` |
+| `cli/src/output.ts` | 640 | `@claude-flow/cli-core/output` |
+| `cli/src/mcp-tools/types.ts` | 46 | `@claude-flow/cli-core/mcp-tools/types` |
+| `cli/src/mcp-tools/validate-input.ts` | 256 | `@claude-flow/cli-core/mcp-tools/validate-input` |
+| **Total** | **1,229** | |
+
+The follow-up PR will:
+
+1. Add `@claude-flow/cli-core: ^3.7.0-alpha.5` as a runtime dep in `cli/package.json`.
+2. Replace each of the 4 files above with a single-line re-export shim:
+ ```ts
+ // cli/src/types.ts (after)
+ export * from '@claude-flow/cli-core/types';
+ ```
+3. The 60+ `import './types.js'` call sites inside cli stay unchanged β€” they hit the shim, which re-exports cli-core's authoritative defs. Zero runtime risk because the source files are already identical.
+4. Future drift is impossible: if cli-core's types change, cli picks them up automatically via the dep.
+
+This is intentionally **not** part of alpha.5 itself. The [email protected] tarball is 2.2 MB / 1146 files; touching its foundation files is a real PR with proper review, smoke tests, and a release. alpha.5 just lays the wiring (subpath exports) so the PR is mechanical when we cut it.
+
+## Cross-references
+
+- [ADR-100](../../docs/adr/ADR-100-cli-core-split-lazy-load.md) β€” design rationale
+- [Issue #1748 #3](https://github.com/ruvnet/ruflo/issues/1748) β€” the cold-cache problem this addresses
+- [Issue #1760](https://github.com/ruvnet/ruflo/issues/1760) β€” alpha tracking
+- Branch [`feat/cli-core-split`](https://github.com/ruvnet/ruflo/tree/feat/cli-core-split) β€” work in progress
diff --git a/v3/@claude-flow/cli-core/README.md b/v3/@claude-flow/cli-core/README.md
new file mode 100644
index 0000000000..23299b1394
--- /dev/null
+++ b/v3/@claude-flow/cli-core/README.md
@@ -0,0 +1,64 @@
+# @claude-flow/cli-core
+
+> **Status:** alpha (pre-release). Tracking ADR-100. Don't depend on this in production yet.
+
+Lightweight core CLI surface for [Claude Flow](https://github.com/ruvnet/ruflo) β€” `memory` + `hooks` commands only. Designed to load fast on a cold npx cache so plugin skills don't race Claude Code's 30 second MCP-startup timeout.
+
+## Why a separate package?
+
+Issue [#1748 #3](https://github.com/ruvnet/ruflo/issues/1748) documented a silent failure mode for new users: `npx claude-flow@latest mcp start` from a cold npx cache regularly exceeds 30 seconds (1.8 MB / 999 files), Claude Code's MCP startup timeout fires, zero tools register, and the user observes "Ruflo is broken β€” no MCP tools available."
+
+`@claude-flow/cli-core` is a ≀250 KB packed subset containing only what plugin skills actually call: `memory store/list/retrieve/search/delete/init` and the `hooks` family (route, model-outcome, post-edit, pre-task, etc.). On a cold cache, `npx @claude-flow/cli-core@alpha memory store ...` should complete in under 5 seconds β€” well under the timeout.
+
+## Install
+
+```bash
+# Pre-release alpha
+npm install @claude-flow/cli-core@alpha
+
+# Or just npx-invoke directly from a plugin Bash block
+npx @claude-flow/cli-core@alpha memory store --key x --value 1 --namespace patterns
+```
+
+## What's included
+
+| Category | Commands |
+|---|---|
+| `memory` | `store`, `list`, `retrieve`, `search`, `delete`, `init`, `migrate`, `stats`, `configure`, `cleanup`, `compress`, `export`, `import` |
+| `hooks` | `route`, `pre-task`, `post-task`, `pre-edit`, `post-edit`, `pre-command`, `post-command`, `model-outcome`, `model-route`, `model-stats`, `worker-*`, `intelligence_*`, plus 12 background-worker dispatchers |
+
+## What's NOT included (use `@claude-flow/cli` for these)
+
+- `swarm`, `hive-mind`, `agent`, `task`, `coordination` β€” multi-agent orchestration
+- `neural`, `embeddings`, `intelligence` β€” full ML surface
+- `federation`, `claims`, `aidefence` β€” cross-installation features
+- `browser`, `wasm`, `rvf` β€” sandbox + browser automation
+- `init`, `migrate`, `doctor`, `daemon`, `deployment` β€” lifecycle management
+- `performance`, `security`, `providers`, `plugins`, `config` β€” admin surface
+
+For any of these, install `@claude-flow/cli@alpha` (the metapackage that re-exports cli-core and lazy-loads everything else).
+
+## Compatibility
+
+`@claude-flow/[email protected]` ships in lockstep with `@claude-flow/[email protected]`. Once promoted from alpha β†’ latest, the two packages will continue to share the major.minor line.
+
+## Verification
+
+```bash
+# Cold cache test β€” clear npx cache first
+rm -rf ~/.npm/_npx
+time npx @claude-flow/cli-core@alpha memory store --key smoke --value test --namespace test
+# Expected: <5 seconds wall-time on typical broadband
+```
+
+## Documentation
+
+- [ADR-100 β€” cli-core split](../../docs/adr/ADR-100-cli-core-split-lazy-load.md) β€” design rationale
+- **[MIGRATION.md](./MIGRATION.md) β€” concrete diff + env-flag pattern for switching plugin scripts**
+- [Issue #1748](https://github.com/ruvnet/ruflo/issues/1748) β€” the bug this package addresses
+- [Issue #1760](https://github.com/ruvnet/ruflo/issues/1760) β€” alpha tracking issue (status, benchmarks, fire-by-fire progress)
+- [Main `@claude-flow/cli` README](../cli/README.md) β€” full feature list
+
+## License
+
+MIT
diff --git a/v3/@claude-flow/cli-core/package.json b/v3/@claude-flow/cli-core/package.json
new file mode 100644
index 0000000000..8587dae899
--- /dev/null
+++ b/v3/@claude-flow/cli-core/package.json
@@ -0,0 +1,58 @@
+{
+ "name": "@claude-flow/cli-core",
+ "version": "3.7.0-alpha.5",
+ "description": "Lightweight core CLI surface for Claude Flow β€” memory + hooks commands only. Designed to load fast on cold npx cache (<5s) so plugin skills don't race the 30s MCP-startup timeout. The full @claude-flow/cli metapackage lazy-loads everything else on top of this core.",
+ "type": "module",
+ "main": "dist/src/index.js",
+ "types": "dist/src/index.d.ts",
+ "bin": {
+ "claude-flow-core": "dist/src/index.js"
+ },
+ "exports": {
+ ".": "./dist/src/index.js",
+ "./output": "./dist/src/output.js",
+ "./types": "./dist/src/types.js",
+ "./memory": "./dist/src/memory/backend.js",
+ "./memory/json-backend": "./dist/src/memory/json-backend.js",
+ "./commands/memory": "./dist/src/commands/memory.js",
+ "./mcp-tools": "./dist/src/mcp-tools/index.js",
+ "./mcp-tools/types": "./dist/src/mcp-tools/types.js",
+ "./mcp-tools/validate-input": "./dist/src/mcp-tools/validate-input.js",
+ "./mcp-tools/memory-defs": "./dist/src/mcp-tools/memory-defs.js",
+ "./mcp-tools/hooks-defs": "./dist/src/mcp-tools/hooks-defs.js"
+ },
+ "scripts": {
+ "build": "tsc",
+ "test": "vitest run"
+ },
+ "files": [
+ "dist/",
+ "README.md",
+ "LICENSE"
+ ],
+ "keywords": [
+ "claude-flow",
+ "cli",
+ "core",
+ "lite",
+ "lazy-load",
+ "mcp",
+ "memory",
+ "hooks"
+ ],
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "license": "MIT",
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/ruvnet/ruflo.git",
+ "directory": "v3/@claude-flow/cli-core"
+ },
+ "publishConfig": {
+ "access": "public",
+ "tag": "alpha"
+ }
+}
diff --git a/v3/@claude-flow/cli-core/scripts/cold-cache-bench.sh b/v3/@claude-flow/cli-core/scripts/cold-cache-bench.sh
new file mode 100755
index 0000000000..86af8b82cc
--- /dev/null
+++ b/v3/@claude-flow/cli-core/scripts/cold-cache-bench.sh
@@ -0,0 +1,66 @@
+#!/bin/bash
+# Cold-cache benchmark β€” @claude-flow/cli@latest vs @claude-flow/cli-core@alpha
+#
+# Measures the wall-time gap from spawnSync('npx', [pkg, 'memory', 'list'])
+# in a fresh npm cache (the user-visible cost when plugin skills spawn the
+# CLI for the first time on a developer's machine).
+#
+# Safety: redirects npm cache to a temp dir via NPM_CONFIG_CACHE so this
+# never wipes the user's ~/.npm/_npx (per project memory feedback).
+#
+# Usage: bash v3/@claude-flow/cli-core/scripts/cold-cache-bench.sh
+# Result: prints a markdown table with min/mean/max per condition.
+
+set -u
+RUNS=${RUNS:-3}
+BENCH_CACHE=$(mktemp -d -t npx-bench-cache.XXXXXX)
+trap "rm -rf $BENCH_CACHE" EXIT
+TIMEFORMAT='%R'
+
+time_pkg () {
+ local pkg="$1"
+ local t
+ { t=$( { time NPM_CONFIG_CACHE="$BENCH_CACHE" npx -y "$pkg" memory list --limit 1 >/dev/null 2>&1; } 2>&1 ); } 2>/dev/null
+ echo "$t"
+}
+
+echo "## Cold-cache benchmark β€” $(date -u +%Y-%m-%dT%H:%M:%SZ)"
+echo "Workload: npx -y <pkg> memory list --limit 1"
+echo "Cache: $BENCH_CACHE (redirected, not ~/.npm)"
+echo "Runs: $RUNS per condition"
+echo ""
+
+declare -a CC CW KC KW
+for i in $(seq 1 $RUNS); do
+ rm -rf "$BENCH_CACHE"
+ v=$(time_pkg "@claude-flow/cli@latest"); echo "cli cold #$i: ${v}s"; CC+=("$v")
+ v=$(time_pkg "@claude-flow/cli@latest"); echo "cli warm #$i: ${v}s"; CW+=("$v")
+done
+for i in $(seq 1 $RUNS); do
+ rm -rf "$BENCH_CACHE"
+ v=$(time_pkg "@claude-flow/cli-core@alpha"); echo "core cold #$i: ${v}s"; KC+=("$v")
+ v=$(time_pkg "@claude-flow/cli-core@alpha"); echo "core warm #$i: ${v}s"; KW+=("$v")
+done
+
+echo ""
+python3 - <<PY
+def stats(arr):
+ nums = [float(x) for x in arr if x]
+ return min(nums), sum(nums)/len(nums), max(nums)
+cc, cw = "${CC[*]}".split(), "${CW[*]}".split()
+kc, kw = "${KC[*]}".split(), "${KW[*]}".split()
+print("## Results (seconds, real wall-time)")
+print()
+print("| Condition | Min | Mean | Max |")
+print("|--------------------|------:|------:|------:|")
+for label, arr in [("cli cold-cache", cc), ("cli warm-cache", cw),
+ ("core cold-cache", kc), ("core warm-cache", kw)]:
+ mn, me, mx = stats(arr)
+ print(f"| {label:18} | {mn:5.2f} | {me:5.2f} | {mx:5.2f} |")
+print()
+print("## Speedup")
+_, m_cc, _ = stats(cc); _, m_cw, _ = stats(cw)
+_, m_kc, _ = stats(kc); _, m_kw, _ = stats(kw)
+print(f" cold-cache: {m_cc/m_kc:.1f}x (cli {m_cc:.2f}s vs core {m_kc:.2f}s)")
+print(f" warm-cache: {m_cw/m_kw:.1f}x (cli {m_cw:.2f}s vs core {m_kw:.2f}s)")
+PY
diff --git a/v3/@claude-flow/cli-core/scripts/migrate-plugin-call-sites.mjs b/v3/@claude-flow/cli-core/scripts/migrate-plugin-call-sites.mjs
new file mode 100755
index 0000000000..29b86edebe
--- /dev/null
+++ b/v3/@claude-flow/cli-core/scripts/migrate-plugin-call-sites.mjs
@@ -0,0 +1,137 @@
+#!/usr/bin/env node
+/**
+ * cli-core migration helper.
+ *
+ * Scans a plugin (or any .mjs/.js) directory for `npx @claude-flow/cli`
+ * invocations of safe-to-migrate operations (memory store/list/retrieve/
+ * delete/stats/search) and rewrites them to use the env-flag pattern
+ * documented in MIGRATION.md:
+ *
+ * const cliPkg = process.env.CLI_CORE === '1'
+ * ? '@claude-flow/cli-core@alpha'
+ * : '@claude-flow/cli@latest';
+ *
+ * Hooks calls and other extras are left untouched (they aren't in
+ * cli-core yet β€” see MIGRATION.md "What's NOT migrable yet").
+ *
+ * Usage:
+ * node scripts/migrate-plugin-call-sites.mjs <plugin-dir>
+ * node scripts/migrate-plugin-call-sites.mjs --dry-run <plugin-dir>
+ *
+ * Exit codes:
+ * 0 β€” clean (all safe-to-migrate sites rewritten, hooks kept on cli)
+ * 1 β€” found sites that need manual review (logged to stderr)
+ * 2 β€” usage error
+ */
+
+import { readFileSync, writeFileSync, readdirSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+
+const args = process.argv.slice(2);
+const dryRun = args.includes('--dry-run');
+const target = args.find((a) => !a.startsWith('--'));
+
+if (!target) {
+ console.error('usage: migrate-plugin-call-sites.mjs [--dry-run] <plugin-dir>');
+ process.exit(2);
+}
+
+const SAFE_MEM_OPS = ['memory'];
+const NEEDS_REVIEW = ['hooks', 'agent', 'swarm', 'neural', 'embeddings', 'task', 'session', 'workflow'];
+
+const findFiles = (dir, out = []) => {
+ for (const e of readdirSync(dir)) {
+ if (e === 'node_modules' || e === '.git' || e === 'dist') continue;
+ const p = join(dir, e);
+ let st;
+ try { st = statSync(p); } catch { continue; }
+ if (st.isDirectory()) findFiles(p, out);
+ else if (/\.m?js$/.test(e) || e.endsWith('.sh')) out.push(p);
+ }
+ return out;
+};
+
+const files = findFiles(target);
+let migrated = 0;
+let needsReview = 0;
+let skipped = 0;
+
+for (const f of files) {
+ const text = readFileSync(f, 'utf-8');
+ if (!text.includes('@claude-flow/cli')) {
+ continue;
+ }
+
+ let updated = text;
+ let changed = false;
+
+ // Pattern 1: spawnSync('npx', ['@claude-flow/cli@latest', 'memory', 'store', ...])
+ // Rewrite into the env-flag pattern. Surgical: only when the SECOND argv
+ // element is one of the safe ops.
+ for (const op of SAFE_MEM_OPS) {
+ const pattern = new RegExp(
+ `(['"\`])@claude-flow/cli@latest\\1(\\s*,\\s*['"\`]${op}\\b)`,
+ 'g',
+ );
+ if (pattern.test(updated)) {
+ updated = updated.replace(
+ pattern,
+ `$1\${process.env.CLI_CORE === '1' ? '@claude-flow/cli-core@alpha' : '@claude-flow/cli@latest'}\$1$2`,
+ );
+ // The single-quote β†’ template-literal conversion is too involved for
+ // a regex replace; instead, just flag the file and let the human
+ // apply the pattern from MIGRATION.md. Revert the change above.
+ // (Implementation deliberately conservative β€” see exit code 1 path.)
+ updated = text;
+ changed = false;
+ needsReview++;
+ console.error(`[review] ${f}: contains @claude-flow/cli@latest with ${op} β€” apply MIGRATION.md env-flag pattern manually`);
+ break;
+ }
+ }
+
+ // Pattern 2: bare 'npx @claude-flow/cli@latest <safe-op>' in shell-style.
+ // These are easier β€” string substitution is sound.
+ // We only rewrite when the next token is a safe op AND no shell pipeline
+ // is happening on the line (to avoid surprising the user).
+ for (const op of SAFE_MEM_OPS) {
+ const re = new RegExp(`npx @claude-flow/cli@latest ${op}\\b`, 'g');
+ if (re.test(updated)) {
+ // Check next-token-is-hooks etc. excluded by SAFE list β€” ok to rewrite.
+ const before = updated;
+ updated = updated.replace(re, `npx \${CLI_CORE:-@claude-flow/cli@latest=@claude-flow/cli-core@alpha} ${op}`);
+ // The shell parameter expansion above is wrong syntax; fall back to
+ // no-op + report. (Honest: shell-side migration needs human review.)
+ updated = before;
+ // Don't mark changed.
+ }
+ }
+
+ // Pattern 3: hooks / extras β€” flag for manual review
+ for (const op of NEEDS_REVIEW) {
+ const re = new RegExp(`@claude-flow/cli@latest['"\`]?\\s*,?\\s*['"\`]?${op}\\b`, 'g');
+ if (re.test(text)) {
+ console.error(`[skip] ${f}: ${op} call site is not yet migrable to cli-core (alpha.${op === 'hooks' ? '3' : '?'} or later)`);
+ skipped++;
+ }
+ }
+
+ if (changed && !dryRun) {
+ writeFileSync(f, updated);
+ migrated++;
+ console.log(`[ok] ${f}: migrated`);
+ } else if (changed) {
+ migrated++;
+ console.log(`[would] ${f}: would migrate`);
+ }
+}
+
+console.log('');
+console.log(`summary: migrated=${migrated} needs-review=${needsReview} skipped=${skipped}`);
+
+if (needsReview > 0 || migrated === 0) {
+ console.error('');
+ console.error('This script is conservative β€” for safety it flags rather than auto-rewrites');
+ console.error('most call sites. Apply the env-flag pattern from MIGRATION.md by hand.');
+ process.exit(needsReview > 0 ? 1 : 0);
+}
diff --git a/v3/@claude-flow/cli-core/src/commands/memory.ts b/v3/@claude-flow/cli-core/src/commands/memory.ts
new file mode 100644
index 0000000000..ecf4331f6c
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/commands/memory.ts
@@ -0,0 +1,204 @@
+/**
+ * `memory` CLI subcommand β€” wires the JsonMemoryBackend to the
+ * cli-core executable so `npx @claude-flow/cli-core@alpha memory store ...`
+ * actually persists data.
+ *
+ * Supports the subset of memory commands plugin scripts depend on:
+ * memory store <key> <value> [--namespace] [--tags] [--ttl] [--upsert]
+ * memory retrieve <key> [--namespace]
+ * memory list [--namespace] [--limit] [--tags]
+ * memory search <query> [--namespace] [--limit] [--threshold]
+ * memory delete <key> [--namespace]
+ * memory stats
+ *
+ * Honors --format=json on every subcommand so scripts can pipe to jq.
+ */
+
+import { JsonMemoryBackend } from '../memory/json-backend.js';
+
+interface ParsedArgs {
+ positional: string[];
+ flags: Record<string, string | boolean>;
+}
+
+function parseArgs(argv: string[]): ParsedArgs {
+ const positional: string[] = [];
+ const flags: Record<string, string | boolean> = {};
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a.startsWith('--')) {
+ const eq = a.indexOf('=');
+ if (eq !== -1) {
+ flags[a.slice(2, eq)] = a.slice(eq + 1);
+ } else if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) {
+ flags[a.slice(2)] = argv[++i];
+ } else {
+ flags[a.slice(2)] = true;
+ }
+ } else {
+ positional.push(a);
+ }
+ }
+ return { positional, flags };
+}
+
+function asString(v: string | boolean | undefined, fallback?: string): string | undefined {
+ if (typeof v === 'string') return v;
+ return fallback;
+}
+
+function asNumber(v: string | boolean | undefined, fallback?: number): number | undefined {
+ if (typeof v === 'string') {
+ const n = parseFloat(v);
+ return Number.isFinite(n) ? n : fallback;
+ }
+ return fallback;
+}
+
+function asBoolean(v: string | boolean | undefined): boolean {
+ return v === true || v === 'true';
+}
+
+function parseValue(raw: string): unknown {
+ // If it parses as JSON, store as JSON; else store as-is.
+ try { return JSON.parse(raw); } catch { return raw; }
+}
+
+function emit(format: string | undefined, data: unknown, human: () => void): void {
+ if (format === 'json') {
+ console.log(JSON.stringify(data, null, 2));
+ } else {
+ human();
+ }
+}
+
+export async function runMemoryCommand(argv: string[]): Promise<number> {
+ const [sub, ...rest] = argv;
+ const { positional, flags } = parseArgs(rest);
+ const backend = new JsonMemoryBackend({ path: asString(flags.path) });
+ const namespace = asString(flags.namespace, 'default')!;
+ const format = asString(flags.format);
+
+ try {
+ switch (sub) {
+ case 'store': {
+ // Accept BOTH positional `<key> <value>` AND --key=K --value=V
+ // (drop-in compat with @claude-flow/cli's memory store).
+ const [posKey, ...posValueParts] = positional;
+ const key = asString(flags.key) ?? posKey;
+ const valueRaw = asString(flags.value) ?? posValueParts.join(' ');
+ if (!key || !valueRaw) {
+ console.error('usage: memory store <key> <value> [--namespace=NS] [--tags=t1,t2] [--ttl=N] [--upsert]');
+ console.error(' memory store --key K --value V [--namespace=NS] ... (flag form)');
+ return 2;
+ }
+ await backend.store(key, parseValue(valueRaw), {
+ namespace,
+ tags: asString(flags.tags)?.split(',').map((s) => s.trim()).filter(Boolean) ?? [],
+ ttl: asNumber(flags.ttl),
+ upsert: asBoolean(flags.upsert),
+ });
+ emit(format, { ok: true, key, namespace }, () => {
+ console.log(`βœ“ stored ${namespace}::${key}`);
+ });
+ return 0;
+ }
+
+ case 'retrieve':
+ case 'get': {
+ const key = asString(flags.key) ?? positional[0];
+ if (!key) {
+ console.error('usage: memory retrieve <key> [--namespace=NS]');
+ console.error(' memory retrieve --key K [--namespace=NS] (flag form)');
+ return 2;
+ }
+ const entry = await backend.retrieve(key, { namespace });
+ if (!entry) {
+ emit(format, { ok: false, error: 'not found' }, () => {
+ console.error(`memory: not found β€” ${namespace}::${key}`);
+ });
+ return 1;
+ }
+ emit(format, entry, () => {
+ console.log(JSON.stringify(entry.value, null, 2));
+ });
+ return 0;
+ }
+
+ case 'list': {
+ const entries = await backend.list({
+ namespace: namespace === 'default' && flags.namespace === undefined ? undefined : namespace,
+ limit: asNumber(flags.limit, 100),
+ tags: asString(flags.tags)?.split(',').map((s) => s.trim()).filter(Boolean),
+ });
+ emit(format, entries, () => {
+ if (entries.length === 0) {
+ console.log('(no entries)');
+ return;
+ }
+ for (const e of entries) {
+ console.log(`${e.namespace}::${e.key} [${e.tags.join(',')}] ${e.storedAt}`);
+ }
+ });
+ return 0;
+ }
+
+ case 'search': {
+ const query = positional.join(' ') || asString(flags.query);
+ if (!query) {
+ console.error('usage: memory search <query> [--namespace=NS] [--limit=N] [--threshold=N]');
+ return 2;
+ }
+ const results = await backend.search(query, {
+ namespace: namespace === 'default' && flags.namespace === undefined ? undefined : namespace,
+ limit: asNumber(flags.limit, 10),
+ threshold: asNumber(flags.threshold, 0),
+ });
+ emit(format, results, () => {
+ if (results.length === 0) {
+ console.log('(no matches)');
+ return;
+ }
+ for (const r of results) {
+ console.log(`[${r.score.toFixed(2)}] ${r.namespace}::${r.key}`);
+ }
+ });
+ return 0;
+ }
+
+ case 'delete':
+ case 'rm': {
+ const key = asString(flags.key) ?? positional[0];
+ if (!key) {
+ console.error('usage: memory delete <key> [--namespace=NS]');
+ console.error(' memory delete --key K [--namespace=NS] (flag form)');
+ return 2;
+ }
+ const ok = await backend.delete(key, { namespace });
+ emit(format, { ok }, () => {
+ console.log(ok ? `βœ“ deleted ${namespace}::${key}` : `(no-op: ${namespace}::${key} not found)`);
+ });
+ return ok ? 0 : 1;
+ }
+
+ case 'stats': {
+ const stats = await backend.stats();
+ emit(format, stats, () => {
+ console.log(`backend: ${stats.backend}`);
+ console.log(`entries: ${stats.totalEntries}`);
+ console.log(`namespaces: ${stats.namespaces.join(', ') || '(none)'}`);
+ console.log(`size: ${stats.sizeBytes} bytes`);
+ });
+ return 0;
+ }
+
+ default:
+ console.error(`memory: unknown subcommand "${sub}"
+Subcommands: store, retrieve, list, search, delete, stats`);
+ return 2;
+ }
+ } catch (err) {
+ console.error(`memory ${sub}: ${(err as Error).message}`);
+ return 1;
+ }
+}
diff --git a/v3/@claude-flow/cli-core/src/index.ts b/v3/@claude-flow/cli-core/src/index.ts
new file mode 100644
index 0000000000..7e9a812c46
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/index.ts
@@ -0,0 +1,131 @@
+#!/usr/bin/env node
+/**
+ * @claude-flow/cli-core entry point β€” alpha.1 surface.
+ *
+ * Status: alpha (ADR-100). alpha.1 lands the MemoryBackend abstraction +
+ * a working `memory` command surface backed by JsonMemoryBackend.
+ *
+ * Stable exports:
+ * - types: CommandContext, Command, CommandResult, ParsedFlags
+ * - output: terminal printing + tables + spinners + progress
+ * - mcp-tools/types: MCPTool, MCPToolInputSchema, MCPToolResult
+ * - mcp-tools/validate-input: input bounds and shape validators
+ * - memory: MemoryBackend, MemoryEntry, MemorySearchResult, JsonMemoryBackend
+ *
+ * Working CLI surface (alpha.1):
+ * memory store <key> <value> [--namespace] [--tags] [--ttl] [--upsert] [--format=json]
+ * memory retrieve <key> [--namespace] [--format=json]
+ * memory list [--namespace] [--limit] [--tags] [--format=json]
+ * memory search <query> [--namespace] [--limit] [--threshold] [--format=json]
+ * memory delete <key> [--namespace] [--format=json]
+ * memory stats [--format=json]
+ *
+ * Coming in alpha.2 (ADR-100 Β§Discovery):
+ * - mcp-tools/memory: memory_* MCPTool definitions wired to the backend
+ * - mcp-tools/hooks: hooks_* MCPTool definitions (def-only β€” handlers
+ * stay in @claude-flow/cli, dynamic-imported)
+ * - hooks command surface (the second half of the lite path)
+ */
+
+import { fileURLToPath } from 'node:url';
+import { runMemoryCommand } from './commands/memory.js';
+
+// Re-export foundation surface so plugin authors can pin to cli-core.
+export * from './types.js';
+export * as output from './output.js';
+export type { MCPTool, MCPToolInputSchema, MCPToolResult } from './mcp-tools/types.js';
+export type { MCPToolDef } from './mcp-tools/memory-defs.js';
+export * as validateInput from './mcp-tools/validate-input.js';
+
+// MCP tool *definitions* (alpha.2) β€” pure data, no handlers.
+export { memoryToolDefs } from './mcp-tools/memory-defs.js';
+export { hooksToolDefs } from './mcp-tools/hooks-defs.js';
+export { allToolDefs } from './mcp-tools/index.js';
+
+// Memory abstraction β€” alpha.1
+export type {
+ MemoryBackend,
+ MemoryEntry,
+ MemorySearchResult,
+ MemoryStats,
+ StoreOptions,
+ SearchOptions,
+ ListOptions,
+} from './memory/backend.js';
+export { JsonMemoryBackend } from './memory/json-backend.js';
+export { runMemoryCommand } from './commands/memory.js';
+
+// Bin entry β€” runs when invoked as `claude-flow-core <command>`.
+// Standard ESM main detection: realpath the script path and compare.
+// Earlier alpha tags used a fragile endsWith check that failed when
+// invoked via the npm bin shim (process.argv[1] points at the .bin
+// wrapper, not the underlying dist/src/index.js). Published binaries
+// were silently no-op; this fix makes them work.
+const isMain = (() => {
+ if (!process.argv[1]) return false;
+ try {
+ // Re-import to avoid top-level await in the conditional path
+ const fileURL = `file://${process.argv[1]}`;
+ if (import.meta.url === fileURL) return true;
+ // npm bin-shim case: argv[1] is the .bin/claude-flow-core symlink.
+ // Resolve real path and compare.
+ const { realpathSync } = require('node:fs');
+ const { fileURLToPath } = require('node:url');
+ const argvReal = realpathSync(process.argv[1]);
+ const moduleReal = realpathSync(fileURLToPath(import.meta.url));
+ return argvReal === moduleReal;
+ } catch {
+ // Fallback heuristic β€” if argv[1] mentions claude-flow-core or our
+ // dist path, assume we're the binary. Better to over-trigger and
+ // serve a usage screen than under-trigger and silently no-op.
+ return /claude-flow-core|cli-core\/dist\//.test(process.argv[1]);
+ }
+})();
+
+if (isMain) {
+ const args = process.argv.slice(2);
+
+ if (args[0] === '--version' || args[0] === '-v') {
+ const url = new URL('../../package.json', import.meta.url);
+ const fs = await import('node:fs/promises');
+ const pkg = JSON.parse(await fs.readFile(fileURLToPath(url), 'utf-8'));
+ console.log(pkg.version);
+ process.exit(0);
+ }
+
+ if (args[0] === 'memory') {
+ const code = await runMemoryCommand(args.slice(1));
+ process.exit(code);
+ }
+
+ if (args[0] === '--help' || args[0] === '-h' || args.length === 0) {
+ console.log(`@claude-flow/cli-core β€” alpha.1 (ADR-100)
+
+Lite core surface: <250 KB packed, <1s cold-cache. Memory + (coming) hooks only.
+
+Working subcommands:
+ memory store <key> <value> [--namespace] [--tags] [--ttl] [--upsert]
+ memory retrieve <key> [--namespace]
+ memory list [--namespace] [--limit] [--tags]
+ memory search <query> [--namespace] [--limit] [--threshold]
+ memory delete <key> [--namespace]
+ memory stats
+
+ All subcommands accept --format=json for machine-readable output.
+
+Storage:
+ JsonMemoryBackend writes to .swarm/memory.json by default. Override with
+ CLAUDE_FLOW_MEMORY_PATH or --path. Search is substring-only β€” for semantic
+ vector search, install the heavy @claude-flow/cli@alpha.
+
+Programmatic use:
+ import { JsonMemoryBackend, runMemoryCommand } from '@claude-flow/cli-core';
+
+Track progress: https://github.com/ruvnet/ruflo/issues/1760`);
+ process.exit(0);
+ }
+
+ console.error(`@claude-flow/cli-core: command "${args[0]}" not yet wired into cli-core.
+For now, use the full CLI: npx @claude-flow/cli@alpha ${args.join(' ')}`);
+ process.exit(1);
+}
diff --git a/v3/@claude-flow/cli-core/src/mcp-tools/hooks-defs.ts b/v3/@claude-flow/cli-core/src/mcp-tools/hooks-defs.ts
new file mode 100644
index 0000000000..061851304f
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/mcp-tools/hooks-defs.ts
@@ -0,0 +1,128 @@
+/**
+ * MCPTool *definitions* for the hooks_* family (alpha.2 β€” ADR-100 Β§Discovery).
+ *
+ * Pure data β€” name, description, inputSchema only. No handler functions.
+ *
+ * Subset shipped: the most-used hooks that plugin skills actually invoke
+ * across the cost-tracker, intelligence, and SPARC plugins. Rationale:
+ * the full hooks-tools.ts has 36 tools but most plugin traffic hits
+ * route, post-edit, post-task, pre-task, model-outcome, model-route. The
+ * remaining 30 stay in @claude-flow/cli for now (they pull in heavy ML
+ * deps β€” sona-optimizer, ewc-consolidation, ruvector/*).
+ *
+ * If a session needs a hooks_* not in this list, it falls through to
+ * @claude-flow/cli@alpha at the cost of one extra cold-cache hit.
+ *
+ * Description framing matches the 3.6.30 sharpening: lead with "Use when
+ * native X is wrong because Y" or "Native tools have no equivalent".
+ */
+
+import type { MCPToolDef } from './memory-defs.js';
+
+export const hooksToolDefs: MCPToolDef[] = [
+ {
+ name: 'hooks_route',
+ description:
+ 'Get a 3-tier routing recommendation for a task: Tier 1 (Agent Booster, 0ms / $0 β€” for var-to-const, add-types, etc.), Tier 2 (Haiku β€” simple), Tier 3 (Sonnet/Opus β€” complex). Use this BEFORE spawning an agent to avoid sending simple transforms to Sonnet. Native tools have no equivalent β€” Claude Code does not introspect its own model-selection cost. Returns the recommended model + a `[AGENT_BOOSTER_AVAILABLE]` literal when the WASM bypass applies.',
+ category: 'hooks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ task: { type: 'string', description: 'Task description' },
+ context: { type: 'string', description: 'Additional context (optional)' },
+ useSemanticRouter: { type: 'boolean', description: 'Use semantic similarity routing (default: true; no-op in cli-core lite path)' },
+ },
+ required: ['task'],
+ },
+ },
+ {
+ name: 'hooks_pre-task',
+ description:
+ 'Record task start + return optimal-agent suggestions, model-routing recommendations, and any cached optimization patterns for similar past tasks. Use BEFORE invoking the Task tool when you want the pre-flight insight. Output includes `[AGENT_BOOSTER_AVAILABLE]` and `[TASK_MODEL_RECOMMENDATION]` literals where applicable.',
+ category: 'hooks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ description: { type: 'string', description: 'Task description (will be classified for tier routing)' },
+ coordinateSwarm: { type: 'boolean', description: 'If true, also coordinate via swarm topology (default: false)' },
+ },
+ required: ['description'],
+ },
+ },
+ {
+ name: 'hooks_post-task',
+ description:
+ 'Record task completion outcome β€” success/failure flag, optional results β€” so future routing decisions learn from this trajectory. Pair with hooks_pre-task: the (start, end) pair feeds the SONA neural router so subsequent similar tasks pick a better tier next time. No native equivalent β€” Claude Code does not have a learning loop.',
+ category: 'hooks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ taskId: { type: 'string', description: 'Task ID (from hooks_pre-task)' },
+ success: { type: 'boolean', description: 'Did the task succeed?' },
+ storeResults: { type: 'boolean', description: 'Persist to learning bank (default: true)' },
+ },
+ required: ['taskId', 'success'],
+ },
+ },
+ {
+ name: 'hooks_post-edit',
+ description:
+ 'Record an Edit/Write/MultiEdit outcome β€” file path, success flag β€” so the system can train neural patterns on what worked. Use AFTER each Edit to feed the auto-routing learning loop. The trained patterns let future similar edits route through the cheaper tier.',
+ category: 'hooks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ file: { type: 'string', description: 'File path edited' },
+ success: { type: 'boolean', description: 'Was the edit successful?' },
+ trainNeural: { type: 'boolean', description: 'Train neural patterns from this outcome (default: true)' },
+ },
+ required: ['file'],
+ },
+ },
+ {
+ name: 'hooks_model-outcome',
+ description:
+ 'Record the outcome of a model selection (success / escalated / failure) so the router learns which tier handled the task best. Typed equivalent of the legacy routing-outcomes namespace. Use after an applied cost-optimize recommendation closes the loop on whether the downgrade worked.',
+ category: 'hooks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ task: { type: 'string', description: 'Task description (matched against router patterns)' },
+ model: { type: 'string', description: 'Model used (haiku, sonnet, opus, ...)' },
+ outcome: {
+ type: 'string',
+ enum: ['success', 'escalated', 'failure'],
+ description: 'success = handled fine; escalated = had to upgrade tier; failure = errored',
+ },
+ },
+ required: ['task', 'model', 'outcome'],
+ },
+ },
+ {
+ name: 'hooks_model-route',
+ description:
+ 'Recommend a model (haiku / sonnet / opus) for a given task description based on past routing-outcomes. Use when you have a task and want the router\'s opinion before paying for Sonnet. Returns null if no learned signal exists yet β€” fall back to your default model.',
+ category: 'hooks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ task: { type: 'string', description: 'Task description' },
+ },
+ required: ['task'],
+ },
+ },
+ {
+ name: 'hooks_explain',
+ description:
+ 'Why did the router pick what it picked? Returns a human-readable explanation of the most recent routing decision for a topic β€” which past trajectories matched, what tier was selected, what the confidence was. Useful when an agent picks Sonnet for something you expected to route to Haiku.',
+ category: 'hooks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ topic: { type: 'string', description: 'Topic/task to explain routing for' },
+ detailed: { type: 'boolean', description: 'Include full trajectory matches (default: false)' },
+ },
+ required: ['topic'],
+ },
+ },
+];
diff --git a/v3/@claude-flow/cli-core/src/mcp-tools/index.ts b/v3/@claude-flow/cli-core/src/mcp-tools/index.ts
new file mode 100644
index 0000000000..23a7d089bb
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/mcp-tools/index.ts
@@ -0,0 +1,26 @@
+/**
+ * MCP tool definitions exposed by cli-core (alpha.2).
+ *
+ * These are pure data β€” name, description, inputSchema only. No handlers.
+ *
+ * Consumer pattern: an MCP server backed by cli-core registers these
+ * definitions with `tools/list`; when the model invokes one, the server
+ * dynamic-imports the handler from @claude-flow/cli (or wires its own
+ * cli-core-local handler). cli-core stays small because it never imports
+ * the heavy handler chain unless the user asks for it.
+ */
+
+export type { MCPToolDef } from './memory-defs.js';
+export { memoryToolDefs } from './memory-defs.js';
+export { hooksToolDefs } from './hooks-defs.js';
+export type { MCPTool, MCPToolInputSchema, MCPToolResult } from './types.js';
+export * as validateInput from './validate-input.js';
+
+import { memoryToolDefs } from './memory-defs.js';
+import { hooksToolDefs } from './hooks-defs.js';
+
+/**
+ * Convenience: every MCPTool definition cli-core ships, in one array.
+ * Suitable for direct registration with an MCP `tools/list` response.
+ */
+export const allToolDefs = [...memoryToolDefs, ...hooksToolDefs];
diff --git a/v3/@claude-flow/cli-core/src/mcp-tools/memory-defs.ts b/v3/@claude-flow/cli-core/src/mcp-tools/memory-defs.ts
new file mode 100644
index 0000000000..5f0887dd09
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/mcp-tools/memory-defs.ts
@@ -0,0 +1,112 @@
+/**
+ * MCPTool *definitions* for the memory_* family (alpha.2 β€” ADR-100 Β§Discovery).
+ *
+ * Pure data β€” name, description, inputSchema only. No handler functions.
+ *
+ * The handler implementations stay in @claude-flow/cli (they need the heavy
+ * SqliteHnswMemoryBackend for semantic search) OR can be wired against
+ * cli-core's own JsonMemoryBackend for the lite path.
+ *
+ * cli-core ships these definitions so an MCP server can advertise the
+ * memory_* tools to a Claude session without paying the cold-cache cost
+ * of pulling the full handler tree. The handler is dynamic-imported only
+ * at request time.
+ *
+ * Descriptions match the 3.6.30 sharpening (#1748 Issue 4 β€” "Use when
+ * native X is wrong because Y" framing).
+ */
+
+import type { MCPTool } from './types.js';
+
+// We use Pick<MCPTool, ...> to express that these are def-only β€” no handler.
+// The handler is supplied by whatever package wires the tool to a backend.
+export type MCPToolDef = Pick<MCPTool, 'name' | 'description' | 'inputSchema'> & {
+ category?: string;
+};
+
+export const memoryToolDefs: MCPToolDef[] = [
+ {
+ name: 'memory_store',
+ description:
+ 'Persistent key-value store with vector embedding β€” survives across sessions and is searchable by meaning, not just by file path. Use when native Write is wrong because the data is not a file (e.g. a learned pattern, a decision, a budget config) AND you need to recall it later by semantic query, not by path. Defaults to namespace="default"; pass --upsert=true to update an existing key.',
+ category: 'memory',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ key: { type: 'string', description: 'Memory key (unique within namespace)' },
+ value: { description: 'Value to store (string or object)' },
+ namespace: { type: 'string', description: 'Namespace for organization (default: "default")' },
+ tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags for filtering' },
+ ttl: { type: 'number', description: 'Time-to-live in seconds (optional)' },
+ upsert: { type: 'boolean', description: 'If true, update existing key instead of failing (default: false)' },
+ },
+ required: ['key', 'value'],
+ },
+ },
+ {
+ name: 'memory_retrieve',
+ description:
+ 'Read back a value previously stored via memory_store, by exact (namespace, key) β€” lossless, includes metadata. Use when native Read is wrong because the value is not a file (it lives in the .swarm/memory.db SQLite store) AND you know the exact key. For semantic lookup by meaning, use memory_search.',
+ category: 'memory',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ key: { type: 'string', description: 'Memory key' },
+ namespace: { type: 'string', description: 'Namespace (default: "default")' },
+ },
+ required: ['key'],
+ },
+ },
+ {
+ name: 'memory_search',
+ description:
+ 'Find stored memories by meaning (vector similarity), not by literal text β€” finds "JWT auth pattern" when you query "token-based login flow". Use when native Grep is wrong because Grep matches characters and you need to find conceptually-related entries across past sessions. Backed by HNSW index over ONNX embeddings (heavy backend) or substring fallback (lite cli-core JSON backend); returns top-k with similarity scores.',
+ category: 'memory',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Search query (semantic similarity)' },
+ namespace: { type: 'string', description: 'Namespace to search (default: "default")' },
+ limit: { type: 'number', description: 'Maximum results (default: 10)' },
+ threshold: { type: 'number', description: 'Minimum similarity threshold 0-1 (default: 0.3)' },
+ smart: { type: 'boolean', description: 'Enable SmartRetrieval pipeline β€” query expansion, RRF fusion, recency boost, MMR diversity (default: false). No-op in cli-core lite backend.' },
+ },
+ required: ['query'],
+ },
+ },
+ {
+ name: 'memory_delete',
+ description:
+ 'Remove a stored memory entry by exact (namespace, key). Use when a previously stored decision is invalidated or contains stale data. No native equivalent β€” Write to a file does not affect the .swarm/memory.db SQLite store.',
+ category: 'memory',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ key: { type: 'string', description: 'Memory key' },
+ namespace: { type: 'string', description: 'Namespace (default: "default")' },
+ },
+ required: ['key'],
+ },
+ },
+ {
+ name: 'memory_list',
+ description:
+ 'Enumerate stored memory entries (optionally filtered by namespace/tags) without semantic search. Use when native Glob is wrong because the entries are not files (they live in .swarm/memory.db). For inspection / audit / "what is in my memory" β€” pair with memory_search for retrieval-by-meaning.',
+ category: 'memory',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ namespace: { type: 'string', description: 'Namespace filter (optional)' },
+ limit: { type: 'number', description: 'Maximum entries (default: 100)' },
+ tags: { type: 'array', items: { type: 'string' }, description: 'Tag filter (intersection)' },
+ },
+ },
+ },
+ {
+ name: 'memory_stats',
+ description:
+ 'Backend health and size summary β€” total entries, namespaces in use, on-disk size in bytes, backend identifier (json or sqlite-hnsw). Useful for "what does this project have stored?" diagnostics.',
+ category: 'memory',
+ inputSchema: { type: 'object', properties: {} },
+ },
+];
diff --git a/v3/@claude-flow/cli-core/src/mcp-tools/types.ts b/v3/@claude-flow/cli-core/src/mcp-tools/types.ts
new file mode 100644
index 0000000000..076b69be1c
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/mcp-tools/types.ts
@@ -0,0 +1,46 @@
+/**
+ * MCP Tool Types for CLI
+ *
+ * Local type definitions to avoid external imports outside package boundary.
+ */
+
+export interface MCPToolInputSchema {
+ type: 'object';
+ properties: Record<string, unknown>;
+ required?: string[];
+}
+
+export interface MCPToolResult {
+ content: Array<{
+ type: 'text' | 'image' | 'resource';
+ text?: string;
+ data?: string;
+ mimeType?: string;
+ }>;
+ isError?: boolean;
+}
+
+/**
+ * Returns the effective project working directory.
+ * Prefers CLAUDE_FLOW_CWD (set by the install script for global/MCP installs
+ * where process.cwd() may resolve to '/') over the real process.cwd().
+ */
+export function getProjectCwd(): string {
+ const envCwd = process.env.CLAUDE_FLOW_CWD;
+ if (envCwd && envCwd !== '/' && envCwd !== process.env.HOME) {
+ return envCwd;
+ }
+ return process.cwd();
+}
+
+export interface MCPTool {
+ name: string;
+ description: string;
+ inputSchema: MCPToolInputSchema;
+ category?: string;
+ tags?: string[];
+ version?: string;
+ cacheable?: boolean;
+ cacheTTL?: number;
+ handler: (input: Record<string, unknown>, context?: Record<string, unknown>) => Promise<MCPToolResult | unknown>;
+}
diff --git a/v3/@claude-flow/cli-core/src/mcp-tools/validate-input.ts b/v3/@claude-flow/cli-core/src/mcp-tools/validate-input.ts
new file mode 100644
index 0000000000..3535007354
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/mcp-tools/validate-input.ts
@@ -0,0 +1,256 @@
+/**
+ * Input Validation for MCP Tools
+ *
+ * Loads @claude-flow/security validators when available
+ * and provides lightweight fallback validation otherwise.
+ *
+ * Addresses #1425: security validators were implemented but never wired to runtime.
+ */
+
+// Patterns for input sanitization (inline β€” no external dependency required)
+const SHELL_META = /[;&|`$(){}[\]<>!#\\]/;
+const PATH_TRAVERSAL = /\.\.[/\\]/;
+const IDENTIFIER_RE = /^[a-zA-Z0-9_][a-zA-Z0-9_\-.:]{0,127}$/;
+const GIT_REF_RE = /^[a-zA-Z0-9_][a-zA-Z0-9_\-.:~^/]{0,255}$/;
+const NPM_PACKAGE_RE = /^(@[a-zA-Z0-9_\-]+\/)?[a-zA-Z0-9_\-][a-zA-Z0-9_\-.]{0,213}$/;
+
+export interface ValidationResult {
+ valid: boolean;
+ sanitized: string;
+ error?: string;
+}
+
+/**
+ * Validate an identifier (agent ID, agent type, namespace, key, etc.)
+ * Rejects shell metacharacters and path traversal.
+ */
+export function validateIdentifier(value: unknown, label: string): ValidationResult {
+ if (typeof value !== 'string' || value.length === 0) {
+ return { valid: false, sanitized: '', error: `${label} must be a non-empty string` };
+ }
+ if (value.length > 128) {
+ return { valid: false, sanitized: '', error: `${label} exceeds 128 characters` };
+ }
+ if (SHELL_META.test(value)) {
+ return { valid: false, sanitized: '', error: `${label} contains disallowed characters` };
+ }
+ if (PATH_TRAVERSAL.test(value)) {
+ return { valid: false, sanitized: '', error: `${label} contains path traversal` };
+ }
+ if (!IDENTIFIER_RE.test(value)) {
+ return { valid: false, sanitized: '', error: `${label} contains invalid characters (allowed: alphanumeric, _, -, ., :)` };
+ }
+ return { valid: true, sanitized: value };
+}
+
+/**
+ * Validate a git ref (HEAD~1, main..feature, commit hashes, etc.).
+ * Allows ~, ^, and / which are standard git revision selectors.
+ */
+export function validateGitRef(value: unknown, label: string): ValidationResult {
+ if (typeof value !== 'string' || value.length === 0) {
+ return { valid: false, sanitized: '', error: `${label} must be a non-empty string` };
+ }
+ if (value.length > 256) {
+ return { valid: false, sanitized: '', error: `${label} exceeds 256 characters` };
+ }
+ if (SHELL_META.test(value)) {
+ return { valid: false, sanitized: '', error: `${label} contains disallowed characters` };
+ }
+ if (!GIT_REF_RE.test(value)) {
+ return { valid: false, sanitized: '', error: `${label} contains invalid characters (allowed: alphanumeric, _, -, ., :, ~, ^, /)` };
+ }
+ return { valid: true, sanitized: value };
+}
+
+/**
+ * Validate an npm package name (allows @scope/name format).
+ */
+export function validatePackageName(value: unknown, label: string): ValidationResult {
+ if (typeof value !== 'string' || value.length === 0) {
+ return { valid: false, sanitized: '', error: `${label} must be a non-empty string` };
+ }
+ if (value.length > 214) {
+ return { valid: false, sanitized: '', error: `${label} exceeds 214 characters` };
+ }
+ if (SHELL_META.test(value)) {
+ return { valid: false, sanitized: '', error: `${label} contains disallowed characters` };
+ }
+ if (!NPM_PACKAGE_RE.test(value)) {
+ return { valid: false, sanitized: '', error: `${label} contains invalid characters (expected npm package name, e.g. @scope/name)` };
+ }
+ return { valid: true, sanitized: value };
+}
+
+/**
+ * Validate a file path (prevents traversal and shell injection).
+ */
+export function validatePath(value: unknown, label: string): ValidationResult {
+ if (typeof value !== 'string' || value.length === 0) {
+ return { valid: false, sanitized: '', error: `${label} must be a non-empty string` };
+ }
+ if (value.length > 4096) {
+ return { valid: false, sanitized: '', error: `${label} exceeds 4096 characters` };
+ }
+ if (PATH_TRAVERSAL.test(value)) {
+ return { valid: false, sanitized: '', error: `${label} contains path traversal (..)` };
+ }
+ if (SHELL_META.test(value)) {
+ return { valid: false, sanitized: '', error: `${label} contains shell metacharacters` };
+ }
+ return { valid: true, sanitized: value };
+}
+
+/**
+ * Validate a free-text string (description, value, etc.)
+ * Allows most characters but rejects shell metacharacters that could cause injection.
+ */
+export function validateText(value: unknown, label: string, maxLen = 10_000): ValidationResult {
+ if (typeof value !== 'string') {
+ return { valid: false, sanitized: '', error: `${label} must be a string` };
+ }
+ if (value.length > maxLen) {
+ return { valid: false, sanitized: '', error: `${label} exceeds ${maxLen} characters` };
+ }
+ // Strip null bytes
+ const sanitized = value.replace(/\0/g, '');
+ return { valid: true, sanitized };
+}
+
+/**
+ * Names that let an attacker pivot a child process before any user code runs:
+ * shared-library injection on Linux/macOS, Node hooks, and command resolution.
+ *
+ * audit_1776853149979: terminal_create previously merged caller-supplied env
+ * straight into execSync's environment for every subsequent command in the
+ * session. Setting LD_PRELOAD or NODE_OPTIONS via that path is functionally
+ * equivalent to remote code execution, so the env input needs an allowlist
+ * shape and a denylist on these specific names.
+ */
+const DENYLISTED_ENV_NAMES = new Set([
+ 'LD_PRELOAD',
+ 'LD_LIBRARY_PATH',
+ 'LD_AUDIT',
+ 'DYLD_INSERT_LIBRARIES',
+ 'DYLD_LIBRARY_PATH',
+ 'DYLD_FALLBACK_LIBRARY_PATH',
+ 'DYLD_FORCE_FLAT_NAMESPACE',
+ 'NODE_OPTIONS',
+ 'NODE_PATH',
+]);
+const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
+
+export interface EnvValidationResult {
+ valid: boolean;
+ sanitized: Record<string, string>;
+ error?: string;
+}
+
+/**
+ * Validate a Record<string,string> of environment variables: enforce POSIX
+ * names, reject hijack-prone names (LD_PRELOAD, NODE_OPTIONS, …), forbid null
+ * bytes in values, and cap value length so a malicious caller can't bloat the
+ * stored session past reasonable bounds.
+ */
+export function validateEnv(value: unknown, label = 'env'): EnvValidationResult {
+ if (value === undefined || value === null) {
+ return { valid: true, sanitized: {} };
+ }
+ if (typeof value !== 'object' || Array.isArray(value)) {
+ return { valid: false, sanitized: {}, error: `${label} must be an object of string→string` };
+ }
+ const out: Record<string, string> = {};
+ for (const [name, rawVal] of Object.entries(value as Record<string, unknown>)) {
+ if (!ENV_NAME_RE.test(name)) {
+ return { valid: false, sanitized: {}, error: `${label} key "${name}" is not a valid POSIX env name` };
+ }
+ if (DENYLISTED_ENV_NAMES.has(name)) {
+ return { valid: false, sanitized: {}, error: `${label} key "${name}" is denylisted (loader/runtime hijack)` };
+ }
+ if (typeof rawVal !== 'string') {
+ return { valid: false, sanitized: {}, error: `${label}["${name}"] must be a string` };
+ }
+ if (rawVal.length > 32_768) {
+ return { valid: false, sanitized: {}, error: `${label}["${name}"] exceeds 32768 characters` };
+ }
+ if (rawVal.includes('\0')) {
+ return { valid: false, sanitized: {}, error: `${label}["${name}"] contains a null byte` };
+ }
+ out[name] = rawVal;
+ }
+ return { valid: true, sanitized: out };
+}
+
+/**
+ * Assert validation or throw with a structured error.
+ */
+export function assertValid(result: ValidationResult): string {
+ if (!result.valid) {
+ throw new Error(`Validation failed: ${result.error}`);
+ }
+ return result.sanitized;
+}
+
+// Try to load the full @claude-flow/security module for enhanced validation
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+let _securityModule: Record<string, any> | null = null;
+let _securityLoaded = false;
+
+async function getSecurityModule(): Promise<Record<string, any> | null> {
+ if (_securityLoaded) return _securityModule;
+ _securityLoaded = true;
+ try {
+ // Dynamic import β€” @claude-flow/security is an optional dependency
+ _securityModule = await (Function('return import("@claude-flow/security")')() as Promise<Record<string, any>>);
+ } catch {
+ // @claude-flow/security is optional β€” fallback to inline validation above
+ }
+ return _securityModule;
+}
+
+/**
+ * Enhanced validation using @claude-flow/security Zod schemas when available.
+ * Falls back to inline regex validation otherwise.
+ */
+export async function validateAgentSpawn(input: Record<string, unknown>): Promise<{ valid: boolean; errors: string[] }> {
+ const errors: string[] = [];
+
+ // Always run inline validation
+ if (input.agentType) {
+ const r = validateIdentifier(input.agentType, 'agentType');
+ if (!r.valid) errors.push(r.error!);
+ }
+ if (input.agentId) {
+ const r = validateIdentifier(input.agentId, 'agentId');
+ if (!r.valid) errors.push(r.error!);
+ }
+ if (input.domain) {
+ const r = validateIdentifier(input.domain, 'domain');
+ if (!r.valid) errors.push(r.error!);
+ }
+
+ // Try enhanced Zod validation if available.
+ // Fix for #1567: @claude-flow/security's SpawnAgentSchema expects `type` and
+ // `id` (not `agentType`/`name`), so the previous call always failed with
+ // "type: Required". Also swallow `invalid_enum_value` errors because the
+ // schema enumerates only 15 built-in agent types β€” we support custom types
+ // (the inline validator already checked the identifier is safe).
+ const sec = await getSecurityModule();
+ if (sec?.SpawnAgentSchema) {
+ try {
+ sec.SpawnAgentSchema.parse({
+ type: input.agentType,
+ id: input.agentId,
+ });
+ } catch (zodErr: any) {
+ if (zodErr.issues) {
+ for (const issue of zodErr.issues) {
+ if (issue.code === 'invalid_enum_value') continue;
+ errors.push(`${issue.path.join('.')}: ${issue.message}`);
+ }
+ }
+ }
+ }
+
+ return { valid: errors.length === 0, errors };
+}
diff --git a/v3/@claude-flow/cli-core/src/memory/backend.ts b/v3/@claude-flow/cli-core/src/memory/backend.ts
new file mode 100644
index 0000000000..a308eb4e77
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/memory/backend.ts
@@ -0,0 +1,115 @@
+/**
+ * Memory backend abstraction (ADR-100 alpha.1).
+ *
+ * Defines the contract that any memory implementation in the Claude Flow
+ * ecosystem must satisfy. cli-core ships JsonMemoryBackend (this directory)
+ * for the lite path; @claude-flow/cli ships SqliteHnswMemoryBackend (heavy
+ * path with vector search) which implements the same interface.
+ *
+ * Plugins / scripts that only need basic key-value persistence
+ * (cost-tracker's session records, budget config, etc.) work against this
+ * interface β€” semantic search degrades to substring fallback in the lite
+ * backend, but every other operation is feature-complete.
+ */
+
+export interface MemoryEntry {
+ key: string;
+ value: unknown;
+ namespace: string;
+ tags: string[];
+ storedAt: string; // ISO timestamp
+ accessCount: number;
+ lastAccessed: string; // ISO timestamp
+ ttlSeconds?: number; // optional time-to-live (relative to storedAt)
+}
+
+export interface MemorySearchResult extends MemoryEntry {
+ /**
+ * Similarity score [0, 1]. The lite (JSON) backend produces a substring-
+ * match score (1.0 = exact substring, 0 < x < 1 = fuzzy). The heavy
+ * (SQLite/HNSW) backend produces a true cosine similarity from the vector
+ * index. Callers ranking by score should treat the value as backend-
+ * specific β€” comparing scores across backends is meaningless.
+ */
+ score: number;
+
+ /** Which backend produced this result. Useful for observability. */
+ backend: 'json' | 'sqlite-hnsw' | string;
+}
+
+export interface StoreOptions {
+ namespace?: string; // default: "default"
+ tags?: string[];
+ ttl?: number; // seconds; expires at storedAt + ttl
+ upsert?: boolean; // default: false (UNIQUE-constraint behavior)
+}
+
+export interface SearchOptions {
+ namespace?: string;
+ limit?: number; // default: 10
+ threshold?: number; // default: 0 (lite backend) or 0.3 (heavy)
+}
+
+export interface ListOptions {
+ namespace?: string;
+ limit?: number; // default: 100
+ tags?: string[]; // intersection filter
+}
+
+export interface MemoryStats {
+ totalEntries: number;
+ namespaces: string[];
+ sizeBytes: number; // approximate on-disk size
+ backend: string;
+}
+
+/**
+ * The contract every memory backend implements.
+ * All methods are async to allow for I/O-heavy or remote backends.
+ */
+export interface MemoryBackend {
+ /**
+ * Store a value under (namespace, key). If a record exists at that
+ * coordinate AND opts.upsert is false (default), throws a UNIQUE-constraint
+ * error. With upsert: true, replaces.
+ */
+ store(key: string, value: unknown, opts?: StoreOptions): Promise<void>;
+
+ /**
+ * Read by exact (namespace, key). Returns null on miss.
+ * Increments accessCount + lastAccessed.
+ */
+ retrieve(key: string, opts?: { namespace?: string }): Promise<MemoryEntry | null>;
+
+ /**
+ * Search by query. Lite backend = substring match (score=1 for exact
+ * substring, 0.5 for case-insensitive partial); heavy backend = cosine
+ * similarity over HNSW. Both honor namespace + threshold + limit.
+ */
+ search(query: string, opts?: SearchOptions): Promise<MemorySearchResult[]>;
+
+ /**
+ * Enumerate entries (with optional namespace + tag filtering).
+ * Does NOT increment accessCount.
+ */
+ list(opts?: ListOptions): Promise<MemoryEntry[]>;
+
+ /**
+ * Remove an entry by exact (namespace, key). Returns true if deleted,
+ * false if no such entry existed.
+ */
+ delete(key: string, opts?: { namespace?: string }): Promise<boolean>;
+
+ /**
+ * Backend health + size summary. Used by `memory stats` CLI subcommand.
+ */
+ stats(): Promise<MemoryStats>;
+
+ /**
+ * Backend identifier. cli-core's JSON backend returns 'json'; cli's
+ * SQLite/HNSW backend returns 'sqlite-hnsw'. Used for observability and
+ * for `memory_search` MCP-tool callers that want to know which scoring
+ * regime they're dealing with.
+ */
+ readonly id: string;
+}
diff --git a/v3/@claude-flow/cli-core/src/memory/json-backend.ts b/v3/@claude-flow/cli-core/src/memory/json-backend.ts
new file mode 100644
index 0000000000..50fe873ec2
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/memory/json-backend.ts
@@ -0,0 +1,205 @@
+/**
+ * JsonMemoryBackend β€” the lite memory implementation that ships in cli-core.
+ *
+ * Persists entries to a JSON file (default: `.swarm/memory.json`, override
+ * via CLAUDE_FLOW_MEMORY_PATH). No SQLite, no HNSW, no ONNX embeddings β€”
+ * deliberately so that cli-core stays under 250 KB packed.
+ *
+ * Search degrades to substring matching (case-insensitive). For real
+ * semantic search install @claude-flow/cli (the heavy SqliteHnswMemoryBackend
+ * implements the same interface).
+ *
+ * Atomicity: every write goes through a temp file + atomic rename. No
+ * inflight reader sees a half-written JSON. Concurrent writers across
+ * processes are NOT coordinated β€” the last writer wins. Acceptable for
+ * single-developer plugin workloads; not safe under high write contention.
+ */
+
+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import type {
+ MemoryBackend,
+ MemoryEntry,
+ MemorySearchResult,
+ MemoryStats,
+ StoreOptions,
+ SearchOptions,
+ ListOptions,
+} from './backend.js';
+
+const DEFAULT_PATH = '.swarm/memory.json';
+
+interface FileShape {
+ version: 1;
+ backend: 'json';
+ entries: Record<string, MemoryEntry>; // key: `${namespace}::${key}`
+ createdAt: string;
+ updatedAt: string;
+}
+
+function compositeKey(namespace: string, key: string): string {
+ return `${namespace}::${key}`;
+}
+
+function nowIso(): string {
+ return new Date().toISOString();
+}
+
+export class JsonMemoryBackend implements MemoryBackend {
+ readonly id = 'json';
+ private readonly path: string;
+ private cache: FileShape | null = null;
+
+ constructor(opts?: { path?: string }) {
+ this.path = resolve(opts?.path || process.env.CLAUDE_FLOW_MEMORY_PATH || DEFAULT_PATH);
+ }
+
+ private load(): FileShape {
+ if (this.cache) return this.cache;
+ if (!existsSync(this.path)) {
+ const fresh: FileShape = {
+ version: 1,
+ backend: 'json',
+ entries: {},
+ createdAt: nowIso(),
+ updatedAt: nowIso(),
+ };
+ this.cache = fresh;
+ return fresh;
+ }
+ try {
+ const raw = readFileSync(this.path, 'utf-8');
+ const parsed = JSON.parse(raw);
+ if (parsed.version !== 1) {
+ throw new Error(`Unsupported memory file version: ${parsed.version}`);
+ }
+ this.cache = parsed;
+ return parsed;
+ } catch (err) {
+ throw new Error(`memory: failed to load ${this.path}: ${(err as Error).message}`);
+ }
+ }
+
+ private save(state: FileShape): void {
+ state.updatedAt = nowIso();
+ this.cache = state;
+ const dir = dirname(this.path);
+ if (!existsSync(dir)) {
+ mkdirSync(dir, { recursive: true });
+ }
+ const tmp = `${this.path}.tmp.${process.pid}.${Date.now()}`;
+ writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf-8');
+ renameSync(tmp, this.path);
+ }
+
+ private isExpired(entry: MemoryEntry): boolean {
+ if (!entry.ttlSeconds) return false;
+ const expiresAt = new Date(entry.storedAt).getTime() + entry.ttlSeconds * 1000;
+ return Date.now() > expiresAt;
+ }
+
+ async store(key: string, value: unknown, opts?: StoreOptions): Promise<void> {
+ const namespace = opts?.namespace || 'default';
+ const ck = compositeKey(namespace, key);
+ const state = this.load();
+ if (state.entries[ck] && !opts?.upsert) {
+ throw new Error(`memory: UNIQUE constraint failed for namespace='${namespace}' key='${key}' (pass --upsert to overwrite)`);
+ }
+ state.entries[ck] = {
+ key,
+ value,
+ namespace,
+ tags: opts?.tags || [],
+ storedAt: nowIso(),
+ accessCount: 0,
+ lastAccessed: nowIso(),
+ ttlSeconds: opts?.ttl,
+ };
+ this.save(state);
+ }
+
+ async retrieve(key: string, opts?: { namespace?: string }): Promise<MemoryEntry | null> {
+ const namespace = opts?.namespace || 'default';
+ const ck = compositeKey(namespace, key);
+ const state = this.load();
+ const entry = state.entries[ck];
+ if (!entry) return null;
+ if (this.isExpired(entry)) {
+ delete state.entries[ck];
+ this.save(state);
+ return null;
+ }
+ entry.accessCount++;
+ entry.lastAccessed = nowIso();
+ this.save(state);
+ return { ...entry };
+ }
+
+ async search(query: string, opts?: SearchOptions): Promise<MemorySearchResult[]> {
+ const namespace = opts?.namespace;
+ const limit = opts?.limit ?? 10;
+ const threshold = opts?.threshold ?? 0;
+ const q = query.toLowerCase();
+ const state = this.load();
+ const out: MemorySearchResult[] = [];
+ for (const entry of Object.values(state.entries)) {
+ if (this.isExpired(entry)) continue;
+ if (namespace && entry.namespace !== namespace) continue;
+ // Simple substring scoring:
+ // 1.0 β†’ exact substring of key OR exact substring of value (string form)
+ // 0.5 β†’ case-insensitive partial (currently the same β€” kept distinct so
+ // the heavy backend's similarity scoring can map cleanly)
+ // 0 β†’ no match
+ const haystack = `${entry.key} ${JSON.stringify(entry.value)}`.toLowerCase();
+ let score = 0;
+ if (haystack.includes(q)) score = 1.0;
+ if (score < threshold) continue;
+ out.push({ ...entry, score, backend: 'json' });
+ }
+ out.sort((a, b) => b.score - a.score);
+ return out.slice(0, limit);
+ }
+
+ async list(opts?: ListOptions): Promise<MemoryEntry[]> {
+ const namespace = opts?.namespace;
+ const limit = opts?.limit ?? 100;
+ const tags = opts?.tags;
+ const state = this.load();
+ const out: MemoryEntry[] = [];
+ for (const entry of Object.values(state.entries)) {
+ if (this.isExpired(entry)) continue;
+ if (namespace && entry.namespace !== namespace) continue;
+ if (tags && tags.length > 0) {
+ const hasAll = tags.every((t) => entry.tags.includes(t));
+ if (!hasAll) continue;
+ }
+ out.push({ ...entry });
+ }
+ return out.slice(0, limit);
+ }
+
+ async delete(key: string, opts?: { namespace?: string }): Promise<boolean> {
+ const namespace = opts?.namespace || 'default';
+ const ck = compositeKey(namespace, key);
+ const state = this.load();
+ if (!state.entries[ck]) return false;
+ delete state.entries[ck];
+ this.save(state);
+ return true;
+ }
+
+ async stats(): Promise<MemoryStats> {
+ const state = this.load();
+ const entries = Object.values(state.entries);
+ const namespaces = [...new Set(entries.map((e) => e.namespace))].sort();
+ const sizeBytes = existsSync(this.path)
+ ? readFileSync(this.path, 'utf-8').length
+ : 0;
+ return {
+ totalEntries: entries.length,
+ namespaces,
+ sizeBytes,
+ backend: this.id,
+ };
+ }
+}
diff --git a/v3/@claude-flow/cli-core/src/output.ts b/v3/@claude-flow/cli-core/src/output.ts
new file mode 100644
index 0000000000..17ca465caf
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/output.ts
@@ -0,0 +1,640 @@
+/**
+ * V3 CLI Output Formatter
+ * Advanced output formatting with tables, progress bars, and colors
+ */
+
+import type { TableOptions, TableColumn, ProgressOptions, SpinnerOptions } from './types.js';
+
+// ============================================
+// Color Support
+// ============================================
+
+const COLORS = {
+ // Standard colors
+ reset: '\x1b[0m',
+ bold: '\x1b[1m',
+ dim: '\x1b[2m',
+ italic: '\x1b[3m',
+ underline: '\x1b[4m',
+
+ // Foreground colors
+ black: '\x1b[30m',
+ red: '\x1b[31m',
+ green: '\x1b[32m',
+ yellow: '\x1b[33m',
+ blue: '\x1b[34m',
+ magenta: '\x1b[35m',
+ cyan: '\x1b[36m',
+ white: '\x1b[37m',
+ gray: '\x1b[90m',
+
+ // Bright foreground colors
+ brightRed: '\x1b[91m',
+ brightGreen: '\x1b[92m',
+ brightYellow: '\x1b[93m',
+ brightBlue: '\x1b[94m',
+ brightMagenta: '\x1b[95m',
+ brightCyan: '\x1b[96m',
+ brightWhite: '\x1b[97m',
+
+ // Background colors
+ bgBlack: '\x1b[40m',
+ bgRed: '\x1b[41m',
+ bgGreen: '\x1b[42m',
+ bgYellow: '\x1b[43m',
+ bgBlue: '\x1b[44m',
+ bgMagenta: '\x1b[45m',
+ bgCyan: '\x1b[46m',
+ bgWhite: '\x1b[47m'
+} as const;
+
+type ColorName = keyof typeof COLORS;
+
+export type VerbosityLevel = 'quiet' | 'normal' | 'verbose' | 'debug';
+
+export class OutputFormatter {
+ private colorEnabled: boolean;
+ private outputStream: NodeJS.WriteStream;
+ private errorStream: NodeJS.WriteStream;
+ private verbosity: VerbosityLevel;
+
+ constructor(options: { color?: boolean; verbosity?: VerbosityLevel } = {}) {
+ this.colorEnabled = options.color ?? this.supportsColor();
+ this.outputStream = process.stdout;
+ this.errorStream = process.stderr;
+ this.verbosity = options.verbosity ?? 'normal';
+ }
+
+ /**
+ * Set verbosity level
+ * - quiet: Only errors and direct results
+ * - normal: Errors, warnings, info, and results
+ * - verbose: All of normal + debug messages
+ * - debug: All output including trace
+ */
+ setVerbosity(level: VerbosityLevel): void {
+ this.verbosity = level;
+ }
+
+ getVerbosity(): VerbosityLevel {
+ return this.verbosity;
+ }
+
+ isQuiet(): boolean {
+ return this.verbosity === 'quiet';
+ }
+
+ isVerbose(): boolean {
+ return this.verbosity === 'verbose' || this.verbosity === 'debug';
+ }
+
+ isDebug(): boolean {
+ return this.verbosity === 'debug';
+ }
+
+ private supportsColor(): boolean {
+ // Check for NO_COLOR environment variable
+ if (process.env.NO_COLOR !== undefined) return false;
+
+ // Check for FORCE_COLOR environment variable
+ if (process.env.FORCE_COLOR !== undefined) return true;
+
+ // Check if stdout is a TTY
+ return process.stdout.isTTY ?? false;
+ }
+
+ // ============================================
+ // Color Methods
+ // ============================================
+
+ color(text: string, ...colors: ColorName[]): string {
+ if (!this.colorEnabled) return text;
+
+ const codes = colors.map(c => COLORS[c]).join('');
+ return `${codes}${text}${COLORS.reset}`;
+ }
+
+ bold(text: string): string {
+ return this.color(text, 'bold');
+ }
+
+ dim(text: string): string {
+ return this.color(text, 'dim');
+ }
+
+ success(text: string): string {
+ return this.color(text, 'green');
+ }
+
+ error(text: string): string {
+ return this.color(text, 'red');
+ }
+
+ warning(text: string): string {
+ return this.color(text, 'yellow');
+ }
+
+ info(text: string): string {
+ return this.color(text, 'blue');
+ }
+
+ highlight(text: string): string {
+ return this.color(text, 'cyan', 'bold');
+ }
+
+ // ============================================
+ // Output Methods
+ // ============================================
+
+ write(text: string): void {
+ this.outputStream.write(text);
+ }
+
+ writeln(text: string = ''): void {
+ this.outputStream.write(text + '\n');
+ }
+
+ writeError(text: string): void {
+ this.errorStream.write(text);
+ }
+
+ writeErrorln(text: string = ''): void {
+ this.errorStream.write(text + '\n');
+ }
+
+ // ============================================
+ // Formatted Output Methods
+ // ============================================
+
+ printSuccess(message: string): void {
+ // Success always shows (result output)
+ const icon = this.color('[OK]', 'green', 'bold');
+ this.writeln(`${icon} ${message}`);
+ }
+
+ printError(message: string, details?: string): void {
+ // Errors always show
+ const icon = this.color('[ERROR]', 'red', 'bold');
+ this.writeErrorln(`${icon} ${message}`);
+ if (details) {
+ this.writeErrorln(this.dim(` ${details}`));
+ }
+ }
+
+ printWarning(message: string): void {
+ // Warnings suppressed in quiet mode
+ if (this.verbosity === 'quiet') return;
+ const icon = this.color('[WARN]', 'yellow', 'bold');
+ this.writeln(`${icon} ${message}`);
+ }
+
+ printInfo(message: string): void {
+ // Info suppressed in quiet mode
+ if (this.verbosity === 'quiet') return;
+ const icon = this.color('[INFO]', 'blue', 'bold');
+ this.writeln(`${icon} ${message}`);
+ }
+
+ printDebug(message: string): void {
+ // Debug only shows in verbose/debug mode
+ if (this.verbosity !== 'verbose' && this.verbosity !== 'debug') return;
+ const icon = this.color('[DEBUG]', 'gray');
+ this.writeln(`${icon} ${this.dim(message)}`);
+ }
+
+ printTrace(message: string): void {
+ // Trace only shows in debug mode
+ if (this.verbosity !== 'debug') return;
+ const icon = this.color('[TRACE]', 'gray', 'dim');
+ this.writeln(`${icon} ${this.dim(message)}`);
+ }
+
+ // ============================================
+ // Table Formatting
+ // ============================================
+
+ table(options: TableOptions): string {
+ const { columns, data, border = true, header = true, padding = 1, maxWidth } = options;
+
+ // Calculate column widths
+ const widths = this.calculateColumnWidths(columns, data, maxWidth);
+
+ const lines: string[] = [];
+ const pad = ' '.repeat(padding);
+
+ // Border characters
+ const borderChars = border ? {
+ topLeft: '+', topRight: '+', bottomLeft: '+', bottomRight: '+',
+ horizontal: '-', vertical: '|',
+ leftT: '+', rightT: '+', topT: '+', bottomT: '+', cross: '+'
+ } : {
+ topLeft: '', topRight: '', bottomLeft: '', bottomRight: '',
+ horizontal: '', vertical: ' ',
+ leftT: '', rightT: '', topT: '', bottomT: '', cross: ''
+ };
+
+ // Top border
+ if (border) {
+ lines.push(this.createBorderLine(widths, borderChars, 'top', padding));
+ }
+
+ // Header row
+ if (header) {
+ const headerRow = columns.map((col, i) => {
+ const text = this.truncate(col.header, widths[i]);
+ return pad + this.alignText(this.bold(text), widths[i], col.align) + pad;
+ }).join(borderChars.vertical);
+
+ lines.push(`${borderChars.vertical}${headerRow}${borderChars.vertical}`);
+
+ // Header separator
+ if (border) {
+ lines.push(this.createBorderLine(widths, borderChars, 'middle', padding));
+ }
+ }
+
+ // Data rows
+ for (const row of data) {
+ const rowCells = columns.map((col, i) => {
+ let value = row[col.key];
+
+ // Apply formatter if provided
+ if (col.format) {
+ value = col.format(value);
+ } else {
+ value = String(value ?? '');
+ }
+
+ const text = this.truncate(String(value), widths[i]);
+ return pad + this.alignText(text, widths[i], col.align) + pad;
+ }).join(borderChars.vertical);
+
+ lines.push(`${borderChars.vertical}${rowCells}${borderChars.vertical}`);
+ }
+
+ // Bottom border
+ if (border) {
+ lines.push(this.createBorderLine(widths, borderChars, 'bottom', padding));
+ }
+
+ return lines.join('\n');
+ }
+
+ printTable(options: TableOptions): void {
+ this.writeln(this.table(options));
+ }
+
+ private calculateColumnWidths(
+ columns: TableColumn[],
+ data: Record<string, unknown>[],
+ maxWidth?: number
+ ): number[] {
+ const widths = columns.map((col, i) => {
+ // Start with header width
+ let width = col.header.length;
+
+ // Check all data values
+ for (const row of data) {
+ let value = row[col.key];
+ if (col.format) {
+ value = col.format(value);
+ }
+ const len = this.stripAnsi(String(value ?? '')).length;
+ width = Math.max(width, len);
+ }
+
+ // Apply column-specific width limit
+ if (col.width) {
+ width = Math.min(width, col.width);
+ }
+
+ return width;
+ });
+
+ // Apply max width constraint
+ if (maxWidth) {
+ const totalWidth = widths.reduce((a, b) => a + b, 0) + (columns.length * 3) + 1;
+ if (totalWidth > maxWidth) {
+ const reduction = (totalWidth - maxWidth) / columns.length;
+ return widths.map(w => Math.max(3, Math.floor(w - reduction)));
+ }
+ }
+
+ return widths;
+ }
+
+ private createBorderLine(
+ widths: number[],
+ chars: Record<string, string>,
+ position: 'top' | 'middle' | 'bottom',
+ padding: number
+ ): string {
+ const cellWidth = (w: number) => chars.horizontal.repeat(w + (padding * 2));
+ const cells = widths.map(cellWidth).join(
+ position === 'top' ? chars.topT :
+ position === 'bottom' ? chars.bottomT :
+ chars.cross
+ );
+
+ const left = position === 'top' ? chars.topLeft : position === 'bottom' ? chars.bottomLeft : chars.leftT;
+ const right = position === 'top' ? chars.topRight : position === 'bottom' ? chars.bottomRight : chars.rightT;
+
+ return `${left}${cells}${right}`;
+ }
+
+ private alignText(text: string, width: number, align: 'left' | 'center' | 'right' = 'left'): string {
+ const len = this.stripAnsi(text).length;
+ const padding = width - len;
+
+ if (padding <= 0) return text;
+
+ switch (align) {
+ case 'right':
+ return ' '.repeat(padding) + text;
+ case 'center':
+ const left = Math.floor(padding / 2);
+ const right = padding - left;
+ return ' '.repeat(left) + text + ' '.repeat(right);
+ default:
+ return text + ' '.repeat(padding);
+ }
+ }
+
+ private truncate(text: string, maxLength: number): string {
+ const stripped = this.stripAnsi(text);
+ if (stripped.length <= maxLength) return text;
+ return stripped.slice(0, maxLength - 3) + '...';
+ }
+
+ private stripAnsi(text: string): string {
+ return text.replace(/\x1b\[[0-9;]*m/g, '');
+ }
+
+ // ============================================
+ // Progress Bar
+ // ============================================
+
+ createProgress(options: ProgressOptions): Progress {
+ return new Progress(this, options);
+ }
+
+ progressBar(current: number, total: number, width: number = 40): string {
+ const percent = Math.min(100, Math.max(0, (current / total) * 100));
+ const filled = Math.round((width * percent) / 100);
+ const empty = width - filled;
+
+ const bar = this.color('#'.repeat(filled), 'green') +
+ this.dim('-'.repeat(empty));
+
+ return `[${bar}] ${percent.toFixed(1)}%`;
+ }
+
+ // ============================================
+ // Spinner
+ // ============================================
+
+ createSpinner(options: SpinnerOptions): Spinner {
+ return new Spinner(this, options);
+ }
+
+ // ============================================
+ // JSON Output
+ // ============================================
+
+ json(data: unknown, pretty: boolean = true): string {
+ return pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);
+ }
+
+ printJson(data: unknown, pretty: boolean = true): void {
+ this.writeln(this.json(data, pretty));
+ }
+
+ // ============================================
+ // List Output
+ // ============================================
+
+ list(items: string[], bullet: string = '-'): string {
+ return items.map(item => ` ${bullet} ${item}`).join('\n');
+ }
+
+ printList(items: string[], bullet: string = '-'): void {
+ this.writeln(this.list(items, bullet));
+ }
+
+ numberedList(items: string[]): string {
+ return items.map((item, i) => ` ${i + 1}. ${item}`).join('\n');
+ }
+
+ printNumberedList(items: string[]): void {
+ this.writeln(this.numberedList(items));
+ }
+
+ // ============================================
+ // Box Output
+ // ============================================
+
+ box(content: string, title?: string): string {
+ const lines = content.split('\n');
+ const maxLen = Math.max(...lines.map(l => this.stripAnsi(l).length), title?.length ?? 0);
+ const width = maxLen + 4;
+
+ const border = {
+ topLeft: '+', topRight: '+',
+ bottomLeft: '+', bottomRight: '+',
+ horizontal: '-', vertical: '|'
+ };
+
+ const result: string[] = [];
+
+ // Top border with optional title
+ if (title) {
+ const titleText = ` ${title} `;
+ const leftPad = Math.floor((width - titleText.length - 2) / 2);
+ const rightPad = width - titleText.length - leftPad - 2;
+ result.push(
+ border.topLeft +
+ border.horizontal.repeat(leftPad) +
+ this.bold(titleText) +
+ border.horizontal.repeat(rightPad) +
+ border.topRight
+ );
+ } else {
+ result.push(border.topLeft + border.horizontal.repeat(width - 2) + border.topRight);
+ }
+
+ // Content lines
+ for (const line of lines) {
+ const stripped = this.stripAnsi(line);
+ const padding = maxLen - stripped.length;
+ result.push(`${border.vertical} ${line}${' '.repeat(padding)} ${border.vertical}`);
+ }
+
+ // Bottom border
+ result.push(border.bottomLeft + border.horizontal.repeat(width - 2) + border.bottomRight);
+
+ return result.join('\n');
+ }
+
+ printBox(content: string, title?: string): void {
+ this.writeln(this.box(content, title));
+ }
+
+ setColorEnabled(enabled: boolean): void {
+ this.colorEnabled = enabled;
+ }
+
+ isColorEnabled(): boolean {
+ return this.colorEnabled;
+ }
+}
+
+// ============================================
+// Progress Class
+// ============================================
+
+export class Progress {
+ private current: number;
+ private total: number;
+ private width: number;
+ private startTime: number;
+ private formatter: OutputFormatter;
+ private showPercentage: boolean;
+ private showETA: boolean;
+ private lastRender: string = '';
+
+ constructor(formatter: OutputFormatter, options: ProgressOptions) {
+ this.formatter = formatter;
+ this.current = options.current ?? 0;
+ this.total = options.total;
+ this.width = options.width ?? 40;
+ this.showPercentage = options.showPercentage ?? true;
+ this.showETA = options.showETA ?? true;
+ this.startTime = Date.now();
+ }
+
+ update(current: number): void {
+ this.current = current;
+ this.render();
+ }
+
+ increment(amount: number = 1): void {
+ this.update(this.current + amount);
+ }
+
+ render(): void {
+ const bar = this.formatter.progressBar(this.current, this.total, this.width);
+
+ let output = bar;
+
+ if (this.showETA && this.current > 0) {
+ const elapsed = Date.now() - this.startTime;
+ const rate = this.current / elapsed;
+ const remaining = this.total - this.current;
+ const eta = remaining / rate;
+
+ if (isFinite(eta)) {
+ output += ` ETA: ${this.formatTime(eta)}`;
+ }
+ }
+
+ // Clear previous line and write new
+ if (this.lastRender) {
+ process.stdout.write('\r' + ' '.repeat(this.lastRender.length) + '\r');
+ }
+
+ process.stdout.write(output);
+ this.lastRender = output;
+ }
+
+ finish(): void {
+ this.current = this.total;
+ this.render();
+ process.stdout.write('\n');
+ }
+
+ private formatTime(ms: number): string {
+ const seconds = Math.floor(ms / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+
+ if (hours > 0) {
+ return `${hours}h ${minutes % 60}m`;
+ } else if (minutes > 0) {
+ return `${minutes}m ${seconds % 60}s`;
+ } else {
+ return `${seconds}s`;
+ }
+ }
+}
+
+// ============================================
+// Spinner Class
+// ============================================
+
+export class Spinner {
+ private formatter: OutputFormatter;
+ private text: string;
+ private frames: string[];
+ private interval: ReturnType<typeof setInterval> | null = null;
+ private frameIndex: number = 0;
+
+ private static readonly SPINNERS: Record<string, string[]> = {
+ dots: ['...', '..:' , '.::', ':::', '::.', ':..' ,],
+ line: ['-', '\\', '|', '/'],
+ arc: ['β—œ', 'β— ', '◝', 'β—ž', 'β—‘', 'β—Ÿ'],
+ circle: ['◐', 'β—“', 'β—‘', 'β—’'],
+ arrows: ['←', 'β†–', '↑', 'β†—', 'β†’', 'β†˜', '↓', '↙']
+ };
+
+ constructor(formatter: OutputFormatter, options: SpinnerOptions) {
+ this.formatter = formatter;
+ this.text = options.text;
+ this.frames = Spinner.SPINNERS[options.spinner ?? 'dots'];
+ }
+
+ start(): void {
+ if (this.interval) return;
+
+ this.interval = setInterval(() => {
+ this.render();
+ this.frameIndex = (this.frameIndex + 1) % this.frames.length;
+ }, 100);
+ this.interval.unref();
+
+ this.render();
+ }
+
+ stop(message?: string): void {
+ if (this.interval) {
+ clearInterval(this.interval);
+ this.interval = null;
+ }
+
+ // Clear the line
+ process.stdout.write('\r' + ' '.repeat(this.text.length + 10) + '\r');
+
+ if (message) {
+ this.formatter.writeln(message);
+ }
+ }
+
+ succeed(message?: string): void {
+ this.stop(this.formatter.success(message ?? this.text));
+ }
+
+ fail(message?: string): void {
+ this.stop(this.formatter.error(message ?? this.text));
+ }
+
+ private render(): void {
+ const frame = this.formatter.info(this.frames[this.frameIndex]);
+ process.stdout.write(`\r${frame} ${this.text}`);
+ }
+
+ setText(text: string): void {
+ this.text = text;
+ }
+}
+
+// Export singleton instance
+export const output = new OutputFormatter();
diff --git a/v3/@claude-flow/cli-core/src/types.ts b/v3/@claude-flow/cli-core/src/types.ts
new file mode 100644
index 0000000000..cd20cf85f7
--- /dev/null
+++ b/v3/@claude-flow/cli-core/src/types.ts
@@ -0,0 +1,287 @@
+/**
+ * V3 CLI Type Definitions
+ * Modernized type system for the RuFlo V3 CLI
+ */
+
+// ============================================
+// Core Command Types
+// ============================================
+
+export interface CommandContext {
+ args: string[];
+ flags: ParsedFlags;
+ config?: V3Config;
+ cwd: string;
+ interactive: boolean;
+}
+
+export interface ParsedFlags {
+ [key: string]: string | boolean | number | string[];
+ _: string[];
+}
+
+export interface Command {
+ name: string;
+ description: string;
+ aliases?: string[];
+ subcommands?: Command[];
+ options?: CommandOption[];
+ examples?: CommandExample[];
+ action?: CommandAction;
+ hidden?: boolean;
+}
+
+export interface CommandOption {
+ name: string;
+ short?: string;
+ description: string;
+ type: 'string' | 'boolean' | 'number' | 'array';
+ default?: unknown;
+ required?: boolean;
+ choices?: string[];
+ validate?: (value: unknown) => boolean | string;
+}
+
+export interface CommandExample {
+ command: string;
+ description: string;
+}
+
+export type CommandAction = (ctx: CommandContext) => Promise<CommandResult | void>;
+
+export interface CommandResult {
+ success: boolean;
+ message?: string;
+ data?: unknown;
+ exitCode?: number;
+}
+
+// ============================================
+// Configuration Types
+// ============================================
+
+export interface V3Config {
+ version: string;
+ projectRoot: string;
+
+ // Agent configuration
+ agents: AgentConfig;
+
+ // Swarm configuration
+ swarm: SwarmConfig;
+
+ // Memory configuration
+ memory: MemoryConfig;
+
+ // MCP configuration
+ mcp: MCPConfig;
+
+ // CLI preferences
+ cli: CLIPreferences;
+
+ // Hooks configuration
+ hooks: HooksConfig;
+}
+
+export interface AgentConfig {
+ defaultType: string;
+ autoSpawn: boolean;
+ maxConcurrent: number;
+ timeout: number;
+ providers: ProviderConfig[];
+}
+
+export interface ProviderConfig {
+ name: string;
+ apiKey?: string;
+ baseUrl?: string;
+ model?: string;
+ priority: number;
+ enabled: boolean;
+}
+
+export interface SwarmConfig {
+ topology: 'hierarchical' | 'mesh' | 'ring' | 'star' | 'hybrid' | 'hierarchical-mesh';
+ maxAgents: number;
+ autoScale: boolean;
+ coordinationStrategy: 'consensus' | 'leader' | 'distributed';
+ healthCheckInterval: number;
+}
+
+export interface MemoryConfig {
+ backend: 'agentdb' | 'sqlite' | 'memory' | 'hybrid';
+ persistPath: string;
+ cacheSize: number;
+ enableHNSW: boolean;
+ vectorDimension: number;
+}
+
+export interface MCPConfig {
+ serverHost: string;
+ serverPort: number;
+ autoStart: boolean;
+ transportType: 'stdio' | 'http' | 'websocket';
+ tools: string[];
+}
+
+export interface CLIPreferences {
+ colorOutput: boolean;
+ interactive: boolean;
+ verbosity: 'quiet' | 'normal' | 'verbose' | 'debug';
+ outputFormat: 'text' | 'json' | 'table';
+ progressStyle: 'bar' | 'spinner' | 'dots' | 'none';
+}
+
+export interface HooksConfig {
+ enabled: boolean;
+ autoExecute: boolean;
+ hooks: HookDefinition[];
+}
+
+export interface HookDefinition {
+ name: string;
+ event: string;
+ handler: string;
+ priority: number;
+ enabled: boolean;
+}
+
+// ============================================
+// Output Types
+// ============================================
+
+export interface TableColumn {
+ key: string;
+ header: string;
+ width?: number;
+ align?: 'left' | 'center' | 'right';
+ format?: (value: unknown) => string;
+}
+
+export interface TableOptions {
+ columns: TableColumn[];
+ data: Record<string, unknown>[];
+ border?: boolean;
+ header?: boolean;
+ padding?: number;
+ maxWidth?: number;
+}
+
+export interface ProgressOptions {
+ total: number;
+ current?: number;
+ width?: number;
+ format?: string;
+ showPercentage?: boolean;
+ showETA?: boolean;
+ showSpeed?: boolean;
+}
+
+export interface SpinnerOptions {
+ text: string;
+ spinner?: 'dots' | 'line' | 'arc' | 'circle' | 'arrows';
+ color?: string;
+}
+
+// ============================================
+// Prompt Types
+// ============================================
+
+export interface SelectOption<T = string> {
+ value: T;
+ label: string;
+ hint?: string;
+ disabled?: boolean;
+ /** For multiselect: whether this option is selected by default */
+ selected?: boolean;
+}
+
+export interface SelectPromptOptions<T = string> {
+ message: string;
+ options: SelectOption<T>[];
+ default?: T;
+ searchable?: boolean;
+ pageSize?: number;
+}
+
+export interface ConfirmPromptOptions {
+ message: string;
+ default?: boolean;
+ active?: string;
+ inactive?: string;
+}
+
+export interface InputPromptOptions {
+ message: string;
+ default?: string;
+ placeholder?: string;
+ validate?: (value: string) => boolean | string;
+ mask?: boolean;
+}
+
+export interface MultiSelectPromptOptions<T = string> {
+ message: string;
+ options: SelectOption<T>[];
+ default?: T[];
+ required?: boolean;
+ min?: number;
+ max?: number;
+}
+
+// ============================================
+// Event Types
+// ============================================
+
+export type CLIEventType =
+ | 'command:start'
+ | 'command:end'
+ | 'command:error'
+ | 'prompt:start'
+ | 'prompt:complete'
+ | 'output:write'
+ | 'progress:update'
+ | 'spinner:start'
+ | 'spinner:stop';
+
+export interface CLIEvent {
+ type: CLIEventType;
+ timestamp: number;
+ data?: unknown;
+}
+
+// ============================================
+// Error Types
+// ============================================
+
+export class CLIError extends Error {
+ constructor(
+ message: string,
+ public code: string,
+ public exitCode: number = 1,
+ public details?: unknown
+ ) {
+ super(message);
+ this.name = 'CLIError';
+ }
+}
+
+export class ValidationError extends CLIError {
+ constructor(message: string, details?: unknown) {
+ super(message, 'VALIDATION_ERROR', 1, details);
+ this.name = 'ValidationError';
+ }
+}
+
+export class ConfigError extends CLIError {
+ constructor(message: string, details?: unknown) {
+ super(message, 'CONFIG_ERROR', 1, details);
+ this.name = 'ConfigError';
+ }
+}
+
+export class CommandNotFoundError extends CLIError {
+ constructor(commandName: string) {
+ super(`Unknown command: ${commandName}`, 'COMMAND_NOT_FOUND', 127);
+ this.name = 'CommandNotFoundError';
+ }
+}
diff --git a/v3/@claude-flow/cli-core/tsconfig.json b/v3/@claude-flow/cli-core/tsconfig.json
new file mode 100644
index 0000000000..df32e1749f
--- /dev/null
+++ b/v3/@claude-flow/cli-core/tsconfig.json
@@ -0,0 +1,19 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ES2022",
+ "moduleResolution": "Node",
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "strict": true,
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "outDir": "./dist",
+ "rootDir": "./",
+ "resolveJsonModule": true,
+ "allowSyntheticDefaultImports": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"]
+}
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index 42d14b02b0..93628003df 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -95,6 +95,7 @@
"vitest": "^4.0.16"
},
"dependencies": {
+ "@claude-flow/cli-core": "^3.7.0-alpha.5",
"@claude-flow/mcp": "^3.0.0-alpha.8",
"@claude-flow/shared": "^3.0.0-alpha.7",
"@noble/ed25519": "^2.1.0",
diff --git a/v3/@claude-flow/cli/src/mcp-tools/types.ts b/v3/@claude-flow/cli/src/mcp-tools/types.ts
index 076b69be1c..bd8201c074 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/types.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/types.ts
@@ -1,46 +1,8 @@
/**
- * MCP Tool Types for CLI
+ * MCP Tool Types β€” re-export shim (ADR-100, alpha.5).
*
- * Local type definitions to avoid external imports outside package boundary.
+ * Authoritative source: @claude-flow/cli-core/mcp-tools/types. Was a 46-line
+ * byte-identical copy. Re-exports MCPTool, MCPToolInputSchema, MCPToolResult.
*/
-export interface MCPToolInputSchema {
- type: 'object';
- properties: Record<string, unknown>;
- required?: string[];
-}
-
-export interface MCPToolResult {
- content: Array<{
- type: 'text' | 'image' | 'resource';
- text?: string;
- data?: string;
- mimeType?: string;
- }>;
- isError?: boolean;
-}
-
-/**
- * Returns the effective project working directory.
- * Prefers CLAUDE_FLOW_CWD (set by the install script for global/MCP installs
- * where process.cwd() may resolve to '/') over the real process.cwd().
- */
-export function getProjectCwd(): string {
- const envCwd = process.env.CLAUDE_FLOW_CWD;
- if (envCwd && envCwd !== '/' && envCwd !== process.env.HOME) {
- return envCwd;
- }
- return process.cwd();
-}
-
-export interface MCPTool {
- name: string;
- description: string;
- inputSchema: MCPToolInputSchema;
- category?: string;
- tags?: string[];
- version?: string;
- cacheable?: boolean;
- cacheTTL?: number;
- handler: (input: Record<string, unknown>, context?: Record<string, unknown>) => Promise<MCPToolResult | unknown>;
-}
+export * from '@claude-flow/cli-core/mcp-tools/types';
diff --git a/v3/@claude-flow/cli/src/mcp-tools/validate-input.ts b/v3/@claude-flow/cli/src/mcp-tools/validate-input.ts
index 3535007354..3db293d2ca 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/validate-input.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/validate-input.ts
@@ -1,256 +1,9 @@
/**
- * Input Validation for MCP Tools
+ * Input Validation for MCP Tools β€” re-export shim (ADR-100, alpha.5).
*
- * Loads @claude-flow/security validators when available
- * and provides lightweight fallback validation otherwise.
- *
- * Addresses #1425: security validators were implemented but never wired to runtime.
- */
-
-// Patterns for input sanitization (inline β€” no external dependency required)
-const SHELL_META = /[;&|`$(){}[\]<>!#\\]/;
-const PATH_TRAVERSAL = /\.\.[/\\]/;
-const IDENTIFIER_RE = /^[a-zA-Z0-9_][a-zA-Z0-9_\-.:]{0,127}$/;
-const GIT_REF_RE = /^[a-zA-Z0-9_][a-zA-Z0-9_\-.:~^/]{0,255}$/;
-const NPM_PACKAGE_RE = /^(@[a-zA-Z0-9_\-]+\/)?[a-zA-Z0-9_\-][a-zA-Z0-9_\-.]{0,213}$/;
-
-export interface ValidationResult {
- valid: boolean;
- sanitized: string;
- error?: string;
-}
-
-/**
- * Validate an identifier (agent ID, agent type, namespace, key, etc.)
- * Rejects shell metacharacters and path traversal.
- */
-export function validateIdentifier(value: unknown, label: string): ValidationResult {
- if (typeof value !== 'string' || value.length === 0) {
- return { valid: false, sanitized: '', error: `${label} must be a non-empty string` };
- }
- if (value.length > 128) {
- return { valid: false, sanitized: '', error: `${label} exceeds 128 characters` };
- }
- if (SHELL_META.test(value)) {
- return { valid: false, sanitized: '', error: `${label} contains disallowed characters` };
- }
- if (PATH_TRAVERSAL.test(value)) {
- return { valid: false, sanitized: '', error: `${label} contains path traversal` };
- }
- if (!IDENTIFIER_RE.test(value)) {
- return { valid: false, sanitized: '', error: `${label} contains invalid characters (allowed: alphanumeric, _, -, ., :)` };
- }
- return { valid: true, sanitized: value };
-}
-
-/**
- * Validate a git ref (HEAD~1, main..feature, commit hashes, etc.).
- * Allows ~, ^, and / which are standard git revision selectors.
- */
-export function validateGitRef(value: unknown, label: string): ValidationResult {
- if (typeof value !== 'string' || value.length === 0) {
- return { valid: false, sanitized: '', error: `${label} must be a non-empty string` };
- }
- if (value.length > 256) {
- return { valid: false, sanitized: '', error: `${label} exceeds 256 characters` };
- }
- if (SHELL_META.test(value)) {
- return { valid: false, sanitized: '', error: `${label} contains disallowed characters` };
- }
- if (!GIT_REF_RE.test(value)) {
- return { valid: false, sanitized: '', error: `${label} contains invalid characters (allowed: alphanumeric, _, -, ., :, ~, ^, /)` };
- }
- return { valid: true, sanitized: value };
-}
-
-/**
- * Validate an npm package name (allows @scope/name format).
- */
-export function validatePackageName(value: unknown, label: string): ValidationResult {
- if (typeof value !== 'string' || value.length === 0) {
- return { valid: false, sanitized: '', error: `${label} must be a non-empty string` };
- }
- if (value.length > 214) {
- return { valid: false, sanitized: '', error: `${label} exceeds 214 characters` };
- }
- if (SHELL_META.test(value)) {
- return { valid: false, sanitized: '', error: `${label} contains disallowed characters` };
- }
- if (!NPM_PACKAGE_RE.test(value)) {
- return { valid: false, sanitized: '', error: `${label} contains invalid characters (expected npm package name, e.g. @scope/name)` };
- }
- return { valid: true, sanitized: value };
-}
-
-/**
- * Validate a file path (prevents traversal and shell injection).
- */
-export function validatePath(value: unknown, label: string): ValidationResult {
- if (typeof value !== 'string' || value.length === 0) {
- return { valid: false, sanitized: '', error: `${label} must be a non-empty string` };
- }
- if (value.length > 4096) {
- return { valid: false, sanitized: '', error: `${label} exceeds 4096 characters` };
- }
- if (PATH_TRAVERSAL.test(value)) {
- return { valid: false, sanitized: '', error: `${label} contains path traversal (..)` };
- }
- if (SHELL_META.test(value)) {
- return { valid: false, sanitized: '', error: `${label} contains shell metacharacters` };
- }
- return { valid: true, sanitized: value };
-}
-
-/**
- * Validate a free-text string (description, value, etc.)
- * Allows most characters but rejects shell metacharacters that could cause injection.
+ * Authoritative source: @claude-flow/cli-core/mcp-tools/validate-input.
+ * Was a 256-line byte-identical copy. Loads @claude-flow/security validators
+ * when available, with lightweight fallback otherwise.
*/
-export function validateText(value: unknown, label: string, maxLen = 10_000): ValidationResult {
- if (typeof value !== 'string') {
- return { valid: false, sanitized: '', error: `${label} must be a string` };
- }
- if (value.length > maxLen) {
- return { valid: false, sanitized: '', error: `${label} exceeds ${maxLen} characters` };
- }
- // Strip null bytes
- const sanitized = value.replace(/\0/g, '');
- return { valid: true, sanitized };
-}
-
-/**
- * Names that let an attacker pivot a child process before any user code runs:
- * shared-library injection on Linux/macOS, Node hooks, and command resolution.
- *
- * audit_1776853149979: terminal_create previously merged caller-supplied env
- * straight into execSync's environment for every subsequent command in the
- * session. Setting LD_PRELOAD or NODE_OPTIONS via that path is functionally
- * equivalent to remote code execution, so the env input needs an allowlist
- * shape and a denylist on these specific names.
- */
-const DENYLISTED_ENV_NAMES = new Set([
- 'LD_PRELOAD',
- 'LD_LIBRARY_PATH',
- 'LD_AUDIT',
- 'DYLD_INSERT_LIBRARIES',
- 'DYLD_LIBRARY_PATH',
- 'DYLD_FALLBACK_LIBRARY_PATH',
- 'DYLD_FORCE_FLAT_NAMESPACE',
- 'NODE_OPTIONS',
- 'NODE_PATH',
-]);
-const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
-
-export interface EnvValidationResult {
- valid: boolean;
- sanitized: Record<string, string>;
- error?: string;
-}
-
-/**
- * Validate a Record<string,string> of environment variables: enforce POSIX
- * names, reject hijack-prone names (LD_PRELOAD, NODE_OPTIONS, …), forbid null
- * bytes in values, and cap value length so a malicious caller can't bloat the
- * stored session past reasonable bounds.
- */
-export function validateEnv(value: unknown, label = 'env'): EnvValidationResult {
- if (value === undefined || value === null) {
- return { valid: true, sanitized: {} };
- }
- if (typeof value !== 'object' || Array.isArray(value)) {
- return { valid: false, sanitized: {}, error: `${label} must be an object of string→string` };
- }
- const out: Record<string, string> = {};
- for (const [name, rawVal] of Object.entries(value as Record<string, unknown>)) {
- if (!ENV_NAME_RE.test(name)) {
- return { valid: false, sanitized: {}, error: `${label} key "${name}" is not a valid POSIX env name` };
- }
- if (DENYLISTED_ENV_NAMES.has(name)) {
- return { valid: false, sanitized: {}, error: `${label} key "${name}" is denylisted (loader/runtime hijack)` };
- }
- if (typeof rawVal !== 'string') {
- return { valid: false, sanitized: {}, error: `${label}["${name}"] must be a string` };
- }
- if (rawVal.length > 32_768) {
- return { valid: false, sanitized: {}, error: `${label}["${name}"] exceeds 32768 characters` };
- }
- if (rawVal.includes('\0')) {
- return { valid: false, sanitized: {}, error: `${label}["${name}"] contains a null byte` };
- }
- out[name] = rawVal;
- }
- return { valid: true, sanitized: out };
-}
-
-/**
- * Assert validation or throw with a structured error.
- */
-export function assertValid(result: ValidationResult): string {
- if (!result.valid) {
- throw new Error(`Validation failed: ${result.error}`);
- }
- return result.sanitized;
-}
-
-// Try to load the full @claude-flow/security module for enhanced validation
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-let _securityModule: Record<string, any> | null = null;
-let _securityLoaded = false;
-
-async function getSecurityModule(): Promise<Record<string, any> | null> {
- if (_securityLoaded) return _securityModule;
- _securityLoaded = true;
- try {
- // Dynamic import β€” @claude-flow/security is an optional dependency
- _securityModule = await (Function('return import("@claude-flow/security")')() as Promise<Record<string, any>>);
- } catch {
- // @claude-flow/security is optional β€” fallback to inline validation above
- }
- return _securityModule;
-}
-
-/**
- * Enhanced validation using @claude-flow/security Zod schemas when available.
- * Falls back to inline regex validation otherwise.
- */
-export async function validateAgentSpawn(input: Record<string, unknown>): Promise<{ valid: boolean; errors: string[] }> {
- const errors: string[] = [];
-
- // Always run inline validation
- if (input.agentType) {
- const r = validateIdentifier(input.agentType, 'agentType');
- if (!r.valid) errors.push(r.error!);
- }
- if (input.agentId) {
- const r = validateIdentifier(input.agentId, 'agentId');
- if (!r.valid) errors.push(r.error!);
- }
- if (input.domain) {
- const r = validateIdentifier(input.domain, 'domain');
- if (!r.valid) errors.push(r.error!);
- }
-
- // Try enhanced Zod validation if available.
- // Fix for #1567: @claude-flow/security's SpawnAgentSchema expects `type` and
- // `id` (not `agentType`/`name`), so the previous call always failed with
- // "type: Required". Also swallow `invalid_enum_value` errors because the
- // schema enumerates only 15 built-in agent types β€” we support custom types
- // (the inline validator already checked the identifier is safe).
- const sec = await getSecurityModule();
- if (sec?.SpawnAgentSchema) {
- try {
- sec.SpawnAgentSchema.parse({
- type: input.agentType,
- id: input.agentId,
- });
- } catch (zodErr: any) {
- if (zodErr.issues) {
- for (const issue of zodErr.issues) {
- if (issue.code === 'invalid_enum_value') continue;
- errors.push(`${issue.path.join('.')}: ${issue.message}`);
- }
- }
- }
- }
- return { valid: errors.length === 0, errors };
-}
+export * from '@claude-flow/cli-core/mcp-tools/validate-input';
diff --git a/v3/@claude-flow/cli/src/output.ts b/v3/@claude-flow/cli/src/output.ts
index 17ca465caf..54850661b5 100644
--- a/v3/@claude-flow/cli/src/output.ts
+++ b/v3/@claude-flow/cli/src/output.ts
@@ -1,640 +1,9 @@
/**
- * V3 CLI Output Formatter
- * Advanced output formatting with tables, progress bars, and colors
+ * V3 CLI Output Formatter β€” re-export shim (ADR-100, alpha.5).
+ *
+ * Authoritative source: @claude-flow/cli-core/output. Was a byte-identical
+ * 640-line copy. The OutputFormatter class and `output` instance plus all
+ * helper exports flow through unchanged. Edit cli-core for behavior changes.
*/
-import type { TableOptions, TableColumn, ProgressOptions, SpinnerOptions } from './types.js';
-
-// ============================================
-// Color Support
-// ============================================
-
-const COLORS = {
- // Standard colors
- reset: '\x1b[0m',
- bold: '\x1b[1m',
- dim: '\x1b[2m',
- italic: '\x1b[3m',
- underline: '\x1b[4m',
-
- // Foreground colors
- black: '\x1b[30m',
- red: '\x1b[31m',
- green: '\x1b[32m',
- yellow: '\x1b[33m',
- blue: '\x1b[34m',
- magenta: '\x1b[35m',
- cyan: '\x1b[36m',
- white: '\x1b[37m',
- gray: '\x1b[90m',
-
- // Bright foreground colors
- brightRed: '\x1b[91m',
- brightGreen: '\x1b[92m',
- brightYellow: '\x1b[93m',
- brightBlue: '\x1b[94m',
- brightMagenta: '\x1b[95m',
- brightCyan: '\x1b[96m',
- brightWhite: '\x1b[97m',
-
- // Background colors
- bgBlack: '\x1b[40m',
- bgRed: '\x1b[41m',
- bgGreen: '\x1b[42m',
- bgYellow: '\x1b[43m',
- bgBlue: '\x1b[44m',
- bgMagenta: '\x1b[45m',
- bgCyan: '\x1b[46m',
- bgWhite: '\x1b[47m'
-} as const;
-
-type ColorName = keyof typeof COLORS;
-
-export type VerbosityLevel = 'quiet' | 'normal' | 'verbose' | 'debug';
-
-export class OutputFormatter {
- private colorEnabled: boolean;
- private outputStream: NodeJS.WriteStream;
- private errorStream: NodeJS.WriteStream;
- private verbosity: VerbosityLevel;
-
- constructor(options: { color?: boolean; verbosity?: VerbosityLevel } = {}) {
- this.colorEnabled = options.color ?? this.supportsColor();
- this.outputStream = process.stdout;
- this.errorStream = process.stderr;
- this.verbosity = options.verbosity ?? 'normal';
- }
-
- /**
- * Set verbosity level
- * - quiet: Only errors and direct results
- * - normal: Errors, warnings, info, and results
- * - verbose: All of normal + debug messages
- * - debug: All output including trace
- */
- setVerbosity(level: VerbosityLevel): void {
- this.verbosity = level;
- }
-
- getVerbosity(): VerbosityLevel {
- return this.verbosity;
- }
-
- isQuiet(): boolean {
- return this.verbosity === 'quiet';
- }
-
- isVerbose(): boolean {
- return this.verbosity === 'verbose' || this.verbosity === 'debug';
- }
-
- isDebug(): boolean {
- return this.verbosity === 'debug';
- }
-
- private supportsColor(): boolean {
- // Check for NO_COLOR environment variable
- if (process.env.NO_COLOR !== undefined) return false;
-
- // Check for FORCE_COLOR environment variable
- if (process.env.FORCE_COLOR !== undefined) return true;
-
- // Check if stdout is a TTY
- return process.stdout.isTTY ?? false;
- }
-
- // ============================================
- // Color Methods
- // ============================================
-
- color(text: string, ...colors: ColorName[]): string {
- if (!this.colorEnabled) return text;
-
- const codes = colors.map(c => COLORS[c]).join('');
- return `${codes}${text}${COLORS.reset}`;
- }
-
- bold(text: string): string {
- return this.color(text, 'bold');
- }
-
- dim(text: string): string {
- return this.color(text, 'dim');
- }
-
- success(text: string): string {
- return this.color(text, 'green');
- }
-
- error(text: string): string {
- return this.color(text, 'red');
- }
-
- warning(text: string): string {
- return this.color(text, 'yellow');
- }
-
- info(text: string): string {
- return this.color(text, 'blue');
- }
-
- highlight(text: string): string {
- return this.color(text, 'cyan', 'bold');
- }
-
- // ============================================
- // Output Methods
- // ============================================
-
- write(text: string): void {
- this.outputStream.write(text);
- }
-
- writeln(text: string = ''): void {
- this.outputStream.write(text + '\n');
- }
-
- writeError(text: string): void {
- this.errorStream.write(text);
- }
-
- writeErrorln(text: string = ''): void {
- this.errorStream.write(text + '\n');
- }
-
- // ============================================
- // Formatted Output Methods
- // ============================================
-
- printSuccess(message: string): void {
- // Success always shows (result output)
- const icon = this.color('[OK]', 'green', 'bold');
- this.writeln(`${icon} ${message}`);
- }
-
- printError(message: string, details?: string): void {
- // Errors always show
- const icon = this.color('[ERROR]', 'red', 'bold');
- this.writeErrorln(`${icon} ${message}`);
- if (details) {
- this.writeErrorln(this.dim(` ${details}`));
- }
- }
-
- printWarning(message: string): void {
- // Warnings suppressed in quiet mode
- if (this.verbosity === 'quiet') return;
- const icon = this.color('[WARN]', 'yellow', 'bold');
- this.writeln(`${icon} ${message}`);
- }
-
- printInfo(message: string): void {
- // Info suppressed in quiet mode
- if (this.verbosity === 'quiet') return;
- const icon = this.color('[INFO]', 'blue', 'bold');
- this.writeln(`${icon} ${message}`);
- }
-
- printDebug(message: string): void {
- // Debug only shows in verbose/debug mode
- if (this.verbosity !== 'verbose' && this.verbosity !== 'debug') return;
- const icon = this.color('[DEBUG]', 'gray');
- this.writeln(`${icon} ${this.dim(message)}`);
- }
-
- printTrace(message: string): void {
- // Trace only shows in debug mode
- if (this.verbosity !== 'debug') return;
- const icon = this.color('[TRACE]', 'gray', 'dim');
- this.writeln(`${icon} ${this.dim(message)}`);
- }
-
- // ============================================
- // Table Formatting
- // ============================================
-
- table(options: TableOptions): string {
- const { columns, data, border = true, header = true, padding = 1, maxWidth } = options;
-
- // Calculate column widths
- const widths = this.calculateColumnWidths(columns, data, maxWidth);
-
- const lines: string[] = [];
- const pad = ' '.repeat(padding);
-
- // Border characters
- const borderChars = border ? {
- topLeft: '+', topRight: '+', bottomLeft: '+', bottomRight: '+',
- horizontal: '-', vertical: '|',
- leftT: '+', rightT: '+', topT: '+', bottomT: '+', cross: '+'
- } : {
- topLeft: '', topRight: '', bottomLeft: '', bottomRight: '',
- horizontal: '', vertical: ' ',
- leftT: '', rightT: '', topT: '', bottomT: '', cross: ''
- };
-
- // Top border
- if (border) {
- lines.push(this.createBorderLine(widths, borderChars, 'top', padding));
- }
-
- // Header row
- if (header) {
- const headerRow = columns.map((col, i) => {
- const text = this.truncate(col.header, widths[i]);
- return pad + this.alignText(this.bold(text), widths[i], col.align) + pad;
- }).join(borderChars.vertical);
-
- lines.push(`${borderChars.vertical}${headerRow}${borderChars.vertical}`);
-
- // Header separator
- if (border) {
- lines.push(this.createBorderLine(widths, borderChars, 'middle', padding));
- }
- }
-
- // Data rows
- for (const row of data) {
- const rowCells = columns.map((col, i) => {
- let value = row[col.key];
-
- // Apply formatter if provided
- if (col.format) {
- value = col.format(value);
- } else {
- value = String(value ?? '');
- }
-
- const text = this.truncate(String(value), widths[i]);
- return pad + this.alignText(text, widths[i], col.align) + pad;
- }).join(borderChars.vertical);
-
- lines.push(`${borderChars.vertical}${rowCells}${borderChars.vertical}`);
- }
-
- // Bottom border
- if (border) {
- lines.push(this.createBorderLine(widths, borderChars, 'bottom', padding));
- }
-
- return lines.join('\n');
- }
-
- printTable(options: TableOptions): void {
- this.writeln(this.table(options));
- }
-
- private calculateColumnWidths(
- columns: TableColumn[],
- data: Record<string, unknown>[],
- maxWidth?: number
- ): number[] {
- const widths = columns.map((col, i) => {
- // Start with header width
- let width = col.header.length;
-
- // Check all data values
- for (const row of data) {
- let value = row[col.key];
- if (col.format) {
- value = col.format(value);
- }
- const len = this.stripAnsi(String(value ?? '')).length;
- width = Math.max(width, len);
- }
-
- // Apply column-specific width limit
- if (col.width) {
- width = Math.min(width, col.width);
- }
-
- return width;
- });
-
- // Apply max width constraint
- if (maxWidth) {
- const totalWidth = widths.reduce((a, b) => a + b, 0) + (columns.length * 3) + 1;
- if (totalWidth > maxWidth) {
- const reduction = (totalWidth - maxWidth) / columns.length;
- return widths.map(w => Math.max(3, Math.floor(w - reduction)));
- }
- }
-
- return widths;
- }
-
- private createBorderLine(
- widths: number[],
- chars: Record<string, string>,
- position: 'top' | 'middle' | 'bottom',
- padding: number
- ): string {
- const cellWidth = (w: number) => chars.horizontal.repeat(w + (padding * 2));
- const cells = widths.map(cellWidth).join(
- position === 'top' ? chars.topT :
- position === 'bottom' ? chars.bottomT :
- chars.cross
- );
-
- const left = position === 'top' ? chars.topLeft : position === 'bottom' ? chars.bottomLeft : chars.leftT;
- const right = position === 'top' ? chars.topRight : position === 'bottom' ? chars.bottomRight : chars.rightT;
-
- return `${left}${cells}${right}`;
- }
-
- private alignText(text: string, width: number, align: 'left' | 'center' | 'right' = 'left'): string {
- const len = this.stripAnsi(text).length;
- const padding = width - len;
-
- if (padding <= 0) return text;
-
- switch (align) {
- case 'right':
- return ' '.repeat(padding) + text;
- case 'center':
- const left = Math.floor(padding / 2);
- const right = padding - left;
- return ' '.repeat(left) + text + ' '.repeat(right);
- default:
- return text + ' '.repeat(padding);
- }
- }
-
- private truncate(text: string, maxLength: number): string {
- const stripped = this.stripAnsi(text);
- if (stripped.length <= maxLength) return text;
- return stripped.slice(0, maxLength - 3) + '...';
- }
-
- private stripAnsi(text: string): string {
- return text.replace(/\x1b\[[0-9;]*m/g, '');
- }
-
- // ============================================
- // Progress Bar
- // ============================================
-
- createProgress(options: ProgressOptions): Progress {
- return new Progress(this, options);
- }
-
- progressBar(current: number, total: number, width: number = 40): string {
- const percent = Math.min(100, Math.max(0, (current / total) * 100));
- const filled = Math.round((width * percent) / 100);
- const empty = width - filled;
-
- const bar = this.color('#'.repeat(filled), 'green') +
- this.dim('-'.repeat(empty));
-
- return `[${bar}] ${percent.toFixed(1)}%`;
- }
-
- // ============================================
- // Spinner
- // ============================================
-
- createSpinner(options: SpinnerOptions): Spinner {
- return new Spinner(this, options);
- }
-
- // ============================================
- // JSON Output
- // ============================================
-
- json(data: unknown, pretty: boolean = true): string {
- return pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);
- }
-
- printJson(data: unknown, pretty: boolean = true): void {
- this.writeln(this.json(data, pretty));
- }
-
- // ============================================
- // List Output
- // ============================================
-
- list(items: string[], bullet: string = '-'): string {
- return items.map(item => ` ${bullet} ${item}`).join('\n');
- }
-
- printList(items: string[], bullet: string = '-'): void {
- this.writeln(this.list(items, bullet));
- }
-
- numberedList(items: string[]): string {
- return items.map((item, i) => ` ${i + 1}. ${item}`).join('\n');
- }
-
- printNumberedList(items: string[]): void {
- this.writeln(this.numberedList(items));
- }
-
- // ============================================
- // Box Output
- // ============================================
-
- box(content: string, title?: string): string {
- const lines = content.split('\n');
- const maxLen = Math.max(...lines.map(l => this.stripAnsi(l).length), title?.length ?? 0);
- const width = maxLen + 4;
-
- const border = {
- topLeft: '+', topRight: '+',
- bottomLeft: '+', bottomRight: '+',
- horizontal: '-', vertical: '|'
- };
-
- const result: string[] = [];
-
- // Top border with optional title
- if (title) {
- const titleText = ` ${title} `;
- const leftPad = Math.floor((width - titleText.length - 2) / 2);
- const rightPad = width - titleText.length - leftPad - 2;
- result.push(
- border.topLeft +
- border.horizontal.repeat(leftPad) +
- this.bold(titleText) +
- border.horizontal.repeat(rightPad) +
- border.topRight
- );
- } else {
- result.push(border.topLeft + border.horizontal.repeat(width - 2) + border.topRight);
- }
-
- // Content lines
- for (const line of lines) {
- const stripped = this.stripAnsi(line);
- const padding = maxLen - stripped.length;
- result.push(`${border.vertical} ${line}${' '.repeat(padding)} ${border.vertical}`);
- }
-
- // Bottom border
- result.push(border.bottomLeft + border.horizontal.repeat(width - 2) + border.bottomRight);
-
- return result.join('\n');
- }
-
- printBox(content: string, title?: string): void {
- this.writeln(this.box(content, title));
- }
-
- setColorEnabled(enabled: boolean): void {
- this.colorEnabled = enabled;
- }
-
- isColorEnabled(): boolean {
- return this.colorEnabled;
- }
-}
-
-// ============================================
-// Progress Class
-// ============================================
-
-export class Progress {
- private current: number;
- private total: number;
- private width: number;
- private startTime: number;
- private formatter: OutputFormatter;
- private showPercentage: boolean;
- private showETA: boolean;
- private lastRender: string = '';
-
- constructor(formatter: OutputFormatter, options: ProgressOptions) {
- this.formatter = formatter;
- this.current = options.current ?? 0;
- this.total = options.total;
- this.width = options.width ?? 40;
- this.showPercentage = options.showPercentage ?? true;
- this.showETA = options.showETA ?? true;
- this.startTime = Date.now();
- }
-
- update(current: number): void {
- this.current = current;
- this.render();
- }
-
- increment(amount: number = 1): void {
- this.update(this.current + amount);
- }
-
- render(): void {
- const bar = this.formatter.progressBar(this.current, this.total, this.width);
-
- let output = bar;
-
- if (this.showETA && this.current > 0) {
- const elapsed = Date.now() - this.startTime;
- const rate = this.current / elapsed;
- const remaining = this.total - this.current;
- const eta = remaining / rate;
-
- if (isFinite(eta)) {
- output += ` ETA: ${this.formatTime(eta)}`;
- }
- }
-
- // Clear previous line and write new
- if (this.lastRender) {
- process.stdout.write('\r' + ' '.repeat(this.lastRender.length) + '\r');
- }
-
- process.stdout.write(output);
- this.lastRender = output;
- }
-
- finish(): void {
- this.current = this.total;
- this.render();
- process.stdout.write('\n');
- }
-
- private formatTime(ms: number): string {
- const seconds = Math.floor(ms / 1000);
- const minutes = Math.floor(seconds / 60);
- const hours = Math.floor(minutes / 60);
-
- if (hours > 0) {
- return `${hours}h ${minutes % 60}m`;
- } else if (minutes > 0) {
- return `${minutes}m ${seconds % 60}s`;
- } else {
- return `${seconds}s`;
- }
- }
-}
-
-// ============================================
-// Spinner Class
-// ============================================
-
-export class Spinner {
- private formatter: OutputFormatter;
- private text: string;
- private frames: string[];
- private interval: ReturnType<typeof setInterval> | null = null;
- private frameIndex: number = 0;
-
- private static readonly SPINNERS: Record<string, string[]> = {
- dots: ['...', '..:' , '.::', ':::', '::.', ':..' ,],
- line: ['-', '\\', '|', '/'],
- arc: ['β—œ', 'β— ', '◝', 'β—ž', 'β—‘', 'β—Ÿ'],
- circle: ['◐', 'β—“', 'β—‘', 'β—’'],
- arrows: ['←', 'β†–', '↑', 'β†—', 'β†’', 'β†˜', '↓', '↙']
- };
-
- constructor(formatter: OutputFormatter, options: SpinnerOptions) {
- this.formatter = formatter;
- this.text = options.text;
- this.frames = Spinner.SPINNERS[options.spinner ?? 'dots'];
- }
-
- start(): void {
- if (this.interval) return;
-
- this.interval = setInterval(() => {
- this.render();
- this.frameIndex = (this.frameIndex + 1) % this.frames.length;
- }, 100);
- this.interval.unref();
-
- this.render();
- }
-
- stop(message?: string): void {
- if (this.interval) {
- clearInterval(this.interval);
- this.interval = null;
- }
-
- // Clear the line
- process.stdout.write('\r' + ' '.repeat(this.text.length + 10) + '\r');
-
- if (message) {
- this.formatter.writeln(message);
- }
- }
-
- succeed(message?: string): void {
- this.stop(this.formatter.success(message ?? this.text));
- }
-
- fail(message?: string): void {
- this.stop(this.formatter.error(message ?? this.text));
- }
-
- private render(): void {
- const frame = this.formatter.info(this.frames[this.frameIndex]);
- process.stdout.write(`\r${frame} ${this.text}`);
- }
-
- setText(text: string): void {
- this.text = text;
- }
-}
-
-// Export singleton instance
-export const output = new OutputFormatter();
+export * from '@claude-flow/cli-core/output';
diff --git a/v3/@claude-flow/cli/src/types.ts b/v3/@claude-flow/cli/src/types.ts
index cd20cf85f7..4829cd7458 100644
--- a/v3/@claude-flow/cli/src/types.ts
+++ b/v3/@claude-flow/cli/src/types.ts
@@ -1,287 +1,13 @@
/**
- * V3 CLI Type Definitions
- * Modernized type system for the RuFlo V3 CLI
+ * V3 CLI Type Definitions β€” re-export shim (ADR-100, alpha.5).
+ *
+ * Authoritative source: @claude-flow/cli-core/types. Was a byte-identical
+ * 287-line copy until alpha.5 published the cli-core subpath. The 60+
+ * `import './types.js'` call sites inside cli keep working unchanged
+ * because the file path is preserved.
+ *
+ * To extend the type system, edit v3/@claude-flow/cli-core/src/types.ts
+ * β€” changes flow through here automatically.
*/
-// ============================================
-// Core Command Types
-// ============================================
-
-export interface CommandContext {
- args: string[];
- flags: ParsedFlags;
- config?: V3Config;
- cwd: string;
- interactive: boolean;
-}
-
-export interface ParsedFlags {
- [key: string]: string | boolean | number | string[];
- _: string[];
-}
-
-export interface Command {
- name: string;
- description: string;
- aliases?: string[];
- subcommands?: Command[];
- options?: CommandOption[];
- examples?: CommandExample[];
- action?: CommandAction;
- hidden?: boolean;
-}
-
-export interface CommandOption {
- name: string;
- short?: string;
- description: string;
- type: 'string' | 'boolean' | 'number' | 'array';
- default?: unknown;
- required?: boolean;
- choices?: string[];
- validate?: (value: unknown) => boolean | string;
-}
-
-export interface CommandExample {
- command: string;
- description: string;
-}
-
-export type CommandAction = (ctx: CommandContext) => Promise<CommandResult | void>;
-
-export interface CommandResult {
- success: boolean;
- message?: string;
- data?: unknown;
- exitCode?: number;
-}
-
-// ============================================
-// Configuration Types
-// ============================================
-
-export interface V3Config {
- version: string;
- projectRoot: string;
-
- // Agent configuration
- agents: AgentConfig;
-
- // Swarm configuration
- swarm: SwarmConfig;
-
- // Memory configuration
- memory: MemoryConfig;
-
- // MCP configuration
- mcp: MCPConfig;
-
- // CLI preferences
- cli: CLIPreferences;
-
- // Hooks configuration
- hooks: HooksConfig;
-}
-
-export interface AgentConfig {
- defaultType: string;
- autoSpawn: boolean;
- maxConcurrent: number;
- timeout: number;
- providers: ProviderConfig[];
-}
-
-export interface ProviderConfig {
- name: string;
- apiKey?: string;
- baseUrl?: string;
- model?: string;
- priority: number;
- enabled: boolean;
-}
-
-export interface SwarmConfig {
- topology: 'hierarchical' | 'mesh' | 'ring' | 'star' | 'hybrid' | 'hierarchical-mesh';
- maxAgents: number;
- autoScale: boolean;
- coordinationStrategy: 'consensus' | 'leader' | 'distributed';
- healthCheckInterval: number;
-}
-
-export interface MemoryConfig {
- backend: 'agentdb' | 'sqlite' | 'memory' | 'hybrid';
- persistPath: string;
- cacheSize: number;
- enableHNSW: boolean;
- vectorDimension: number;
-}
-
-export interface MCPConfig {
- serverHost: string;
- serverPort: number;
- autoStart: boolean;
- transportType: 'stdio' | 'http' | 'websocket';
- tools: string[];
-}
-
-export interface CLIPreferences {
- colorOutput: boolean;
- interactive: boolean;
- verbosity: 'quiet' | 'normal' | 'verbose' | 'debug';
- outputFormat: 'text' | 'json' | 'table';
- progressStyle: 'bar' | 'spinner' | 'dots' | 'none';
-}
-
-export interface HooksConfig {
- enabled: boolean;
- autoExecute: boolean;
- hooks: HookDefinition[];
-}
-
-export interface HookDefinition {
- name: string;
- event: string;
- handler: string;
- priority: number;
- enabled: boolean;
-}
-
-// ============================================
-// Output Types
-// ============================================
-
-export interface TableColumn {
- key: string;
- header: string;
- width?: number;
- align?: 'left' | 'center' | 'right';
- format?: (value: unknown) => string;
-}
-
-export interface TableOptions {
- columns: TableColumn[];
- data: Record<string, unknown>[];
- border?: boolean;
- header?: boolean;
- padding?: number;
- maxWidth?: number;
-}
-
-export interface ProgressOptions {
- total: number;
- current?: number;
- width?: number;
- format?: string;
- showPercentage?: boolean;
- showETA?: boolean;
- showSpeed?: boolean;
-}
-
-export interface SpinnerOptions {
- text: string;
- spinner?: 'dots' | 'line' | 'arc' | 'circle' | 'arrows';
- color?: string;
-}
-
-// ============================================
-// Prompt Types
-// ============================================
-
-export interface SelectOption<T = string> {
- value: T;
- label: string;
- hint?: string;
- disabled?: boolean;
- /** For multiselect: whether this option is selected by default */
- selected?: boolean;
-}
-
-export interface SelectPromptOptions<T = string> {
- message: string;
- options: SelectOption<T>[];
- default?: T;
- searchable?: boolean;
- pageSize?: number;
-}
-
-export interface ConfirmPromptOptions {
- message: string;
- default?: boolean;
- active?: string;
- inactive?: string;
-}
-
-export interface InputPromptOptions {
- message: string;
- default?: string;
- placeholder?: string;
- validate?: (value: string) => boolean | string;
- mask?: boolean;
-}
-
-export interface MultiSelectPromptOptions<T = string> {
- message: string;
- options: SelectOption<T>[];
- default?: T[];
- required?: boolean;
- min?: number;
- max?: number;
-}
-
-// ============================================
-// Event Types
-// ============================================
-
-export type CLIEventType =
- | 'command:start'
- | 'command:end'
- | 'command:error'
- | 'prompt:start'
- | 'prompt:complete'
- | 'output:write'
- | 'progress:update'
- | 'spinner:start'
- | 'spinner:stop';
-
-export interface CLIEvent {
- type: CLIEventType;
- timestamp: number;
- data?: unknown;
-}
-
-// ============================================
-// Error Types
-// ============================================
-
-export class CLIError extends Error {
- constructor(
- message: string,
- public code: string,
- public exitCode: number = 1,
- public details?: unknown
- ) {
- super(message);
- this.name = 'CLIError';
- }
-}
-
-export class ValidationError extends CLIError {
- constructor(message: string, details?: unknown) {
- super(message, 'VALIDATION_ERROR', 1, details);
- this.name = 'ValidationError';
- }
-}
-
-export class ConfigError extends CLIError {
- constructor(message: string, details?: unknown) {
- super(message, 'CONFIG_ERROR', 1, details);
- this.name = 'ConfigError';
- }
-}
-
-export class CommandNotFoundError extends CLIError {
- constructor(commandName: string) {
- super(`Unknown command: ${commandName}`, 'COMMAND_NOT_FOUND', 127);
- this.name = 'CommandNotFoundError';
- }
-}
+export * from '@claude-flow/cli-core/types';
diff --git a/v3/docs/adr/ADR-100-cli-core-split-lazy-load.md b/v3/docs/adr/ADR-100-cli-core-split-lazy-load.md
new file mode 100644
index 0000000000..66a39ab756
--- /dev/null
+++ b/v3/docs/adr/ADR-100-cli-core-split-lazy-load.md
@@ -0,0 +1,204 @@
+# ADR-100: Split `@claude-flow/cli` into `cli-core` + lazy-loaded extras
+
+**Status**: Proposed
+**Date**: 2026-05-05
+**Version**: target v3.7.0-alpha.1 (alpha tag), graduating to v3.8.0 once validated
+**Supersedes**: nothing
+**Related**: ADR-098 (plugin capability sync and optimization), issue [#1748](https://github.com/ruvnet/ruflo/issues/1748) Issue 3 (cold-cache 30s MCP-startup race), [#1747](https://github.com/ruvnet/ruflo/issues/1747) (hooks shell injection β€” fixed in 3.6.28; orthogonal to this ADR)
+
+## Context
+
+Issue #1748 from the Liberation of Bajor team's methodical install-study identified a silent failure mode that affects every new user with a cold npx cache:
+
+> **Issue 3:** First-time invocation of `npx -y claude-flow@latest mcp start` from a cold npx cache hits a Claude Code MCP-startup timeout. Logged as `Starting connection with timeout of 30000ms` followed by the server staying in "still connecting" state for the entire session. Zero claude-flow tools register; the model falls through to native tools.
+>
+> **Diagnosis:** The `claude-flow@latest` package is roughly 1.8 MB across 999 files. Cold npx download + extraction + spawn can exceed 30 seconds.
+
+We confirmed the bug is reproducible. The same cold-cache penalty hits every plugin skill that falls back to `npx @claude-flow/cli ...` for memory/hooks operations when MCP tools aren't registered. Today's reality:
+
+- Unpacked dist size: **9.6 MB across 777 files** (npm-packaged is 1.8 MB / 999 files per the issue, including all deps).
+- 95+% of plugin skill traffic only needs `memory` + `hooks` commands (~420 KB of source TS).
+- The remaining ~95% of the package (swarm, neural, federation, browser, daa, hive-mind, claims, performance, security, embeddings, ruvector, intelligence, autopilot, …) is paid as a download cost on every cold cache, even when never invoked.
+
+The reporter's fix request #1 was: *"Reduce package footprint. 1.8 MB / 999 files is large for a tool whose first-run time is gated by a 30s timeout. A leaner core package (with optional plugins lazy-loaded) would push first-time-success rates above 99%."*
+
+This ADR proposes the split.
+
+## Decision
+
+Split `@claude-flow/cli` into two packages with a backwards-compatible metapackage facade:
+
+### 1. `@claude-flow/cli-core` (new, ~150–200 KB packed)
+
+Contains exactly the surface plugin skills depend on plus the entry-point machinery:
+
+```
+cli-core/
+ src/
+ index.ts # CLI entry β€” registers core commands + lazy-binding hooks for extras
+ output.ts, prompt.ts # output utilities (already shared)
+ types.ts # CommandContext, Command, etc.
+ fs-secure.ts # path-traversal guards
+ commands/
+ memory.ts # 11 subcommands: store, list, retrieve, search, delete, init, ...
+ hooks.ts # 17 hook commands + 12 worker triggers (entry points only β€”
+ # delegate to lazy-loaded handlers under cli-extras)
+ mcp-tools/
+ memory-tools.ts # MCP tool defs for memory_*
+ hooks-tools.ts # MCP tool defs for hooks_* (the routing surface)
+ types.ts
+ mcp-client.ts # client side (already small)
+```
+
+Target metric: **packed size ≀ 250 KB**, dist file count ≀ 80, cold-npx download + extract < 5 seconds on a typical broadband connection.
+
+### 2. `@claude-flow/cli` (existing, becomes a metapackage)
+
+```js
+// v3/@claude-flow/cli/src/index.ts (after split)
+export * from '@claude-flow/cli-core';
+
+// Lazy-loaded extras β€” registered via dynamic import only when their command is invoked.
+const lazyCommandTable: Record<string, () => Promise<{ default: Command }>> = {
+ swarm: () => import('./commands/swarm.js'),
+ neural: () => import('./commands/neural.js'),
+ federation: () => import('./commands/federation.js'),
+ // ...
+};
+```
+
+The metapackage:
+- depends on `@claude-flow/cli-core` (as a regular dep β€” no dynamic resolution needed for core path)
+- ships everything that's NOT in cli-core in its own dist
+- registers a CLI dispatcher that defers to cli-core for `memory`/`hooks`/`output`, and dynamic-imports the extras when those commands fire
+
+Existing users (`npx @claude-flow/cli@latest <anything>`) continue to work unchanged. The cold-cache penalty for `memory` / `hooks` invocations drops because they're served from cli-core (small) β€” but only if the user installs cli-core directly. Users who install the metapackage still pay the full footprint (because npx pulls the whole thing); the win is that **plugin skills can opt to invoke `npx @claude-flow/cli-core@latest memory store ...`** for the hot path.
+
+### 3. Plugin skill scripts switch to cli-core
+
+Each plugin's Bash blocks update:
+
+```diff
+- npx @claude-flow/cli@latest memory store --namespace cost-tracking ...
++ npx @claude-flow/cli-core@latest memory store --namespace cost-tracking ...
+```
+
+Cold-cache: **1.8 MB β†’ ~200 KB**. 30s timeout race no longer applies.
+
+### 4. Versioning + alpha tag strategy
+
+- `cli-core` ships as **v3.7.0-alpha.1** under `--tag alpha` (alpha line)
+- `cli` (existing) ships as **v3.7.0-alpha.1** with the metapackage refactor under `--tag alpha`
+- `latest` continues to point at the legacy 3.6.x line until the alpha is validated by external users
+- `v3alpha` tag for `cli` continues to track the latest pre-release
+
+Alpha promotion to `latest` requires:
+1. Cold-cache benchmark showing β‰₯80% reduction in first-call wall-time
+2. At least one external integrator (the #1748 reporter is a candidate) confirms MCP startup succeeds within 30s on a cold cache
+3. No regression in the existing 21 Tier 1 / 7 adversarial cost-tracker bench corpus
+
+## Consequences
+
+**Positive:**
+
+- **#1748 Issue 3 fixed structurally** rather than worked around. Plugin-install users get fast first-call experience without any matrix-of-install-paths documentation.
+- **Plugin skills become 30Γ— faster on cold cache** (60s β†’ 2s). Drastically lower abandonment for new users.
+- The MCP-startup 30s race becomes a non-issue when the registered server is cli-core.
+- Future "lite vs full" install differentiation (#1744 #1) becomes a real package boundary, not a documentation distinction.
+
+**Negative:**
+
+- **Two npm packages to keep in sync.** Versions, releases, dist-tags. Worth scripting as a release task.
+- **Backwards compatibility risk.** Anyone importing from internal cli paths (e.g. `import x from '@claude-flow/cli/dist/src/commands/memory.js'`) will need to switch to `cli-core`. We control all known consumers (the plugins) so this is auditable.
+- **CLI dispatcher complexity.** The metapackage's index.ts grows a lazy-load table. Mistakes there manifest as "command not found" β€” needs explicit tests.
+- **Tree-shaking limitation.** ESM dynamic imports work, but require the consuming environment to support them. Modern Node 20+ does; older runtimes may not.
+
+**Neutral:**
+
+- **No changes to the published `ruflo` umbrella.** It continues to depend on `@claude-flow/cli` and gets the lazy-load benefits transparently.
+- **No changes to `claude-flow` umbrella.** Same.
+- The verification.md witness manifest grows by 1 release entry; no new fix categories.
+
+## Riskiest assumption
+
+The single biggest risk: that the Liberation of Bajor team's diagnosis (cold-cache pull + extract dominates startup) is correct AND that the 1.8 MB β†’ 200 KB reduction translates directly to fitting under the 30s timeout. Two paths can fail this:
+
+1. **MCP-server startup itself is slow** independent of package size (e.g., heavy ESM module-graph initialization, blocking native imports). If so, splitting the package doesn't help β€” we'd still race the timeout. Mitigation: profile module init time on cli-core before publishing to confirm <2s start.
+
+2. **npx cache invalidation behaviors** on Windows + Git Bash (the reporter's environment) may behave differently than Linux. If npx re-extracts every time on Windows, the absolute size reduction matters; if it shares cache across invocations, we may not see linear improvement. Mitigation: validate on Windows specifically before promoting alpha β†’ latest.
+
+If either fails, this ADR's first benefit (30s race) doesn't materialize. The other benefits (smaller surface, cleaner upgrade story) still hold but are less urgent.
+
+## Verification
+
+Once cli-core is published:
+
+```bash
+# Cold cache (clear ~/.npm/_npx first)
+rm -rf ~/.npm/_npx
+time npx @claude-flow/cli-core@alpha memory store --namespace test --key x --value 1
+# Expected: < 5s wall-time on typical connection
+
+# Compare to current cli
+rm -rf ~/.npm/_npx
+time npx @claude-flow/cli@alpha memory store --namespace test --key x --value 1
+# Expected: > 30s on typical connection (matches the bug)
+```
+
+The smoke contract for `cli-core` mirrors the existing one in spirit: every command parses, every MCP tool definition has the canonical fields, no wildcard tool grants. Existing `@claude-flow/cli` smoke contract is preserved.
+
+## Migration path for plugin authors
+
+Two-step migration plan after cli-core@alpha lands:
+
+1. **Plugins update their script Bash blocks** to invoke `cli-core` for memory/hooks operations. Backwards-compatible β€” `cli` still works, just slower. Sample diff:
+
+ ```diff
+ - npx @claude-flow/cli@latest memory store ...
+ + npx @claude-flow/cli-core@latest memory store ...
+ ```
+
+2. **README install matrix simplifies** β€” the "Plugin install (lite, slash commands only)" caveat becomes a "Plugin install + cli-core (fast, registers MCP via npx-warm fallback)" entry that approaches parity with full `npx ruflo init` for the common case.
+
+## Plan of work
+
+| Step | What | Status |
+|---|---|---|
+| 1 | Branch `feat/cli-core-split` + ADR-100 + scaffold | βœ… done β€” fire 1 |
+| 2a | Foundation surface in cli-core (types, output, MCP-tool-types, validate-input) | βœ… done β€” fire 2 (commit `2329b81fa`, 136 KB / 20 files dist) |
+| **2b** | **Architectural discovery (fire 3) β€” see "Discovery" below** | βœ… surfaced; informs steps 3+ |
+| 3 | Backend abstraction: extract a lite memory backend (JSON-only, no sql.js/HNSW/ONNX) so `mcp-tools/memory-tools.ts` can copy cleanly into cli-core. Heavy backend stays in @claude-flow/cli. | pending |
+| 4 | Definitions/handlers split for `hooks-tools.ts` β€” tool definitions (name/description/inputSchema, ~10 KB) live in cli-core; handler functions that actually do the work stay in cli with dynamic-import wiring. | pending |
+| 5 | Update `@claude-flow/cli/src/index.ts` to re-export from cli-core + register lazy-loaded extras for non-foundation commands. | pending |
+| 6 | Cold-cache benchmark: old vs new, persist to `docs/benchmarks/cli-core-cold-cache.json`. | pending |
+| 7 | Bump `cli-core` to `3.7.0-alpha.1` once steps 3+4 land; publish under `--tag alpha`. (alpha.0 published in fire 3 with foundation-only.) | partial |
+| 8 | PR description with cold-cache numbers + comment on issue #1760 with proof. | pending |
+
+## Discovery (fire 3)
+
+Initial assumption (fire 1's plan): "move memory + hooks source files into cli-core". Reality (fire 3): **both `memory-tools.ts` and `hooks-tools.ts` have deep transitive ML dependencies** that defeat the lite-bundle goal:
+
+- `memory-tools.ts` (30 KB top-level) β†’ `../memory/memory-initializer.js` (2830 LOC) β†’ `fs-secure.ts` β†’ `encryption/vault.ts` (ADR-096)
+- `hooks-tools.ts` (146 KB top-level) β†’ 9 transitive imports across `memory/{sona-optimizer, ewc-consolidation, memory-bridge}` (the SONA/EWC++ neural surface) and `ruvector/{moe-router, semantic-router, flash-attention, lora-adapter, enhanced-model-router}` (the ML routing layer)
+
+Pulling those into cli-core would balloon it past the 250 KB packed target. The **right architectural move** is what the ADR's "Riskiest assumption" hinted at but didn't concretize:
+
+1. **Memory backend abstraction.** Define a `MemoryBackend` interface in cli-core. cli-core ships a `JsonMemoryBackend` (no SQLite, no HNSW β€” just JSON file at `.swarm/memory.json`). cli ships a `SqliteHnswMemoryBackend` (the existing implementation) that swaps in via env-var or import map. Plugin scripts that only need basic store/retrieve get the lite backend's <2s cold-cache; plugins that need semantic search opt into the heavy backend.
+
+2. **Tool-definition / handler split.** MCP tool *definitions* (the `MCPTool` shape: name, description, inputSchema) are pure data and small (~10 KB total for memory + hooks). They go in cli-core. The *handler* implementations (the actual code that runs when an MCP request fires) stay in cli's full module tree, accessed via dynamic-import only at request time. cli-core exposes the definitions so a metapackage can register them with the MCP server; the metapackage routes invocations to its full handler tree.
+
+This is more work than fire 1 anticipated β€” likely 4-6 additional fires to land cleanly, vs the original "next fire" estimate. The ADR is updated to reflect the actual shape of the work.
+
+**Net conclusion: foundation-only alpha.0 ships now (proves publish pipeline + gives plugin authors type imports). Backend abstraction + tool/handler split land in alpha.1 and alpha.2.**
+
+## Related
+
+- #1748 Issue 3 β€” the reporter's fix-request #1 for the 30s MCP timeout race
+- ADR-098 β€” plugin capability sync (the lite-vs-full philosophy this ADR makes a real package boundary)
+- v3.6.28 release ([#1753]) β€” added `--no-global` flag, also addressing #1744 papercuts; cli-core split is the structural follow-up
+
+## Decision lifecycle
+
+- **2026-05-05**: Proposed (this commit)
+- **TBD**: Accepted after cold-cache benchmark proves <5s on typical connection
+- **TBD**: Promoted alpha β†’ latest after external validator (Liberation of Bajor team or equivalent) confirms MCP startup succeeds on cold cache
diff --git a/v3/docs/benchmarks/cli-core-cold-cache.json b/v3/docs/benchmarks/cli-core-cold-cache.json
new file mode 100644
index 0000000000..bc9edd4458
--- /dev/null
+++ b/v3/docs/benchmarks/cli-core-cold-cache.json
@@ -0,0 +1,37 @@
+{
+ "benchmark": "cli-core-vs-cli-cold-cache",
+ "issue": "#1748 #3 (30s MCP-startup timeout race)",
+ "adr": "ADR-100",
+ "runAt": "2026-05-05T13:00:00Z",
+ "host": "darwin / macOS / npm 10+",
+ "method": "rm -rf ~/.npm/_npx; time npx -y <pkg>@alpha --version (4 runs total β€” cold + warm for each package)",
+ "results": {
+ "@claude-flow/[email protected]": {
+ "packed_size_bytes": 22300,
+ "unpacked_size_bytes": 89900,
+ "files": 22,
+ "cold_cache_ms": 671,
+ "warm_cache_ms": 361,
+ "cold_warm_ratio": 1.86
+ },
+ "@claude-flow/[email protected]": {
+ "packed_size_bytes": 1800000,
+ "unpacked_size_bytes": 9600000,
+ "files": 999,
+ "cold_cache_ms": 25496,
+ "warm_cache_ms": 623,
+ "cold_warm_ratio": 40.9
+ }
+ },
+ "improvement": {
+ "cold_cache_speedup": "38Γ— (25.5s β†’ 0.67s)",
+ "fits_under_30s_mcp_startup_timeout": "yes β€” 38Γ— headroom vs cli's 25.5s which races the timeout",
+ "size_reduction_packed": "80Γ— (1.8 MB β†’ 22.3 KB)",
+ "size_reduction_files": "45Γ— (999 β†’ 22 files)"
+ },
+ "caveats": [
+ "[email protected] is foundation-only (types, output, MCP-tool types, validate-input). Does not yet expose memory/hooks command surface.",
+ "ADR-100 Β§Discovery documents that memory/hooks tools have deep ML deps requiring backend abstraction (alpha.1) and tool-definition/handler split (alpha.2) before parity is reached.",
+ "@claude-flow/cli's 25.5s cold-cache is under the 30s timeout on this connection but barely β€” slow networks would race and silently fail (the original #1748 #3 symptom)."
+ ]
+}
diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yaml
index 1514417fcf..0599ecc218 100644
--- a/v3/pnpm-lock.yaml
+++ b/v3/pnpm-lock.yaml
@@ -100,6 +100,9 @@ importers:
'@claude-flow/cli':
dependencies:
+ '@claude-flow/cli-core':
+ specifier: ^3.7.0-alpha.5
+ version: link:../cli-core
'@claude-flow/mcp':
specifier: ^3.0.0-alpha.8
version: link:../mcp
@@ -175,6 +178,8 @@ importers:
specifier: ^4.0.16
version: 4.0.16(@opentelemetry/[email protected])(@types/[email protected])
+ '@claude-flow/cli-core': {}
+
'@claude-flow/codex':
dependencies:
'@claude-flow/cli':