moflo 4.7.7 → 4.8.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 (61) hide show
  1. package/.claude/helpers/statusline.cjs +34 -26
  2. package/.claude/settings.json +2 -2
  3. package/README.md +1 -1
  4. package/bin/hooks.mjs +33 -3
  5. package/bin/session-start-launcher.mjs +88 -3
  6. package/package.json +3 -5
  7. package/src/@claude-flow/cli/README.md +1 -1
  8. package/src/@claude-flow/cli/dist/src/commands/daemon.js +42 -95
  9. package/src/@claude-flow/cli/dist/src/commands/doctor.js +11 -5
  10. package/src/@claude-flow/cli/dist/src/commands/init.js +0 -145
  11. package/src/@claude-flow/cli/dist/src/config/moflo-config.d.ts +5 -0
  12. package/src/@claude-flow/cli/dist/src/config/moflo-config.js +16 -0
  13. package/src/@claude-flow/cli/dist/src/config-adapter.d.ts +1 -1
  14. package/src/@claude-flow/cli/dist/src/init/executor.js +74 -7
  15. package/src/@claude-flow/cli/dist/src/init/mcp-generator.d.ts +3 -4
  16. package/src/@claude-flow/cli/dist/src/init/mcp-generator.js +65 -22
  17. package/src/@claude-flow/cli/dist/src/init/types.d.ts +0 -4
  18. package/src/@claude-flow/cli/dist/src/init/types.js +0 -5
  19. package/src/@claude-flow/cli/dist/src/mcp-server.js +36 -0
  20. package/src/@claude-flow/cli/dist/src/memory/memory-bridge.d.ts +6 -0
  21. package/src/@claude-flow/cli/dist/src/memory/memory-bridge.js +66 -0
  22. package/src/@claude-flow/cli/dist/src/memory/memory-initializer.js +52 -1
  23. package/src/@claude-flow/cli/dist/src/services/daemon-lock.d.ts +39 -0
  24. package/src/@claude-flow/cli/dist/src/services/daemon-lock.js +213 -0
  25. package/src/@claude-flow/cli/package.json +2 -6
  26. package/.claude/helpers/README.md +0 -97
  27. package/.claude/helpers/adr-compliance.sh +0 -186
  28. package/.claude/helpers/aggressive-microcompact.mjs +0 -36
  29. package/.claude/helpers/auto-commit.sh +0 -178
  30. package/.claude/helpers/checkpoint-manager.sh +0 -251
  31. package/.claude/helpers/context-persistence-hook.mjs +0 -1979
  32. package/.claude/helpers/daemon-manager.sh +0 -252
  33. package/.claude/helpers/ddd-tracker.sh +0 -144
  34. package/.claude/helpers/github-safe.js +0 -106
  35. package/.claude/helpers/github-setup.sh +0 -28
  36. package/.claude/helpers/guidance-hook.sh +0 -13
  37. package/.claude/helpers/guidance-hooks.sh +0 -102
  38. package/.claude/helpers/health-monitor.sh +0 -108
  39. package/.claude/helpers/learning-hooks.sh +0 -329
  40. package/.claude/helpers/learning-optimizer.sh +0 -127
  41. package/.claude/helpers/learning-service.mjs +0 -1211
  42. package/.claude/helpers/memory.cjs +0 -84
  43. package/.claude/helpers/metrics-db.mjs +0 -492
  44. package/.claude/helpers/patch-aggressive-prune.mjs +0 -184
  45. package/.claude/helpers/pattern-consolidator.sh +0 -86
  46. package/.claude/helpers/perf-worker.sh +0 -160
  47. package/.claude/helpers/quick-start.sh +0 -19
  48. package/.claude/helpers/router.cjs +0 -62
  49. package/.claude/helpers/security-scanner.sh +0 -127
  50. package/.claude/helpers/session.cjs +0 -125
  51. package/.claude/helpers/setup-mcp.sh +0 -18
  52. package/.claude/helpers/standard-checkpoint-hooks.sh +0 -189
  53. package/.claude/helpers/swarm-comms.sh +0 -353
  54. package/.claude/helpers/swarm-hooks.sh +0 -761
  55. package/.claude/helpers/swarm-monitor.sh +0 -211
  56. package/.claude/helpers/sync-v3-metrics.sh +0 -245
  57. package/.claude/helpers/update-v3-progress.sh +0 -166
  58. package/.claude/helpers/v3-quick-status.sh +0 -58
  59. package/.claude/helpers/v3.sh +0 -111
  60. package/.claude/helpers/validate-v3-config.sh +0 -216
  61. package/.claude/helpers/worker-manager.sh +0 -170
@@ -1,125 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Claude Flow Cross-Platform Session Manager
4
- * Works on Windows, macOS, and Linux
5
- */
6
-
7
- const fs = require('fs');
8
- const path = require('path');
9
- const os = require('os');
10
-
11
- const platform = os.platform();
12
- const homeDir = os.homedir();
13
-
14
- function getDataDir() {
15
- const localDir = path.join(process.cwd(), '.claude-flow', 'sessions');
16
- if (fs.existsSync(path.dirname(localDir))) {
17
- return localDir;
18
- }
19
-
20
- switch (platform) {
21
- case 'win32':
22
- return path.join(process.env.APPDATA || homeDir, 'claude-flow', 'sessions');
23
- case 'darwin':
24
- return path.join(homeDir, 'Library', 'Application Support', 'claude-flow', 'sessions');
25
- default:
26
- return path.join(homeDir, '.claude-flow', 'sessions');
27
- }
28
- }
29
-
30
- const SESSION_DIR = getDataDir();
31
- const SESSION_FILE = path.join(SESSION_DIR, 'current.json');
32
-
33
- function ensureDir(dir) {
34
- if (!fs.existsSync(dir)) {
35
- fs.mkdirSync(dir, { recursive: true });
36
- }
37
- }
38
-
39
- const commands = {
40
- start: () => {
41
- ensureDir(SESSION_DIR);
42
- const sessionId = `session-${Date.now()}`;
43
- const session = {
44
- id: sessionId,
45
- startedAt: new Date().toISOString(),
46
- platform: platform,
47
- cwd: process.cwd(),
48
- context: {},
49
- metrics: { edits: 0, commands: 0, tasks: 0, errors: 0 }
50
- };
51
- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));
52
- console.log(`Session started: ${sessionId}`);
53
- return session;
54
- },
55
-
56
- restore: () => {
57
- if (!fs.existsSync(SESSION_FILE)) {
58
- console.log('No session to restore');
59
- return null;
60
- }
61
- const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
62
- session.restoredAt = new Date().toISOString();
63
- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));
64
- console.log(`Session restored: ${session.id}`);
65
- return session;
66
- },
67
-
68
- end: () => {
69
- if (!fs.existsSync(SESSION_FILE)) {
70
- console.log('No active session');
71
- return null;
72
- }
73
- const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
74
- session.endedAt = new Date().toISOString();
75
- session.duration = Date.now() - new Date(session.startedAt).getTime();
76
-
77
- const archivePath = path.join(SESSION_DIR, `${session.id}.json`);
78
- fs.writeFileSync(archivePath, JSON.stringify(session, null, 2));
79
- fs.unlinkSync(SESSION_FILE);
80
-
81
- console.log(`Session ended: ${session.id}`);
82
- console.log(`Duration: ${Math.round(session.duration / 1000 / 60)} minutes`);
83
- return session;
84
- },
85
-
86
- status: () => {
87
- if (!fs.existsSync(SESSION_FILE)) {
88
- console.log('No active session');
89
- return null;
90
- }
91
- const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
92
- const duration = Date.now() - new Date(session.startedAt).getTime();
93
- console.log(`Session: ${session.id}`);
94
- console.log(`Platform: ${session.platform}`);
95
- console.log(`Started: ${session.startedAt}`);
96
- console.log(`Duration: ${Math.round(duration / 1000 / 60)} minutes`);
97
- return session;
98
- },
99
-
100
- metric: (name) => {
101
- if (!fs.existsSync(SESSION_FILE)) {
102
- return null;
103
- }
104
- const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
105
- if (session.metrics[name] !== undefined) {
106
- session.metrics[name]++;
107
- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));
108
- }
109
- return session;
110
- }
111
- };
112
-
113
- module.exports = commands;
114
-
115
- // CLI - only run when executed directly
116
- if (require.main === module) {
117
- const [,, command, ...args] = process.argv;
118
- if (command && commands[command]) {
119
- commands[command](...args);
120
- } else {
121
- console.log('Usage: session.js <start|restore|end|status|metric>');
122
- console.log(`Platform: ${platform}`);
123
- console.log(`Data dir: ${SESSION_DIR}`);
124
- }
125
- }
@@ -1,18 +0,0 @@
1
- #!/bin/bash
2
- # Setup MCP server for Claude Flow
3
-
4
- echo "🚀 Setting up Claude Flow MCP server..."
5
-
6
- # Check if claude command exists
7
- if ! command -v claude &> /dev/null; then
8
- echo "❌ Error: Claude Code CLI not found"
9
- echo "Please install Claude Code first"
10
- exit 1
11
- fi
12
-
13
- # Add MCP server
14
- echo "📦 Adding Claude Flow MCP server..."
15
- claude mcp add claude-flow npx claude-flow mcp start
16
-
17
- echo "✅ MCP server setup complete!"
18
- echo "🎯 You can now use mcp__claude-flow__ tools in Claude Code"
@@ -1,189 +0,0 @@
1
- #!/bin/bash
2
- # Standard checkpoint hook functions for Claude settings.json (without GitHub features)
3
-
4
- # Function to handle pre-edit checkpoints
5
- pre_edit_checkpoint() {
6
- local tool_input="$1"
7
- # Handle both JSON input and plain file path
8
- if echo "$tool_input" | jq -e . >/dev/null 2>&1; then
9
- local file=$(echo "$tool_input" | jq -r '.file_path // empty')
10
- else
11
- local file="$tool_input"
12
- fi
13
-
14
- if [ -n "$file" ]; then
15
- local checkpoint_branch="checkpoint/pre-edit-$(date +%Y%m%d-%H%M%S)"
16
- local current_branch=$(git branch --show-current)
17
-
18
- # Create checkpoint
19
- git add -A
20
- git stash push -m "Pre-edit checkpoint for $file" >/dev/null 2>&1
21
- git branch "$checkpoint_branch"
22
-
23
- # Store metadata
24
- mkdir -p .claude/checkpoints
25
- cat > ".claude/checkpoints/$(date +%s).json" <<EOF
26
- {
27
- "branch": "$checkpoint_branch",
28
- "file": "$file",
29
- "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
30
- "type": "pre-edit",
31
- "original_branch": "$current_branch"
32
- }
33
- EOF
34
-
35
- # Restore working directory
36
- git stash pop --quiet >/dev/null 2>&1 || true
37
-
38
- echo "✅ Created checkpoint: $checkpoint_branch for $file"
39
- fi
40
- }
41
-
42
- # Function to handle post-edit checkpoints
43
- post_edit_checkpoint() {
44
- local tool_input="$1"
45
- # Handle both JSON input and plain file path
46
- if echo "$tool_input" | jq -e . >/dev/null 2>&1; then
47
- local file=$(echo "$tool_input" | jq -r '.file_path // empty')
48
- else
49
- local file="$tool_input"
50
- fi
51
-
52
- if [ -n "$file" ] && [ -f "$file" ]; then
53
- # Check if file was modified - first check if file is tracked
54
- if ! git ls-files --error-unmatch "$file" >/dev/null 2>&1; then
55
- # File is not tracked, add it first
56
- git add "$file"
57
- fi
58
-
59
- # Now check if there are changes
60
- if git diff --cached --quiet "$file" 2>/dev/null && git diff --quiet "$file" 2>/dev/null; then
61
- echo "ℹ️ No changes to checkpoint for $file"
62
- else
63
- local tag_name="checkpoint-$(date +%Y%m%d-%H%M%S)"
64
- local current_branch=$(git branch --show-current)
65
-
66
- # Create commit
67
- git add "$file"
68
- if git commit -m "🔖 Checkpoint: Edit $file
69
-
70
- Automatic checkpoint created by Claude
71
- - File: $file
72
- - Branch: $current_branch
73
- - Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)
74
-
75
- [Auto-checkpoint]" --quiet; then
76
- # Create tag only if commit succeeded
77
- git tag -a "$tag_name" -m "Checkpoint after editing $file"
78
-
79
- # Store metadata
80
- mkdir -p .claude/checkpoints
81
- local diff_stats=$(git diff HEAD~1 --stat | tr '\n' ' ' | sed 's/"/\"/g')
82
- cat > ".claude/checkpoints/$(date +%s).json" <<EOF
83
- {
84
- "tag": "$tag_name",
85
- "file": "$file",
86
- "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
87
- "type": "post-edit",
88
- "branch": "$current_branch",
89
- "diff_summary": "$diff_stats"
90
- }
91
- EOF
92
-
93
- echo "✅ Created checkpoint: $tag_name for $file"
94
- else
95
- echo "ℹ️ No commit created (no changes or commit failed)"
96
- fi
97
- fi
98
- fi
99
- }
100
-
101
- # Function to handle task checkpoints
102
- task_checkpoint() {
103
- local user_prompt="$1"
104
- local task=$(echo "$user_prompt" | head -c 100 | tr '\n' ' ')
105
-
106
- if [ -n "$task" ]; then
107
- local checkpoint_name="task-$(date +%Y%m%d-%H%M%S)"
108
-
109
- # Commit current state
110
- git add -A
111
- git commit -m "🔖 Task checkpoint: $task..." --quiet || true
112
-
113
- # Store metadata
114
- mkdir -p .claude/checkpoints
115
- cat > ".claude/checkpoints/task-$(date +%s).json" <<EOF
116
- {
117
- "checkpoint": "$checkpoint_name",
118
- "task": "$task",
119
- "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
120
- "commit": "$(git rev-parse HEAD)"
121
- }
122
- EOF
123
-
124
- echo "✅ Created task checkpoint: $checkpoint_name"
125
- fi
126
- }
127
-
128
- # Function to handle session end
129
- session_end_checkpoint() {
130
- local session_id="session-$(date +%Y%m%d-%H%M%S)"
131
- local summary_file=".claude/checkpoints/summary-$session_id.md"
132
-
133
- mkdir -p .claude/checkpoints
134
-
135
- # Create summary
136
- cat > "$summary_file" <<EOF
137
- # Session Summary - $(date +'%Y-%m-%d %H:%M:%S')
138
-
139
- ## Checkpoints Created
140
- $(find .claude/checkpoints -name '*.json' -mtime -1 -exec basename {} \; | sort)
141
-
142
- ## Files Modified
143
- $(git diff --name-only $(git log --format=%H -n 1 --before="1 hour ago" 2>/dev/null) 2>/dev/null || echo "No files tracked")
144
-
145
- ## Recent Commits
146
- $(git log --oneline -10 --grep="Checkpoint" || echo "No checkpoint commits")
147
-
148
- ## Rollback Instructions
149
- To rollback to a specific checkpoint:
150
- \`\`\`bash
151
- # List all checkpoints
152
- git tag -l 'checkpoint-*' | sort -r
153
-
154
- # Rollback to a checkpoint
155
- git checkout checkpoint-YYYYMMDD-HHMMSS
156
-
157
- # Or reset to a checkpoint (destructive)
158
- git reset --hard checkpoint-YYYYMMDD-HHMMSS
159
- \`\`\`
160
- EOF
161
-
162
- # Create final checkpoint
163
- git add -A
164
- git commit -m "🏁 Session end checkpoint: $session_id" --quiet || true
165
- git tag -a "session-end-$session_id" -m "End of Claude session"
166
-
167
- echo "✅ Session summary saved to: $summary_file"
168
- echo "📌 Final checkpoint: session-end-$session_id"
169
- }
170
-
171
- # Main entry point
172
- case "$1" in
173
- pre-edit)
174
- pre_edit_checkpoint "$2"
175
- ;;
176
- post-edit)
177
- post_edit_checkpoint "$2"
178
- ;;
179
- task)
180
- task_checkpoint "$2"
181
- ;;
182
- session-end)
183
- session_end_checkpoint
184
- ;;
185
- *)
186
- echo "Usage: $0 {pre-edit|post-edit|task|session-end} [input]"
187
- exit 1
188
- ;;
189
- esac
@@ -1,353 +0,0 @@
1
- #!/bin/bash
2
- # RuFlo V3 - Optimized Swarm Communications
3
- # Non-blocking, batched, priority-based inter-agent messaging
4
-
5
- set -euo pipefail
6
-
7
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
8
- PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
9
- SWARM_DIR="$PROJECT_ROOT/.claude-flow/swarm"
10
- QUEUE_DIR="$SWARM_DIR/queue"
11
- BATCH_DIR="$SWARM_DIR/batch"
12
- POOL_FILE="$SWARM_DIR/connection-pool.json"
13
-
14
- mkdir -p "$QUEUE_DIR" "$BATCH_DIR"
15
-
16
- # Priority levels
17
- PRIORITY_CRITICAL=0
18
- PRIORITY_HIGH=1
19
- PRIORITY_NORMAL=2
20
- PRIORITY_LOW=3
21
-
22
- # Batch settings
23
- BATCH_SIZE=10
24
- BATCH_TIMEOUT_MS=100
25
-
26
- # =============================================================================
27
- # NON-BLOCKING MESSAGE QUEUE
28
- # =============================================================================
29
-
30
- # Enqueue message (instant return, async processing)
31
- enqueue() {
32
- local to="${1:-*}"
33
- local content="${2:-}"
34
- local priority="${3:-$PRIORITY_NORMAL}"
35
- local msg_type="${4:-context}"
36
-
37
- local msg_id="msg_$(date +%s%N)"
38
- local timestamp=$(date +%s)
39
-
40
- # Write to priority queue (non-blocking)
41
- cat > "$QUEUE_DIR/${priority}_${msg_id}.json" << EOF
42
- {"id":"$msg_id","to":"$to","content":"$content","type":"$msg_type","priority":$priority,"timestamp":$timestamp}
43
- EOF
44
-
45
- echo "$msg_id"
46
- }
47
-
48
- # Process queue in background
49
- process_queue() {
50
- local processed=0
51
-
52
- # Process by priority (0=critical first)
53
- for priority in 0 1 2 3; do
54
- shopt -s nullglob
55
- for msg_file in "$QUEUE_DIR"/${priority}_*.json; do
56
- [ -f "$msg_file" ] || continue
57
-
58
- # Process message
59
- local msg=$(cat "$msg_file")
60
- local to=$(echo "$msg" | jq -r '.to' 2>/dev/null)
61
-
62
- # Route to agent mailbox
63
- if [ "$to" != "*" ]; then
64
- mkdir -p "$SWARM_DIR/mailbox/$to"
65
- mv "$msg_file" "$SWARM_DIR/mailbox/$to/"
66
- else
67
- # Broadcast - copy to all agent mailboxes
68
- for agent_dir in "$SWARM_DIR/mailbox"/*; do
69
- [ -d "$agent_dir" ] && cp "$msg_file" "$agent_dir/"
70
- done
71
- rm "$msg_file"
72
- fi
73
-
74
- processed=$((processed + 1))
75
- done
76
- done
77
-
78
- echo "$processed"
79
- }
80
-
81
- # =============================================================================
82
- # MESSAGE BATCHING
83
- # =============================================================================
84
-
85
- # Add to batch (collects messages, flushes when full or timeout)
86
- batch_add() {
87
- local agent_id="${1:-}"
88
- local content="${2:-}"
89
- local batch_file="$BATCH_DIR/${agent_id}.batch"
90
-
91
- # Append to batch
92
- echo "$content" >> "$batch_file"
93
-
94
- # Check batch size
95
- local count=$(wc -l < "$batch_file" 2>/dev/null || echo "0")
96
-
97
- if [ "$count" -ge "$BATCH_SIZE" ]; then
98
- batch_flush "$agent_id"
99
- fi
100
- }
101
-
102
- # Flush batch (send all at once)
103
- batch_flush() {
104
- local agent_id="${1:-}"
105
- local batch_file="$BATCH_DIR/${agent_id}.batch"
106
-
107
- if [ -f "$batch_file" ]; then
108
- local content=$(cat "$batch_file")
109
- rm "$batch_file"
110
-
111
- # Send as single batched message
112
- enqueue "$agent_id" "$content" "$PRIORITY_NORMAL" "batch"
113
- fi
114
- }
115
-
116
- # Flush all pending batches
117
- batch_flush_all() {
118
- shopt -s nullglob
119
- for batch_file in "$BATCH_DIR"/*.batch; do
120
- [ -f "$batch_file" ] || continue
121
- local agent_id=$(basename "$batch_file" .batch)
122
- batch_flush "$agent_id"
123
- done
124
- }
125
-
126
- # =============================================================================
127
- # CONNECTION POOLING
128
- # =============================================================================
129
-
130
- # Initialize connection pool
131
- pool_init() {
132
- cat > "$POOL_FILE" << EOF
133
- {
134
- "maxConnections": 10,
135
- "activeConnections": 0,
136
- "available": [],
137
- "inUse": [],
138
- "lastUpdated": "$(date -Iseconds)"
139
- }
140
- EOF
141
- }
142
-
143
- # Get connection from pool (or create new)
144
- pool_acquire() {
145
- local agent_id="${1:-}"
146
-
147
- if [ ! -f "$POOL_FILE" ]; then
148
- pool_init
149
- fi
150
-
151
- # Check for available connection
152
- local available=$(jq -r '.available[0] // ""' "$POOL_FILE" 2>/dev/null)
153
-
154
- if [ -n "$available" ]; then
155
- # Reuse existing connection
156
- jq ".available = .available[1:] | .inUse += [\"$available\"]" "$POOL_FILE" > "$POOL_FILE.tmp" && mv "$POOL_FILE.tmp" "$POOL_FILE"
157
- echo "$available"
158
- else
159
- # Create new connection ID
160
- local conn_id="conn_$(date +%s%N | tail -c 8)"
161
- jq ".inUse += [\"$conn_id\"] | .activeConnections += 1" "$POOL_FILE" > "$POOL_FILE.tmp" && mv "$POOL_FILE.tmp" "$POOL_FILE"
162
- echo "$conn_id"
163
- fi
164
- }
165
-
166
- # Release connection back to pool
167
- pool_release() {
168
- local conn_id="${1:-}"
169
-
170
- if [ -f "$POOL_FILE" ]; then
171
- jq ".inUse = (.inUse | map(select(. != \"$conn_id\"))) | .available += [\"$conn_id\"]" "$POOL_FILE" > "$POOL_FILE.tmp" && mv "$POOL_FILE.tmp" "$POOL_FILE"
172
- fi
173
- }
174
-
175
- # =============================================================================
176
- # ASYNC PATTERN BROADCAST
177
- # =============================================================================
178
-
179
- # Broadcast pattern to swarm (non-blocking)
180
- broadcast_pattern_async() {
181
- local strategy="${1:-}"
182
- local domain="${2:-general}"
183
- local quality="${3:-0.7}"
184
-
185
- # Fire and forget
186
- (
187
- local broadcast_id="pattern_$(date +%s%N)"
188
-
189
- # Write pattern broadcast
190
- mkdir -p "$SWARM_DIR/patterns"
191
- cat > "$SWARM_DIR/patterns/$broadcast_id.json" << EOF
192
- {"id":"$broadcast_id","strategy":"$strategy","domain":"$domain","quality":$quality,"timestamp":$(date +%s),"status":"pending"}
193
- EOF
194
-
195
- # Notify all agents via queue
196
- enqueue "*" "{\"type\":\"pattern_broadcast\",\"id\":\"$broadcast_id\"}" "$PRIORITY_HIGH" "event"
197
-
198
- ) &
199
-
200
- echo "pattern_broadcast_queued"
201
- }
202
-
203
- # =============================================================================
204
- # OPTIMIZED CONSENSUS
205
- # =============================================================================
206
-
207
- # Start consensus (non-blocking)
208
- start_consensus_async() {
209
- local question="${1:-}"
210
- local options="${2:-}"
211
- local timeout="${3:-30}"
212
-
213
- (
214
- local consensus_id="consensus_$(date +%s%N)"
215
- mkdir -p "$SWARM_DIR/consensus"
216
-
217
- cat > "$SWARM_DIR/consensus/$consensus_id.json" << EOF
218
- {"id":"$consensus_id","question":"$question","options":"$options","votes":{},"timeout":$timeout,"created":$(date +%s),"status":"open"}
219
- EOF
220
-
221
- # Notify agents
222
- enqueue "*" "{\"type\":\"consensus_request\",\"id\":\"$consensus_id\"}" "$PRIORITY_HIGH" "event"
223
-
224
- # Auto-resolve after timeout (background)
225
- (
226
- sleep "$timeout"
227
- if [ -f "$SWARM_DIR/consensus/$consensus_id.json" ]; then
228
- jq '.status = "resolved"' "$SWARM_DIR/consensus/$consensus_id.json" > "$SWARM_DIR/consensus/$consensus_id.json.tmp" && mv "$SWARM_DIR/consensus/$consensus_id.json.tmp" "$SWARM_DIR/consensus/$consensus_id.json"
229
- fi
230
- ) &
231
-
232
- echo "$consensus_id"
233
- ) &
234
- }
235
-
236
- # Vote on consensus (non-blocking)
237
- vote_async() {
238
- local consensus_id="${1:-}"
239
- local vote="${2:-}"
240
- local agent_id="${AGENTIC_FLOW_AGENT_ID:-anonymous}"
241
-
242
- (
243
- local file="$SWARM_DIR/consensus/$consensus_id.json"
244
- if [ -f "$file" ]; then
245
- jq ".votes[\"$agent_id\"] = \"$vote\"" "$file" > "$file.tmp" && mv "$file.tmp" "$file"
246
- fi
247
- ) &
248
- }
249
-
250
- # =============================================================================
251
- # PERFORMANCE METRICS
252
- # =============================================================================
253
-
254
- get_comms_stats() {
255
- local queued=$(ls "$QUEUE_DIR"/*.json 2>/dev/null | wc -l | tr -d '[:space:]')
256
- queued=${queued:-0}
257
- local batched=$(ls "$BATCH_DIR"/*.batch 2>/dev/null | wc -l | tr -d '[:space:]')
258
- batched=${batched:-0}
259
- local patterns=$(ls "$SWARM_DIR/patterns"/*.json 2>/dev/null | wc -l | tr -d '[:space:]')
260
- patterns=${patterns:-0}
261
- local consensus=$(ls "$SWARM_DIR/consensus"/*.json 2>/dev/null | wc -l | tr -d '[:space:]')
262
- consensus=${consensus:-0}
263
-
264
- local pool_active=0
265
- if [ -f "$POOL_FILE" ]; then
266
- pool_active=$(jq '.activeConnections // 0' "$POOL_FILE" 2>/dev/null | tr -d '[:space:]')
267
- pool_active=${pool_active:-0}
268
- fi
269
-
270
- echo "{\"queue\":$queued,\"batch\":$batched,\"patterns\":$patterns,\"consensus\":$consensus,\"pool\":$pool_active}"
271
- }
272
-
273
- # =============================================================================
274
- # MAIN DISPATCHER
275
- # =============================================================================
276
-
277
- case "${1:-help}" in
278
- # Queue operations
279
- "enqueue"|"send")
280
- enqueue "${2:-*}" "${3:-}" "${4:-2}" "${5:-context}"
281
- ;;
282
- "process")
283
- process_queue
284
- ;;
285
-
286
- # Batch operations
287
- "batch")
288
- batch_add "${2:-}" "${3:-}"
289
- ;;
290
- "flush")
291
- batch_flush_all
292
- ;;
293
-
294
- # Pool operations
295
- "acquire")
296
- pool_acquire "${2:-}"
297
- ;;
298
- "release")
299
- pool_release "${2:-}"
300
- ;;
301
-
302
- # Async operations
303
- "broadcast-pattern")
304
- broadcast_pattern_async "${2:-}" "${3:-general}" "${4:-0.7}"
305
- ;;
306
- "consensus")
307
- start_consensus_async "${2:-}" "${3:-}" "${4:-30}"
308
- ;;
309
- "vote")
310
- vote_async "${2:-}" "${3:-}"
311
- ;;
312
-
313
- # Stats
314
- "stats")
315
- get_comms_stats
316
- ;;
317
-
318
- "help"|*)
319
- cat << 'EOF'
320
- RuFlo V3 - Optimized Swarm Communications
321
-
322
- Non-blocking, batched, priority-based inter-agent messaging.
323
-
324
- Usage: swarm-comms.sh <command> [args]
325
-
326
- Queue (Non-blocking):
327
- enqueue <to> <content> [priority] [type] Add to queue (instant return)
328
- process Process pending queue
329
-
330
- Batching:
331
- batch <agent> <content> Add to batch
332
- flush Flush all batches
333
-
334
- Connection Pool:
335
- acquire [agent] Get connection from pool
336
- release <conn_id> Return connection to pool
337
-
338
- Async Operations:
339
- broadcast-pattern <strategy> [domain] [quality] Async pattern broadcast
340
- consensus <question> <options> [timeout] Start async consensus
341
- vote <consensus_id> <vote> Vote (non-blocking)
342
-
343
- Stats:
344
- stats Get communication stats
345
-
346
- Priority Levels:
347
- 0 = Critical (processed first)
348
- 1 = High
349
- 2 = Normal (default)
350
- 3 = Low
351
- EOF
352
- ;;
353
- esac