claude-flow 3.47.0 → 3.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/.claude/helpers/auto-memory-hook.mjs +6 -2
  2. package/.claude/helpers/learning-service.mjs +4 -2
  3. package/.claude/helpers/metrics-db.mjs +4 -2
  4. package/node_modules/@claude-flow/codex/package.json +1 -1
  5. package/node_modules/@claude-flow/mcp/dist/tool-registry.d.ts.map +1 -1
  6. package/node_modules/@claude-flow/mcp/dist/tool-registry.js +11 -3
  7. package/node_modules/@claude-flow/mcp/dist/tool-registry.js.map +1 -1
  8. package/node_modules/@claude-flow/mcp/package.json +6 -3
  9. package/node_modules/@claude-flow/plugin-agent-federation/package.json +3 -3
  10. package/node_modules/@claude-flow/security/package.json +2 -3
  11. package/package.json +7 -7
  12. package/v3/@claude-flow/cli/README.md +0 -2
  13. package/v3/@claude-flow/cli/bin/cli.js +4 -1
  14. package/v3/@claude-flow/cli/catalog-manifest.json +2 -2
  15. package/v3/@claude-flow/cli/dist/src/commands/analyze.js +2 -2
  16. package/v3/@claude-flow/cli/dist/src/commands/config.js +5 -7
  17. package/v3/@claude-flow/cli/dist/src/commands/hive-mind-worker.d.ts +88 -0
  18. package/v3/@claude-flow/cli/dist/src/commands/hive-mind-worker.js +242 -0
  19. package/v3/@claude-flow/cli/dist/src/commands/hive-mind.js +24 -41
  20. package/v3/@claude-flow/cli/dist/src/commands/hooks.js +15 -5
  21. package/v3/@claude-flow/cli/dist/src/commands/memory.js +89 -27
  22. package/v3/@claude-flow/cli/dist/src/commands/metaharness.js +1 -0
  23. package/v3/@claude-flow/cli/dist/src/commands/security.js +113 -55
  24. package/v3/@claude-flow/cli/dist/src/commands/session.js +6 -6
  25. package/v3/@claude-flow/cli/dist/src/commands/task.js +5 -4
  26. package/v3/@claude-flow/cli/dist/src/init/helpers-generator.js +4 -2
  27. package/v3/@claude-flow/cli/dist/src/mcp-server.js +10 -3
  28. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-tools.js +29 -62
  29. package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.d.ts +0 -4
  30. package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.js +139 -37
  31. package/v3/@claude-flow/cli/dist/src/mcp-tools/memory-tools.js +89 -35
  32. package/v3/@claude-flow/cli/dist/src/mcp-tools/policy-enforcer.d.ts +8 -1
  33. package/v3/@claude-flow/cli/dist/src/mcp-tools/policy-enforcer.js +80 -8
  34. package/v3/@claude-flow/cli/dist/src/mcp-tools/session-tools.js +34 -8
  35. package/v3/@claude-flow/cli/dist/src/mcp-tools/task-tools.js +73 -53
  36. package/v3/@claude-flow/cli/dist/src/memory/feedback-patterns.d.ts +13 -0
  37. package/v3/@claude-flow/cli/dist/src/memory/feedback-patterns.js +14 -0
  38. package/v3/@claude-flow/cli/dist/src/memory/live-memory-row.d.ts +3 -0
  39. package/v3/@claude-flow/cli/dist/src/memory/live-memory-row.js +5 -0
  40. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.d.ts +11 -20
  41. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.js +348 -134
  42. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.d.ts +9 -1
  43. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +41 -31
  44. package/v3/@claude-flow/cli/dist/src/ruvector/graph-analyzer.js +4 -1
  45. package/v3/@claude-flow/cli/dist/src/services/config-file-manager.js +30 -8
  46. package/v3/@claude-flow/cli/dist/src/services/memory-backup.d.ts +1 -1
  47. package/v3/@claude-flow/cli/dist/src/services/memory-backup.js +67 -27
  48. package/v3/@claude-flow/cli/dist/src/services/worker-daemon.d.ts +2 -2
  49. package/v3/@claude-flow/cli/dist/src/services/worker-daemon.js +23 -14
  50. package/v3/@claude-flow/cli/package.json +9 -9
  51. package/v3/@claude-flow/guidance/package.json +5 -6
  52. package/v3/@claude-flow/shared/package.json +6 -3
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Hive-mind worker execution: the MCP config handed to a spawned Claude, and
3
+ * `hive-mind work`, which actually runs a queued task.
4
+ *
5
+ * Before this, `hive-mind task` only wrote a `pending` row to the task store.
6
+ * Workers are records, not processes, and nothing ever claimed the row: the
7
+ * task stayed pending and the worker stayed idle forever. `work` is the missing
8
+ * consumer — claim one task, assign it to an idle hive worker, run it through
9
+ * `claude -p`, and record the outcome.
10
+ */
11
+ import { output } from '../output.js';
12
+ import { callMCPTool, MCPClientError } from '../mcp-client.js';
13
+ import { spawn as childSpawn } from 'child_process';
14
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
15
+ import { join } from 'path';
16
+ import { resolveClaudeLaunchCommand } from '../runtime/claude-command.js';
17
+ /** The server key the hive-mind prompt addresses (`mcp__ruflo__*`). */
18
+ const RUFLO_SERVER = 'ruflo';
19
+ function readServers(path, cwd) {
20
+ try {
21
+ if (!existsSync(path))
22
+ return null;
23
+ const parsed = JSON.parse(readFileSync(path, 'utf-8'));
24
+ const isMap = (v) => !!v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length > 0;
25
+ if (isMap(parsed.mcpServers))
26
+ return parsed.mcpServers;
27
+ // ~/.claude.json keeps project-scoped servers under projects[<cwd>].
28
+ const project = parsed.projects?.[cwd];
29
+ if (isMap(project?.mcpServers))
30
+ return project.mcpServers;
31
+ }
32
+ catch {
33
+ // Unreadable or not JSON: not a usable config.
34
+ }
35
+ return null;
36
+ }
37
+ /**
38
+ * The MCP config file to pass to a spawned Claude.
39
+ *
40
+ * A source file is never passed through as-is. `~/.claude.json` is Claude
41
+ * Code's whole state file; on a machine where it has no top-level
42
+ * `mcpServers` (a fresh desktop), Claude exits at startup with "Invalid MCP
43
+ * configuration: mcpServers: Invalid input", before any task can run. And a
44
+ * config lacking a `ruflo` server leaves the worker without the tools its
45
+ * prompt names. So the servers are extracted, a `ruflo` server is guaranteed,
46
+ * and the result is written as a config Claude is known to accept.
47
+ */
48
+ export function resolveWorkerMcpConfig(opts) {
49
+ if (opts.explicit)
50
+ return opts.explicit;
51
+ const candidates = [join(opts.cwd, '.mcp.json')];
52
+ if (opts.home)
53
+ candidates.push(join(opts.home, '.claude.json'), join(opts.home, '.claude', 'mcp.json'));
54
+ let servers = {};
55
+ for (const c of candidates) {
56
+ const found = readServers(c, opts.cwd);
57
+ if (found) {
58
+ servers = found;
59
+ break;
60
+ }
61
+ }
62
+ if (!servers[RUFLO_SERVER]) {
63
+ servers = {
64
+ ...servers,
65
+ [RUFLO_SERVER]: {
66
+ command: opts.rufloServer.command,
67
+ args: opts.rufloServer.args,
68
+ // The MCP server keys its stores off this, so the worker's tool calls
69
+ // land in the same task/agent stores as the CLI that dispatched it.
70
+ env: { CLAUDE_FLOW_CWD: opts.cwd },
71
+ },
72
+ };
73
+ }
74
+ mkdirSync(opts.outDir, { recursive: true });
75
+ const path = join(opts.outDir, `mcp-${opts.swarmId}.json`);
76
+ writeFileSync(path, JSON.stringify({ mcpServers: servers }, null, 2), 'utf-8');
77
+ return path;
78
+ }
79
+ /**
80
+ * The ruflo MCP server as launched by THIS cli, so a worker and the CLI that
81
+ * dispatched it share one version and one store format. `@latest` could
82
+ * resolve to a different release mid-session.
83
+ */
84
+ export function currentRufloServer() {
85
+ const entry = process.argv[1];
86
+ return entry
87
+ ? { command: process.execPath, args: [entry, 'mcp', 'start'] }
88
+ : { command: 'npx', args: ['-y', '@claude-flow/cli@latest', 'mcp', 'start'] };
89
+ }
90
+ /** Run one prompt through `claude -p` and parse its JSON result. */
91
+ export const runWithClaude = (prompt, opts) => new Promise((resolve) => {
92
+ const started = Date.now();
93
+ const launch = resolveClaudeLaunchCommand();
94
+ if (!launch) {
95
+ resolve({ ok: false, output: 'Claude Code CLI not found in PATH', exitCode: null, durationMs: 0 });
96
+ return;
97
+ }
98
+ // The prompt goes on stdin, not argv: a task description has no length
99
+ // bound and `--mcp-config` is variadic (#1780).
100
+ const child = childSpawn(launch.command, [...launch.argsPrefix, '-p', '--output-format', 'json', `--mcp-config=${opts.mcpConfig}`], { cwd: opts.cwd, stdio: ['pipe', 'pipe', 'pipe'] });
101
+ let stdout = '';
102
+ let stderr = '';
103
+ child.stdout.on('data', (d) => (stdout += d));
104
+ child.stderr.on('data', (d) => (stderr += d));
105
+ const timer = setTimeout(() => child.kill('SIGTERM'), opts.timeoutMs);
106
+ child.on('error', (e) => {
107
+ clearTimeout(timer);
108
+ resolve({ ok: false, output: e.message, exitCode: null, durationMs: Date.now() - started });
109
+ });
110
+ child.on('close', (code, signal) => {
111
+ clearTimeout(timer);
112
+ const durationMs = Date.now() - started;
113
+ try {
114
+ const r = JSON.parse(stdout);
115
+ resolve({
116
+ ok: code === 0 && !r.is_error,
117
+ output: r.result ?? '',
118
+ exitCode: code,
119
+ sessionId: r.session_id,
120
+ costUsd: r.total_cost_usd,
121
+ durationMs,
122
+ });
123
+ }
124
+ catch {
125
+ const why = signal === 'SIGTERM' ? `timed out after ${opts.timeoutMs}ms` : (stderr || stdout).trim().slice(-2000);
126
+ resolve({ ok: false, output: why, exitCode: code, durationMs });
127
+ }
128
+ });
129
+ child.stdin.end(prompt);
130
+ });
131
+ function timeoutFromTags(tags, fallback) {
132
+ const tag = tags?.find((t) => /^timeout:\d+s$/.test(t));
133
+ return tag ? Number(tag.slice('timeout:'.length, -1)) * 1000 : fallback;
134
+ }
135
+ /**
136
+ * One dispatch cycle: the oldest pending hive task goes to an idle hive worker,
137
+ * runs, and its outcome is recorded on the task. Every state change goes
138
+ * through the MCP task tools, so the store is the same one `hive-mind status`
139
+ * and `task status` read.
140
+ */
141
+ export async function workOnce(opts) {
142
+ let taskId = opts.taskId;
143
+ if (!taskId) {
144
+ const listed = await callMCPTool('task_list', { status: 'pending', type: 'hive-mind', limit: 1000 });
145
+ const oldest = [...(listed.tasks ?? [])].sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
146
+ if (!oldest)
147
+ return { dispatched: false, reason: 'No pending hive-mind tasks' };
148
+ taskId = oldest.taskId;
149
+ }
150
+ const task = await callMCPTool('task_status', { taskId });
151
+ if (task.status !== 'pending') {
152
+ return { dispatched: false, reason: `Task ${taskId} is ${task.status}, not pending` };
153
+ }
154
+ let workerId = opts.workerId;
155
+ if (!workerId) {
156
+ const hive = await callMCPTool('hive-mind_status', {});
157
+ workerId = hive.workers?.find((w) => w.status === 'idle')?.id;
158
+ if (!workerId)
159
+ return { dispatched: false, reason: 'No idle hive worker — run "hive-mind spawn" first' };
160
+ }
161
+ await callMCPTool('task_assign', { taskId, agentIds: [workerId] });
162
+ const prompt = `You are hive-mind worker ${workerId}. Complete this task, then reply with ` +
163
+ `the result only.\n\nTask ${taskId}:\n${task.description}`;
164
+ const outcome = await opts.runner(prompt, {
165
+ mcpConfig: opts.mcpConfig,
166
+ timeoutMs: timeoutFromTags(task.tags, opts.defaultTimeoutMs ?? 300_000),
167
+ cwd: opts.cwd,
168
+ });
169
+ const result = {
170
+ worker: workerId,
171
+ output: outcome.output,
172
+ exitCode: outcome.exitCode,
173
+ durationMs: outcome.durationMs,
174
+ ...(outcome.sessionId ? { sessionId: outcome.sessionId } : {}),
175
+ ...(outcome.costUsd !== undefined ? { costUsd: outcome.costUsd } : {}),
176
+ };
177
+ if (outcome.ok) {
178
+ await callMCPTool('task_complete', { taskId, result });
179
+ return { dispatched: true, taskId, workerId, status: 'completed', outcome };
180
+ }
181
+ await callMCPTool('task_update', { taskId, status: 'failed', result });
182
+ return { dispatched: true, taskId, workerId, status: 'failed', outcome };
183
+ }
184
+ export const workCommand = {
185
+ name: 'work',
186
+ description: 'Run the next pending hive task on an idle worker via Claude Code and record the result',
187
+ options: [
188
+ { name: 'task', description: 'Run this task id instead of the oldest pending one', type: 'string' },
189
+ { name: 'worker', description: 'Assign to this worker id instead of the first idle one', type: 'string' },
190
+ { name: 'mcp-config', description: 'MCP config for the worker (default: generated, with the ruflo server)', type: 'string' },
191
+ ],
192
+ examples: [
193
+ { command: 'claude-flow hive-mind work', description: 'Run the oldest pending hive task' },
194
+ { command: 'claude-flow hive-mind work --task task-123', description: 'Run a specific task' },
195
+ ],
196
+ action: async (ctx) => {
197
+ const cwd = ctx.cwd || process.cwd();
198
+ try {
199
+ const mcpConfig = resolveWorkerMcpConfig({
200
+ explicit: ctx.flags.mcpConfig,
201
+ cwd,
202
+ home: process.env.HOME || process.env.USERPROFILE || '',
203
+ outDir: join(cwd, '.hive-mind', 'sessions'),
204
+ swarmId: 'worker',
205
+ rufloServer: currentRufloServer(),
206
+ });
207
+ const r = await workOnce({
208
+ cwd,
209
+ mcpConfig,
210
+ runner: runWithClaude,
211
+ taskId: ctx.flags.task,
212
+ workerId: ctx.flags.worker,
213
+ });
214
+ if (ctx.flags.format === 'json') {
215
+ output.printJson(r);
216
+ }
217
+ else if (!r.dispatched) {
218
+ output.printInfo(r.reason);
219
+ }
220
+ else {
221
+ output.printBox([
222
+ `Task ID: ${r.taskId}`,
223
+ `Worker: ${r.workerId}`,
224
+ `Status: ${r.status}`,
225
+ `Duration: ${r.outcome.durationMs}ms`,
226
+ '',
227
+ r.outcome.output.slice(0, 2000),
228
+ ].join('\n'), r.status === 'completed' ? 'Task Completed' : 'Task Failed');
229
+ output.writeln(output.dim(` Full record: claude-flow task status ${r.taskId}`));
230
+ }
231
+ // Nothing to do is not an error; a task that ran and failed is.
232
+ const failed = r.dispatched && r.status === 'failed';
233
+ return { success: !failed, exitCode: failed ? 1 : 0, data: r };
234
+ }
235
+ catch (error) {
236
+ const msg = error instanceof MCPClientError ? error.message : String(error);
237
+ output.printError(`Work error: ${msg}`);
238
+ return { success: false, exitCode: 1 };
239
+ }
240
+ },
241
+ };
242
+ //# sourceMappingURL=hive-mind-worker.js.map
@@ -10,7 +10,7 @@ import { select, confirm, input } from '../prompt.js';
10
10
  import { callMCPTool, MCPClientError } from '../mcp-client.js';
11
11
  import { spawn as childSpawn } from 'child_process';
12
12
  import { mkdir, writeFile } from 'fs/promises';
13
- import { existsSync } from 'fs';
13
+ import { resolveWorkerMcpConfig, currentRufloServer, workCommand } from './hive-mind-worker.js';
14
14
  import { join } from 'path';
15
15
  import { resolveClaudeLaunchCommand } from '../runtime/claude-command.js';
16
16
  import { getHiveTokenForCli } from '../mcp-tools/hive-mind-tools.js';
@@ -202,44 +202,25 @@ async function spawnClaudeCodeInstance(swarmId, swarmName, objective, workers, f
202
202
  // Build arguments - flags first, then prompt
203
203
  const claudeArgs = [];
204
204
  // #1748 Issue 2 — pass --mcp-config so the spawned worker actually has
205
- // mcp__ruflo__* tools registered. Before this, the coordination prompt
206
- // referenced tools the worker didn't know about and exited silently.
207
- // Resolution order:
208
- // 1. explicit --mcp-config <path> flag passed by the caller
209
- // 2. ./.mcp.json in cwd (project-local Ruflo MCP config)
210
- // 3. ~/.claude.json or ~/.claude/mcp.json (user-global)
211
- // If none found, we still spawn but warn — that's the pre-fix behavior
212
- // and the user's debug log will surface the missing tools.
213
- const explicitMcpConfig = flags['mcp-config'];
214
- let mcpConfigPath = explicitMcpConfig;
215
- if (!mcpConfigPath) {
216
- const candidates = [
217
- join(process.cwd(), '.mcp.json'),
218
- join(process.env.HOME || process.env.USERPROFILE || '', '.claude.json'),
219
- join(process.env.HOME || process.env.USERPROFILE || '', '.claude', 'mcp.json'),
220
- ];
221
- for (const c of candidates) {
222
- try {
223
- if (c && existsSync(c)) {
224
- mcpConfigPath = c;
225
- break;
226
- }
227
- }
228
- catch { /* continue */ }
229
- }
230
- }
231
- if (mcpConfigPath) {
232
- // #1780 — Claude Code's `--mcp-config` is variadic; passing it as two
233
- // argv tokens (`--mcp-config`, `<path>`) lets a later positional (the
234
- // hive-mind prompt) be slurped as a second config file, producing
235
- // `ENAMETOOLONG: name too long, open` once the prompt exceeds PATH_MAX.
236
- // Use `=`-syntax so the flag stays attached to its single value.
237
- claudeArgs.push(`--mcp-config=${mcpConfigPath}`);
238
- output.printInfo(`Spawned worker MCP config: ${mcpConfigPath}`);
239
- }
240
- else {
241
- output.printWarning('No .mcp.json or ~/.claude.json found — spawned worker will not have mcp__ruflo__* tools (#1748 Issue 2). Pass --mcp-config <path> or run "ruflo init" to generate one.');
242
- }
205
+ // mcp__ruflo__* tools registered. The config is always a generated file
206
+ // that Claude accepts; see resolveWorkerMcpConfig for why a source
207
+ // config (notably ~/.claude.json) is never passed through as-is.
208
+ // The parser stores flags camelCased (#2269), so read both forms.
209
+ const mcpConfigPath = resolveWorkerMcpConfig({
210
+ explicit: (flags['mcp-config'] ?? flags.mcpConfig),
211
+ cwd: process.cwd(),
212
+ home: process.env.HOME || process.env.USERPROFILE || '',
213
+ outDir: sessionsDir,
214
+ swarmId,
215
+ rufloServer: currentRufloServer(),
216
+ });
217
+ // #1780 — Claude Code's `--mcp-config` is variadic; passing it as two
218
+ // argv tokens (`--mcp-config`, `<path>`) lets a later positional (the
219
+ // hive-mind prompt) be slurped as a second config file, producing
220
+ // `ENAMETOOLONG: name too long, open` once the prompt exceeds PATH_MAX.
221
+ // Use `=`-syntax so the flag stays attached to its single value.
222
+ claudeArgs.push(`--mcp-config=${mcpConfigPath}`);
223
+ output.printInfo(`Spawned worker MCP config: ${mcpConfigPath}`);
243
224
  // Check for non-interactive mode
244
225
  const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;
245
226
  if (isNonInteractive) {
@@ -882,7 +863,8 @@ const taskCommand = {
882
863
  ].join('\n'), 'Task Submitted');
883
864
  output.writeln();
884
865
  output.printSuccess('Task submitted to hive');
885
- output.writeln(output.dim(` Track with: claude-flow hive-mind task-status ${result.taskId}`));
866
+ output.writeln(output.dim(` Run it with: claude-flow hive-mind work --task ${result.taskId}`));
867
+ output.writeln(output.dim(` Track with: claude-flow task status ${result.taskId}`));
886
868
  return { success: true, data: result };
887
869
  }
888
870
  catch (error) {
@@ -1210,7 +1192,7 @@ export const hiveMindCommand = {
1210
1192
  name: 'hive-mind',
1211
1193
  aliases: ['hive'],
1212
1194
  description: 'Queen-led consensus-based multi-agent coordination',
1213
- subcommands: [initCommand, spawnCommand, statusCommand, taskCommand, joinCommand, leaveCommand, consensusCommand, broadcastCommand, memorySubCommand, optimizeMemoryCommand, shutdownCommand],
1195
+ subcommands: [initCommand, spawnCommand, statusCommand, taskCommand, workCommand, joinCommand, leaveCommand, consensusCommand, broadcastCommand, memorySubCommand, optimizeMemoryCommand, shutdownCommand],
1214
1196
  options: [],
1215
1197
  examples: [
1216
1198
  { command: 'claude-flow hive-mind init -t hierarchical-mesh', description: 'Initialize hive' },
@@ -1230,6 +1212,7 @@ export const hiveMindCommand = {
1230
1212
  `${output.highlight('spawn')} - Spawn worker agents (use --claude to launch Claude Code)`,
1231
1213
  `${output.highlight('status')} - Show hive status`,
1232
1214
  `${output.highlight('task')} - Submit task to hive`,
1215
+ `${output.highlight('work')} - Run the next pending task on an idle worker`,
1233
1216
  `${output.highlight('join')} - Join an agent to the hive`,
1234
1217
  `${output.highlight('leave')} - Remove an agent from the hive`,
1235
1218
  `${output.highlight('consensus')} - Manage consensus proposals`,
@@ -1,7 +1,4 @@
1
- /**
2
- * V3 CLI Hooks Command
3
- * Self-learning hooks system for intelligent workflow automation
4
- */
1
+ import { validateFeedbackPatterns } from '../memory/feedback-patterns.js';
5
2
  import { output } from '../output.js';
6
3
  import { confirm } from '../prompt.js';
7
4
  import { callMCPTool, MCPClientError } from '../mcp-client.js';
@@ -572,6 +569,11 @@ const postCommandCommand = {
572
569
  short: 'd',
573
570
  description: 'Execution duration in milliseconds',
574
571
  type: 'number'
572
+ },
573
+ {
574
+ name: 'ttl',
575
+ description: 'Command history lifetime in seconds (default: 30 days)',
576
+ type: 'number'
575
577
  }
576
578
  ],
577
579
  examples: [
@@ -594,11 +596,16 @@ const postCommandCommand = {
594
596
  success,
595
597
  exitCode: ctx.flags.exitCode || 0,
596
598
  duration: ctx.flags.duration,
599
+ ttl: ctx.flags.ttl,
597
600
  timestamp: Date.now(),
598
601
  });
599
602
  if (ctx.flags.format === 'json') {
600
603
  output.printJson(result);
601
- return { success: true, data: result };
604
+ return { success: result.recorded, exitCode: result.recorded ? 0 : 1, data: result };
605
+ }
606
+ if (!result.recorded) {
607
+ output.printError('Command outcome could not be recorded');
608
+ return { success: false, exitCode: 1, data: result };
602
609
  }
603
610
  output.writeln();
604
611
  output.printSuccess('Command outcome recorded');
@@ -1699,6 +1706,7 @@ const postTaskCommand = {
1699
1706
  name: 'post-task',
1700
1707
  description: 'Record task completion for learning',
1701
1708
  options: [
1709
+ { name: 'patterns', description: 'JSON array of learned pattern strings for feedback and skill creation', type: 'string' },
1702
1710
  {
1703
1711
  name: 'task-id',
1704
1712
  short: 'i',
@@ -1784,8 +1792,10 @@ const postTaskCommand = {
1784
1792
  const success = ctx.flags.success !== undefined ? ctx.flags.success : true;
1785
1793
  output.printInfo(`Recording outcome for task: ${output.highlight(taskId)}`);
1786
1794
  try {
1795
+ const patterns = validateFeedbackPatterns(ctx.flags.patterns === undefined ? undefined : JSON.parse(ctx.flags.patterns));
1787
1796
  const result = await callMCPTool('hooks_post-task', {
1788
1797
  taskId,
1798
+ patterns,
1789
1799
  success,
1790
1800
  quality: ctx.flags.quality,
1791
1801
  agent: ctx.flags.agent,
@@ -9,6 +9,8 @@ import { distillCommand } from './memory-distill.js';
9
9
  import { backupCommand } from './memory-backup.js';
10
10
  import { countSiblingStoreRows } from '../memory/sibling-store.js';
11
11
  import { resolveDbPath } from '../memory/memory-initializer.js';
12
+ import { existsSync } from 'node:fs';
13
+ import { siblingAgentDbPath } from '../memory/memory-bridge.js';
12
14
  /**
13
15
  * #3228: a miss in one store is not a miss in the memory.
14
16
  *
@@ -26,6 +28,24 @@ async function warnIfSiblingHasRows(pathFlag) {
26
28
  `That store is written by the MCP/AgentDB path; read it with --path ${unread.path}.`);
27
29
  }
28
30
  }
31
+ /** Default CLI writes may be mirrored into AgentDB; remove both copies. */
32
+ function removalDbTargets(pathFlag) {
33
+ const primary = resolveDbPath(pathFlag);
34
+ // An explicit file selection is a single-store operation, as documented by
35
+ // --path. Do not widen a caller's requested destructive scope.
36
+ if (pathFlag || process.env.CLAUDE_FLOW_DB_PATH)
37
+ return [{ dbPath: primary }];
38
+ const sibling = siblingAgentDbPath(primary);
39
+ // The AgentDB mirror is consumed by native SQLite and must stay plaintext.
40
+ // Pass this per operation, including preview migrations; never toggle the
41
+ // process encryption setting while asynchronous operations are in flight.
42
+ const targets = [
43
+ { dbPath: primary },
44
+ ...(sibling ? [{ dbPath: sibling, encryptWrites: false }] : []),
45
+ ].filter(target => existsSync(target.dbPath));
46
+ // Preserve the existing missing-database error when neither store exists.
47
+ return targets.length ? targets : [{ dbPath: primary }];
48
+ }
29
49
  // Memory backends
30
50
  const BACKENDS = [
31
51
  { value: 'agentdb', label: 'AgentDB', hint: 'Vector database with HNSW indexing (150x-12,500x faster)' },
@@ -820,7 +840,7 @@ function formatRelativeTime(isoDate) {
820
840
  const deleteCommand = {
821
841
  name: 'delete',
822
842
  aliases: ['rm'],
823
- description: 'Delete memory entry',
843
+ description: 'Delete a memory entry from the default store and its AgentDB mirror (use --path to select one store)',
824
844
  options: [
825
845
  {
826
846
  name: 'key',
@@ -870,16 +890,24 @@ const deleteCommand = {
870
890
  }
871
891
  // Use sql.js directly for consistent data access (Issue #980)
872
892
  try {
873
- const { deleteEntry, resolveDbPath: _rdbDelete } = await import('../memory/memory-initializer.js');
874
- const dbPathDelete = _rdbDelete(ctx.flags.path);
875
- const result = await deleteEntry({ key, namespace, dbPath: dbPathDelete });
876
- if (!result.success) {
877
- output.printError(result.error || 'Failed to delete');
878
- return { success: false, exitCode: 1 };
893
+ const { deleteEntry } = await import('../memory/memory-initializer.js');
894
+ const paths = removalDbTargets(ctx.flags.path);
895
+ const stores = [];
896
+ for (const target of paths) {
897
+ const { dbPath } = target;
898
+ const entry = await deleteEntry({ key, namespace, ...target });
899
+ if (!entry.success)
900
+ throw new Error(`${dbPath}: ${entry.error || 'Failed to delete'}`);
901
+ stores.push({ dbPath, ...entry });
879
902
  }
903
+ const result = {
904
+ success: true, key, namespace, stores,
905
+ deleted: stores.some(entry => entry.deleted),
906
+ remainingEntries: stores.reduce((total, entry) => total + entry.remainingEntries, 0),
907
+ };
880
908
  if (result.deleted) {
881
909
  output.printSuccess(`Deleted "${key}" from namespace "${namespace}"`);
882
- output.printInfo(`Remaining entries: ${result.remainingEntries}`);
910
+ output.printInfo(`Remaining entries across ${paths.length} store(s): ${result.remainingEntries}`);
883
911
  }
884
912
  else {
885
913
  output.printWarning(`Key not found: "${key}" in namespace "${namespace}"`);
@@ -901,7 +929,7 @@ const deleteCommand = {
901
929
  // either interactive confirmation or --force.
902
930
  const purgeCommand = {
903
931
  name: 'purge',
904
- description: 'Permanently delete every entry in a namespace (hard delete — not the soft delete/tombstone that `memory delete` uses)',
932
+ description: 'Permanently delete a namespace from the default store and its AgentDB mirror (use --path to select one store)',
905
933
  options: [
906
934
  {
907
935
  name: 'namespace',
@@ -939,17 +967,22 @@ const purgeCommand = {
939
967
  return { success: false, exitCode: 1 };
940
968
  }
941
969
  try {
942
- const { listEntries, purgeNamespace, resolveDbPath: _rdbPurge } = await import('../memory/memory-initializer.js');
943
- const resolvedDbPath = _rdbPurge(dbPath);
944
- const preview = await listEntries({ namespace, limit: 1, dbPath: resolvedDbPath });
945
- const previewCount = preview.total ?? preview.entries?.length ?? 0;
970
+ const { listEntries, purgeNamespace } = await import('../memory/memory-initializer.js');
971
+ const paths = removalDbTargets(dbPath);
972
+ let previewCount = 0;
973
+ for (const target of paths) {
974
+ const preview = await listEntries({ namespace, limit: 1, ...target });
975
+ if (!preview.success)
976
+ throw new Error(`${target.dbPath}: ${preview.error || 'Failed to read purge target'}`);
977
+ previewCount += preview.total ?? preview.entries?.length ?? 0;
978
+ }
946
979
  if (dryRun) {
947
- output.printInfo(`Would permanently delete ${previewCount} entr${previewCount === 1 ? 'y' : 'ies'} from namespace "${namespace}" (dry run — nothing deleted)`);
980
+ output.printInfo(`Would permanently delete ${previewCount} entr${previewCount === 1 ? 'y' : 'ies'} from namespace "${namespace}" across ${paths.length} store(s) (dry run — nothing deleted)`);
948
981
  return { success: true, data: { namespace, wouldDelete: previewCount } };
949
982
  }
950
983
  if (!force && ctx.interactive) {
951
984
  const confirmed = await confirm({
952
- message: `Permanently delete ${previewCount} entr${previewCount === 1 ? 'y' : 'ies'} from namespace "${namespace}"? This is a hard delete — not reversible with \`memory delete\`'s soft-undo.`,
985
+ message: `Permanently delete ${previewCount} entr${previewCount === 1 ? 'y' : 'ies'} from namespace "${namespace}" across ${paths.length} store(s)? This is a hard delete — not reversible with \`memory delete\`'s soft-undo.`,
953
986
  default: false
954
987
  });
955
988
  if (!confirmed) {
@@ -961,13 +994,20 @@ const purgeCommand = {
961
994
  output.printError(`Refusing to purge namespace "${namespace}" without --force in non-interactive mode`);
962
995
  return { success: false, exitCode: 1 };
963
996
  }
964
- const result = await purgeNamespace({ namespace, dbPath: resolvedDbPath });
965
- if (!result.success) {
966
- output.printError(result.error || 'Failed to purge');
967
- return { success: false, exitCode: 1 };
997
+ const stores = [];
998
+ for (const target of paths) {
999
+ const purged = await purgeNamespace({ namespace, ...target });
1000
+ if (!purged.success)
1001
+ throw new Error(`${target.dbPath}: ${purged.error || 'Failed to purge'}`);
1002
+ stores.push({ dbPath: target.dbPath, ...purged });
968
1003
  }
1004
+ const result = {
1005
+ success: true, stores,
1006
+ deletedCount: stores.reduce((total, store) => total + store.deletedCount, 0),
1007
+ remainingEntries: stores.reduce((total, store) => total + store.remainingEntries, 0),
1008
+ };
969
1009
  output.printSuccess(`Purged ${result.deletedCount} entr${result.deletedCount === 1 ? 'y' : 'ies'} from namespace "${namespace}"`);
970
- output.printInfo(`Remaining entries (all namespaces): ${result.remainingEntries}`);
1010
+ output.printInfo(`Remaining entries (all namespaces, ${paths.length} store(s)): ${result.remainingEntries}`);
971
1011
  return { success: true, data: result };
972
1012
  }
973
1013
  catch (error) {
@@ -984,8 +1024,16 @@ const statsCommand = {
984
1024
  action: async (ctx) => {
985
1025
  // Call MCP memory/stats tool for real statistics
986
1026
  try {
987
- const statsResult = await callMCPTool('memory_stats', {});
1027
+ const dbPath = resolveDbPath(ctx.flags.path);
1028
+ const statsResult = await callMCPTool('memory_stats', { dbPath });
1029
+ if (statsResult.available === false) {
1030
+ output.printError(`Failed to get stats: ${statsResult.error || 'Store unavailable'}`);
1031
+ return { success: false, exitCode: 1 };
1032
+ }
1033
+ const unreadStore = await countSiblingStoreRows(dbPath);
988
1034
  const stats = {
1035
+ ...(unreadStore ? { unreadStore } : {}),
1036
+ ...(statsResult.truncated ? { truncated: true } : {}),
989
1037
  backend: statsResult.backend,
990
1038
  entries: {
991
1039
  total: statsResult.totalEntries,
@@ -993,7 +1041,7 @@ const statsCommand = {
993
1041
  text: statsResult.totalEntries
994
1042
  },
995
1043
  storage: {
996
- total: statsResult.totalSize,
1044
+ total: statsResult.totalSize ?? 'unknown',
997
1045
  location: statsResult.location
998
1046
  },
999
1047
  version: statsResult.version,
@@ -1004,6 +1052,9 @@ const statsCommand = {
1004
1052
  output.printJson(stats);
1005
1053
  return { success: true, data: stats };
1006
1054
  }
1055
+ if (unreadStore) {
1056
+ output.printWarning(`${unreadStore.rows} entries are in ${unreadStore.path} and were not read here. Read them with --path ${unreadStore.path}.`);
1057
+ }
1007
1058
  output.writeln();
1008
1059
  output.writeln(output.bold('Memory Statistics'));
1009
1060
  output.writeln();
@@ -1245,19 +1296,27 @@ const cleanupCommand = {
1245
1296
  { command: 'claude-flow memory cleanup --expired-only', description: 'Clean expired entries' }
1246
1297
  ],
1247
1298
  action: async (ctx) => {
1248
- const dryRun = ctx.flags.dryRun;
1249
- const force = ctx.flags.force;
1299
+ const dryRun = ctx.flags.dryRun === true;
1300
+ const force = ctx.flags.force === true;
1301
+ if (ctx.flags.format === 'json' && !dryRun && !force) {
1302
+ output.printJson({ success: false, error: 'Use --dry-run to preview or --force to authorize cleanup with --format json.' });
1303
+ return { success: false, exitCode: 1 };
1304
+ }
1250
1305
  if (dryRun) {
1251
1306
  output.writeln(output.warning('DRY RUN - No changes will be made'));
1252
1307
  }
1253
1308
  output.printInfo('Analyzing memory for cleanup...');
1254
1309
  try {
1255
- const result = await callMCPTool('memory_cleanup', {
1256
- dryRun,
1310
+ const selectors = {
1257
1311
  olderThan: ctx.flags.olderThan,
1258
1312
  expiredOnly: ctx.flags.expiredOnly,
1259
1313
  lowQualityThreshold: ctx.flags.lowQuality,
1260
1314
  namespace: ctx.flags.namespace,
1315
+ };
1316
+ // Preview before asking: dryRun:false executes deletion inside the tool.
1317
+ let result = await callMCPTool('memory_cleanup', {
1318
+ ...selectors,
1319
+ dryRun: dryRun || !force,
1261
1320
  });
1262
1321
  if (ctx.flags.format === 'json') {
1263
1322
  output.printJson(result);
@@ -1286,6 +1345,7 @@ const cleanupCommand = {
1286
1345
  output.printInfo('Cleanup cancelled');
1287
1346
  return { success: true, data: result };
1288
1347
  }
1348
+ result = await callMCPTool('memory_cleanup', { ...selectors, dryRun: false });
1289
1349
  }
1290
1350
  if (!dryRun) {
1291
1351
  output.writeln();
@@ -1525,7 +1585,8 @@ const importCommand = {
1525
1585
  short: 'n',
1526
1586
  description: 'Import into specific namespace',
1527
1587
  type: 'string'
1528
- }
1588
+ },
1589
+ DB_PATH_OPTION
1529
1590
  ],
1530
1591
  examples: [
1531
1592
  { command: 'claude-flow memory import -i ./backup.json', description: 'Import from file' },
@@ -1543,6 +1604,7 @@ const importCommand = {
1543
1604
  inputPath,
1544
1605
  merge: ctx.flags.merge ?? true,
1545
1606
  namespace: ctx.flags.namespace,
1607
+ dbPath: resolveDbPath(ctx.flags.path),
1546
1608
  });
1547
1609
  output.printSuccess(`Imported from ${result.inputPath}`);
1548
1610
  output.printList([
@@ -279,6 +279,7 @@ export const metaharnessCommand = {
279
279
  'verbose', 'v',
280
280
  'quiet', 'q',
281
281
  'help', 'h',
282
+ 'interactive', 'i', // CLI-only default; plugin scripts are non-interactive
282
283
  ]);
283
284
  // Parser normalizes kebab-case → camelCase (--per-dimension → perDimension).
284
285
  // Plugin scripts expect kebab-case at argv, so we re-kebab here.