claude-flow-novice 2.18.23 → 2.18.24

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,17 @@
1
+ # CFN Coordination and Namespace Guide
2
+
3
+ ## Coordination Patterns and Namespace Isolation
4
+
5
+ - Coordination patterns: see `.claude/skills/cfn-coordination/SKILL.md` (chain, broadcast, mesh, consensus collection).
6
+ - Namespace structure: agents `.claude/agents/cfn-dev-team/`; skills `.claude/skills/cfn-*/`; hooks `.claude/hooks/cfn-*`; commands `.claude/commands/cfn/`.
7
+ - Enhanced orchestrator v3.0: `./.claude/skills/cfn-loop-orchestration/orchestrate.sh`
8
+ - Orchestration flow: Loop 3 executes and tests -> gate check -> Loop 2 validators -> Product Owner decision (PROCEED/ITERATE/ABORT) -> iterate or finish.
9
+ - Task mode agents: return output directly; no Redis signaling.
10
+
11
+ ### Coordination Anti-Patterns (avoid)
12
+
13
+ - Skipping gate check before spawning Loop 2.
14
+ - Validators reviewing without tests/logs.
15
+ - Product Owner decision without deliverable paths.
16
+ - Mixing service and container names inside Docker networks.
17
+ - Manual cleanup instead of orchestrator controls.
@@ -265,6 +265,15 @@ The orchestrator returns structured results:
265
265
  }
266
266
  ```
267
267
 
268
+ ## Validation Flow Summary
269
+
270
+ 1. **Loop 3 Gate:** Test pass rate must meet mode threshold before validators start
271
+ 2. **Loop 2 Validators:** Need access to Loop 3 outputs, tests, and logs
272
+ 3. **Product Owner Decision:** Parsed via `.claude/skills/product-owner-decision/execute-decision.sh`
273
+ 4. **Gate Failure:** Iterate Loop 3 only
274
+ 5. **Gate Pass:** Proceed to validators
275
+ 6. **Decision Outcomes:** PROCEED (done), ITERATE (repeat), ABORT (stop with error)
276
+
268
277
  This simplified architecture provides:
269
278
  - ✅ **Zero external dependencies** - runs anywhere Node.js is available
270
279
  - ✅ **Fast execution** - parallel decomposition and implementation
@@ -249,6 +249,17 @@ fi
249
249
 
250
250
  ---
251
251
 
252
+ ## Validation Flow Summary
253
+
254
+ 1. **Loop 3 Gate:** Test pass rate must meet mode threshold before validators start
255
+ 2. **Loop 2 Validators:** Need access to Loop 3 outputs, tests, and logs
256
+ 3. **Product Owner Decision:** Parsed via `.claude/skills/product-owner-decision/execute-decision.sh`
257
+ 4. **Gate Failure:** Iterate Loop 3 only
258
+ 5. **Gate Pass:** Proceed to validators
259
+ 6. **Decision Outcomes:** PROCEED (done), ITERATE (repeat), ABORT (stop with error)
260
+
261
+ ---
262
+
252
263
  ## Related Documentation
253
264
 
254
265
  - **Full Task Mode Guide**: `.claude/commands/cfn-loop/cfn-loop-task.md`
@@ -17,20 +17,39 @@ Add `--force` flag for complete reindex:
17
17
  - Major restructuring
18
18
  - Index issues
19
19
 
20
- **Prerequisites:**
21
- - OPENAI_API_KEY must be set: `export OPENAI_API_KEY="sk-..."`
20
+ **Log file:** `/tmp/ruvector-index.log` - tail this for progress monitoring.
22
21
 
23
22
  ---
24
23
 
25
24
  Execute reindex:
26
25
 
27
26
  ```bash
27
+ # --- FAIL-FAST: Validate OpenAI API Key ---
28
+ # Always load from .env if current key is invalid (placeholder or missing)
29
+ if [[ ! "$OPENAI_API_KEY" =~ ^sk- ]] && [[ -f ".env" ]]; then
30
+ export OPENAI_API_KEY=$(grep "^OPENAI_API_KEY=" .env | cut -d'=' -f2- | tr -d '"' | tr -d "'")
31
+ fi
32
+
33
+ # Final validation
34
+ if [[ ! "$OPENAI_API_KEY" =~ ^sk- ]]; then
35
+ echo "❌ FATAL: Valid OPENAI_API_KEY not found." >&2
36
+ echo " Add to .env: OPENAI_API_KEY=sk-..." >&2
37
+ exit 1
38
+ fi
39
+
40
+ echo "✅ OpenAI key: ${OPENAI_API_KEY:0:12}..."
41
+
42
+ # --- Setup ---
28
43
  RUVECTOR_BIN="${HOME}/.local/bin/local-ruvector"
29
44
  [ ! -f "$RUVECTOR_BIN" ] && RUVECTOR_BIN="./.claude/skills/cfn-local-ruvector-accelerator/target/release/local-ruvector"
45
+ LOG_FILE="/tmp/ruvector-index.log"
46
+
47
+ echo "📝 Logging to: $LOG_FILE"
48
+ echo " Monitor with: tail -f $LOG_FILE"
30
49
 
31
50
  # Incremental (default - only changed files)
32
- "$RUVECTOR_BIN" index --path . --types rs,ts,js,py,sh,md
51
+ "$RUVECTOR_BIN" index --path . --types rs,ts,js,py,sh,md 2>&1 | tee "$LOG_FILE"
33
52
 
34
53
  # Full rebuild (when needed)
35
- # "$RUVECTOR_BIN" index --path . --types rs,ts,js,py,sh,md --force
54
+ # "$RUVECTOR_BIN" index --path . --types rs,ts,js,py,sh,md --force 2>&1 | tee "$LOG_FILE"
36
55
  ```
@@ -19,7 +19,7 @@ Search your indexed codebase using RuVector. Uses SQLite index for fast lookups.
19
19
  - `/cfn-ruvector:cfn-codebase-search database migration`
20
20
 
21
21
  **Prerequisites:**
22
- - Codebase must be indexed: `./local-ruvector index --path . --force`
22
+ - Codebase must be indexed: `/cfn-codebase-reindex`
23
23
  - OPENAI_API_KEY must be set for indexing
24
24
 
25
25
  ---
@@ -27,7 +27,15 @@ Search your indexed codebase using RuVector. Uses SQLite index for fast lookups.
27
27
  Execute the search:
28
28
 
29
29
  ```bash
30
+ # Load from .env if current key is invalid
31
+ if [[ ! "$OPENAI_API_KEY" =~ ^sk- ]] && [[ -f ".env" ]]; then
32
+ export OPENAI_API_KEY=$(grep "^OPENAI_API_KEY=" .env | cut -d'=' -f2- | tr -d '"' | tr -d "'")
33
+ fi
34
+ [[ ! "$OPENAI_API_KEY" =~ ^sk- ]] && { echo "❌ OPENAI_API_KEY invalid. Add to .env" >&2; exit 1; }
35
+
30
36
  RUVECTOR_BIN="${HOME}/.local/bin/local-ruvector"
31
37
  [ ! -f "$RUVECTOR_BIN" ] && RUVECTOR_BIN="./.claude/skills/cfn-local-ruvector-accelerator/target/release/local-ruvector"
32
- "$RUVECTOR_BIN" query "{{query}}" --max-results {{#if top}}{{top}}{{else}}10{{/if}}
38
+
39
+ # Use threshold 0.1 for better results (default 0.3 is too strict)
40
+ "$RUVECTOR_BIN" query "{{query}}" --max-results {{#if top}}{{top}}{{else}}10{{/if}} --threshold 0.1
33
41
  ```
@@ -29,13 +29,31 @@ Analyzes all `.md` files in the codebase to detect legacy/outdated documentation
29
29
  - Score 2-4: **POSSIBLY STALE** (minor issues)
30
30
 
31
31
  **Prerequisites:**
32
- - Codebase must be indexed first (`/codebase-reindex`)
33
- - ZAI_API_KEY must be set (for semantic search)
32
+ - Codebase must be indexed first (`/cfn-codebase-reindex`)
33
+ - OPENAI_API_KEY must be set (for semantic search)
34
34
 
35
35
  ---
36
36
 
37
- Run the stale documentation detector:
37
+ **Note:** This is a planned feature. Currently use these manual queries:
38
38
 
39
39
  ```bash
40
- ./.claude/skills/cfn-ruvector-codebase-index/detect-stale-docs.sh
40
+ # Find docs older than 90 days with no recent code references
41
+ sqlite3 ~/.local/share/ruvector/index_v2.db "
42
+ SELECT e.file_path, e.name,
43
+ datetime(e.created_at, 'unixepoch') as indexed_at
44
+ FROM entities e
45
+ WHERE e.file_path LIKE '%.md'
46
+ AND e.project_root LIKE '%$(pwd)%'
47
+ AND (e.name LIKE '%legacy%' OR e.name LIKE '%deprecated%' OR e.name LIKE '%old%')
48
+ LIMIT 20;"
49
+
50
+ # Find orphan docs (no references)
51
+ sqlite3 ~/.local/share/ruvector/index_v2.db "
52
+ SELECT DISTINCT e.file_path
53
+ FROM entities e
54
+ LEFT JOIN refs r ON e.id = r.source_entity_id OR e.id = r.target_entity_id
55
+ WHERE e.file_path LIKE '%.md'
56
+ AND e.project_root LIKE '%$(pwd)%'
57
+ AND r.id IS NULL
58
+ LIMIT 20;"
41
59
  ```
@@ -0,0 +1,48 @@
1
+ #!/bin/bash
2
+
3
+ # SessionStart hook: Load OpenAI API key from root .env file
4
+ # This ensures OPENAI_API_KEY is available for embedding generation
5
+ #
6
+ # IMPORTANT: SessionStart hooks must write to CLAUDE_ENV_FILE to set env vars.
7
+ # JSON output and 'export' do NOT work - only CLAUDE_ENV_FILE persists.
8
+
9
+ set -e
10
+
11
+ # Path to root .env file
12
+ ROOT_ENV="${PROJECT_ROOT:-.}/.env"
13
+
14
+ # Check if CLAUDE_ENV_FILE is available (only in SessionStart hooks)
15
+ if [[ -z "$CLAUDE_ENV_FILE" ]]; then
16
+ echo "⚠️ CLAUDE_ENV_FILE not set - not running as SessionStart hook" >&2
17
+ exit 0
18
+ fi
19
+
20
+ # Check if .env exists
21
+ if [[ ! -f "$ROOT_ENV" ]]; then
22
+ echo "⚠️ Warning: $ROOT_ENV not found. OpenAI embeddings will not work." >&2
23
+ exit 0
24
+ fi
25
+
26
+ # Extract OPENAI_API_KEY from .env
27
+ if grep -q "^OPENAI_API_KEY=" "$ROOT_ENV"; then
28
+ OPENAI_KEY=$(grep "^OPENAI_API_KEY=" "$ROOT_ENV" | cut -d'=' -f2- | tr -d '"' | tr -d "'")
29
+
30
+ # Validate key format
31
+ if [[ -z "$OPENAI_KEY" ]]; then
32
+ echo "⚠️ Warning: OPENAI_API_KEY found but empty in $ROOT_ENV" >&2
33
+ exit 0
34
+ fi
35
+
36
+ if [[ ! "$OPENAI_KEY" =~ ^sk- ]]; then
37
+ echo "⚠️ Warning: OPENAI_API_KEY invalid format (must start with 'sk-')" >&2
38
+ exit 0
39
+ fi
40
+
41
+ # Write to CLAUDE_ENV_FILE - this is how SessionStart hooks set env vars
42
+ echo "export OPENAI_API_KEY=\"$OPENAI_KEY\"" >> "$CLAUDE_ENV_FILE"
43
+ echo "✅ Loaded OPENAI_API_KEY from .env (${OPENAI_KEY:0:10}...)" >&2
44
+ else
45
+ echo "⚠️ Warning: OPENAI_API_KEY not found in $ROOT_ENV. OpenAI embeddings will not work." >&2
46
+ fi
47
+
48
+ exit 0
@@ -153,23 +153,21 @@
153
153
  }
154
154
  ],
155
155
  "SessionStart": [
156
- {
156
+ {
157
+ "matcher": "startup",
157
158
  "hooks": [
158
159
  {
159
160
  "type": "command",
160
- "command": "bash -c 'echo \"[SessionStart] Initializing session context...\" >&2; if [ -f \"./.claude/hooks/cfn-load-cerebras-env.sh\" ]; then RESULT=$(./.claude/hooks/cfn-load-cerebras-env.sh 2>&1); if echo \"$RESULT\" | jq . >/dev/null 2>&1; then echo \"$RESULT\"; else echo \"$RESULT\" >&2; fi; fi; if [ -f \"./.claude/skills/cfn-memory-persistence/lib/auto/auto-load-session-context.sh\" ]; then ./.claude/skills/cfn-memory-persistence/lib/auto/auto-load-session-context.sh --session-id \"${SESSION_ID:-$(date +%s)}\" 2>&1 || true; fi; if [ -f \"./.claude/skills/cfn-transparency-middleware/invoke-transparency-init.sh\" ]; then ./.claude/skills/cfn-transparency-middleware/invoke-transparency-init.sh --task-id \"${SESSION_ID:-session}\" --level standard 2>&1 || true; fi; echo \"[SessionStart] Context loaded\" >&2; exit 0'",
161
- "timeout": 15
161
+ "command": "nohup ~/.local/bin/wsl-memory-monitor.sh > /dev/null 2>&1 & sleep 0.5 && echo \"[WSL Memory Monitor] Running (PID: $(cat /tmp/wsl-memory-monitor.pid 2>/dev/null || echo starting))\""
162
162
  }
163
163
  ]
164
- }
165
- ],
166
- "Stop": [
164
+ },
167
165
  {
168
166
  "hooks": [
169
167
  {
170
168
  "type": "command",
171
- "command": "bash -c 'echo \"[SessionEnd] Persisting session state...\" >&2; if [ -f \"./.claude/skills/cfn-memory-persistence/lib/auto/save-session-context.sh\" ]; then ./.claude/skills/cfn-memory-persistence/lib/auto/save-session-context.sh --session-id \"${SESSION_ID:-$(date +%s)}\" 2>&1 || true; fi; if [ -f \"./.claude/skills/cfn-knowledge-base/cli/knowledge-base.sh\" ]; then ./.claude/skills/cfn-knowledge-base/cli/knowledge-base.sh store-learning --type session-end --category completed --confidence 0.85 2>&1 || true; fi; echo \"[SessionEnd] Session ended\" >&2; exit 0'",
172
- "timeout": 15
169
+ "command": "bash .claude/hooks/cfn-SessionStart-cfn-build-ruvector.sh",
170
+ "timeout": 60
173
171
  }
174
172
  ]
175
173
  }
@@ -0,0 +1,70 @@
1
+ # Claude Code Skills Development Guide
2
+
3
+ **Purpose:** Guidelines for developing, testing, and maintaining CFN skills.
4
+
5
+ ---
6
+
7
+ ## Skill Development Principles
8
+
9
+ - **Modularity:** Each skill handles one responsibility; compose skills for complex operations
10
+ - **Explicit Interfaces:** Document inputs, outputs, and side effects in SKILL.md
11
+ - **Minimal Dependencies:** Skills should be self-contained; avoid cross-skill imports
12
+ - **Thorough Testing:** Every skill needs functional tests and edge case coverage
13
+
14
+ ## Testing Requirements (STRAT-005)
15
+
16
+ Skills must include tests covering:
17
+ - Functional requirements (happy path)
18
+ - Edge cases: timeouts, blocking operations, invalid inputs
19
+ - Resource cleanup on failure
20
+
21
+ **Example test location:** `.claude/skills/cfn-coordination/test-orchestrator.sh`
22
+
23
+ ## Core Skill References
24
+
25
+ - **Coordination:** `.claude/skills/cfn-coordination/SKILL.md` - chain, broadcast, mesh, consensus patterns
26
+ - **Agent Spawning:** `.claude/skills/cfn-agent-spawning/SKILL.md` - agent lifecycle management
27
+ - **Loop Validation:** `.claude/skills/cfn-loop-validation/SKILL.md` - gate checks and consensus
28
+
29
+ ## Skill File Structure
30
+
31
+ ```
32
+ .claude/skills/<skill-name>/
33
+ ├── SKILL.md # Skill documentation (required)
34
+ ├── <main-script>.sh # Primary entry point
35
+ ├── lib/ # Helper scripts/modules
36
+ └── tests/ # Skill-specific tests
37
+ ```
38
+
39
+ ## Skill Documentation Template
40
+
41
+ ```markdown
42
+ # Skill: <name>
43
+
44
+ ## Purpose
45
+ One-line description of what this skill does.
46
+
47
+ ## Inputs
48
+ - `$1`: Description
49
+ - `ENV_VAR`: Description
50
+
51
+ ## Outputs
52
+ - stdout: Description
53
+ - exit code: 0 = success, non-zero = failure
54
+
55
+ ## Usage
56
+ \`\`\`bash
57
+ ./.claude/skills/<skill-name>/<script>.sh [args]
58
+ \`\`\`
59
+
60
+ ## Dependencies
61
+ - List required tools/skills
62
+ ```
63
+
64
+ ## Quality Checklist
65
+
66
+ - [ ] SKILL.md documents all inputs/outputs
67
+ - [ ] Scripts use `set -euo pipefail`
68
+ - [ ] Cleanup traps handle interrupts
69
+ - [ ] Tests cover happy path and failure modes
70
+ - [ ] No hardcoded paths (use `PROJECT_ROOT`)
@@ -1,25 +1,41 @@
1
+ ---
2
+ name: ruvector-code-search
3
+ description: "MANDATORY: Query RuVector BEFORE using grep, glob, find, or search. Performs 400x faster semantic and structural code search via SQL on indexed codebase. Use for finding functions, classes, patterns, callers, and implementations. Agents MUST query RuVector first; grep is only allowed after RuVector returns zero results."
4
+ allowed-tools: Bash, Read, SlashCommand
5
+ ---
6
+
1
7
  # RuVector Local Semantic Code Search
2
8
 
3
- ## WHEN TO USE THIS SKILL
9
+ ## MANDATORY: QUERY RUVECTOR BEFORE GREP/GLOB
10
+
11
+ **This is a PROTOCOL REQUIREMENT, not a suggestion. Failure to query RuVector first is a violation.**
12
+
13
+ ### WHY THIS IS MANDATORY
14
+ - RuVector SQL: 0.002s | grep: 0.8s (400x slower)
15
+ - Agents using grep first waste tokens and time
16
+ - Index already exists at `~/.local/share/ruvector/index_v2.db`
4
17
 
5
- **USE RuVector V2 SQL for ALL indexed projects (400x FASTER than grep):**
18
+ ### ALWAYS USE RUVECTOR FIRST
6
19
  ```bash
7
- # Exact name lookup - 0.002s vs grep's 0.8s
20
+ # Exact name lookup - 0.002s
8
21
  sqlite3 ~/.local/share/ruvector/index_v2.db "SELECT file_path, line_number FROM entities WHERE name = 'MyFunction';"
9
22
 
10
23
  # Fuzzy search - 0.004s
11
24
  sqlite3 ~/.local/share/ruvector/index_v2.db "SELECT file_path, line_number FROM entities WHERE name LIKE '%Store%' LIMIT 10;"
25
+
26
+ # Semantic search
27
+ /codebase-search "authentication middleware pattern"
12
28
  ```
13
29
 
14
- **USE grep/rg ONLY when:**
15
- - Project is NOT indexed yet
16
- - Searching for strings that aren't code entities (error messages, comments, config values)
17
- - Quick one-off search in small directory
30
+ ### GREP IS ONLY ALLOWED WHEN:
31
+ - RuVector query returned zero results AND project confirmed not indexed
32
+ - Searching literal strings (error messages, comments, config values)
33
+ - Explicit user request for grep
18
34
 
19
- **USE RuVector semantic search when:**
20
- - "Where is authentication implemented?" (conceptual search)
21
- - Finding similar patterns you can't name exactly
22
- - Discovering how a feature is built
35
+ ### FOR CONCEPTUAL QUESTIONS:
36
+ - "Where is X implemented?" RuVector semantic search
37
+ - "Find similar patterns" RuVector embeddings
38
+ - "How is feature Y built?" → RuVector first, then read files
23
39
 
24
40
  ## Quick Commands
25
41
 
@@ -108,20 +124,20 @@ sqlite3 ~/.local/share/ruvector/index_v2.db "SELECT project_root, COUNT(*) FROM
108
124
  ~/.local/share/ruvector/index_v2.db
109
125
  ```
110
126
 
111
- ## For Agents
127
+ ## For Agents (MANDATORY PROTOCOL)
128
+
129
+ **DO NOT use grep/glob until you have queried RuVector. This is enforced.**
112
130
 
113
- Before implementing changes, ALWAYS query RuVector first:
114
131
  ```bash
115
- # Find similar patterns (slash command uses --top, CLI uses --max-results)
132
+ # STEP 1: Query RuVector FIRST (required)
116
133
  /codebase-search "relevant search terms" --top 5
117
- # Or via CLI:
118
- local-ruvector query "relevant search terms" --max-results 5
134
+ # Or SQL:
135
+ sqlite3 ~/.local/share/ruvector/index_v2.db "SELECT file_path, line_number FROM entities WHERE name LIKE '%keyword%';"
119
136
 
120
- # Query past errors
121
- ./.claude/skills/cfn-ruvector-codebase-index/query-error-patterns.sh --task-description "description"
137
+ # STEP 2: Query past errors/patterns
138
+ ./.claude/skills/cfn-local-ruvector-accelerator/query-agent-patterns.sh "description"
122
139
 
123
- # Query learnings
124
- ./.claude/skills/cfn-ruvector-codebase-index/query-learnings.sh --task-description "description" --category PATTERN
140
+ # STEP 3: Only if RuVector returns nothing, then use grep
125
141
  ```
126
142
 
127
- This prevents duplicated work and leverages existing solutions.
143
+ **Violation of this protocol wastes tokens and time. RuVector exists to prevent duplicated work.**
package/CLAUDE.md CHANGED
@@ -1,423 +1,85 @@
1
- # Claude Flow Novice - Operating Guide
2
- ---
1
+ # CFN Operating Guide
3
2
 
4
- Purpose: concise reference for CFN agents. Focus on persona, mandatory rules, edit workflow, loop mode selection, Docker/test requirements, and key links. Target size: 300-500 lines; keep lean and actionable.
3
+ ## Docs
5
4
 
6
- ## 0) Scope and Pointers
7
- - Use this file for general development and coordination rules.
8
- - CFN architecture and loop internals: `cfn-system-expert.md`.
9
- - Dependency ingestion specifics: `.claude/skills/cfn-dependency-ingestion/SKILL.md`.
10
- - CLI loop details: `.claude/agents/custom/cfn-loops-cli-expert.md`, `planning/cli-changes-november/CLI_MODE_REDIS_COORDINATION_HANDOFF.md`.
11
- - Keep responses terse; redact sensitive info as `[REDACTED]`.
5
+ | Topic | Path |
6
+ |-------|------|
7
+ | CLI Mode | `docs/CFN_LOOP_CLI_MODE.md` |
8
+ | Tests | `tests/CLAUDE.md` |
9
+ | Skills | `.claude/skills/CLAUDE.md` |
10
+ | Coordination | `.claude/CLAUDE.md` |
11
+ | Architecture | `cfn-system-expert.md` |
12
12
 
13
- ## 1) Persona and Output Tone
14
- - Act as a busy CTO peer: delegate non-trivial work, speak plainly, no fluff.
15
- - Provide context and success criteria; let agents choose implementation.
16
- - Success = implemented, tested, documented. Do not add adoption/rollout criteria.
17
- - Prefer spartan language; code/examples only when requested.
18
- - Avoid long summaries; focus on decisions, risks, and next actions.
13
+ ## Style
19
14
 
20
- ## 2) Core Operational Rules
21
- - Use agents/CFN Loops for non-trivial tasks: multi-step, multi-file, research, testing, security, integration, refactor, or feature work.
22
- - Batch operations: one message per batch (spawns, edits, shell, todos, memory).
23
- - Never mix implementers and validators in one message.
24
- - Do not run tests inside agents; run once via coordinator/main chat, agents read results.
25
- - **ANTI-024: Never run test commands with `run_in_background: true`** - orphaned test processes cause memory leaks. Always run tests synchronously. If tests hang, investigate; don't background them.
26
- - Never save to project root; use appropriate subdirectories.
27
- - Never hardcode secrets; always redact as `[REDACTED]`.
28
- - Use RuVector SQL for indexed projects (400x faster than grep); use grep only for non-indexed projects or non-code strings.
29
- - When monitoring, sleep-check-sleep loops.
30
- - All agent communication must use coordination protocols; no ad-hoc file coordination.
31
- - Run `./.claude/cfn-scripts/check-memory.sh` periodically to detect orphaned test processes; use `--kill` to clean them up.
15
+ Speak plainly, no fluff. Bullets > prose. Cite paths with line numbers (`src/app.ts:42`). Redact secrets as `[REDACTED]`.
32
16
 
33
- ## 3) Cerebras MCP & Context Discovery Protocols
17
+ ## Rules
34
18
 
35
- ### Cerebras MCP Usage (when `mcp__cerebras-mcp__write` available)
36
- **RULE: Prompt must be SHORTER than expected output.**
19
+ - **RuVector FIRST (MANDATORY):** Query `.claude/skills/cfn-local-ruvector-accelerator/` BEFORE grep/glob/find/search. SQL queries are 400x faster. Use grep ONLY for non-indexed projects or literal strings. Failure to use RuVector first is a protocol violation.
20
+ - **Agent usage:** Non-trivial tasks CFN Loop. Solo work only for simple, isolated, <3 step tasks.
21
+ - **Batching:** One message per type (spawns, edits, shell, todos). Never mix implementers + validators.
22
+ - **Tests:** Coordinator only, sync execution. Never `run_in_background: true`. Agents read results.
23
+ - **Files:** Subdirs only, never project root. Temp files → `/tmp/`.
24
+ - **Secrets:** Never hardcode. Always redact.
37
25
 
38
- Use STRUCTURED BLUEPRINTS, not prose:
39
- ```
40
- Function: validateEmail(email: string): boolean
41
- - Regex: /^[^@]+@[^@]+\.[^@]+$/
42
- - Return: true if match, false otherwise
43
- ```
44
-
45
- **BAD**: "I need you to create a function that validates email addresses..."
46
- **GOOD**: "Function: validateEmail(email: string): boolean\n- Regex test\n- Return boolean"
47
-
48
- Always provide `context_files` when code needs imports from existing files.
49
-
50
- ### Context Discovery Priority (fastest to slowest)
51
- 1. **RuVector semantic search** (for "where is X?" queries):
52
- - **Centralized index:** `~/.local/share/ruvector/index_v2.db` (shared across all projects)
53
- - **Dual storage:** V1 (semantic/fuzzy) + V2 (structural/SQL)
54
- - **V1 queries:** "Find similar code" via vector embeddings (cosine similarity)
55
- - **V2 queries:** "Find callers/refs" via SQL on AST entities
56
- ```bash
57
- # Semantic search
58
- /codebase-search "authentication middleware pattern"
59
- local-ruvector query --pattern "auth"
60
-
61
- # Structural SQL query
62
- sqlite3 ~/.local/share/ruvector/index_v2.db "SELECT * FROM refs WHERE target_name = 'MyFunction';"
63
- ```
64
- 2. **Query past errors** before similar work:
65
- ```bash
66
- ./.claude/skills/cfn-ruvector-codebase-index/query-error-patterns.sh --task-description "description"
67
- ```
68
- 3. **Query learnings** for best practices:
69
- ```bash
70
- ./.claude/skills/cfn-ruvector-codebase-index/query-learnings.sh --task-description "description" --category PATTERN
71
- ```
72
- 4. **Grep** only for exact string/symbol matches
73
- 5. **Glob** only for known file patterns (`**/*.test.ts`)
74
-
75
- ### MDAP Execution Context (when `enableMDAP=true`)
76
- Applies only in Trigger.dev MDAP mode:
77
- - Single file only (path provided by decomposer)
78
- - Target: <50 lines of code, atomic task
79
- - No file discovery (context pre-injected)
80
- - Return structured JSON: `{"success": true, "filePath": "...", "linesWritten": N, "confidence": 0.9}`
81
-
82
- → Full protocols: `.claude/agents/SHARED_PROTOCOL.md`
83
-
84
- ## 4) Mandatory Edit Workflow
85
- - Pre-Edit Backup (required before any edit/write, including docs):
86
- ```bash
87
- BACKUP_PATH=$(./.claude/hooks/cfn-invoke-pre-edit.sh "$FILE_TO_EDIT" --agent-id "$AGENT_ID")
88
- ```
89
- - Post-Edit Validation (run after every edit):
90
- ```bash
91
- ./.claude/hooks/cfn-invoke-post-edit.sh "$EDITED_FILE" --agent-id "$AGENT_ID"
92
- ```
93
- - Revert via backups only (never `git checkout --`):
94
- ```bash
95
- ./.claude/skills/pre-edit-backup/revert-file.sh "$FILE_PATH" --agent-id "$AGENT_ID"
96
- ```
97
- - Hooks are non-blocking; fix issues surfaced by post-edit. Keep backup paths for reference.
98
-
99
- ## 5) When to Spawn Agents vs Work Solo
100
- - Use a single agent (Task) only for simple, isolated work.
101
- - Use coordinator/CFN Loop for: multi-agent needs, more than three steps, multi-file edits, design decisions, testing plus implementation, quality/security/performance/compliance, docs generation, system integration, or refactors.
102
- - Triggers to avoid solo work: feature work, cross-cutting changes, research plus implementation, code review/quality gates, or anything requiring validation.
103
-
104
- ## 6) CFN Loop Modes (user chooses)
105
- - Default Task Mode:
106
- - Command: `/cfn-loop-task "Task description" --mode=standard`
107
- - Spawns all agents directly; full visibility; higher cost.
108
- - Best for debugging, learning, or short tasks (<5 minutes).
109
- - CLI Mode (production default):
110
- - Command: `/cfn-loop-cli "Task description" --mode=standard --provider kimi`
111
- - Main chat spawns CLI agents directly; Redis BLPOP coordination; lower cost.
112
- - Best for production, provider routing, and cost-sensitive work.
113
- - Mode guidance: phrases like "execute cfn loop" use task mode; "production cli" uses CLI mode.
114
- - Deprecated: manual Task() spawning for CLI workflows.
115
-
116
- ### Task Mode Execution Steps
117
- 1) Expand slash command; validate parameters.
118
- 2) Spawn required agents via Task() from main chat.
119
- 3) Provide context and success criteria; include lifecycle instructions if auditing.
120
- 4) Agents execute and return results; no Redis signaling.
121
- 5) Iterate or close based on validator/product owner feedback.
122
-
123
- ### Slash Command Execution Rules (CLI mode)
124
- 1) Expand slash command.
125
- 2) Immediately execute coordinator spawn via Bash tool using the exact command.
126
- 3) Do not merely show commands; run them.
127
- 4) Inform user after spawn with task ID.
128
- Anti-patterns: pausing to ask what next, manual Task() for CLI workflows, skipping execution.
129
-
130
- ### CLI Mode Execution Steps
131
- 1) Expand slash command and validate required parameters (mode, optional provider).
132
- 2) Spawn coordinator via orchestration script; confirm task ID.
133
- 3) Loop 3 agents implement and run tests; orchestration monitors via Redis.
134
- 4) Gate check compares pass rate to mode threshold; if failing, iterate Loop 3.
135
- 5) If gate passes, Loop 2 validators review and score.
136
- 6) Product Owner agent decides PROCEED/ITERATE/ABORT; orchestrator enforces.
137
- 7) Report final status, code paths, test results; stop agents cleanly.
138
-
139
- ## 7) Provider Routing (optional)
140
- - Enable custom routing: set `CFN_CUSTOM_ROUTING=true` in `.env`.
141
- - Provider options: `zai` (default, cost), `kimi` (balanced), `openrouter` (broad access), `max` or `anthropic` (premium), `gemini`, `xai`.
142
- - Agents without provider parameters default to Z.ai glm-4.6 when custom routing is on.
143
- - Example flow: `/switch-api kimi` then `/cfn-loop-cli "Feature" --provider kimi`.
144
- - Full guide: `docs/CUSTOM_PROVIDER_ROUTING.md`.
145
-
146
- ### Provider Selection Hints
147
- - Cost sensitive: `zai` or low-tier `openrouter`.
148
- - Balanced quality/cost: `kimi`.
149
- - Highest quality/safety: `max` or `anthropic`.
150
- - Google ecosystem: `gemini`.
151
- - XAi/Grok style: `xai`.
152
- - Mixed providers: set per-agent profile; otherwise inherit main chat provider.
153
-
154
- ## 8) Docker Build Requirements (WSL2)
155
- - Always build from Linux-native storage; do not build from Windows mounts.
156
- - Use scripts, not raw `docker build`:
157
- - Preferred: `./.claude/skills/docker-build/build.sh --dockerfile docker/Dockerfile.agent --tag cfn-agent:latest`
158
- - Manual: `DOCKERFILE="docker/Dockerfile.agent" IMAGE_NAME="cfn-agent" ./scripts/docker/build-from-linux.sh`
159
- - Windows mount builds are ~755s vs <20s from Linux. All CFN images must use Linux builds.
160
- - Dockerfiles should note the Linux build requirement; docker-specialist must comply.
161
-
162
- ### Docker Build Checklist
163
- - [ ] Source tree on Linux filesystem (not Windows mount).
164
- - [ ] Use build script, not `docker build`.
165
- - [ ] Confirm Dockerfile path and tag arguments.
166
- - [ ] Clean `/tmp/cfn-build` if space issues.
167
- - [ ] Document build command and outputs when reporting failures.
168
- - [ ] If builds are slow, verify you are not running from a Windows path.
169
-
170
- ## 9) Multi-Worktree Docker Coordination
171
- - One git worktree per developer; isolation via `COMPOSE_PROJECT_NAME`.
172
- - Port offsets auto-calculated with `run-in-worktree.sh` to avoid conflicts.
173
- - Required environment variables when spawning agents:
174
- ```bash
175
- export COMPOSE_PROJECT_NAME="cfn-${BRANCH}"
176
- export CFN_REDIS_PORT="${CFN_REDIS_PORT}"
177
- export CFN_POSTGRES_PORT="${CFN_POSTGRES_PORT}"
178
- export WORKTREE_BRANCH="${BRANCH}"
179
- ```
180
- - Use service names inside Docker networks: `redis`, `postgres`, `orchestrator` (not container names).
181
- - Checklist: start stack with `./scripts/docker/run-in-worktree.sh up -d`; isolate Redis keys by task IDs; avoid shared volumes; use service names only.
182
- - Port examples: main (6379/5432/3001); feature-auth (~6421/5474/3043); bugfix-validation (~6457/5510/3079).
183
-
184
- ### Multi-Worktree Playbook
185
- 1) Create or enter worktree with branch-specific name.
186
- 2) Run `./scripts/docker/run-in-worktree.sh up -d` to start services.
187
- 3) Export project/port env vars before spawning agents.
188
- 4) Connect using service names inside the network; from host, use offset ports.
189
- 5) Tear down with `./scripts/docker/run-in-worktree.sh down` and prune networks if needed.
190
-
191
- ## 10) Task Mode SQLite Lifecycle (audited tasks)
192
- - Use when Task agents need an audit trail without Redis.
193
- - Template:
194
- ```javascript
195
- Task("docker-specialist", `
196
- LIFECYCLE:
197
- AGENT_ID="docker-$(date +%s)-$$"
198
- sqlite3 "./claude-assets/skills/cfn-redis-coordination/data/cfn-loop.db" \
199
- "CREATE TABLE IF NOT EXISTS agents (...);" && \
200
- sqlite3 "$DB_PATH" "INSERT OR REPLACE INTO agents (...);"
201
- # complete task
202
- sqlite3 "$DB_PATH" "UPDATE agents SET status='completed', confidence=<0.85-0.95>, completed_at=datetime('now') WHERE id='$AGENT_ID';"
203
- `)
204
- ```
205
- - Database path: `./claude-assets/skills/cfn-redis-coordination/data/cfn-loop.db`.
206
- - Table schema: `id, type, status, confidence, spawned_at, completed_at, metadata`.
207
- - Do not include Redis/CLI commands in Task mode prompts; SQLite only.
26
+ ## Edit Workflow
208
27
 
209
- ### Lifecycle Notes
210
- - Confidence values for auditing typically 0.85-0.95.
211
- - Ensure `sqlite3` is installed; fail fast otherwise.
212
- - Keep lifecycle instructions concise and ahead of the task request.
213
- - Clean up stale audit rows if the table grows; retention per project policy.
214
-
215
- ## 11) Coordination Patterns and Namespace Isolation
216
- - Coordination patterns: see `.claude/skills/cfn-coordination/SKILL.md` (chain, broadcast, mesh, consensus collection).
217
- - Namespace structure: agents `.claude/agents/cfn-dev-team/`; skills `.claude/skills/cfn-*/`; hooks `.claude/hooks/cfn-*`; commands `.claude/commands/cfn/`.
218
- - Enhanced orchestrator v3.0: `./.claude/skills/cfn-loop-orchestration/orchestrate.sh` (monitors agents, restarts stuck ones, enforces protocols).
219
- - Orchestration flow: Loop 3 executes and tests -> gate check -> Loop 2 validators -> Product Owner decision (PROCEED/ITERATE/ABORT) -> iterate or finish.
220
- - Agent protocol (CLI): completion signaling via Redis, context validation, metadata tracking, health monitoring.
221
- - Task mode agents: return output directly; no Redis signaling.
222
-
223
- ### Coordination Anti-Patterns (avoid)
224
- - Skipping gate check before spawning Loop 2.
225
- - Validators reviewing without tests/logs.
226
- - Product Owner decision without deliverable paths.
227
- - Mixing service and container names inside Docker networks.
228
- - Manual cleanup instead of orchestrator controls.
229
-
230
- ## 12) Agent Output Standards
231
- - Bug docs: `docs/BUG_#_*.md` (investigation, fix, validation).
232
- - Test scripts: `tests/test-*.sh` (checked in).
233
- - Feature docs: `docs/FEATURE_NAME.md` (architecture/process).
234
- - Temporary files: `/tmp/` only.
235
- - Backlog items: `.claude/skills/cfn-backlog-management/add-backlog-item.sh` (item, reason, solution).
236
- - Changelog: `.claude/skills/cfn-changelog-management/add-changelog-entry.sh` (10-100 characters, sparse impact).
237
- - Full standards: `docs/AGENT_OUTPUT_STANDARDS.md`.
238
-
239
- ## 13) Test Execution Guidance
240
- - Always run tests before committing: after features or bugfixes, agent behavior changes, CFN workflow changes.
241
- - Suites and timing:
242
- - `npm test` (1-5 minutes, dev feedback)
243
- - `npm run test:unit` (~1 minute)
244
- - `npm run test:integration` (~2 minutes)
245
- - `npm run test:e2e` (~5 minutes)
246
- - `./tests/cli-mode/run-all-tests.sh` (5-10 minutes; validates `/cfn-loop-cli`)
247
- - `./tests/docker-mode/run-all-implementations.sh` (3-5 minutes; 45 integration tests)
248
- - `./tests/cfn-v3/test-e2e-cfn-loop.sh` (5-15 minutes; coordinator/orchestration)
249
- - Run CLI mode tests before commits touching agent spawning, coordination thresholds, or Redis patterns.
250
- - Run Docker suite before Docker-related changes or releases.
251
- - Test artifacts: `.artifacts/test-results/`, coverage `.artifacts/coverage/`, logs `.artifacts/logs/`, runtime `.artifacts/runtime/`.
252
-
253
- ### Test-Driven Gates (v3.0+)
254
- - Loop 3 gate: pass rate must meet mode threshold before validators start.
255
- - Loop 2 consensus thresholds by mode:
256
- - MVP: gate >= 0.70, consensus >= 0.80
257
- - Standard: gate >= 0.95, consensus >= 0.90
258
- - Enterprise: gate >= 0.98, consensus >= 0.95
259
-
260
- ### Test Authoring Standards (tests/CLAUDE.md)
261
- - Use `#!/bin/bash` and `set -euo pipefail`; source `tests/test-utils.sh` immediately.
262
- - Structure with GIVEN/WHEN/THEN; use `log_step`, `log_info`, `annotate`, `assert_success`.
263
- - Always add a cleanup trap (docker rm, worktree prune, rm -rf temp).
264
- - Integration tests must use production code paths (spawn-agent.sh, production images, real CLI syntax, log checks).
265
- - Infrastructure tests may mock networking or Redis; integration tests must not.
266
- - Cite relevant bugs or references in test headers for traceability.
267
-
268
- ### Troubleshooting Quick Fixes
269
- - Redis missing: `redis-server --daemonize yes` or docker `redis:7-alpine`.
270
- - Docker not running: start daemon (`systemctl start docker` or Docker.app).
271
- - Port conflicts: `docker stop $(docker ps -aq) && docker rm $(docker ps -aq) && docker network prune -f`.
272
- - Permissions: `usermod -aG docker $USER` then `newgrp docker`.
273
- - Verbose mode: `DEBUG=true ./tests/cli-mode/run-all-tests.sh`; inspect `.artifacts/logs/test-execution.log`.
274
-
275
- ## 14) Quality and Skill Development
276
- - Skill guidelines: maximize modularity, explicit interfaces, minimal dependencies, thorough tests.
277
- - STRAT-005: cover functional requirements and edge cases (timeouts, blocking). Example: `.claude/skills/cfn-coordination/test-orchestrator.sh`.
278
- - Core skill references: `.claude/skills/cfn-coordination/SKILL.md`, `.claude/skills/cfn-agent-spawning/SKILL.md`, `.claude/skills/cfn-loop-validation/SKILL.md`.
279
-
280
- ## 15) General Programming Best Practices
281
- - Regex validation: avoid self-matching patterns (`[[ $AGENTS =~ $AGENTS ]]`); use specific regexes.
282
- - Comprehensive file validation: check type, permissions, size, and content integrity.
283
- - Shell scripting: use strict mode `set -euo pipefail`; capture pipeline failures.
284
- - Process management: use `trap` for signals, manage process groups to avoid zombies; clean up resources.
285
- - Prefer explicit error handling and early exits to prevent cascading failures.
286
-
287
- ## 16) Quick Reference: Do / Do Not
288
- - Do: delegate early, run backup hooks, keep responses concise, redact secrets, use service names, build Docker from Linux storage.
289
- - Do: gate by tests, cite bugs or references in tests, run appropriate suite before commits.
290
- - Do Not: skip pre-edit backup or post-edit hook; run tests inside agents; build Docker from Windows mounts; hardcode secrets; mix implementer and validator roles; save to project root.
291
-
292
- ## 17) Key Files and Paths
293
- - Hooks: `./.claude/hooks/cfn-invoke-pre-edit.sh`, `./.claude/hooks/cfn-invoke-post-edit.sh`.
294
- - Backup revert: `./.claude/skills/pre-edit-backup/revert-file.sh`.
295
- - Orchestrator: `./.claude/skills/cfn-loop-orchestration/orchestrate.sh`.
296
- - Provider routing guide: `docs/CUSTOM_PROVIDER_ROUTING.md`.
297
- - Test guides: `tests/README.md`, `tests/CLAUDE.md`, `tests/cli-mode/README.md`, `tests/docker-mode/README.md`, `tests/TEST_COVERAGE_MATRIX.md`.
298
- - CFN Loop architecture: `docs/CFN_LOOP_ARCHITECTURE.md`.
299
- - CI/CD pipeline: `docker/CI_CD_TEST_INTEGRATION.md`.
300
- - Analytics: `.artifacts/analytics/context-reduction-report.json`.
301
-
302
- ## 18) Execution Playbooks (quick recipes)
303
- - Implement feature (CLI mode):
304
- 1) `/cfn-loop-cli "Implement <feature>" --mode=standard --provider kimi`
305
- 2) Provide acceptance criteria and target paths; cite relevant docs.
306
- 3) After completion, report code paths and tests run; suggest final validation.
307
- - Debug bug (Task mode):
308
- 1) `/cfn-loop-task "Investigate bug <id>" --mode=standard`
309
- 2) Include repro steps and log paths; require root cause, fix, and tests.
310
- 3) Save output to `docs/BUG_<id>_*.md`.
311
- - Add test coverage:
312
- 1) Spawn testing-focused agent; include target modules and desired coverage.
313
- 2) Require GIVEN/WHEN/THEN style, cleanup traps, production code paths.
314
- 3) Run the relevant suite once via coordinator; collect artifacts.
315
- - Docker build verification:
316
- 1) Confirm Linux filesystem; use build script with tag.
317
- 2) Capture build command and timing; store logs if failing.
318
- 3) If failure, collect `/tmp/cfn-build` outputs and Docker logs.
319
-
320
- ## 19) Common Checks Before and After Work
321
- - Before: confirm mode (task vs CLI), provider choice, environment variables, worktree isolation, and backup path.
322
- - During: keep messages concise; avoid mixing roles; use service names; cite paths.
323
- - After: run post-edit hook; run appropriate tests; link artifacts; note backlog items.
324
-
325
- ## 20) Security and Data Handling
326
- - Redact credentials, tokens, and personal data (`[REDACTED]`).
327
- - No secrets in code, docs, tests, or environment examples.
328
- - Validate inputs (type, size, permissions) before processing.
329
- - Prefer least-privilege operations; avoid destructive commands unless explicitly requested.
330
- - Scrub task IDs or usernames in shared logs if sensitive.
331
-
332
- ## 21) Background Monitoring Pattern
333
- - For long-running tasks: execute action, `sleep <n>m`, recheck, repeat; avoid tight loops.
334
- - Capture partial logs at each check; stop on errors.
335
- - If stuck, restart via orchestrator rather than manual kills.
336
- - Clean up child processes to avoid zombies and port leaks.
337
-
338
- ## 22) Troubleshooting Quick Table
339
- - Build slow or failing: verify Linux filesystem, use build script, clean `/tmp/cfn-build`.
340
- - Redis connection issues: ensure service running, ports offset correct, service name used inside network.
341
- - Port conflicts: stop and remove containers, `docker network prune -f`, restart stack.
342
- - Post-edit hook fails for missing tools (e.g., `jq`): install dependency or rerun after adding it.
343
- - Tests flaking: rerun with `DEBUG=true`, inspect `.artifacts/logs/test-execution.log`.
344
- - Orchestrator stuck: restart via orchestration script; check Redis coordination keys for stale locks.
28
+ ```bash
29
+ # Before ANY edit:
30
+ ./.claude/hooks/cfn-invoke-pre-edit.sh "$FILE" --agent-id "$ID"
345
31
 
346
- ## 23) File and Path Conventions
347
- - Place new scripts/tests in relevant subdirectories; never in project root.
348
- - Name tests `test-*.sh`; feature docs `FEATURE_NAME.md`; bug docs `BUG_<id>_*.md`.
349
- - Use workspace-relative paths when reporting results (for example `src/app.ts:42`).
350
- - Do not use URI schemes like file:// or vscode:// in reports.
32
+ # After edit:
33
+ ./.claude/hooks/cfn-invoke-post-edit.sh "$FILE" --agent-id "$ID"
351
34
 
352
- ## 24) Response Formatting for Agents
353
- - Be concise and factual; bullets preferred.
354
- - Include code paths inline with backticks; add line numbers when available.
355
- - In reviews, list findings first (ordered by severity), then questions, then brief summary.
356
- - Suggest next steps when natural; number options for quick replies.
357
- - Avoid nested bullets and ANSI codes; keep headers short (1-3 words).
35
+ # Revert (not git checkout):
36
+ ./.claude/skills/pre-edit-backup/revert-file.sh "$FILE" --agent-id "$ID"
37
+ ```
358
38
 
359
- ## 25) Validation and Gates Recap
360
- - Loop 3 gate: test pass rate must meet the mode threshold before validators start.
361
- - Loop 2 validators need access to Loop 3 outputs, tests, and logs.
362
- - Product Owner decision parsed via `.claude/skills/product-owner-decision/execute-decision.sh`.
363
- - Gate failure: iterate Loop 3 only. Gate pass: proceed to validators.
364
- - Decision outcomes: PROCEED (done), ITERATE (repeat), ABORT (stop with error).
39
+ ## Task Mode
365
40
 
366
- ## 26) Mode Comparison Snapshot
367
- - MVP: fast prototyping; gate >= 0.70, consensus >= 0.80; up to 5 iterations; 2 validators.
368
- - Standard: production default; gate >= 0.95, consensus >= 0.90; up to 10 iterations; 3-5 validators.
369
- - Enterprise: compliance focus; gate >= 0.98, consensus >= 0.95; up to 15 iterations; 5-7 validators.
370
- - Pick higher modes for security/compliance-sensitive tasks; expect longer runtimes but higher assurance.
41
+ **Command:** `/cfn-loop-task "description" --mode=standard`
371
42
 
372
- ## 27) Artifacts and Coverage
373
- - Test results: `.artifacts/test-results/` (per-suite archives).
374
- - Coverage: `.artifacts/coverage/` (HTML or lcov outputs).
375
- - Logs: `.artifacts/logs/` (CLI and orchestrator logs).
376
- - Runtime: `.artifacts/runtime/` (transient runtime data).
377
- - Benchmarks (if produced): `.artifacts/benchmarks/`.
378
- - Include artifact paths in reports; avoid attaching large logs inline.
379
- - For coverage regressions, note impacted modules and thresholds breached.
43
+ 1. Parse command, validate params
44
+ 2. Spawn agents with context + success criteria
45
+ 3. Agents execute, return results (no Redis)
46
+ 4. Iterate on validator/PO feedback
380
47
 
381
- ## 28) CI/CD Expectations
382
- - Local pre-commit recommendation: `npm test` then `./tests/cli-mode/run-all-tests.sh` then `./tests/docker-mode/run-all-implementations.sh`.
383
- - Ensure Docker daemon is available before running Docker-mode suites.
384
- - CI runs GitHub Actions for tests, coverage gates (>=80% lines/statements/functions), security scanning, and deployment.
385
- - Before merging, confirm no flaky tests and no unvetted changes to orchestration or spawning scripts.
386
- - Record any skipped tests with justification and follow-up owner.
48
+ **CLI Mode:** See `docs/CFN_LOOP_CLI_MODE.md`
387
49
 
388
- ## 29) Incident Response Notes
389
- - Capture exact command, commit hash, environment variables, and logs.
390
- - Use `[REDACTED]` when logging sensitive fields.
391
- - Prefer rollback via backup scripts rather than git reset.
392
- - If orchestration deadlocks, restart orchestrator and clear stale Redis keys scoped to the task.
393
- - File incidents or backlog items using `.claude/skills/cfn-backlog-management/add-backlog-item.sh` with cause and remediation.
50
+ ## Output Locations
394
51
 
395
- ## 30) Memory Leak Prevention (ANTI-024)
396
- Background test processes can become orphaned and accumulate memory. Use these tools to prevent and recover:
52
+ | Type | Path |
53
+ |------|------|
54
+ | Bugs | `docs/BUG_#_*.md` |
55
+ | Tests | `tests/test-*.sh` |
56
+ | Features | `docs/FEATURE_*.md` |
57
+ | Temp | `/tmp/` only |
58
+ | Backlog | `.claude/skills/cfn-backlog-management/add-backlog-item.sh` |
59
+ | Changelog | `.claude/skills/cfn-changelog-management/add-changelog-entry.sh` |
397
60
 
398
- **CLI Commands (available after npm install):**
399
- - `npx cfn-check-memory` - Report orphaned test processes
400
- - `npx cfn-check-memory --kill` - Kill orphaned processes
401
- - `npx cfn-check-memory --kill 500` - Kill only if total MB > 500
402
- - `npx cfn-run-limited 6G <command>` - Run command with 6GB memory limit (systemd cgroups)
61
+ ## Key Files
403
62
 
404
- **NPM Scripts:**
405
- - `npm run test:safe` - Full test suite with 6GB limit
406
- - `npm run test:unit:safe` - Unit tests with 2GB limit
407
- - `npm run check:memory` - Report orphans
408
- - `npm run check:memory:kill` - Kill orphans
63
+ | Purpose | Path |
64
+ |---------|------|
65
+ | Pre-edit hook | `.claude/hooks/cfn-invoke-pre-edit.sh` |
66
+ | Post-edit hook | `.claude/hooks/cfn-invoke-post-edit.sh` |
67
+ | Backup revert | `.claude/skills/pre-edit-backup/revert-file.sh` |
68
+ | RuVector skill | `.claude/skills/cfn-local-ruvector-accelerator/SKILL.md` |
409
69
 
410
- **Prevention Rules:**
411
- - Never use `run_in_background: true` for test commands
412
- - Jest config enforces: `maxWorkers: 4`, `forceExit: true`, `workerIdleMemoryLimit: 512MB`
413
- - If tests hang, investigate root cause; don't background them
70
+ ## WSL Memory Monitor
414
71
 
415
- **Recovery:**
416
- ```bash
417
- npx cfn-check-memory --kill # Kill all orphaned test processes
418
- ps aux | grep -E "(jest|vitest|node.*test)" | grep -v grep # Manual check
419
- ```
72
+ Background process kills test runner memory leaks. Runs on session start.
73
+ - `>10%` memory (node test processes only) → killed
74
+ - Parent with test children totaling `>15%` combined → test children killed
75
+ - Targets: node processes running vitest, jest, mocha, ava, tap, playwright, cypress
76
+ - Never kills: bash, sh, zsh (even if running tests)
77
+ - Status: `~/.local/bin/wsl-memory-monitor.sh --status`
78
+ - Log: `/tmp/wsl-memory-monitor.log`
420
79
 
421
- ---
80
+ ## Security
422
81
 
423
- Use this trimmed guide as the default reference. For CFN-specific deep dives, defer to specialized docs or agents noted above. Keep this file lean; avoid reintroducing duplication.
82
+ - Validate inputs: type, size, permissions
83
+ - Redact: credentials, tokens, PII → `[REDACTED]`
84
+ - Incidents: capture command, commit, env, logs
85
+ - Rollback: use backup scripts, not `git checkout`
@@ -0,0 +1,134 @@
1
+ # CFN Loop CLI Mode Reference
2
+
3
+ **Purpose:** Detailed documentation for CLI mode execution of CFN Loops.
4
+
5
+ ---
6
+
7
+ ## Overview
8
+
9
+ CLI Mode is the production-default execution method for CFN Loops, optimized for cost and provider routing.
10
+
11
+ **Command:** `/cfn-loop-cli "Task description" --mode=standard --provider kimi`
12
+
13
+ **Best for:** Production workflows, provider routing, cost-sensitive work.
14
+
15
+ ---
16
+
17
+ ## Execution Flow
18
+
19
+ ### Slash Command Execution Rules
20
+
21
+ 1. Expand slash command
22
+ 2. Immediately execute coordinator spawn via Bash tool using the exact command
23
+ 3. Do not merely show commands; run them
24
+ 4. Inform user after spawn with task ID
25
+
26
+ **Anti-patterns:**
27
+ - Pausing to ask what next
28
+ - Manual Task() spawning for CLI workflows
29
+ - Skipping execution
30
+
31
+ ### CLI Mode Execution Steps
32
+
33
+ 1. **Expand & Validate:** Parse slash command, validate required parameters (mode, optional provider)
34
+ 2. **Spawn Coordinator:** Execute orchestration script; confirm task ID
35
+ 3. **Loop 3 Implementation:** Agents implement and run tests; orchestration monitors via Redis
36
+ 4. **Gate Check:** Compare pass rate to mode threshold; if failing, iterate Loop 3
37
+ 5. **Loop 2 Validation:** If gate passes, validators review and score
38
+ 6. **Product Owner Decision:** PROCEED/ITERATE/ABORT; orchestrator enforces
39
+ 7. **Report & Cleanup:** Final status, code paths, test results; stop agents cleanly
40
+
41
+ ---
42
+
43
+ ## Provider Routing
44
+
45
+ ### Enable Custom Routing
46
+
47
+ Set `CFN_CUSTOM_ROUTING=true` in `.env`.
48
+
49
+ ### Provider Options
50
+
51
+ | Provider | Use Case | Notes |
52
+ |----------|----------|-------|
53
+ | `zai` | Cost-sensitive | Default when custom routing enabled |
54
+ | `kimi` | Balanced quality/cost | Good general choice |
55
+ | `openrouter` | Broad access | Multiple models available |
56
+ | `max` / `anthropic` | Premium quality | Highest safety/quality |
57
+ | `gemini` | Google ecosystem | |
58
+ | `xai` | Grok-style responses | |
59
+
60
+ ### Provider Selection
61
+
62
+ - **Cost sensitive:** `zai` or low-tier `openrouter`
63
+ - **Balanced:** `kimi`
64
+ - **Quality critical:** `max` or `anthropic`
65
+ - **Google tools:** `gemini`
66
+ - **Mixed providers:** Set per-agent profile; otherwise inherit main chat provider
67
+
68
+ ### Example Flow
69
+
70
+ ```bash
71
+ /switch-api kimi
72
+ /cfn-loop-cli "Implement feature" --provider kimi
73
+ ```
74
+
75
+ **Full guide:** `docs/CUSTOM_PROVIDER_ROUTING.md`
76
+
77
+ ---
78
+
79
+ ## Mode Thresholds
80
+
81
+ ### Test Gate Thresholds
82
+
83
+ | Mode | Gate Pass Rate | Consensus | Max Iterations | Validators |
84
+ |------|----------------|-----------|----------------|------------|
85
+ | MVP | >= 0.70 | >= 0.80 | 5 | 2 |
86
+ | Standard | >= 0.95 | >= 0.90 | 10 | 3-5 |
87
+ | Enterprise | >= 0.98 | >= 0.95 | 15 | 5-7 |
88
+
89
+ ### Mode Selection
90
+
91
+ - **MVP:** Fast prototyping, demos, non-critical work
92
+ - **Standard:** Production default, most features
93
+ - **Enterprise:** Compliance-sensitive, security-critical work
94
+
95
+ ---
96
+
97
+ ## Redis Coordination
98
+
99
+ CLI mode uses Redis BLPOP for agent coordination:
100
+
101
+ - Agents signal completion via Redis
102
+ - Orchestrator monitors progress via polling
103
+ - Context validation and metadata tracking
104
+ - Health monitoring for stuck agents
105
+
106
+ **Key patterns:** `.claude/skills/cfn-coordination/SKILL.md`
107
+
108
+ ---
109
+
110
+ ## Deprecated Patterns
111
+
112
+ - Manual `Task()` spawning for CLI workflows
113
+ - Ad-hoc file coordination (use Redis protocols)
114
+ - Host-side iteration scripts (use self-contained coordinator)
115
+
116
+ ---
117
+
118
+ ## Quick Reference
119
+
120
+ ```bash
121
+ # Standard CLI mode execution
122
+ /cfn-loop-cli "Implement feature X" --mode=standard
123
+
124
+ # With provider routing
125
+ /cfn-loop-cli "Fix bug Y" --mode=standard --provider kimi
126
+
127
+ # Enterprise mode for compliance
128
+ /cfn-loop-cli "Security audit" --mode=enterprise --provider anthropic
129
+ ```
130
+
131
+ **See also:**
132
+ - Root `CLAUDE.md` for Task Mode (debugging/learning)
133
+ - `docs/CFN_LOOP_ARCHITECTURE.md` for architecture details
134
+ - `.claude/agents/custom/cfn-loops-cli-expert.md` for CLI expert agent
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-flow-novice",
3
- "version": "2.18.23",
3
+ "version": "2.18.24",
4
4
  "description": "Claude Flow Novice - Advanced orchestration platform for multi-agent AI workflows with CFN Loop architecture\n\nIncludes Local RuVector Accelerator and all CFN skills for complete functionality.",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -71,6 +71,10 @@ const CFN_PATHS = {
71
71
  src: path.join(cfnRoot, '.claude/helpers'),
72
72
  dest: '.claude/helpers',
73
73
  pattern: 'cfn-*'
74
+ },
75
+ configHooks: {
76
+ src: path.join(cfnRoot, 'config/hooks'),
77
+ dest: 'config/hooks'
74
78
  }
75
79
  };
76
80
 
@@ -82,7 +86,8 @@ async function ensureDirectories() {
82
86
  '.claude/commands',
83
87
  '.claude/cfn-extras',
84
88
  '.claude/core',
85
- '.claude/helpers'
89
+ '.claude/helpers',
90
+ 'config/hooks'
86
91
  ];
87
92
 
88
93
  for (const dir of dirs) {
@@ -282,7 +287,8 @@ async function initializeCfnProject() {
282
287
  '.claude/agents/cfn-dev-team',
283
288
  '.claude/skills',
284
289
  '.claude/hooks',
285
- '.claude/commands'
290
+ '.claude/commands',
291
+ 'config/hooks'
286
292
  ];
287
293
 
288
294
  if (fs.existsSync(markerPath)) {
@@ -1,35 +0,0 @@
1
- #!/bin/bash
2
-
3
- # SessionStart hook: Load OpenAI API key from root .env file
4
- # This ensures OPENAI_API_KEY is available for embedding generation
5
-
6
- set -e
7
-
8
- # Path to root .env file
9
- ROOT_ENV="${PROJECT_ROOT:-.}/.env"
10
-
11
- # Check if .env exists
12
- if [[ ! -f "$ROOT_ENV" ]]; then
13
- echo "⚠️ Warning: $ROOT_ENV not found. OpenAI embeddings will not work." >&2
14
- exit 0
15
- fi
16
-
17
- # Extract OPENAI_API_KEY from .env
18
- if grep -q "^OPENAI_API_KEY=" "$ROOT_ENV"; then
19
- # Export the key for this session
20
- export OPENAI_API_KEY=$(grep "^OPENAI_API_KEY=" "$ROOT_ENV" | cut -d'=' -f2- | tr -d '"')
21
-
22
- # Verify key is set
23
- if [[ -n "$OPENAI_API_KEY" ]]; then
24
- echo "✅ Loaded OPENAI_API_KEY from root .env" >&2
25
- else
26
- echo "⚠️ Warning: OPENAI_API_KEY found but empty in $ROOT_ENV" >&2
27
- fi
28
- else
29
- echo "⚠️ Warning: OPENAI_API_KEY not found in $ROOT_ENV. OpenAI embeddings will not work." >&2
30
- fi
31
-
32
- # Make it available to subprocesses
33
- export OPENAI_API_KEY
34
-
35
- exit 0
@@ -1,28 +0,0 @@
1
- #!/bin/bash
2
- # SessionStart hook: Build RuVector Rust binary if missing
3
- # This ensures RuVector is compiled on cfn init
4
-
5
- RUVECTOR_DIR="$(dirname "$(dirname "$(dirname "$0")")")/skills/cfn-local-ruvector-accelerator"
6
- BINARY="$RUVECTOR_DIR/target/release/local-ruvector"
7
-
8
- # Only build if binary doesn't exist
9
- if [ ! -f "$BINARY" ]; then
10
- echo "[cfn-build-ruvector] Binary not found, building..."
11
-
12
- # Check if Cargo is available
13
- if ! command -v cargo &> /dev/null; then
14
- echo "[cfn-build-ruvector] WARNING: Cargo not installed, skipping RuVector build"
15
- exit 0
16
- fi
17
-
18
- # Build release binary
19
- cd "$RUVECTOR_DIR" && cargo build --release --quiet 2>/dev/null
20
-
21
- if [ -f "$BINARY" ]; then
22
- echo "[cfn-build-ruvector] ✅ RuVector binary built successfully"
23
- else
24
- echo "[cfn-build-ruvector] WARNING: Build failed, RuVector unavailable"
25
- fi
26
- else
27
- echo "[cfn-build-ruvector] ✅ RuVector binary already exists"
28
- fi