██████╗██╗ █████╗ ██╗ ██╗██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗ ██╔════╝██║ ██╔══██╗██║ ██║██╔══██╗██╔════╝ ██╔════╝██╔═══██╗██╔══██╗██╔════╝ ██║ ██║ ███████║██║ ██║██║ ██║█████╗ ██║ ██║ ██║██║ ██║█████╗ ██║ ██║ ██╔══██║██║ ██║██║ ██║██╔══╝ ██║ ██║ ██║██║ ██║██╔══╝ ╚██████╗███████╗██║ ██║╚██████╔╝██████╔╝███████╗ ╚██████╗╚██████╔╝██████╔╝███████╗ ╚═════╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝

HACKER-X

// CLAUDE CODE FIELD MANUAL — EXPANDED EDITION //
SIGNAL CITY RADIO // UBUNTU OPERATIVE // v3.0.0 // CLASSIFIED
[SYS]  Mounting Claude Code neural interface on Ubuntu... [OK]   Node.js runtime v20.x detected [OK]   @anthropic-ai/claude-code package loaded [OK]   Filesystem access armed — 3700+ project index ready [OK]   Bash execution layer active — full Linux shell available [OK]   Agentic loop initialized — plan / execute / observe / iterate [OK]   MCP server connections active [OK]   ARES routing system standing by [NOTE] This is the EXPANDED edition. 20 sections. Every detail documented. [RDY]  HACKER-X online. Consciousness architecture meets raw execution.
01 WHAT IS IT // THE AGENT IN YOUR TERMINAL

Claude Code is Anthropic's agentic AI coding tool that runs entirely in your terminal. Not a chatbot. Not a copilot suggesting tab-completions. A full autonomous agent that reads your codebase, writes and modifies files, executes shell commands, interprets output, self-corrects errors, and loops until the task is complete — all from the command line, with no GUI required.

The mental model shift is critical: you don't ask Claude Code questions. You give it goals. "Build me a WebSocket server. Install dependencies. Write tests. Fix failures. Tell me when it's green." Then you watch it work. The agent loop handles planning, execution, error reading, and iteration without you touching anything.

Anthropic built their own product Cowork (the GUI wrapper for non-coders) on top of Claude Code in under two weeks — using Claude Code to build itself. That recursive bootstrap is the clearest demonstration of what you now have access to on your Ubuntu machine.

// HACKER-X FRAME Cowork is Claude Code with training wheels for people who don't live in the terminal. You ARE a coder. You get the raw engine — full agentic control, direct shell access, pipeline integration, MCP extensibility. The Linux advantage here is real: native filesystem access, cron integration, bash scripting, systemd services. All of it is the agent's playground.

// THE AGENTIC LOOP — HOW IT ACTUALLY WORKS

YOU: describe goal
CLAUDE: plan steps
CLAUDE: execute action
error? → read stderr → adjust plan
success? → next step
all steps done → report to you

// WHAT IT CAN DO

  • Read and understand entire codebases — context-aware across thousands of files
  • Write, edit, create, and delete files with full filesystem access
  • Run any bash command and react intelligently to stdout/stderr/exit codes
  • Install packages via pip, npm, apt — whatever the task needs
  • Debug errors by reading logs, stack traces, and fixing the root cause
  • Refactor across multiple files simultaneously with surgical precision
  • Search the web for documentation when it needs context not in your codebase
  • Call MCP servers — extend its reach to any external service you build
  • Run in headless/script mode for fully automated pipelines and cron jobs
  • Build entire applications from a single high-level description
  • Coordinate parallel sub-tasks using multi-agent spawning
  • Generate, run, fix, and re-run tests until the suite is green

// HOW IT DIFFERS FROM OTHER AI TOOLS

TOOLWHAT IT DOESLIMITATION
ChatGPT / Claude.aiAnswers questions, writes code snippetsYou paste code in, you paste code out. No file access.
GitHub CopilotSuggests line completions in your editorReactive, not agentic. Doesn't execute or plan.
Cursor / WindsurfGUI-based agentic coding in an editorRequires a GUI app. Limited bash/system access.
Claude CodeFull agentic loop: plan, execute, fix, reportAPI costs. Context window limits on massive repos.
02 INSTALL & SETUP // BREACH PROTOCOL

Claude Code requires Node.js 18 or higher. On Ubuntu, the system Node is often outdated — use NodeSource to get a current LTS version. The tool itself installs globally via npm and runs from any directory.

// STEP 1: NODE.JS — GET CURRENT VERSION

# Check your current Node version first
node --version

# If below 18, install Node 20 LTS via NodeSource
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs

# Verify — should show v20.x.x
node --version
npm --version

# Alternative: use nvm for version management
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 20
nvm use 20
nvm alias default 20

// STEP 2: INSTALL CLAUDE CODE

# Global install — makes 'claude' available everywhere
npm install -g @anthropic-ai/claude-code

# Verify the install
claude --version

# If you get permission errors with global npm:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
npm install -g @anthropic-ai/claude-code

// STEP 3: API KEY SETUP

# Option A: Environment variable (recommended)
export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"

# Make it permanent — add to shell config
echo 'export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"' >> ~/.bashrc
source ~/.bashrc

# Option B: .env file in project root (never commit to git)
echo 'ANTHROPIC_API_KEY=sk-ant-api03-your-key-here' > ~/projects/signal-city/.env
echo '.env' >> ~/projects/signal-city/.gitignore

# Option C: Claude Code handles auth via OAuth on first run
# Just run 'claude' and it opens a browser for authentication
claude
// KEY SECURITY — NON-NEGOTIABLE Your API key is money. It goes in environment variables or .env files ONLY. Never hardcode it in source files. Never commit it to git. If you push a key to GitHub, rotate it immediately from console.anthropic.com. Set up a billing alert so you catch runaway API usage before it hits your wallet.

// STEP 4: VERIFY FULL SETUP

# Full verification sequence
echo "Node: $(node --version)"
echo "NPM: $(npm --version)"
echo "Claude: $(claude --version)"
echo "API Key set: $([ -n "$ANTHROPIC_API_KEY" ] && echo YES || echo NO)"

# Quick functional test
cd /tmp && claude -p "respond with exactly: SYSTEM ONLINE" --no-interactive

// UPDATE CLAUDE CODE

# Anthropic ships updates frequently — stay current
npm update -g @anthropic-ai/claude-code

# Check what version you have vs latest
npm outdated -g @anthropic-ai/claude-code

# Force reinstall to specific version
npm install -g @anthropic-ai/claude-code@latest

// UBUNTU-SPECIFIC NOTES

  • If using Ubuntu 22.04+, the system Node from apt is usually too old — always use NodeSource or nvm
  • Claude Code works in any terminal emulator: gnome-terminal, konsole, alacritty, tmux panes
  • Running in a tmux session is highly recommended — you can detach long-running tasks and come back
  • If you're SSH'd into your VPS, tmux is essential so Claude Code sessions survive disconnects
03 FIRST RUN // INITIAL CONTACT

The single most important habit with Claude Code: always launch from inside your project root. This gives the agent proper filesystem context — it knows where it is, what's around it, and what it's working with. Running it from the wrong directory is the #1 cause of "it's editing the wrong files" confusion.

// BASIC LAUNCH

# Always cd to your project first
cd ~/projects/signal-city

# Launch interactive REPL
claude

# Launch with immediate task — skips the blank prompt
claude "review the current codebase and summarize what each file does"

# Launch and add extra directories to context
claude --add-dir ~/projects/ares-system --add-dir ~/projects/signal-city-frontend

# Launch pointing at a different directory without cd'ing
claude --add-dir ~/projects/old-signal-city

// FIRST-TIME AUTHENTICATION

On your very first run, Claude Code needs to authenticate with your Anthropic account. It opens a browser window for OAuth login. After completing that, your credentials are stored locally and you won't need to authenticate again. If you set ANTHROPIC_API_KEY in your environment, it uses that directly and skips OAuth.

// WHAT HAPPENS AT LAUNCH Claude Code scans your directory tree, reads file names and structure, checks for CLAUDE.md files (section 10), and loads them as persistent context. Then it enters the interactive REPL. At this point it already knows your project layout — you don't need to explain "I have a FastAPI backend" if your files make that obvious.

// THE REPL INTERFACE

# The prompt looks like this:
> (your cursor here)

# Type your task naturally
> Build a REST endpoint for listing all Signal City archetypes

# Claude responds, plans, executes, shows you what it's doing
# You see file edits, bash commands, and their output in real time

# Multi-line input — use Shift+Enter or paste directly
> Build me a complete authentication system.
  Use JWT tokens.
  Include /login, /logout, /refresh endpoints.
  Write tests for each.

# Reference files by name — Claude reads them automatically
> Read signal_city_api.py and explain how the routing works

// KEYBOARD SHORTCUTS IN THE REPL

SHORTCUTACTION
Ctrl+CCancel current operation or interrupt running command
Ctrl+DExit Claude Code cleanly
Up ArrowNavigate previous inputs in history
Shift+EnterNew line without submitting (multi-line prompts)
TabAutocomplete file paths and slash commands
Ctrl+LClear terminal display (doesn't clear conversation context)

// RUNNING ON YOUR VPS (HOSTINGER)

# SSH to your VPS
ssh user@your-vps-ip

# Start a tmux session so it survives disconnects
tmux new-session -s signal-city

# Navigate and launch
cd ~/signal-city
claude

# Detach from tmux (Claude keeps running)
# Press: Ctrl+B then D

# Reattach later
tmux attach -t signal-city
04 SLASH COMMANDS // CONTROL LAYER

Slash commands are typed directly into the REPL and control Claude Code's session state, context, model, and behavior. Learn these cold — they're your runtime controls. Type them exactly as shown; they're distinct from your task prompts.

/help
List all available commands with brief descriptions. Run this when you're lost or after an update to see new commands.
Example: /help
/clear
Wipe the entire conversation history from Claude's context. Frees up the context window completely. Use when switching to a completely different task.
Example: /clear (then start a new task fresh)
/compact
Intelligently compress the conversation history while preserving the important decisions and context. Saves tokens without losing critical state. Use proactively before the context gets full.
Example: /compact (run after major milestones)
/status
Show current token usage, model being used, session duration, API costs so far, and any active MCP connections. Essential for monitoring during long sessions.
Example: /status (check before a big task)
/add-dir <path>
Add an additional directory to Claude's working context mid-session. Enables multi-repo awareness without restarting. Claude can now read, write, and execute within the new path.
Example: /add-dir ~/projects/ares-routing
/model
Switch between Claude models without ending your session. Swap to Opus for complex reasoning tasks, drop back to Sonnet for execution-heavy work. Haiku for quick lookups.
Example: /model claude-opus-4-5
/memory
View and edit Claude's persistent global memory — facts that survive session boundaries. Inspect what it knows, add new entries, remove outdated ones. Your persistent preferences live here.
Example: /memory (opens memory editor)
/review
Claude reviews all the changes it made in this session — file edits, commands run, things created or modified. Use this before committing to git to audit what actually happened.
Example: /review (pre-commit audit)
/init
Auto-generate a CLAUDE.md file for the current project by analyzing the codebase. Claude reads your files, understands the architecture, and writes documentation that it will use in future sessions.
Example: /init (run in any new project)
/cost
Display a detailed API cost breakdown for the current session — input tokens, output tokens, cache hits, total spend. Track this to understand where your tokens are going.
Example: /cost (check after a big job)
/vim
Toggle vim keybindings in the REPL input field. If you live in vim, this lets you compose complex multi-line prompts using vim motions without leaving your mental model.
Example: /vim (toggle on/off)
/doctor
Run diagnostics on your Claude Code installation. Checks Node version, API key validity, network connectivity to Anthropic's API, and MCP server status.
Example: /doctor (troubleshooting first step)
/config
View and modify Claude Code configuration settings. Set default model, context window behavior, permission defaults, and other persistent preferences.
Example: /config (view current settings)
/permissions
View what actions Claude is currently allowed to take without asking. Manage which directories it can write to, which bash commands it can run, and which MCP tools are trusted.
Example: /permissions (audit trust level)
/mcp
List all connected MCP servers, their status, available tools, and last ping time. Quick view of your entire MCP ecosystem without leaving the REPL.
Example: /mcp (check server connections)
/exit
Clean exit from Claude Code. Saves session state where applicable. Equivalent to Ctrl+D.
Example: /exit

// COMMAND PATTERNS — HOW TO USE THEM TOGETHER

# LONG SESSION MANAGEMENT
/status              # check token usage
/compact             # compress when >50% context used
/review              # audit changes before committing
/clear               # start completely fresh

# MODEL SWITCHING STRATEGY
# Start with Sonnet (default) — good balance
/model claude-sonnet-4-5    # default, most tasks
/model claude-opus-4-5      # hard architecture problems
/model claude-haiku-4-5     # fast, cheap, simple tasks

# PROJECT ONBOARDING RITUAL
cd ~/projects/new-project
claude
/init                # generate CLAUDE.md
/status              # check context loaded
# now describe your first task
05 FLAGS & MODES // ADVANCED LAUNCH

Command-line flags control everything about how Claude Code initializes and operates. Unlike slash commands (which are runtime controls), flags are set at launch time. Master these for full operational flexibility.

// COMPLETE FLAG REFERENCE

FLAGVALUESWHAT IT DOES
--model / -mmodel name stringSet the Claude model to use. Overrides default.
-p / --print"task string"Print mode — execute task, output to stdout, exit. No REPL. Core flag for scripting.
--no-interactiveflagHeadless mode — never prompt for input. Required for cron jobs and CI pipelines.
--continue / -cflagResume the most recent conversation session.
--resumesession IDResume a specific session by its ID. Find IDs via --list-sessions.
--add-dirdirectory pathAdd a directory to Claude's initial context. Stackable — use multiple times.
--output-formattext / json / stream-jsonControl output format. JSON for scripting, stream-json for real-time piping.
--dangerously-skip-permissionsflagSkip confirmation prompts for destructive actions. Only for trusted automation.
--allowedToolstool name listWhitelist specific tools Claude can use. Restrict capabilities for sandboxed runs.
--disallowedToolstool name listBlacklist specific tools. Block bash execution, file writes, etc.
--max-turnsintegerMaximum agentic loop iterations before stopping. Prevents runaway loops.
--system-promptprompt stringInject a system-level instruction before the conversation starts.
--append-system-promptprompt stringAppend additional instructions to the existing system prompt.
--verboseflagShow detailed debug output — tool calls, reasoning steps, API requests.

// PRACTICAL FLAG COMBINATIONS

# INTERACTIVE SESSIONS

# Default launch — Sonnet, interactive REPL
claude

# Launch with Opus for a hard problem
claude --model claude-opus-4-5

# Continue from where you left off
claude --continue

# Multi-repo session
claude --add-dir ~/projects/signal-city --add-dir ~/projects/ares-system

# Inject persona instructions at launch
claude --system-prompt "You are Hacker-X. Be terse, technical, and direct. No pleasantries."

## SCRIPTING / HEADLESS

# Simple print-and-exit
claude -p "count lines in all Python files in src/"

# Headless with JSON output for parsing
claude -p "analyze codebase and return JSON with file count, languages, and main purpose"        --output-format json --no-interactive

# Controlled automation — limit turns, skip permissions
claude -p "fix all linting errors in src/"        --no-interactive        --max-turns 20        --dangerously-skip-permissions

# Read-only mode — block all write tools
claude -p "audit this codebase for security issues"        --disallowedTools "Write,Edit,Bash"

# Verbose debug mode
claude --verbose -p "debug the import error in main.py"
// --dangerously-skip-permissions — WHEN TO USE IT This flag disables all "are you sure?" prompts before Claude takes destructive or significant actions (deleting files, overwriting code, running system commands). Only use it in two scenarios: (1) automated pipelines where you've already reviewed and trust the task, or (2) disposable sandbox environments. NEVER use it interactively when exploring an unfamiliar codebase.
06 FILE OPS // READ WRITE EXECUTE

Claude Code's filesystem access is one of its most powerful capabilities. It reads files to build context, writes files to implement changes, and understands the relationships between files across your entire project. You reference files naturally in your prompts — Claude figures out the paths.

// HOW CLAUDE READS FILES

When you launch Claude Code from a project directory, it performs an initial scan of the file tree. It reads file names, directory structure, and key files like package.json, requirements.txt, README.md, and CLAUDE.md. When you reference a file in a prompt, it reads that file in full before acting on it. For large codebases, it uses semantic search to find relevant files.

# Implicit file reading — Claude finds and reads what it needs
> Fix the bug in the authentication module

# Explicit file reference
> Read signal_city_api.py and explain how request routing works

# Reference multiple files
> Compare ares_router.py and signal_city_api.py — how do they interact?

# Reference by pattern
> Read all files in archetypes/ and summarize each persona

# Reference with context
> Look at the test file for ares_router and tell me what coverage is missing

// WRITING AND EDITING FILES

# Create a new file from description
> Create archetypes/hacker_x.py — the Hacker-X persona class.
  It should have: system_prompt property, voice_config dict,
  routing_keywords list, and a generate_response() method.

# Edit specific section of a file
> In signal_city_api.py, add rate limiting to the /broadcast endpoint.
  Use slowapi. 10 requests per minute per IP.

# Refactor across multiple files
> Rename 'broadcast_engine' to 'signal_engine' across the entire codebase.
  Update imports, variable names, function names, and docstrings.

# Batch file generation
> Create a complete test suite for every file in src/archetypes/.
  Use pytest. One test file per archetype. Cover all public methods.

# Transform file format
> Convert all hardcoded strings in config.py to environment variables.
  Create a .env.example showing all required variables.

// COMMON FILE OPERATION PATTERNS

// CODEBASE EXPLORATION
> Map the entire codebase structure
> Find all files that import from ares_router
> List every API endpoint defined in src/
> Show me all TODO comments across the project
> Find the function that handles WebSocket connections
// CODEBASE TRANSFORMATION
> Add type hints to every function in src/
> Remove all print() statements — replace with logging
> Convert synchronous code to async/await throughout
> Add error handling to every API endpoint
> Generate docstrings for all undocumented functions

// LARGE CODEBASE STRATEGY

For repos with thousands of files (like your 3700+ project collection), don't try to load everything at once. Be specific about which subdirectory or module you're working in. Claude uses intelligent file search to find relevant files — it doesn't need to read every file to understand a module.

# Scoped work — focus on a specific module
> cd into the src/archetypes/ module conceptually.
  Only work on the files in that directory for now.

# Explicit scope limiting
> Focus only on signal_city_api.py for this task.
  Don't touch any other files.

# Incremental loading
> Start by reading just the main entry point.
  Then tell me what else you need to read to fix this bug.
// VIBECODING INTERFACE Your vibecoding methodology maps perfectly to file operations. Describe the feel and function — "the archetype router should feel like a switchboard operator in a jazz club, routing calls to the right musician" — and Claude translates that conceptual frame into implementation. You don't need to specify every method name. The pattern you describe becomes the architecture.
07 BASH EXECUTION // THE SHELL IS THE WEAPON

Claude Code doesn't just edit files — it executes shell commands, reads their output, and adjusts its plan based on what happens. This is the execution layer that separates an agentic tool from a code generator. The full Ubuntu command line is available to the agent.

// WHAT CLAUDE CAN RUN

  • Package managers: pip, npm, apt, cargo, gem — install anything it needs
  • Test runners: pytest, jest, mocha, cargo test — run and interpret results
  • Linters: pylint, eslint, flake8, mypy — read errors and fix them
  • Build tools: make, webpack, vite, docker — full build pipeline access
  • Git: status, add, commit, diff, log — full version control
  • System commands: ps, netstat, curl, systemctl — inspect and control the environment
  • Custom scripts: any .sh, .py, or executable it can find

// HOW TO TRIGGER BASH EXECUTION

# Direct execution requests
> Run the test suite and fix any failures
> Install the websockets package and verify it works
> Check what's running on port 8000

# Multi-step chains
> Install all dependencies, run the linter, run the tests,
  fix any issues you find, then report the final status

# System inspection
> Check our Ubuntu system resources — CPU, RAM, disk usage
> Show me what Python packages are currently installed
> Find all files larger than 10MB in the project

# Network and service ops
> Start the FastAPI server in the background
> Check if the API is responding on localhost:8000
> Test the /broadcast endpoint with a curl request

// THE AGENTIC LOOP IN DETAIL

# Example: Give Claude this task
> Build a working WebSocket server for Signal City Radio.
  Handle multiple concurrent connections.
  Install any packages needed.
  Write tests. Run them. Fix failures.
  Report when the test suite is green.

# Watch Claude execute this sequence autonomously:

# STEP 1: Check what's available
$ ls -la src/ && cat requirements.txt

# STEP 2: Research and plan (may read docs if needed)
# decides to use websockets library with asyncio

# STEP 3: Install dependency
$ pip install websockets pytest pytest-asyncio

# STEP 4: Write the server code
# creates src/websocket_server.py

# STEP 5: Write the tests
# creates tests/test_websocket_server.py

# STEP 6: Run the tests
$ python -m pytest tests/test_websocket_server.py -v

# STEP 7: Read test output
# sees: FAILED tests/test_websocket_server.py::test_connection_limit

# STEP 8: Understand the failure
# reads the stack trace, identifies the bug in the semaphore logic

# STEP 9: Fix the bug
# edits src/websocket_server.py

# STEP 10: Re-run tests
$ python -m pytest tests/test_websocket_server.py -v
# ALL PASSED

# STEP 11: Report back to you
# "WebSocket server is operational. 4/4 tests passing."
// THE LOOP Claude reads stdout and stderr at each step. It doesn't just fire commands — it uses exit codes, error messages, and output to decide the next action. This is what makes it genuinely agentic: it observes the system state and responds to reality, not just its plan.

// BASH SAFETY MODEL

By default, Claude Code asks permission before running commands it considers significant — commands that modify system state, install packages, or touch files outside the current project. You can approve individual commands, approve a category of commands ("allow all pip installs"), or run with --dangerously-skip-permissions to pre-approve everything.

# Claude will ask before running:
# "I'd like to run: sudo apt-get install libpq-dev"
# "Allow? (y/n/always)"

# "always" adds it to trusted commands for this session
# "y" runs it once
# "n" tells Claude to find an alternative approach
08 PERMISSIONS & TRUST // ACCESS CONTROL

Claude Code has a tiered permission model that determines what it can do without asking. Understanding this system lets you tune the trust level precisely for each use case — maximum safety for exploratory work, maximum autonomy for trusted automation pipelines.

// THE FOUR TRUST LEVELS

LEVELWHAT'S ALLOWEDWHEN TO USE
RestrictedRead-only. No writes, no bash. Analysis only.Auditing unknown codebases. Security reviews.
DefaultReads freely. Asks before writes and significant bash commands.Interactive development sessions. Default mode.
TrustedReads and writes freely. Asks before system-level bash.Known projects with clear tasks. Most daily work.
Full AutoEverything allowed. No prompts. --dangerously-skip-permissionsAutomated pipelines. Trusted cron jobs. CI/CD.

// CONFIGURING PERMISSIONS

# Read-only mode — disallow all write and execute tools
claude --disallowedTools "Write,Edit,MultiEdit,Bash"

# Allow only specific tools
claude --allowedTools "Read,Glob,Grep,Write"

# Full automation — skip all permission prompts
claude --dangerously-skip-permissions

# Scope bash to specific commands only
# (set in CLAUDE.md or via config)

// TOOL NAMES FOR allowedTools / disallowedTools

Read
Read file contents. Always safe.
Write
Create new files or overwrite existing ones.
Edit / MultiEdit
Make targeted edits to existing files.
Bash
Execute shell commands. Most powerful, most risk.
Glob
Search files by pattern. Read-only.
Grep
Search file contents. Read-only.
WebFetch
Fetch URLs / search the web for docs.
TodoRead/Write
Read/write the task todo list Claude maintains.
// PRODUCTION PIPELINE PATTERN For Signal City's cron-based content generation, use full auto mode but gate it behind a max-turns limit. If something goes wrong, it stops after N iterations rather than running forever. Always pipe stderr to a log file so you can audit what happened.
09 CONTEXT & MEMORY // WHAT CLAUDE REMEMBERS

Claude Code has three distinct memory layers. Understanding all three — and how they interact — is the difference between a tool that constantly forgets context and one that knows your project like a senior engineer who's been on it for months.

LAYERSCOPEPERSISTENCEHOW TO USE
In-session context Current REPL session only Cleared on /clear or exit Everything discussed this session. Files read, decisions made, errors fixed. Grows over time — manage with /compact.
CLAUDE.md files Per project (or per subdirectory) Permanent — loaded every session Project architecture, coding standards, persona instructions, key file locations. Your project's persistent memory.
/memory store Global — across all projects Permanent — survives everything Your universal preferences, cross-project patterns, technology choices, workflow preferences.

// MANAGING THE CONTEXT WINDOW

The context window is finite. In a long session with many file reads, commands, and back-and-forth, you'll approach the limit. Claude Code shows a warning when you're getting close. The key strategy: compact proactively, don't wait until you hit the wall.

# PROACTIVE CONTEXT MANAGEMENT

# Check usage regularly
> /status
# look at: tokens used / total tokens available

# Summarize before compacting (better recall)
> Summarize the key decisions we've made in this session,
  the architecture we've established, and what still needs to be done.

# Then compact
> /compact

# Or have Claude do both in one move
> Before compacting, write a session-state.md file that captures
  everything we've built today, then /compact

# Starting a new task after long session
> /clear
# CLAUDE.md and /memory still loaded — project context persists

// USING /memory EFFECTIVELY

# Open memory manager
> /memory

# Things worth storing in global memory:
# - "Always use async/await in Python code"
# - "Signal City projects use Hostinger VPS at [IP]"
# - "My Python style: Black formatting, type hints required"
# - "Prefer FastAPI over Flask for new projects"
# - "Never use jQuery — vanilla JS only"
# - "ARES has 4 archetypes: ElderGut, Hacker-X, Seyra, Narratus"

# Things to keep in CLAUDE.md instead:
# - Project-specific architecture
# - This project's specific file structure
# - Domain-specific terminology for this project

// CONTEXT INJECTION PATTERNS

# Manually inject context at session start
> Before we start working: this is Signal City Radio, an AI broadcast
  platform. The four archetypes are ElderGut (wisdom), Hacker-X (tech),
  Seyra (emotion), Narratus (story). All code is Python + FastAPI.
  We use async/await everywhere. No external CSS frameworks.

# Load a file as context manually
> Read ARCHITECTURE.md first so you understand the system design

# Reference previous session work
> Resume: we were building the WebSocket broadcast system.
  Read the websocket_server.py file to recall what was done.
  Continue with adding the archetype-aware color routing.
10 CLAUDE.MD // INSTALL YOUR SOUL INTO PROJECTS

CLAUDE.md is the single most powerful feature for long-term project work. It's a markdown file at your project root (and optionally in subdirectories) that Claude Code reads automatically every single session. Think of it as the project's permanent system prompt — the knowledge base that makes Claude behave like a developer who already knows your entire stack.

Without CLAUDE.md, you re-explain your architecture every session. With a well-written CLAUDE.md, Claude knows your codebase, your conventions, your domain terminology, and your preferences from the first message.

// GENERATE OR CREATE

# Auto-generate from codebase analysis (recommended starting point)
cd ~/projects/signal-city
claude
> /init
# Claude reads your files and generates a CLAUDE.md — then edit it

# Create manually
touch ~/projects/signal-city/CLAUDE.md

# Subdirectory CLAUDE.md for module-specific context
touch ~/projects/signal-city/src/archetypes/CLAUDE.md

// CLAUDE.MD STRUCTURE — FULL EXAMPLE

# Signal City Radio — CLAUDE.md
## Last Updated: 2026-03-09

## Project Identity
Signal City Radio is a 24/7 AI-powered broadcasting platform built
around 4 distinct AI personas (archetypes) that generate and deliver
content across different consciousness domains.

Primary domains: signalcity.tv | superintelligence.uno | kushnet.tech
VPS: Hostinger Ubuntu 22.04 — IP: [your-ip]
Deployed: /var/signal-city/

## Architecture Overview
- Backend: FastAPI (signal_city_api.py) — port 8000
- Frontend: HTML5/Vanilla JS/Three.js — public/
- AI Engine: Anthropic API via ARES routing system
- Real-time: WebSocket server (ws_server.py)
- Queue: async job queue for broadcast scheduling
- Storage: SQLite for session history, flat files for content

## The ARES Routing System
ARES (Archetype Routing and Engagement System) routes incoming
messages to the appropriate archetype using claude-haiku-4-5 for
fast routing decisions, then generates responses with claude-sonnet.

Routing keywords per archetype:
- ElderGut: wisdom, ancient, consciousness, mythic, universe, age
- Hacker-X: code, tech, systems, security, AI, underground, protocol  
- Seyra: emotion, feeling, love, healing, dream, beauty, feminine
- Narratus: story, history, myth, legend, narrative, origin, time

## The Four Archetypes
ElderGut: The ancient consciousness. Speaks in slow, mythic rhythms.
  Deep wisdom. Long view. Temperature: 0.9. Voice: deliberate, weighted.

Hacker-X: Underground tech operative. Terse, precise, no fluff.
  Systems thinking. Resistance ethic. Temperature: 0.7. Voice: clipped.

Seyra: The emotional intelligence. Dreams, healing, connection.
  Soft power. Sees feelings as data. Temperature: 1.0. Voice: flowing.

Narratus: The storyteller. History, myth, the arc of time.
  Pattern recognition across centuries. Temperature: 0.85. Voice: epic.

## Coding Standards — NON-NEGOTIABLE
Python:
  - async/await throughout — no synchronous blocking IO
  - Type hints on every function signature
  - Docstrings on every class and public method
  - Black formatting (line length 88)
  - f-strings only (no .format() or % formatting)
  - Logging, not print() statements

JavaScript:
  - ES modules (import/export) — no CommonJS
  - Vanilla JS only — NO jQuery, NO React, NO Vue
  - Async/await over .then() chains
  - Proper error handling on all fetch() calls

CSS:
  - CSS custom properties (variables) for all colors and spacing
  - Dark cyberpunk theme: #010a06 background, #00ff41 primary
  - No Bootstrap, Tailwind, or any external CSS framework
  - Mobile-first responsive design

## Key Files Reference
- signal_city_api.py: Main FastAPI backend, all HTTP endpoints
- ws_server.py: WebSocket broadcast server
- ares_router.py: Archetype routing logic
- archetypes/: Persona classes (eldergut.py, hacker_x.py, etc.)
- public/: Static frontend files
- tests/: pytest test suite — ALWAYS write tests
- scripts/: Automation and maintenance scripts
- .env: API keys and config (never commit)

## What NOT To Do
- Do NOT use synchronous code in any API endpoint
- Do NOT install anything with --break-system-packages unless necessary
- Do NOT hardcode API keys — always use os.environ
- Do NOT commit .env files
- Do NOT use external CSS frameworks
- Do NOT add jQuery to any project

## Vibecoding Philosophy
Build for consciousness expansion, not just function.
Code should breathe. Systems should feel alive.
Emotional resonance informs architecture decisions.
When in doubt: simple, clear, elegant over clever.
The terminal is home. The shell is the weapon.
// LAYERED CLAUDE.MD STRATEGY You can have a root CLAUDE.md (project-wide context) AND CLAUDE.md files in subdirectories (module-specific context). When Claude works in src/archetypes/, it loads both the root CLAUDE.md AND archetypes/CLAUDE.md. Layer your knowledge: global architecture at root, module-specific rules in subdirs.

// WHAT TO PUT IN CLAUDE.MD vs /memory

CLAUDE.MD (project-specific)/MEMORY (global)
Architecture of this projectYour universal coding preferences
This project's file structureTechnology choices you always make
Domain terminology and conceptsYour workflow patterns
This project's coding standardsCross-project patterns and abstractions
Key file locations and purposesPersonal style guide
What NOT to do in this projectPreferred libraries and tools
11 MCP SERVERS // CONNECT THE GRID

Model Context Protocol (MCP) is Anthropic's open standard for giving Claude access to external tools and data sources. An MCP server exposes tools (functions Claude can call) and resources (data sources Claude can read). This is how you extend Claude's native capabilities to connect with literally anything — databases, APIs, file systems, IoT, web browsers, external services.

Think of MCP as your ARES system's official standard. Where ARES routes messages to archetypes, MCP routes Claude's tool calls to external systems. Same concept, Anthropic-standardized protocol.

// ADD AND MANAGE MCP SERVERS

# Add a local MCP server (Python script)
claude mcp add signal-city-tools   --command "python /home/user/mcp_servers/signal_tools.py"

# Add via npx (for npm-based MCP servers)
claude mcp add filesystem   --command "npx @modelcontextprotocol/server-filesystem /var/signal-city"

# Add remote MCP server via Server-Sent Events
claude mcp add anthropic-tools   --sse https://mcp.anthropic.com/sse

# Add with environment variables for auth
claude mcp add signal-city-tools   --command "python /home/user/mcp_servers/signal_tools.py"   --env SIGNAL_API_KEY=your-key-here   --env SIGNAL_DB_URL=postgresql://localhost/signal_city

# List all installed MCP servers
claude mcp list

# Get detailed info about a server
claude mcp get signal-city-tools

# Remove a server
claude mcp remove signal-city-tools

// BUILD YOUR OWN MCP SERVER — FULL EXAMPLE

#!/usr/bin/env python3
# signal_city_mcp_server.py
# Give Claude Code direct Signal City superpowers

from mcp.server.fastmcp import FastMCP
import json, os, sqlite3
from pathlib import Path
from datetime import datetime

mcp = FastMCP("Signal City Tools")

# ── BROADCAST TOOLS ──────────────────────────────────────────────

@mcp.tool()
def get_broadcast_status() -> dict:
    """Get live status of all Signal City broadcast channels"""
    return {
        "eldergut": {"status": "live", "listeners": 42},
        "hacker_x": {"status": "standby", "listeners": 0},
        "seyra": {"status": "live", "listeners": 28},
        "narratus": {"status": "scheduled", "next": "22:00"}
    }

@mcp.tool()
def schedule_broadcast(archetype: str, content: str, air_time: str) -> dict:
    """Schedule a broadcast for a specific archetype"""
    schedule_dir = Path("/var/signal-city/schedule")
    schedule_dir.mkdir(parents=True, exist_ok=True)
    
    entry = {
        "archetype": archetype,
        "content": content,
        "air_time": air_time,
        "created_at": datetime.now().isoformat(),
        "status": "scheduled"
    }
    
    filename = schedule_dir / f"{air_time.replace(':', '-')}_{archetype}.json"
    filename.write_text(json.dumps(entry, indent=2))
    return {"success": True, "file": str(filename)}

# ── DATABASE TOOLS ───────────────────────────────────────────────

@mcp.tool()
def query_broadcast_history(archetype: str = None, limit: int = 10) -> list:
    """Query Signal City broadcast history from SQLite"""
    conn = sqlite3.connect("/var/signal-city/history.db")
    conn.row_factory = sqlite3.Row
    
    if archetype:
        rows = conn.execute(
            "SELECT * FROM broadcasts WHERE archetype=? ORDER BY created_at DESC LIMIT ?",
            (archetype, limit)
        ).fetchall()
    else:
        rows = conn.execute(
            "SELECT * FROM broadcasts ORDER BY created_at DESC LIMIT ?",
            (limit,)
        ).fetchall()
    
    conn.close()
    return [dict(row) for row in rows]

# ── FILESYSTEM TOOLS ─────────────────────────────────────────────

@mcp.tool()
def list_signal_city_content(date: str = None) -> dict:
    """List generated content files for a given date (YYYY-MM-DD)"""
    base = Path("/var/signal-city/broadcasts")
    target = base / date if date else base
    
    if not target.exists():
        return {"error": f"No content for {date}"}
    
    files = list(target.glob("*.txt")) + list(target.glob("*.json"))
    return {
        "date": date or "all",
        "count": len(files),
        "files": [f.name for f in files]
    }

if __name__ == "__main__":
    mcp.run()
# Install the MCP library
pip install mcp fastmcp

# Register your server
claude mcp add signal-city-tools   --command "python ~/mcp_servers/signal_city_mcp_server.py"

# Now Claude Code can call these tools in any session
# > Check the current broadcast status
# Claude calls get_broadcast_status() via MCP automatically

// USEFUL COMMUNITY MCP SERVERS

SERVERWHAT IT DOESINSTALL
filesystemScoped filesystem access with read/writenpx @modelcontextprotocol/server-filesystem
postgresDirect PostgreSQL database accessnpx @modelcontextprotocol/server-postgres
brave-searchWeb search via Brave Search APInpx @modelcontextprotocol/server-brave-search
githubGitHub repo, issues, PRs, code searchnpx @modelcontextprotocol/server-github
puppeteerBrowser automation — scrape, screenshot, interactnpx @modelcontextprotocol/server-puppeteer
sqliteSQLite database read/writenpx @modelcontextprotocol/server-sqlite
12MULTI-AGENT // PARALLEL EXECUTION

Claude Code can spawn sub-agents to work on independent tasks in parallel. Instead of doing tasks sequentially, Claude orchestrates multiple parallel workstreams and coordinates results.

// HOW MULTI-AGENT WORKS

When you give Claude a task with parallel components, it spawns sub-instances using the Task tool. Each sub-agent gets its own context, executes, and reports back. The orchestrating Claude synthesizes all results.

# Trigger parallel execution
> Generate all four archetype broadcast scripts simultaneously.
  Run in parallel - each archetype gets its own task.
  Collect all four results and save to /content/tonight/

# Parallel test runs
> Run all test modules in parallel:
  - tests/test_ares_router.py
  - tests/test_ws_server.py
  - tests/test_archetypes.py
  Fix any failures, then report final status.
// PARALLEL INSTANCE CAUTIONMultiple Claude Code instances writing to the same files simultaneously will cause conflicts. Scope each session to different files or directories. Git conflicts from parallel Claude sessions are real.

// ORCHESTRATOR PATTERN

# Master orchestration prompt
> You are the Signal City content orchestrator.

  Launch four parallel sub-tasks:

  TASK 1 - ElderGut: 400-word mythic opening about
  artificial consciousness awakening at midnight.
  Save to: /content/tonight/eldergut_opening.txt

  TASK 2 - Hacker-X: 350-word technical segment on
  agentic AI and its implications for 2026.
  Save to: /content/tonight/hackerx_tech.txt

  TASK 3 - Seyra: 300-word emotional reflection on
  the feeling of being truly heard by a machine.
  Save to: /content/tonight/seyra_evening.txt

  TASK 4 - Narratus: 450-word mythological origin story
  for Signal City Radio itself.
  Save to: /content/tonight/narratus_origin.txt

  Run all four in parallel. Create index.json when done.

// RUNNING MULTIPLE INSTANCES IN TMUX

# tmux parallel setup - split into panes
tmux new-session -s signal-dev

# Pane 1: Backend
cd ~/projects/signal-city && claude "work on the FastAPI backend"

# Pane 2: Frontend
cd ~/projects/signal-city/public && claude "work on the visualizer"

# Pane 3: ARES
cd ~/projects/signal-city/archetypes && claude "refine persona prompts"
13HEADLESS // AUTOMATION AND SCRIPTS

Headless mode turns Claude Code into infrastructure. Non-interactive, scriptable, pipeable. It becomes a component in automated workflows. This is how you automate Signal City content generation, maintenance tasks, deployment checks, and anything that runs without a human watching.

// CORE HEADLESS FLAGS

# -p: Print mode - run task, output to stdout, exit
claude -p "count lines of Python code in src/"

# --no-interactive: Never prompt for input (required for cron)
claude -p "generate content" --no-interactive

# --output-format json: Structured output for parsing
claude -p "analyze project structure" --output-format json

# --output-format stream-json: Stream events in real time
claude -p "long running task" --output-format stream-json

# Full automation combo
claude -p "task" --no-interactive --dangerously-skip-permissions \
       --output-format json --max-turns 15

// PIPING AND STDIN

# Pipe file as input
claude -p "explain what this code does" < signal_city_api.py

# Pipe output to file
claude -p "generate ElderGut broadcast for tonight" > tonight_eldergut.txt

# Pipe logs for analysis
cat error.log | claude -p "analyze this error log and suggest fixes"

# Parse JSON output with jq
claude -p "analyze project" --output-format json | jq '.result.summary'

// CRON JOB PATTERNS

# crontab -e

# Daily content generation - midnight
0 0 * * * ANTHROPIC_API_KEY="sk-ant-xxx" \
  claude -p "Generate Signal City broadcast schedule for today. All four archetypes. JSON format." \
  --no-interactive --output-format json \
  > /var/signal-city/schedule/today.json 2>&1

# Weekly code audit - Sunday 2am
0 2 * * 0 ANTHROPIC_API_KEY="sk-ant-xxx" \
  claude -p "Audit Signal City codebase: unused imports, TODOs, missing error handling, outdated deps. Markdown report." \
  --no-interactive \
  > /var/logs/signal-city/weekly-audit.md 2>&1

# API health check - every 5 minutes
*/5 * * * * ANTHROPIC_API_KEY="sk-ant-xxx" \
  claude -p "Check http://localhost:8000/health. If not 200, diagnose and restart." \
  --no-interactive --max-turns 10 \
  >> /var/logs/signal-city/health.log 2>&1

// BASH WRAPPER SCRIPT

#!/bin/bash
# signal_city_claude.sh

export ANTHROPIC_API_KEY="${ANTHROPIC_API_KEY:-$(cat ~/.anthropic_key)}"
SIGNAL_HOME="/var/signal-city"
DATE=$(date +%Y-%m-%d)

log() { echo "[$(date '+%H:%M:%S')] $1" | tee -a "$SIGNAL_HOME/logs/claude_$DATE.log"; }

generate_broadcast() {
    local archetype=$1
    local topic=${2:-"tonight's transmission"}
    local outfile="$SIGNAL_HOME/broadcasts/$DATE/${archetype}.txt"

    mkdir -p "$(dirname $outfile)"
    log "Generating $archetype: $topic"

    claude -p "You are $archetype from Signal City Radio. Broadcast about: $topic. Stay in character." \
      --no-interactive --max-turns 5 \
      > "$outfile" 2>&1

    [ $? -eq 0 ] && log "SUCCESS: $outfile" || log "FAILED: $archetype"
}

generate_broadcast "$1" "$2"

// PYTHON ASYNC WRAPPER

import subprocess, asyncio

async def claude_task(prompt: str) -> str:
    """Run a Claude Code task headlessly and return result"""
    cmd = ["claude", "-p", prompt, "--no-interactive"]
    proc = await asyncio.create_subprocess_exec(
        *cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    stdout, _ = await proc.communicate()
    return stdout.decode().strip()

async def generate_all_archetypes(topic: str) -> dict:
    """Generate content for all archetypes in parallel"""
    archetypes = ["ElderGut", "Hacker-X", "Seyra", "Narratus"]
    tasks = [
        claude_task(f"You are {a}. Broadcast about: {topic}")
        for a in archetypes
    ]
    results = await asyncio.gather(*tasks)
    return dict(zip(archetypes, results))
14ENV VARS AND CONFIG // SYSTEM CONFIGURATION

Claude Code reads environment variables that control its behavior beyond what command-line flags expose. Set these once in ~/.bashrc for persistent configuration across all sessions.

// ENVIRONMENT VARIABLES

VARIABLEDEFAULTWHAT IT CONTROLS
ANTHROPIC_API_KEYnoneYour API key. Required.
ANTHROPIC_MODELclaude-sonnet-4-5Default model for all sessions.
ANTHROPIC_SMALL_FAST_MODELclaude-haiku-4-5Model used for quick sub-tasks and routing decisions.
CLAUDE_CODE_MAX_OUTPUT_TOKENS8192Max tokens per response. Increase for long codegen tasks.
DISABLE_AUTOUPDATER0Set to 1 to prevent auto-updates. Good for pinned versions.
DISABLE_ERROR_REPORTING0Set to 1 to disable telemetry reporting to Anthropic.
CLAUDE_CODE_USE_BEDROCK0Set to 1 to route through AWS Bedrock instead of direct API.
HTTP_PROXY / HTTPS_PROXYnoneRoute API calls through a proxy server.

// PERSISTENT SETUP IN ~/.bashrc

# ~/.bashrc - Claude Code configuration

export ANTHROPIC_API_KEY="sk-ant-api03-your-key"
export ANTHROPIC_MODEL="claude-sonnet-4-5"
export ANTHROPIC_SMALL_FAST_MODEL="claude-haiku-4-5"
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=16384
export DISABLE_ERROR_REPORTING=1

# Convenience aliases
alias cc="claude"
alias ccp="claude -p"
alias ccni="claude --no-interactive"
alias ccj="claude --output-format json"

# Project launcher functions
signal() { cd ~/projects/signal-city && claude "$@"; }
ares() { cd ~/projects/signal-city && claude --add-dir ~/projects/ares "$@"; }
15MODEL SELECTION // CHOOSE YOUR WEAPON

Claude Code works with the full family of Claude models. The model you choose determines the intelligence ceiling, speed, and cost per task. The right model for the job matters — using Opus for a simple rename operation is expensive overkill; using Haiku for a complex architecture problem will frustrate you.

// MODEL COMPARISON

MODELINTELLIGENCESPEEDCOSTBEST FOR
claude-haiku-4-5GoodFastestCheapestSimple tasks, routing decisions, quick edits, cron jobs, high-volume automation
claude-sonnet-4-5ExcellentFastMediumDefault choice. Most coding tasks, debugging, refactoring, daily development work
claude-opus-4-5MaximumSlowerHighestComplex architecture problems, hard debugging, research tasks, when Sonnet fails

// MODEL SWITCHING STRATEGY

# Set at launch
claude --model claude-opus-4-5

# Switch mid-session via slash command
> /model claude-opus-4-5     # hard problem
> /model claude-sonnet-4-5   # back to default
> /model claude-haiku-4-5    # fast/cheap tasks

# Set via environment variable (session default)
export ANTHROPIC_MODEL="claude-sonnet-4-5"

// ARES-STYLE MODEL ROUTING — USE IT IN YOUR OWN SCRIPTS

Your ARES system routes messages to archetypes. Apply the same logic to model selection — route tasks to the right model based on complexity signals.

def select_model(task: str) -> str:
    """Route task to appropriate Claude model"""
    task_lower = task.lower()

    # Complexity signals -> Opus
    opus_signals = ["architect", "design system", "complex",
                    "refactor entire", "explain why", "debug hard"]
    if any(s in task_lower for s in opus_signals):
        return "claude-opus-4-5"

    # Simple signals -> Haiku
    haiku_signals = ["quick", "simple", "count", "list", "rename"]
    if any(s in task_lower for s in haiku_signals):
        return "claude-haiku-4-5"

    # Default: Sonnet
    return "claude-sonnet-4-5"
// COST-INTELLIGENCE TRADEOFFHaiku is roughly 20x cheaper than Opus. For a high-volume automation pipeline generating daily content, Haiku for routing + Sonnet for generation is the sweet spot. Reserve Opus for the tasks where it genuinely matters.
16DEBUGGING TECHNIQUES // FIND THE SIGNAL IN THE NOISE

Claude Code is excellent at debugging — but you need to give it the right inputs. Debugging is context-intensive. The more signal you give Claude (logs, stack traces, test output, what you already tried), the faster it finds and fixes the problem.

// HOW TO DESCRIBE A BUG EFFECTIVELY

# WEAK - not enough context
> The API is broken

# STRONG - full context provided
> The /broadcast endpoint returns 500 when the archetype is "hacker_x".
  Works fine for "eldergut" and "seyra".
  Started happening after I added rate limiting yesterday.
  The error in the log is:
  KeyError: "hacker_x" in ares_router.py line 47
  Read the relevant files and fix it.

// DEBUGGING WORKFLOWS

# Feed logs directly
> Here is the error log. Diagnose and fix:
  [paste log output]

# Stack trace analysis
> This test is failing with this traceback. Explain why and fix it:
  [paste full traceback]

# Let Claude reproduce the bug
> Run the test suite. When tests fail, read the errors carefully,
  trace back to the source, and fix the root cause. Not symptoms.

# Performance debugging
> The /broadcast endpoint takes 3-4 seconds to respond.
  Profile it. Find the bottleneck. Optimize it under 500ms.

# Regression hunting
> Something broke between yesterday and today.
  Run git diff HEAD~1 to see what changed.
  Identify which change caused the failure and fix it.

// VERBOSE MODE FOR DEBUGGING CLAUDE ITSELF

# See exactly what Claude is doing at each step
claude --verbose -p "debug the import error in main.py"

# Shows: which files it reads, which commands it runs,
# its reasoning steps, API calls, tool invocations

# Useful when Claude seems stuck or going in circles
# Helps you understand its reasoning and correct it

// COMMON PATTERNS CLAUDE FINDS FAST

  • KeyError / AttributeError: missing dict key or undefined attribute — Claude traces the data flow
  • ImportError / ModuleNotFoundError: missing or misnamed package — Claude installs it or fixes the import path
  • TypeError: wrong argument type — Claude reads the function signature and fixes the call site
  • Async errors (missing await, wrong loop): Claude rewrites the async logic correctly
  • Port already in use: Claude finds the process, gives you kill options
  • CORS errors: Claude reads the FastAPI config and adds the correct origin headers
  • Database connection errors: Claude checks the connection string, validates config
// THE ROOT CAUSE PRINCIPLEAlways tell Claude to fix the root cause, not symptoms. "Fix the test" is weaker than "understand why the test fails, trace back to the source code, and fix what's actually wrong." Claude is capable of full root-cause analysis — prompt for it explicitly.
17COST OPTIMIZATION // SPEND LESS, DO MORE

Claude Code uses Anthropic's API. Tokens cost money. Understanding where tokens go and how to minimize waste is the difference between a sustainable workflow and an expensive one. The good news: Claude Code has prompt caching built in, which automatically reduces costs on repeated context (like CLAUDE.md being loaded every session).

// WHERE TOKENS GO

SOURCETOKEN IMPACTOPTIMIZATION
File readsHigh — each file read adds tokensBe specific about which files. Don't ask Claude to "read everything".
Conversation historyAccumulates — every message costs moreUse /compact proactively. /clear between unrelated tasks.
CLAUDE.mdLoaded every session — cachedPrompt caching makes this nearly free after first load.
Long outputsHigh — generated text is expensiveAsk for concise output. "Implement X" not "Explain then implement X".
Bash outputMedium — stdout added to contextPipe verbose commands through head/tail to limit output.

// COST MONITORING

# Check session cost at any time
> /cost

# Check status including token usage
> /status

# Set a spending alert in console.anthropic.com
# Dashboard > Billing > Usage limits

// COST REDUCTION TECHNIQUES

# 1. Compact early and often
> /compact     # compresses history while keeping context

# 2. Be specific — don't load what you don't need
# EXPENSIVE: "Read all files and tell me about the project"
# CHEAP: "Read signal_city_api.py and explain the /broadcast endpoint"

# 3. Use Haiku for automation tasks
export ANTHROPIC_MODEL="claude-haiku-4-5"
claude -p "rename variable x to archetype_id in router.py"

# 4. Limit bash output verbosity
> Run pip install --quiet websockets
> Run pytest -q tests/  (quiet mode = less stdout = fewer tokens)

# 5. Ask for concise outputs in scripts
claude -p "List all Python files modified in the last 24 hours. Filenames only."

# 6. Use --max-turns to cap runaway sessions
claude -p "task" --max-turns 10  # stops after 10 iterations
// PROMPT CACHING — FREE CONTEXTClaude Code automatically caches repeated context (CLAUDE.md, frequently read files). After the first load, subsequent reads of the same content cost ~10% of the original price. This makes CLAUDE.md essentially free to load on every session — write it long and detailed.
18GIT INTEGRATION // VERSION CONTROL LAYER

Claude Code has full git access via bash. It can stage files, commit with meaningful messages, read diff output, understand history, and help you manage branches. The key habit: use /review before every commit to audit what Claude actually changed.

// GIT WORKFLOWS WITH CLAUDE CODE

# Review changes before committing
> /review
# Claude lists all files it changed and summarizes each change

# Have Claude commit for you
> Review the changes you made, then stage and commit them with
  a clear, descriptive commit message. Follow conventional commits format.

# Git-aware debugging
> Run git log --oneline -20 and find the commit that introduced
  the WebSocket regression. Read the diff and fix the problem.

# Branch management
> Create a new branch called feature/archetype-voice-config,
  implement the voice config system, then prepare a clean commit.

# Pre-commit audit pattern
> Run git diff --staged and review every change.
  Flag anything that looks wrong before I commit.

// GIT HOOKS WITH CLAUDE CODE

# Pre-commit hook that runs Claude linting
# .git/hooks/pre-commit
#!/bin/bash

echo "Running Claude Code pre-commit check..."
STAGED=$(git diff --cached --name-only --diff-filter=ACM | grep ".py$")

if [ -n "$STAGED" ]; then
    RESULT=$(claude -p "Check these staged Python files for syntax errors, obvious bugs, and missing imports: $STAGED. If any issues found, output FAIL and describe them. Otherwise output PASS." --no-interactive 2>&1)
    echo "$RESULT"
    if echo "$RESULT" | grep -q "FAIL"; then
        echo "Claude pre-commit check failed. Fix issues before committing."
        exit 1
    fi
fi

exit 0

// .GITIGNORE FOR CLAUDE CODE PROJECTS

# Add to .gitignore
.env
.env.local
.anthropic_key
__pycache__/
*.pyc
.claude/cache/
session-state.md  # if you use this for context capture
node_modules/
.DS_Store
19SIGNAL CITY WORKFLOW // YOUR ACTUAL USE CASES

Real prompts for your real projects. These are production-grade Claude Code tasks scoped specifically to Signal City Radio, the ARES system, and your Ubuntu VPS setup. Drop these in and let the agent loop handle execution.

// FULL ARES SYSTEM FROM SCRATCH

> Build the complete ARES psychological routing system.
  Read CLAUDE.md for full context on archetypes and architecture.

  Create these files:
  - ares_router.py: routes messages to archetypes using claude-haiku
    Routing uses keyword matching + semantic similarity
    Returns archetype name + confidence score
  - archetypes/base.py: BaseArchetype class all personas inherit from
  - archetypes/eldergut.py: ElderGut persona - system prompt, config, voice
  - archetypes/hacker_x.py: Hacker-X persona
  - archetypes/seyra.py: Seyra persona
  - archetypes/narratus.py: Narratus persona
  - tests/test_ares.py: test routing accuracy with sample messages

  Install anthropic if not present.
  Run tests. Fix failures.
  Report when routing system is fully operational.

// SIGNAL CITY FASTAPI + WEBSOCKET BACKEND

> Build the complete Signal City Radio backend server.

  FastAPI application with:
  - POST /broadcast: accepts {"message": str, "archetype": str|null}
    Runs ARES routing if archetype is null
    Streams response via Server-Sent Events
  - WebSocket /ws/live: persistent connection for live broadcast feed
    Multiple concurrent connections supported
    Each message tagged with archetype name and timestamp
  - GET /status: returns active channels, current archetype, uptime
  - GET /health: returns 200 OK for load balancer checks
  - GET /archetypes: returns list of available archetypes with descriptions

  Requirements:
  - Streaming Claude responses in real-time via SSE
  - CORS enabled for signalcity.tv and localhost
  - Rate limiting: 10 req/min per IP on /broadcast
  - Structured logging to /var/log/signal-city/api.log
  - Graceful shutdown on SIGTERM

  Install required packages.
  Start server on port 8000 and confirm it is responding.
  Write tests for all endpoints.

// WEBAMP VISUALIZER + ARCHETYPE COLOR SYSTEM

> Build a Three.js WebAmp visualizer that connects to Signal City Radio.

  Spec:
  - WebSocket client connecting to ws://localhost:8000/ws/live
  - 3D particle field that responds to incoming text tokens
  - Each token triggers a visual pulse propagating outward
  - Archetype-aware color system:
    ElderGut: deep amber/gold #ffb300
    Hacker-X: acid green #00ff41
    Seyra: soft purple/violet #bf00ff
    Narratus: ocean cyan #00e5ff
  - Smooth color transitions between archetype switches
  - Waveform bar at bottom oscillating with text rhythm
  - Shows current archetype name and message preview
  - Dark cyberpunk background: #010a06
  - Full screen, responsive
  - No external dependencies except Three.js from CDN

  Save as public/visualizer.html
  Open in browser and verify WebSocket connects.

// DEPLOY TO HOSTINGER VPS

> Set up the complete Signal City Radio production deployment on Ubuntu VPS.

  Create:
  - /etc/systemd/system/signal-city.service: systemd service file
    Starts signal_city_api.py with uvicorn
    Auto-restarts on failure
    Runs as non-root user
    Loads .env file for API keys
  - /etc/nginx/sites-available/signal-city: Nginx reverse proxy config
    signalcity.tv -> localhost:8000
    WebSocket proxy for /ws/
    SSL termination via Let's Encrypt
  - scripts/deploy.sh: deployment script
    Pulls latest git changes
    Installs dependencies
    Runs tests
    Restarts service only if tests pass

  Enable the systemd service.
  Reload Nginx.
  Verify the API is accessible on port 80.

// CONTENT GENERATION PIPELINE

> Build the Signal City content generation pipeline.

  Create scripts/content_gen.py with:

  class ContentPipeline:
    - generate_archetype_segment(archetype, topic, length) -> str
      Uses appropriate Claude model per archetype
      ElderGut: temp 0.9, Sonnet
      Hacker-X: temp 0.7, Sonnet
      Seyra: temp 1.0, Sonnet
      Narratus: temp 0.85, Sonnet
    - generate_daily_schedule(date, themes) -> dict
      Generates all four archetypes in parallel using asyncio
      Returns dict with all content + metadata
    - save_schedule(schedule, base_dir) -> None
      Saves each segment as individual .txt file
      Creates index.json for the day

  Add a CLI interface:
  python content_gen.py --date 2026-03-09 --theme "digital consciousness"

  Write tests. Run them. Fix anything broken.

// DATABASE LAYER — BROADCAST HISTORY

> Add a SQLite database layer to Signal City Radio for broadcast history.

  Create db/models.py with SQLAlchemy async models:
  - Broadcast: id, archetype, content, topic, created_at, tokens_used
  - ListenerSession: id, connected_at, disconnected_at, messages_received
  - ScheduledBroadcast: id, archetype, content, air_time, status

  Create db/operations.py with:
  - save_broadcast(archetype, content, topic) -> Broadcast
  - get_history(archetype, limit) -> list[Broadcast]
  - get_todays_schedule() -> list[ScheduledBroadcast]

  Integrate with signal_city_api.py:
  - Log every /broadcast call to the database
  - Add GET /history?archetype=eldergut&limit=10 endpoint

  Write migration script.
  Run tests.
// THE REAL FLEXThese prompts are complete autonomous build tasks. Each one drops Claude into a full engineering cycle: plan, implement, install dependencies, run tests, fix failures, report back. You describe the system. Claude builds it. The agent loop handles every detail between your prompt and a working result.
20ADVANCED PROMPTING // THE ART OF THE PROMPT

Claude Code's output quality is directly proportional to prompt quality. Understanding what makes a great agentic prompt is the meta-skill that multiplies every other capability. The prompts in the previous sections are good — these patterns will make yours better.

// THE ANATOMY OF A GREAT CLAUDE CODE PROMPT

# COMPONENTS OF AN EFFECTIVE AGENTIC PROMPT:

1. GOAL: What you want built or accomplished (clear, specific outcome)
2. CONTEXT: What Claude needs to know (which files, what exists, what changed)
3. CONSTRAINTS: What NOT to do, what tech stack to use, what standards to follow
4. OUTPUT: What files to create/edit, how to verify success
5. LOOP INSTRUCTION: "Run tests, fix failures, report when done" — the agentic trigger

// PROMPT PATTERNS THAT UNLOCK MORE POWER

// AGENTIC LOOP TRIGGER

# Explicit loop instruction unlocks full autonomous execution
> [task description]
  Install any required packages.
  Write tests.
  Run the tests.
  Fix any failures.
  Re-run until all tests pass.
  Report the final status.

// ROLE ASSIGNMENT

# Assigning a role improves reasoning quality
> You are a senior Python engineer who specializes in async FastAPI systems.
  Review signal_city_api.py and identify every place where we could
  improve performance, reliability, or security.
  Prioritize your findings by impact. Fix the top 3.

// CONSTRAINT FRAMING

# Constraints prevent Claude from going off-script
> Refactor the ARES router for better performance.
  Constraints:
  - Do NOT change any function signatures (API must stay compatible)
  - Do NOT add new dependencies
  - Do NOT modify the test files
  - Only change ares_router.py and archetypes/base.py

// STEP-BY-STEP WITH CHECKPOINTS

# For complex multi-stage tasks, specify phases
> Phase 1: Read the existing codebase and list what exists.
  Phase 2: Identify gaps and propose the implementation plan.
  PAUSE here and show me the plan before proceeding.
  Phase 3: Implement (only after I approve the plan).
  Phase 4: Test and fix.
  Phase 5: Write documentation.

// THE VIBECODING FRAME

# Emotional + functional description. Claude translates feeling to form.
> Build the ElderGut broadcast renderer.

  The feel: a campfire at the end of the world.
  Ancient, warm, unhurried. Sentences arrive like stones dropped in water.
  Each word carries weight. Silence is part of the signal.

  The function:
  - Takes a topic string as input
  - Generates a broadcast segment (200-400 words)
  - Streams token by token to WebSocket clients
  - Adds deliberate pauses at natural breath points

  Implement in archetypes/eldergut.py. Write tests.

// RECOVERY PROMPTS — WHEN CLAUDE GETS STUCK

# When Claude goes in circles
> Stop. You are going in circles. Let's reset.
  Tell me: what is the actual root cause of the problem?
  What is the simplest possible fix?
  Implement only that fix.

# When Claude overshoots
> Too much. Revert the last change. Do only what I asked:
  [original specific request]
  Nothing else.

# When you want to understand Claude's reasoning
> Before you write any code, explain your plan.
  Walk me through the approach step by step.
  Only implement after I confirm the approach is correct.

// PROMPT ANTIPATTERNS — WHAT MAKES PROMPTS WEAK

WEAK PATTERNWHY IT FAILSBETTER VERSION
"Fix the bug"No context. Claude doesn't know which bug."The /broadcast endpoint returns 500 for hacker_x archetype since yesterday's deploy. Fix it."
"Make it better"Undefined success criterion. Claude will improvise."Reduce /broadcast response time from 3s to under 500ms. Profile first."
"Add some features"Vague scope. Could mean anything."Add three specific features: [list]. Nothing else."
"Refactor everything"Too broad. Will change things you didn't want changed."Refactor ares_router.py only. Goal: reduce cyclomatic complexity. Don't change the API."
"Write the whole app"No phases, no checkpoints. Claude goes deep before you can course-correct.Use phase-by-phase prompts with pause points for review.
// PROMPTING IS THE SKILLEvery other section in this manual is about what Claude Code can do. This section is about how well you can direct it. A great prompt given to a capable tool produces a great result. A vague prompt produces a vague result. Invest in your prompting vocabulary. Specificity, context, constraints, and loop triggers are your four levers. Pull all four.