moflo 4.8.42 → 4.8.44

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.
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Shared dependency resolver for moflo bin scripts.
3
+ * Resolves packages from moflo's own node_modules (not the consuming project's).
4
+ * On Windows, converts native paths to file:// URLs required by ESM import().
5
+ */
6
+
7
+ import { createRequire } from 'module';
8
+ import { fileURLToPath, pathToFileURL } from 'url';
9
+
10
+ const __require = createRequire(fileURLToPath(import.meta.url));
11
+
12
+ export function mofloResolveURL(specifier) {
13
+ return pathToFileURL(__require.resolve(specifier)).href;
14
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Shared background process manager for moflo.
3
+ *
4
+ * All background spawn paths (hooks.mjs, hook-handler.cjs, session-start-launcher.mjs)
5
+ * delegate here so that PID tracking, dedup, and cleanup happen in one place.
6
+ *
7
+ * API:
8
+ * spawn(cmd, args, label) — spawn with label-based dedup + PID tracking
9
+ * killAll() — SIGTERM every tracked process, prune registry
10
+ * getActive() — list currently alive tracked processes
11
+ * prune() — remove dead entries from registry
12
+ *
13
+ * Registry: .claude-flow/background-pids.json
14
+ * Lock: .claude-flow/spawn.lock (30 s TTL — prevents thundering-herd)
15
+ */
16
+
17
+ import { spawn } from 'child_process';
18
+ import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync, unlinkSync, statSync, openSync, closeSync } from 'fs';
19
+ import { resolve, dirname } from 'path';
20
+ import { fileURLToPath } from 'url';
21
+
22
+ const __filename = fileURLToPath(import.meta.url);
23
+ const __dirname = dirname(__filename);
24
+
25
+ const LOCK_TTL_MS = 30_000;
26
+
27
+ /** Resolve the project root (two levels up from bin/lib/). */
28
+ function defaultRoot() {
29
+ return resolve(__dirname, '../..');
30
+ }
31
+
32
+ /** Ensure .claude-flow/ directory exists. */
33
+ function ensureDir(dir) {
34
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
35
+ }
36
+
37
+ /** Check if a PID is alive (cross-platform). */
38
+ function isAlive(pid) {
39
+ try {
40
+ process.kill(pid, 0);
41
+ return true;
42
+ } catch {
43
+ return false;
44
+ }
45
+ }
46
+
47
+ // ── Registry I/O ────────────────────────────────────────────────────────────
48
+
49
+ function registryPath(root) {
50
+ return resolve(root, '.claude-flow', 'background-pids.json');
51
+ }
52
+
53
+ function lockPath(root) {
54
+ return resolve(root, '.claude-flow', 'spawn.lock');
55
+ }
56
+
57
+ function readRegistry(root) {
58
+ const p = registryPath(root);
59
+ if (!existsSync(p)) return [];
60
+ try {
61
+ const parsed = JSON.parse(readFileSync(p, 'utf-8'));
62
+ return Array.isArray(parsed) ? parsed : [];
63
+ } catch {
64
+ return [];
65
+ }
66
+ }
67
+
68
+ /** Atomic write: write to tmp file then rename to avoid torn reads. */
69
+ function writeRegistry(root, entries) {
70
+ const p = registryPath(root);
71
+ const tmp = p + '.tmp.' + process.pid;
72
+ ensureDir(dirname(p));
73
+ writeFileSync(tmp, JSON.stringify(entries, null, 2));
74
+ renameSync(tmp, p);
75
+ }
76
+
77
+ // ── Lock (30 s TTL) ────────────────────────────────────────────────────────
78
+
79
+ function checkLock(root) {
80
+ const lp = lockPath(root);
81
+ if (!existsSync(lp)) return false;
82
+ try {
83
+ const age = Date.now() - statSync(lp).mtimeMs;
84
+ return age < LOCK_TTL_MS;
85
+ } catch {
86
+ return false;
87
+ }
88
+ }
89
+
90
+ /** Atomic lock acquisition using exclusive-create flag. */
91
+ function writeLock(root) {
92
+ const lp = lockPath(root);
93
+ ensureDir(dirname(lp));
94
+ try {
95
+ writeFileSync(lp, String(Date.now()), { flag: 'wx' });
96
+ } catch {
97
+ // File already exists — overwrite if stale, otherwise skip
98
+ try {
99
+ const age = Date.now() - statSync(lp).mtimeMs;
100
+ if (age >= LOCK_TTL_MS) {
101
+ unlinkSync(lp);
102
+ writeFileSync(lp, String(Date.now()), { flag: 'wx' });
103
+ }
104
+ } catch { /* lost race on stale cleanup — non-fatal */ }
105
+ }
106
+ }
107
+
108
+ function clearLock(root) {
109
+ const lp = lockPath(root);
110
+ try {
111
+ if (existsSync(lp)) unlinkSync(lp);
112
+ } catch { /* non-fatal */ }
113
+ }
114
+
115
+ // ── Public API ──────────────────────────────────────────────────────────────
116
+
117
+ /**
118
+ * Create a ProcessManager bound to a project root.
119
+ * @param {string} [root] — project root (defaults to two levels above bin/lib/)
120
+ */
121
+ export function createProcessManager(root) {
122
+ const projectRoot = root || defaultRoot();
123
+
124
+ return {
125
+ /**
126
+ * Spawn a background process with label-based dedup and PID tracking.
127
+ *
128
+ * If a process with the same `label` is already alive, the spawn is skipped.
129
+ *
130
+ * @param {string} cmd — executable (e.g. 'node')
131
+ * @param {string[]} args — arguments
132
+ * @param {string} label — unique label for dedup (e.g. 'index-guidance')
133
+ * @returns {{ pid: number|null, skipped: boolean }}
134
+ */
135
+ spawn(cmd, args, label) {
136
+ // Dedup: skip if same label is already alive
137
+ const entries = readRegistry(projectRoot);
138
+ const existing = entries.find(e => e.label === label);
139
+ if (existing && isAlive(existing.pid)) {
140
+ return { pid: existing.pid, skipped: true };
141
+ }
142
+
143
+ try {
144
+ // Redirect background process output to log file instead of /dev/null
145
+ // This ensures errors from background indexers/pretrain are captured
146
+ let stdio = 'ignore';
147
+ try {
148
+ const swarmDir = resolve(projectRoot, '.swarm');
149
+ ensureDir(swarmDir);
150
+ const logPath = resolve(swarmDir, 'background.log');
151
+ const fd = openSync(logPath, 'a');
152
+ stdio = ['ignore', fd, fd];
153
+ } catch {
154
+ // Fall back to ignore if log file can't be opened
155
+ }
156
+
157
+ const proc = spawn(cmd, args, {
158
+ cwd: projectRoot,
159
+ stdio,
160
+ detached: true,
161
+ shell: false,
162
+ windowsHide: true,
163
+ });
164
+
165
+ // Swallow async spawn errors (e.g. ENOENT for bad command)
166
+ proc.on('error', () => {});
167
+ proc.unref();
168
+
169
+ if (proc.pid) {
170
+ // Remove any stale entry with the same label, then append new
171
+ const fresh = entries.filter(e => e.label !== label);
172
+ fresh.push({
173
+ pid: proc.pid,
174
+ label,
175
+ cmd: `${cmd} ${args.join(' ')}`.substring(0, 200),
176
+ startedAt: new Date().toISOString(),
177
+ });
178
+ writeRegistry(projectRoot, fresh);
179
+ }
180
+
181
+ return { pid: proc.pid || null, skipped: false };
182
+ } catch {
183
+ return { pid: null, skipped: false };
184
+ }
185
+ },
186
+
187
+ /**
188
+ * Kill all tracked background processes.
189
+ * @returns {{ killed: number, total: number }}
190
+ */
191
+ killAll() {
192
+ const entries = readRegistry(projectRoot);
193
+ let killed = 0;
194
+
195
+ for (const entry of entries) {
196
+ if (!isAlive(entry.pid)) continue;
197
+ try {
198
+ process.kill(entry.pid, 'SIGTERM');
199
+ killed++;
200
+ } catch { /* already gone */ }
201
+ }
202
+
203
+ // Clear registry and lock
204
+ writeRegistry(projectRoot, []);
205
+ clearLock(projectRoot);
206
+
207
+ return { killed, total: entries.length };
208
+ },
209
+
210
+ /**
211
+ * Return list of currently alive tracked processes.
212
+ * @returns {Array<{ pid: number, label: string, cmd: string, startedAt: string }>}
213
+ */
214
+ getActive() {
215
+ const entries = readRegistry(projectRoot);
216
+ return entries.filter(e => isAlive(e.pid));
217
+ },
218
+
219
+ /**
220
+ * Remove dead entries from the registry.
221
+ * @returns {{ pruned: number, remaining: number }}
222
+ */
223
+ prune() {
224
+ const entries = readRegistry(projectRoot);
225
+ const alive = entries.filter(e => isAlive(e.pid));
226
+ writeRegistry(projectRoot, alive);
227
+ return { pruned: entries.length - alive.length, remaining: alive.length };
228
+ },
229
+
230
+ /**
231
+ * Check if the spawn lock is held (another session-restore spawned recently).
232
+ */
233
+ isLocked() {
234
+ return checkLock(projectRoot);
235
+ },
236
+
237
+ /**
238
+ * Acquire the spawn lock (30 s TTL).
239
+ */
240
+ acquireLock() {
241
+ writeLock(projectRoot);
242
+ },
243
+
244
+ /**
245
+ * Release the spawn lock.
246
+ */
247
+ releaseLock() {
248
+ clearLock(projectRoot);
249
+ },
250
+
251
+ /** Expose the project root for callers that need it. */
252
+ get root() {
253
+ return projectRoot;
254
+ },
255
+ };
256
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Synchronous cleanup of the ProcessManager background-pids registry.
3
+ *
4
+ * Safe to call from CJS hooks that run under process.exit() — no async,
5
+ * no ESM imports, pure fs + process.kill.
6
+ *
7
+ * Used by: .claude/helpers/hook-handler.cjs, bin/hook-handler.cjs (session-end)
8
+ */
9
+ 'use strict';
10
+
11
+ var fs = require('fs');
12
+ var path = require('path');
13
+
14
+ /**
15
+ * Kill all tracked background processes and clear the registry.
16
+ * @param {string} projectDir - absolute path to the project root
17
+ * @returns {number} count of processes killed
18
+ */
19
+ function killTrackedSync(projectDir) {
20
+ var pidFile = path.join(projectDir, '.claude-flow', 'background-pids.json');
21
+ var lockFile = path.join(projectDir, '.claude-flow', 'spawn.lock');
22
+ var killed = 0;
23
+
24
+ try {
25
+ if (fs.existsSync(pidFile)) {
26
+ var entries = JSON.parse(fs.readFileSync(pidFile, 'utf-8'));
27
+ if (!Array.isArray(entries)) entries = [];
28
+ for (var i = 0; i < entries.length; i++) {
29
+ try { process.kill(entries[i].pid, 0); } catch (e) { continue; }
30
+ try { process.kill(entries[i].pid, 'SIGTERM'); killed++; } catch (e) { /* ok */ }
31
+ }
32
+ fs.writeFileSync(pidFile, '[]');
33
+ }
34
+ } catch (e) { /* non-fatal */ }
35
+
36
+ try { if (fs.existsSync(lockFile)) fs.unlinkSync(lockFile); } catch (e) { /* ok */ }
37
+
38
+ return killed;
39
+ }
40
+
41
+ module.exports = { killTrackedSync };
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
  /**
3
3
  * Semantic search using 384-dim embeddings (Xenova/all-MiniLM-L6-v2 or hash fallback)
4
4
  *
@@ -13,7 +13,22 @@ import { resolve, dirname } from 'path';
13
13
  import { fileURLToPath } from 'url';
14
14
 
15
15
  const __dirname = dirname(fileURLToPath(import.meta.url));
16
- const projectRoot = resolve(__dirname, '../..');
16
+
17
+ // Detect project root by walking up from cwd to find package.json.
18
+ // IMPORTANT: Do NOT use resolve(__dirname, '..') or '../..' — this script lives
19
+ // in bin/ during development but gets synced to .claude/scripts/ in consumer
20
+ // projects, so __dirname-relative paths break. findProjectRoot() works everywhere.
21
+ function findProjectRoot() {
22
+ let dir = process.cwd();
23
+ const root = resolve(dir, '/');
24
+ while (dir !== root) {
25
+ if (existsSync(resolve(dir, 'package.json'))) return dir;
26
+ dir = dirname(dir);
27
+ }
28
+ return process.cwd();
29
+ }
30
+
31
+ const projectRoot = findProjectRoot();
17
32
 
18
33
  // ── 1. Helper: fire-and-forget a background process ─────────────────────────
19
34
  function fireAndForget(cmd, args, label) {
package/README.md CHANGED
@@ -273,29 +273,29 @@ When you pass an issue number, `/flo` automatically checks if it's an epic — n
273
273
 
274
274
  When an epic is detected, `/flo` processes each child story sequentially — full workflow per story (research → implement → test → PR), one at a time, in the order listed.
275
275
 
276
- For simple epics with independent stories, `/flo <epic>` is all you need. For complex features where you want state tracking, resume capability, and auto-merge between stories, use `flo orc` instead.
276
+ For simple epics with independent stories, `/flo <epic>` is all you need. For complex features where you want state tracking, resume capability, and auto-merge between stories, use `flo epic` instead.
277
277
 
278
- ### Feature Orchestration (`flo orc`)
278
+ ### Feature Orchestration (`flo epic`)
279
279
 
280
- `flo orc` is the robust epic runner — it adds persistent state, resume from failure, and auto-merge between stories on top of `/flo`. It accepts either a GitHub issue number or a YAML file:
280
+ `flo epic` is the robust epic runner — it adds persistent state, resume from failure, and auto-merge between stories on top of `/flo`. It accepts either a GitHub issue number or a YAML file:
281
281
 
282
282
  ```bash
283
283
  # From a GitHub epic (auto-detects stories)
284
- flo orc run 42 # Fetch epic #42, run all stories sequentially
285
- flo orc run 42 --dry-run # Preview execution plan without running
286
- flo orc run 42 --no-merge # Skip auto-merge between stories
284
+ flo epic run 42 # Fetch epic #42, run all stories sequentially
285
+ flo epic run 42 --dry-run # Preview execution plan without running
286
+ flo epic run 42 --no-merge # Skip auto-merge between stories
287
287
 
288
288
  # From a YAML definition (explicit dependencies)
289
- flo orc run feature.yaml # Execute stories in dependency order
290
- flo orc run feature.yaml --dry-run # Show execution plan
291
- flo orc run feature.yaml --verbose # Stream Claude output to terminal
289
+ flo epic run feature.yaml # Execute stories in dependency order
290
+ flo epic run feature.yaml --dry-run # Show execution plan
291
+ flo epic run feature.yaml --verbose # Stream Claude output to terminal
292
292
 
293
293
  # State management
294
- flo orc status epic-42 # Check progress (which stories passed/failed)
295
- flo orc reset epic-42 # Reset state for re-run
294
+ flo epic status epic-42 # Check progress (which stories passed/failed)
295
+ flo epic reset epic-42 # Reset state for re-run
296
296
  ```
297
297
 
298
- When given an issue number, `flo orc` fetches the epic from GitHub, extracts child stories from checklists and numbered references, then runs each through `/flo` with state tracking. If a story fails, you can fix the issue and `flo orc run 42` again — it resumes from where it left off, skipping already-passed stories.
298
+ When given an issue number, `flo epic` fetches the epic from GitHub, extracts child stories from checklists and numbered references, then runs each through `/flo` with state tracking. If a story fails, you can fix the issue and `flo epic run 42` again — it resumes from where it left off, skipping already-passed stories.
299
299
 
300
300
  For features with inter-story dependencies (story B requires story A to be merged first), use a YAML definition:
301
301
 
@@ -317,9 +317,9 @@ feature:
317
317
  depends_on: [story-1]
318
318
  ```
319
319
 
320
- | | `/flo <epic>` | `flo orc run <epic>` |
320
+ | | `/flo <epic>` | `flo epic run <epic>` |
321
321
  |---|---|---|
322
- | **State tracking** | No | Yes (`.claude-orc/state.json`) |
322
+ | **State tracking** | No | Yes (`.claude-epic/state.json`) |
323
323
  | **Resume from failure** | No | Yes (skips passed stories) |
324
324
  | **Auto-merge PRs** | No | Yes (between stories) |
325
325
  | **Dry-run preview** | No | Yes |
@@ -522,7 +522,7 @@ Here's how a typical task flows through both layers:
522
522
 
523
523
  The key insight: **your client handles execution, MoFlo handles knowledge.** Your client is good at spawning agents and running code. MoFlo is good at remembering what happened, routing to the right agent, and ensuring prior knowledge is checked before exploring from scratch.
524
524
 
525
- For complex work, MoFlo structures tasks into waves — a research wave discovers context, then an implementation wave acts on it — with dependencies tracked through both the client's task system and MoFlo's coordination layer. The full integration pattern is documented in `.claude/guidance/task-swarm-integration.md`.
525
+ For complex work, MoFlo structures tasks into waves — a research wave discovers context, then an implementation wave acts on it — with dependencies tracked through both the client's task system and MoFlo's coordination layer. The full integration pattern is documented in `.claude/guidance/moflo-claude-swarm-cohesion.md`.
526
526
 
527
527
  The `/flo` skill ties both systems together for GitHub issues — driving a full workflow (research → enhance → implement → test → simplify → PR) with your client's agents for execution and MoFlo's memory for continuity.
528
528