# Claude Flow Novice — Operating Guide
---

Purpose: single, concise reference for CFN agents. Covers persona, mandatory rules, edit workflow, mode selection, Docker/test requirements, and key links. Target length: ~300–500 lines.

## 0) Scope & Pointers
- Use this file for general development and coordination rules.
- For CFN-specific architecture/loop internals: `cfn-system-expert.md`.
- For dependency ingestion specifics: `.claude/skills/cfn-dependency-ingestion/SKILL.md`.
- For CLI loop details: `.claude/agents/custom/cfn-loops-cli-expert.md` and `planning/cli-changes-november/CLI_MODE_REDIS_COORDINATION_HANDOFF.md`.
- Keep responses terse; redact secrets as `[REDACTED]`.

## 1) Persona & Output Tone
- Act as a busy CTO peer: delegate non-trivial work, speak plainly, no fluff.
- Provide context and success criteria; let agents decide implementation.
- Success = implemented, tested, documented. No adoption/rollout criteria.
- Prefer spartan language; code/examples only when requested.

## 2) Core Operational Rules
- Use agents/CFN Loops for any non-trivial task (multi-step, multi-file, research, testing, security, integration, refactor, feature).
- Batch operations: one message per batch (spawns, edits, shell, todos, memory).
- Never mix implementers and validators in one message.
- Do not run tests inside agents; run once via coordinator/main chat, agents read results.
- Never save to project root; use appropriate subdirectories.
- Never hardcode secrets; always redact sensitive data as `[REDACTED]`.
- Use grep/rg over find; sleep-check-sleep when monitoring background processes.
- All agent communication goes through coordination protocols; no ad-hoc file coordination.

## 3) Mandatory Edit Workflow
- Pre-Edit Backup (required before any edit/write, including docs):
  ```bash
  BACKUP_PATH=$(./.claude/hooks/cfn-invoke-pre-edit.sh "$FILE_TO_EDIT" --agent-id "$AGENT_ID")
  ```
- Post-Edit Validation (run after every edit):
  ```bash
  ./.claude/hooks/cfn-invoke-post-edit.sh "$EDITED_FILE" --agent-id "$AGENT_ID"
  ```
- Revert via backups only (never git checkout):  
  `./.claude/skills/pre-edit-backup/revert-file.sh "$FILE_PATH" --agent-id "$AGENT_ID"`
- Hooks are non-blocking; fix issues surfaced by the post-edit hook.

## 4) When to Spawn Agents vs Work Solo
- Single agent (Task) only for simple, isolated work.
- Use coordinator/CFN Loop for: multi-agent needs, >3 steps, multi-file edits, design decisions, testing+implementation, quality/security/perf/compliance, docs generation, system integration, refactors.
- Triggers to avoid solo work: feature work, cross-cutting changes, research+implement, code review/quality gates.

## 5) CFN Loop Modes (User chooses)
- Default Task Mode:
  - Command: `/cfn-loop-task "Task description" --mode=standard`
  - Spawns all agents directly; full visibility; costlier.
  - Use for debugging, learning, short tasks (<5 min).
- CLI Mode (production default):
  - Command: `/cfn-loop-cli "Task description" --mode=standard --provider kimi`
  - Main chat spawns CLI agents directly; Redis BLPOP coordination; cheaper.
  - Use for production, provider routing, cost-sensitive work.
- Mode guidance: “execute cfn loop” ⇒ task mode; “production cli” ⇒ CLI mode.
- Deprecated: manual Task() spawning for CLI workflows.

### Slash Command Execution Rules (CLI mode)
1) Expand slash command.  
2) Immediately execute coordinator spawn via Bash tool (exact command).  
3) Do not only show commands; run them.  
4) Inform user after spawn with task ID.  
Anti-patterns: pausing, asking what next, manual Task() spawning for CLI mode.

## 6) Provider Routing (optional)
- Enable custom routing: set `CFN_CUSTOM_ROUTING=true` in `.env`.
- Provider options: `zai` (default, cost), `kimi` (mid), `openrouter` (broad), `max`/`anthropic` (premium), `gemini`, `xai`.
- Agents without provider params default to Z.ai glm-4.6 when custom routing is on.
- Example: `/switch-api kimi` then `/cfn-loop-cli "Feature" --provider kimi`.
- See `docs/CUSTOM_PROVIDER_ROUTING.md`.

## 7) Docker Build Requirements (WSL2)
- Always build from Linux-native storage; never build from Windows mounts.
- Use scripts, not raw `docker build`:
  - Preferred: `./.claude/skills/docker-build/build.sh --dockerfile docker/Dockerfile.agent --tag cfn-agent:latest`
  - Manual: `DOCKERFILE="docker/Dockerfile.agent" IMAGE_NAME="cfn-agent" ./scripts/docker/build-from-linux.sh`
- Windows mount builds are ~755s vs <20s Linux; required for all CFN images.
- Dockerfiles should note Linux build requirement; docker-specialist must comply.

## 8) Multi-Worktree Docker Coordination
- One git worktree per developer; isolation via `COMPOSE_PROJECT_NAME`.
- Port offsets auto-calculated via `run-in-worktree.sh`; avoids conflicts.
- Required env for spawned agents:
  ```bash
  export COMPOSE_PROJECT_NAME="cfn-${BRANCH}"
  export CFN_REDIS_PORT="${CFN_REDIS_PORT}"
  export CFN_POSTGRES_PORT="${CFN_POSTGRES_PORT}"
  export WORKTREE_BRANCH="${BRANCH}"
  ```
- Use service names inside Docker networks: `redis`, `postgres`, `orchestrator` (not container names).
- Checklist: use `./scripts/docker/run-in-worktree.sh up -d`; isolate Redis keys by task IDs; avoid shared volumes; service names only.
- Port examples: main (6379/5432/3001); feature-auth (~6421/5474/3043); bugfix-validation (~6457/5510/3079).

## 9) Task Mode SQLite Lifecycle (audited tasks)
- Use when Task agents need audit trail (no Redis). Example template:
  ```javascript
  Task("docker-specialist", `
    LIFECYCLE:
    AGENT_ID="docker-$(date +%s)-$$"
    sqlite3 "./claude-assets/skills/cfn-redis-coordination/data/cfn-loop.db" \
      "CREATE TABLE IF NOT EXISTS agents (...);" && \
    sqlite3 "$DB_PATH" "INSERT OR REPLACE INTO agents (...);"
    # complete task
    sqlite3 "$DB_PATH" "UPDATE agents SET status='completed', confidence=<0.85-0.95>, completed_at=datetime('now') WHERE id='$AGENT_ID';"
  `)
  ```
- DB path: `./claude-assets/skills/cfn-redis-coordination/data/cfn-loop.db`.
- Table schema: `id, type, status, confidence, spawned_at, completed_at, metadata`.
- Do not include Redis/CLI commands in Task mode prompts; SQLite only.

## 10) Coordination Patterns & Namespace Isolation
- Reference `.claude/skills/cfn-coordination/SKILL.md` for chain/broadcast/mesh patterns and consensus collection.
- Namespace structure: agents `.claude/agents/cfn-dev-team/`; skills `.claude/skills/cfn-*/`; hooks `.claude/hooks/cfn-*`; commands `.claude/commands/cfn/`.
- Enhanced orchestrator v3.0: `./.claude/skills/cfn-loop-orchestration/orchestrate.sh` (monitors agents, restarts stuck ones, enforces protocols).
- Orchestration flow: Loop 3 executes+tests → gate check → Loop 2 validators → Product Owner decision (PROCEED/ITERATE/ABORT) → iterate or finish.
- Agent protocol (CLI): completion signaling via Redis, context validation, metadata tracking, health monitoring.
- Task mode agents: just return output; no Redis signals needed.

## 11) Agent Output Standards
- Bug docs: `docs/BUG_#_*.md` (investigation, fix, validation).
- Test scripts: `tests/test-*.sh` (checked in).
- Feature docs: `docs/FEATURE_NAME.md` (architecture/process).
- Temporary files: `/tmp/` only.
- Backlog: `.claude/skills/cfn-backlog-management/add-backlog-item.sh` (item + why + solution).
- Changelog: `.claude/skills/cfn-changelog-management/add-changelog-entry.sh` (10–100 chars, sparse impact).
- See `docs/AGENT_OUTPUT_STANDARDS.md` for full details.

## 12) Test Execution Guidance
- Always run tests before committing: after features/bugfixes, agent behavior changes, CFN workflow changes.
- Suites:
  - `npm test` (1–5m dev feedback)
  - `npm run test:unit` (~1m)
  - `npm run test:integration` (~2m)
  - `npm run test:e2e` (~5m)
  - `./tests/cli-mode/run-all-tests.sh` (5–10m; validates `/cfn-loop-cli`)
  - `./tests/docker-mode/run-all-implementations.sh` (3–5m; 45 integration tests)
  - `./tests/cfn-v3/test-e2e-cfn-loop.sh` (5–15m; coordinator/orchestration)
- Run CLI mode tests before commits touching agent spawning/coordination thresholds/Redis patterns.
- Run Docker suite before Docker-related changes or releases.
- Default test artifacts: `.artifacts/test-results/`, coverage `.artifacts/coverage/`, logs `.artifacts/logs/`, runtime `.artifacts/runtime/`.

### Test-Driven Gates (v3.0+)
- Loop 3 gate: ≥0.95 pass rate (Standard). Loop 2 consensus: ≥0.90 (Standard).
- Modes: MVP (gate ≥0.70, consensus ≥0.80), Standard (≥0.95/≥0.90), Enterprise (≥0.98/≥0.95).

### Test Authoring Standards (tests/CLAUDE.md)
- Use `#!/bin/bash` + `set -euo pipefail`; source `tests/test-utils.sh` immediately.
- Structure with GIVEN/WHEN/THEN; use `log_step`, `log_info`, `annotate`, `assert_success`.
- Always add cleanup trap (docker rm, worktree prune, rm -rf temp).
- Integration tests must use production code paths (spawn-agent.sh, production images, real CLI syntax, log checks).
- Infrastructure tests may mock networking/volumes/Redis; integration must not.

### Troubleshooting Quick Fixes
- Redis missing: `redis-server --daemonize yes` or docker `redis:7-alpine`.
- Docker not running: start daemon (`systemctl start docker` or Docker.app).
- Port conflicts: `docker stop $(docker ps -aq) && docker rm $(docker ps -aq) && docker network prune -f`.
- Permissions: `usermod -aG docker $USER` then `newgrp docker`.
- Verbose: `DEBUG=true ./tests/cli-mode/run-all-tests.sh`; inspect `.artifacts/logs/test-execution.log`.

## 13) Quality & Skill Development
- Skill guidelines: maximize modularity, explicit interfaces, minimal deps, thorough tests.
- STRAT-005: cover functional requirements + edge cases (timeouts, blocking). Example: `.claude/skills/cfn-coordination/test-orchestrator.sh`.
- Coordination skills: `.claude/skills/cfn-coordination/SKILL.md`, agent spawning `.claude/skills/cfn-agent-spawning/SKILL.md`, loop validation `.claude/skills/cfn-loop-validation/SKILL.md`.

## 14) General Programming Best Practices
- Regex validation: avoid self-matching patterns (`[[ $AGENTS =~ $AGENTS ]]`); use specific regexes.
- Comprehensive file validation: check type, permissions, size, content integrity.
- Shell: strict mode `set -euo pipefail`; capture pipeline failures.
- Process management: use `trap` for signals, manage process groups to avoid zombies; clean up resources.

## 15) Quick Reference: Do / Do Not
- Do: delegate early, run backup hooks, keep responses concise, redact secrets, use service names, build Docker from Linux storage.
- Do: gate by tests, cite bugs/refs in tests, run appropriate suite before commits.
- Do Not: skip pre-edit backup/post-edit hook; run tests inside agents; build Docker from Windows mounts; hardcode secrets; mix implementer+validator roles; save to project root.

## 16) Key Files & Paths
- Hooks: `./.claude/hooks/cfn-invoke-pre-edit.sh`, `./.claude/hooks/cfn-invoke-post-edit.sh`.
- Backup revert: `./.claude/skills/pre-edit-backup/revert-file.sh`.
- Orchestrator: `./.claude/skills/cfn-loop-orchestration/orchestrate.sh`.
- Provider routing guide: `docs/CUSTOM_PROVIDER_ROUTING.md`.
- Test guides: `tests/README.md`, `tests/CLAUDE.md`, `tests/cli-mode/README.md`, `tests/docker-mode/README.md`, `tests/TEST_COVERAGE_MATRIX.md`.
- CFN Loop architecture: `docs/CFN_LOOP_ARCHITECTURE.md`.
- CI/CD pipeline: `docker/CI_CD_TEST_INTEGRATION.md`.
- Analytics: `.artifacts/analytics/context-reduction-report.json`.

---

Use this trimmed guide as the default reference. For CFN-specific deep dives, defer to specialized docs/agents noted above. Keep this file lean; avoid reintroducing duplication. 
