Explore the CC ROI Dashboard system that already exists in this workspace. I need to understand:

1. How the current ROI tracking works (cc-track.sh, cc-services.sh)
2. The database schema and data structures used
3. The API endpoints available (port 9001)
4. What metrics are being tracked

Look in:
- Scripts/cc/ folder
- Services/servers/ folder
- Any SQLite databases
- CC-ROI-QUICKSTART.md or related docs

Provide a comprehensive summary of the existing ROI tracking infrastructure.


I'll explore the CC ROI Dashboard system to understand the current infrastructure. Let me start by examining the key components.


/Users/neog/Scripts/cc/cc-services.sh
/Users/neog/Scripts/cc/cc-daily-report.sh
/Users/neog/Scripts/cc/cc-test-flow.sh
/Users/neog/Scripts/cc/cc-track.sh
/Users/neog/Scripts/cc/cc-quick-stats.sh
/Users/neog/Scripts/cc/cc-action.sh
/Users/neog/Scripts/cc/cc-watch.sh
/Users/neog/Scripts/cc/cc-scheduler.sh
/Users/neog/Scripts/cc/cc-value.sh
/Users/neog/Scripts/cc/cc.sh


/Users/neog/Services/servers/https_server.py
/Users/neog/Services/servers/wifi-api-server.py
/Users/neog/Services/servers/system-monitor-server.py
/Users/neog/Services/servers/system-monitor-server-v2.py
/Users/neog/Services/servers/scraper_server.py
/Users/neog/Services/servers/system-metrics-server.py
/Users/neog/Services/servers/bitcoin-monitor-server.py
/Users/neog/Services/servers/crypto-grok-server.py
/Users/neog/Services/servers/terminal-remote-server.py
/Users/neog/Services/servers/domain-validator-server.py
/Users/neog/Services/servers/claude-cli-server.py
/Users/neog/Services/servers/transcript-server.py
/Users/neog/Services/servers/workspace-manager-api.py
/Users/neog/Services/servers/abr-telecom-server.py
/Users/neog/Services/servers/cc-live-tracker.py
/Users/neog/Services/servers/log-server.py
/Users/neog/Services/servers/neog-gateway.py
/Users/neog/Services/servers/youtube-audio-server.py
/Users/neog/Services/servers/ip-whitelist-proxy.py
/Users/neog/Services/servers/proxy-websocket-server.py
/Users/neog/Services/servers/youtube-transcript-server.py


No files found


Now let me read the key scripts and check for the CC-ROI-QUICKSTART.md file mentioned in the CLAUDE.md:


Bash

find /Users/neog -name "CC-ROI-QUICKSTART.md" -o -name "*roi*" -type f 2>/dev/null | head -20

Find ROI-related documentation files


     1→#!/bin/bash
     2→# cc-track.sh - Track Claude Code runs for ROI Dashboard
     3→#
     4→# Usage:
     5→#   ./cc-track.sh start "Your prompt here" [source]     # Start tracking a run
     6→#   ./cc-track.sh complete <run_id> [value_usd]         # Complete a run with optional revenue
     7→#   ./cc-track.sh value <run_id> <value_usd>            # Add revenue value to a run
     8→#   ./cc-track.sh status                                # Show today's stats
     9→#   ./cc-track.sh runs [limit]                          # List recent runs
    10→#   ./cc-track.sh gate "prompt"                         # Pre-check gates before running
    11→
    12→API_BASE="http://localhost:9001/api/cc"
    13→
    14→RED='\033[0;31m'
    15→GREEN='\033[0;32m'
    16→YELLOW='\033[1;33m'
    17→CYAN='\033[0;36m'
    18→NC='\033[0m'
    19→
    20→case "${1:-help}" in
    21→    start)
    22→        PROMPT="${2:-Manual automation task}"
    23→        SOURCE="${3:-manual}"
    24→
    25→        echo -e "${CYAN}📊 CC Tracker - Starting run...${NC}"
    26→        echo "   Prompt: $PROMPT"
    27→        echo "   Source: $SOURCE"
    28→
    29→        RESPONSE=$(curl -s -X POST "$API_BASE/run" \
    30→            -H "Content-Type: application/json" \
    31→            -d "{\"prompt\": \"$PROMPT\", \"source\": \"$SOURCE\"}")
    32→
    33→        RUN_ID=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin).get('run_id',''))" 2>/dev/null)
    34→
    35→        if [ -z "$RUN_ID" ]; then
    36→            echo -e "${RED}❌ Failed to create run${NC}"
    37→            exit 1
    38→        fi
    39→
    40→        echo ""
    41→        echo -e "${GREEN}✓ Run started: $RUN_ID${NC}"
    42→        echo ""
    43→        echo "To complete this run:"
    44→        echo -e "  ${YELLOW}./cc-track.sh complete $RUN_ID [value_usd]${NC}"
    45→        echo ""
    46→        echo "Example with \$5 value generated:"
    47→        echo "  ./cc-track.sh complete $RUN_ID 5.00"
    48→        ;;
    49→
    50→    complete)
    51→        RUN_ID="${2}"
    52→        VALUE="${3:-0}"
    53→
    54→        if [ -z "$RUN_ID" ]; then
    55→            echo -e "${RED}❌ Usage: ./cc-track.sh complete <run_id> [value_usd]${NC}"
    56→            exit 1
    57→        fi
    58→
    59→        echo -e "${CYAN}📊 CC Tracker - Completing run...${NC}"
    60→
    61→        RESPONSE=$(curl -s -X POST "$API_BASE/run/$RUN_ID/complete" \
    62→            -H "Content-Type: application/json" \
    63→            -d "{\"status\": \"completed\", \"value_generated_usd\": $VALUE}")
    64→
    65→        DURATION=$(echo "$RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f\"{d.get('duration_ms',0)/1000:.1f}s\")" 2>/dev/null)
    66→        COST=$(echo "$RESPONSE" | python3 -c "import sys,json; print(f\"\${json.load(sys.stdin).get('cost_usd',0):.4f}\")" 2>/dev/null)
    67→
    68→        echo ""
    69→        echo -e "${GREEN}✓ Run completed${NC}"
    70→        echo "   Duration: $DURATION"
    71→        echo "   Cost:     $COST"
    72→        echo "   Value:    \$$VALUE"
    73→        ;;
    74→
    75→    value)
    76→        RUN_ID="${2}"
    77→        VALUE="${3}"
    78→
    79→        if [ -z "$RUN_ID" ] || [ -z "$VALUE" ]; then
    80→            echo -e "${RED}❌ Usage: ./cc-track.sh value <run_id> <value_usd>${NC}"
    81→            exit 1
    82→        fi
    83→
    84→        echo -e "${CYAN}📊 CC Tracker - Adding value...${NC}"
    85→
    86→        curl -s -X PATCH "$API_BASE/run/$RUN_ID" \
    87→            -H "Content-Type: application/json" \
    88→            -d "{\"value_generated_usd\": $VALUE}" > /dev/null
    89→
    90→        echo -e "${GREEN}✓ Added \$$VALUE value to run $RUN_ID${NC}"
    91→        ;;
    92→
    93→    status)
    94→        echo -e "${CYAN}📊 CC Tracker - Today's Status${NC}"
    95→        echo ""
    96→
    97→        # Get health/budget
    98→        HEALTH=$(curl -s "$API_BASE/health" 2>/dev/null)
    99→        echo "$HEALTH" | python3 -c "
   100→import sys,json
   101→d=json.load(sys.stdin)
   102→b = d.get('gates',{}).get('budget',{})
   103→g = d.get('gates',{}).get('guardrails',{})
   104→print(f\"  Budget:     \${b.get('spent_usd',0):.2f} / \${b.get('limit_usd',10):.2f} ({b.get('used_pct',0):.1f}%)\")
   105→print(f\"  Guardrails: {g.get('active_rules',0)} active | Status: {g.get('status','?')}\")
   106→print(f\"  Overall:    {d.get('overall','?')}\")
   107→" 2>/dev/null
   108→
   109→        echo ""
   110→
   111→        # Get ROI summary
   112→        SUMMARY=$(curl -s "$API_BASE/roi/summary" 2>/dev/null)
   113→        echo "$SUMMARY" | python3 -c "
   114→import sys,json
   115→d=json.load(sys.stdin)
   116→print('  ROI Summary:')
   117→print(f\"    Cost:     \${d.get('today_cost',0):.4f}\")
   118→print(f\"    Revenue:  \${d.get('today_revenue',0):.2f}\")
   119→print(f\"    Profit:   \${d.get('today_profit',0):.2f}\")
   120→roi = d.get('roi_percent',0)
   121→print(f\"    ROI:      {'+' if roi > 0 else ''}{roi:.0f}%\")
   122→print(f\"    Runs:     {d.get('today_runs',0)}\")
   123→" 2>/dev/null
   124→        ;;
   125→
   126→    runs)
   127→        LIMIT="${2:-10}"
   128→        echo -e "${CYAN}📊 CC Tracker - Recent Runs (last $LIMIT)${NC}"
   129→        echo ""
   130→
   131→        curl -s "$API_BASE/runs?limit=$LIMIT" | python3 -c "
   132→import sys,json
   133→runs = json.load(sys.stdin)
   134→for r in runs:
   135→    status = '✅' if r.get('status') == 'completed' else '⏳' if r.get('status') == 'running' else '❌'
   136→    prompt = (r.get('prompt','')[:35] + '...') if len(r.get('prompt','')) > 35 else r.get('prompt','')
   137→    cost = r.get('cost_usd',0)
   138→    value = r.get('value_generated_usd',0) or 0
   139→    profit = value - cost
   140→    print(f\"  {status} {r.get('source','?'):8} | \${cost:.3f} cost | \${value:.2f} value | {prompt}\")
   141→" 2>/dev/null
   142→        ;;
   143→
   144→    gate)
   145→        PROMPT="${2}"
   146→        TOKENS="${3:-5000}"
   147→
   148→        if [ -z "$PROMPT" ]; then
   149→            echo -e "${RED}❌ Usage: ./cc-track.sh gate \"prompt\" [estimated_tokens]${NC}"
   150→            exit 1
   151→        fi
   152→
   153→        echo -e "${CYAN}🛡 CC Tracker - Gate Pre-check${NC}"
   154→        echo ""
   155→
   156→        RESPONSE=$(curl -s -X POST "$API_BASE/gate/check" \
   157→            -H "Content-Type: application/json" \
   158→            -d "{\"prompt\": \"$PROMPT\", \"estimated_tokens\": $TOKENS}")
   159→
   160→        PASSED=$(echo "$RESPONSE" | python3 -c "import sys,json; print('true' if json.load(sys.stdin).get('passed') else 'false')" 2>/dev/null)
   161→
   162→        if [ "$PASSED" = "true" ]; then
   163→            echo -e "  ${GREEN}✓ All gates passed - safe to proceed${NC}"
   164→        else
   165→            echo -e "  ${RED}✗ Gates failed - do not proceed${NC}"
   166→            echo ""
   167→            echo "$RESPONSE" | python3 -c "
   168→import sys,json
   169→d=json.load(sys.stdin)
   170→for gate, info in d.get('gates',{}).items():
   171→    if not info.get('passed', True):
   172→        print(f\"  ❌ {gate}: {info.get('reason') or info.get('violations', [])}\")
   173→" 2>/dev/null
   174→        fi
   175→        ;;
   176→
   177→    export)
   178→        FORMAT="${2:-json}"
   179→        DAYS="${3:-30}"
   180→        OUTPUT_FILE="${4:-}"
   181→
   182→        echo -e "${CYAN}📊 CC Tracker - Export Data${NC}"
   183→        echo ""
   184→
   185→        if [ "$FORMAT" = "csv" ]; then
   186→            if [ -n "$OUTPUT_FILE" ]; then
   187→                curl -s "$API_BASE/export/runs?format=csv&days=$DAYS" > "$OUTPUT_FILE"
   188→                echo -e "${GREEN}✓ Exported to $OUTPUT_FILE${NC}"
   189→            else
   190→                OUTPUT_FILE="cc_runs_${DAYS}d.csv"
   191→                curl -s "$API_BASE/export/runs?format=csv&days=$DAYS" > "$OUTPUT_FILE"
   192→                echo -e "${GREEN}✓ Exported to $OUTPUT_FILE${NC}"
   193→            fi
   194→        elif [ "$FORMAT" = "summary" ]; then
   195→            curl -s "$API_BASE/export/summary" | python3 -m json.tool
   196→        else
   197→            curl -s "$API_BASE/export/runs?days=$DAYS" | python3 -m json.tool
   198→        fi
   199→        ;;
   200→
   201→    budget)
   202→        ACTION="${2:-status}"
   203→
   204→        case "$ACTION" in
   205→            status)
   206→                echo -e "${CYAN}📊 CC Tracker - Budget Status${NC}"
   207→                echo ""
   208→                curl -s "$API_BASE/budget" | python3 -c "
   209→import sys,json
   210→d = json.load(sys.stdin)
   211→print(f'  Daily Limit:     \${d.get(\"daily_limit_usd\", 10):.2f}')
   212→print(f'  Monthly Limit:   \${d.get(\"monthly_limit_usd\", 200):.2f}')
   213→print(f'  Per-Run Limit:   \${d.get(\"max_cost_per_run_usd\", 2):.2f}')
   214→print(f'  Alert Threshold: {d.get(\"alert_threshold_pct\", 80)}%')
   215→print()
   216→print(f'  Spent Today:     \${d.get(\"spent_today\", 0):.4f}')
   217→print(f'  Spent This Month:\${d.get(\"spent_month\", 0):.4f}')
   218→" 2>/dev/null
   219→                ;;
   220→            set)
   221→                LIMIT="${3}"
   222→                if [ -z "$LIMIT" ]; then
   223→                    echo -e "${RED}❌ Usage: ./cc-track.sh budget set <daily_limit>${NC}"
   224→                    exit 1
   225→                fi
   226→                curl -s -X POST "$API_BASE/budget" \
   227→                    -H "Content-Type: application/json" \
   228→                    -d "{\"daily_limit_usd\": $LIMIT}" > /dev/null
   229→                echo -e "${GREEN}✓ Daily limit set to \$$LIMIT${NC}"
   230→                ;;
   231→            *)
   232→                echo "Usage: ./cc-track.sh budget [status|set <limit>]"
   233→                ;;
   234→        esac
   235→        ;;
   236→
   237→    help|*)
   238→        echo -e "${CYAN}📊 CC Tracker - Claude Code ROI Tracking${NC}"
   239→        echo ""
   240→        echo "Usage:"
   241→        echo "  ./cc-track.sh start \"prompt\" [source]    Start tracking a run"
   242→        echo "  ./cc-track.sh complete <run_id> [value]  Complete run with optional value"
   243→        echo "  ./cc-track.sh value <run_id> <value>     Add revenue to existing run"
   244→        echo "  ./cc-track.sh status                     Show today's stats"
   245→        echo "  ./cc-track.sh runs [limit]               List recent runs"
   246→        echo "  ./cc-track.sh gate \"prompt\"              Pre-check gates"
   247→        echo "  ./cc-track.sh export [json|csv|summary] [days]  Export data"
   248→        echo "  ./cc-track.sh budget [status|set <limit>]       Manage budget"
   249→        echo ""
   250→        echo "Examples:"
   251→        echo "  ./cc-track.sh start \"Build auth module\" ios_app"
   252→        echo "  ./cc-track.sh complete abc123 25.00"
   253→        echo "  ./cc-track.sh gate \"sudo rm -rf /\""
   254→        echo "  ./cc-track.sh export csv 7               Export last 7 days as CSV"
   255→        echo "  ./cc-track.sh budget set 20              Set daily limit to \$20"
   256→        echo ""
   257→        echo "Dashboard: http://localhost:9001/roi"
   258→        ;;
   259→esac
   260→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

#!/bin/bash
# cc-track.sh - Track Claude Code runs for ROI Dashboard
#
# Usage:
#   ./cc-track.sh start "Your prompt here" [source]     # Start tracking a run
#   ./cc-track.sh complete <run_id> [value_usd]         # Complete a run with optional revenue
#   ./cc-track.sh value <run_id> <value_usd>            # Add revenue value to a run
#   ./cc-track.sh status                                # Show today's stats
#   ./cc-track.sh runs [limit]                          # List recent runs
#   ./cc-track.sh gate "prompt"                         # Pre-check gates before running

API_BASE="http://localhost:9001/api/cc"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

case "${1:-help}" in
    start)
        PROMPT="${2:-Manual automation task}"
        SOURCE="${3:-manual}"

        echo -e "${CYAN}📊 CC Tracker - Starting run...${NC}"
        echo "   Prompt: $PROMPT"
        echo "   Source: $SOURCE"

        RESPONSE=$(curl -s -X POST "$API_BASE/run" \
            -H "Content-Type: application/json" \
            -d "{\"prompt\": \"$PROMPT\", \"source\": \"$SOURCE\"}")

        RUN_ID=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin).get('run_id',''))" 2>/dev/null)

        if [ -z "$RUN_ID" ]; then
            echo -e "${RED}❌ Failed to create run${NC}"
            exit 1
        fi

        echo ""
        echo -e "${GREEN}✓ Run started: $RUN_ID${NC}"
        echo ""
        echo "To complete this run:"
        echo -e "  ${YELLOW}./cc-track.sh complete $RUN_ID [value_usd]${NC}"
        echo ""
        echo "Example with \$5 value generated:"
        echo "  ./cc-track.sh complete $RUN_ID 5.00"
        ;;

    complete)
        RUN_ID="${2}"
        VALUE="${3:-0}"

        if [ -z "$RUN_ID" ]; then
            echo -e "${RED}❌ Usage: ./cc-track.sh complete <run_id> [value_usd]${NC}"
            exit 1
        fi

        echo -e "${CYAN}📊 CC Tracker - Completing run...${NC}"

        RESPONSE=$(curl -s -X POST "$API_BASE/run/$RUN_ID/complete" \
            -H "Content-Type: application/json" \
            -d "{\"status\": \"completed\", \"value_generated_usd\": $VALUE}")

        DURATION=$(echo "$RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f\"{d.get('duration_ms',0)/1000:.1f}s\")" 2>/dev/null)
        COST=$(echo "$RESPONSE" | python3 -c "import sys,json; print(f\"\${json.load(sys.stdin).get('cost_usd',0):.4f}\")" 2>/dev/null)

        echo ""
        echo -e "${GREEN}✓ Run completed${NC}"
        echo "   Duration: $DURATION"
        echo "   Cost:     $COST"
        echo "   Value:    \$$VALUE"
        ;;

    value)
        RUN_ID="${2}"
        VALUE="${3}"

        if [ -z "$RUN_ID" ] || [ -z "$VALUE" ]; then
            echo -e "${RED}❌ Usage: ./cc-track.sh value <run_id> <value_usd>${NC}"
            exit 1
        fi

        echo -e "${CYAN}📊 CC Tracker - Adding value...${NC}"

        curl -s -X PATCH "$API_BASE/run/$RUN_ID" \
            -H "Content-Type: application/json" \
            -d "{\"value_generated_usd\": $VALUE}" > /dev/null

        echo -e "${GREEN}✓ Added \$$VALUE value to run $RUN_ID${NC}"
        ;;

    status)
        echo -e "${CYAN}📊 CC Tracker - Today's Status${NC}"
        echo ""

        # Get health/budget
        HEALTH=$(curl -s "$API_BASE/health" 2>/dev/null)
        echo "$HEALTH" | python3 -c "
import sys,json
d=json.load(sys.stdin)
b = d.get('gates',{}).get('budget',{})
g = d.get('gates',{}).get('guardrails',{})
print(f\"  Budget:     \${b.get('spent_usd',0):.2f} / \${b.get('limit_usd',10):.2f} ({b.get('used_pct',0):.1f}%)\")
print(f\"  Guardrails: {g.get('active_rules',0)} active | Status: {g.get('status','?')}\")
print(f\"  Overall:    {d.get('overall','?')}\")
" 2>/dev/null

        echo ""

        # Get ROI summary
        SUMMARY=$(curl -s "$API_BASE/roi/summary" 2>/dev/null)
        echo "$SUMMARY" | python3 -c "
import sys,json
d=json.load(sys.stdin)
print('  ROI Summary:')
print(f\"    Cost:     \${d.get('today_cost',0):.4f}\")
print(f\"    Revenue:  \${d.get('today_revenue',0):.2f}\")
print(f\"    Profit:   \${d.get('today_profit',0):.2f}\")
roi = d.get('roi_percent',0)
print(f\"    ROI:      {'+' if roi > 0 else ''}{roi:.0f}%\")
print(f\"    Runs:     {d.get('today_runs',0)}\")
" 2>/dev/null
        ;;

    runs)
        LIMIT="${2:-10}"
        echo -e "${CYAN}📊 CC Tracker - Recent Runs (last $LIMIT)${NC}"
        echo ""

        curl -s "$API_BASE/runs?limit=$LIMIT" | python3 -c "
import sys,json
runs = json.load(sys.stdin)
for r in runs:
    status = '✅' if r.get('status') == 'completed' else '⏳' if r.get('status') == 'running' else '❌'
    prompt = (r.get('prompt','')[:35] + '...') if len(r.get('prompt','')) > 35 else r.get('prompt','')
    cost = r.get('cost_usd',0)
    value = r.get('value_generated_usd',0) or 0
    profit = value - cost
    print(f\"  {status} {r.get('source','?'):8} | \${cost:.3f} cost | \${value:.2f} value | {prompt}\")
" 2>/dev/null
        ;;

    gate)
        PROMPT="${2}"
        TOKENS="${3:-5000}"

        if [ -z "$PROMPT" ]; then
            echo -e "${RED}❌ Usage: ./cc-track.sh gate \"prompt\" [estimated_tokens]${NC}"
            exit 1
        fi

        echo -e "${CYAN}🛡 CC Tracker - Gate Pre-check${NC}"
        echo ""

        RESPONSE=$(curl -s -X POST "$API_BASE/gate/check" \
            -H "Content-Type: application/json" \
            -d "{\"prompt\": \"$PROMPT\", \"estimated_tokens\": $TOKENS}")

        PASSED=$(echo "$RESPONSE" | python3 -c "import sys,json; print('true' if json.load(sys.stdin).get('passed') else 'false')" 2>/dev/null)

        if [ "$PASSED" = "true" ]; then
            echo -e "  ${GREEN}✓ All gates passed - safe to proceed${NC}"
        else
            echo -e "  ${RED}✗ Gates failed - do not proceed${NC}"
            echo ""
            echo "$RESPONSE" | python3 -c "
import sys,json
d=json.load(sys.stdin)
for gate, info in d.get('gates',{}).items():
    if not info.get('passed', True):
        print(f\"  ❌ {gate}: {info.get('reason') or info.get('violations', [])}\")
" 2>/dev/null
        fi
        ;;

    export)
        FORMAT="${2:-json}"
        DAYS="${3:-30}"
        OUTPUT_FILE="${4:-}"

        echo -e "${CYAN}📊 CC Tracker - Export Data${NC}"
        echo ""

        if [ "$FORMAT" = "csv" ]; then
            if [ -n "$OUTPUT_FILE" ]; then
                curl -s "$API_BASE/export/runs?format=csv&days=$DAYS" > "$OUTPUT_FILE"
                echo -e "${GREEN}✓ Exported to $OUTPUT_FILE${NC}"
            else
                OUTPUT_FILE="cc_runs_${DAYS}d.csv"
                curl -s "$API_BASE/export/runs?format=csv&days=$DAYS" > "$OUTPUT_FILE"
                echo -e "${GREEN}✓ Exported to $OUTPUT_FILE${NC}"
            fi
        elif [ "$FORMAT" = "summary" ]; then
            curl -s "$API_BASE/export/summary" | python3 -m json.tool
        else
            curl -s "$API_BASE/export/runs?days=$DAYS" | python3 -m json.tool
        fi
        ;;

    budget)
        ACTION="${2:-status}"

        case "$ACTION" in
            status)
                echo -e "${CYAN}📊 CC Tracker - Budget Status${NC}"
                echo ""
                curl -s "$API_BASE/budget" | python3 -c "
import sys,json
d = json.load(sys.stdin)
print(f'  Daily Limit:     \${d.get(\"daily_limit_usd\", 10):.2f}')
print(f'  Monthly Limit:   \${d.get(\"monthly_limit_usd\", 200):.2f}')
print(f'  Per-Run Limit:   \${d.get(\"max_cost_per_run_usd\", 2):.2f}')
print(f'  Alert Threshold: {d.get(\"alert_threshold_pct\", 80)}%')
print()
print(f'  Spent Today:     \${d.get(\"spent_today\", 0):.4f}')
print(f'  Spent This Month:\${d.get(\"spent_month\", 0):.4f}')
" 2>/dev/null
                ;;
            set)
                LIMIT="${3}"
                if [ -z "$LIMIT" ]; then
                    echo -e "${RED}❌ Usage: ./cc-track.sh budget set <daily_limit>${NC}"
                    exit 1
                fi
                curl -s -X POST "$API_BASE/budget" \
                    -H "Content-Type: application/json" \
                    -d "{\"daily_limit_usd\": $LIMIT}" > /dev/null
                echo -e "${GREEN}✓ Daily limit set to \$$LIMIT${NC}"
                ;;
            *)
                echo "Usage: ./cc-track.sh budget [status|set <limit>]"
                ;;
        esac
        ;;

    help|*)
        echo -e "${CYAN}📊 CC Tracker - Claude Code ROI Tracking${NC}"
        echo ""
        echo "Usage:"
        echo "  ./cc-track.sh start \"prompt\" [source]    Start tracking a run"
        echo "  ./cc-track.sh complete <run_id> [value]  Complete run with optional value"
        echo "  ./cc-track.sh value <run_id> <value>     Add revenue to existing run"
        echo "  ./cc-track.sh status                     Show today's stats"
        echo "  ./cc-track.sh runs [limit]               List recent runs"
        echo "  ./cc-track.sh gate \"prompt\"              Pre-check gates"
        echo "  ./cc-track.sh export [json|csv|summary] [days]  Export data"
        echo "  ./cc-track.sh budget [status|set <limit>]       Manage budget"
        echo ""
        echo "Examples:"
        echo "  ./cc-track.sh start \"Build auth module\" ios_app"
        echo "  ./cc-track.sh complete abc123 25.00"
        echo "  ./cc-track.sh gate \"sudo rm -rf /\""
        echo "  ./cc-track.sh export csv 7               Export last 7 days as CSV"
        echo "  ./cc-track.sh budget set 20              Set daily limit to \$20"
        echo ""
        echo "Dashboard: http://localhost:9001/roi"
        ;;
esac


     1→#!/bin/bash
     2→# cc-services.sh - Manage Claude Code automation services
     3→# Usage: ./cc-services.sh [start|stop|status|restart]
     4→
     5→LOG_SERVER_PORT=9001
     6→CLI_SERVER_PORT=9003
     7→
     8→RED='\033[0;31m'
     9→GREEN='\033[0;32m'
    10→YELLOW='\033[1;33m'
    11→CYAN='\033[0;36m'
    12→NC='\033[0m'
    13→
    14→print_header() {
    15→    echo ""
    16→    echo -e "${CYAN}═══════════════════════════════════════════════════════════${NC}"
    17→    echo -e "${CYAN}  CC Automation Services Manager${NC}"
    18→    echo -e "${CYAN}═══════════════════════════════════════════════════════════${NC}"
    19→}
    20→
    21→check_port() {
    22→    local port=$1
    23→    lsof -ti :$port > /dev/null 2>&1
    24→}
    25→
    26→get_pid() {
    27→    local port=$1
    28→    lsof -ti :$port 2>/dev/null
    29→}
    30→
    31→start_services() {
    32→    echo ""
    33→    echo -e "${YELLOW}Starting services...${NC}"
    34→    echo ""
    35→
    36→    # Start log-server (port 9001)
    37→    if check_port $LOG_SERVER_PORT; then
    38→        echo -e "  ${GREEN}✓${NC} Log Server (port $LOG_SERVER_PORT) already running"
    39→    else
    40→        cd /Users/neog
    41→        python3 log-server.py > /tmp/log-server.log 2>&1 &
    42→        sleep 2
    43→        if check_port $LOG_SERVER_PORT; then
    44→            echo -e "  ${GREEN}✓${NC} Log Server started (port $LOG_SERVER_PORT)"
    45→        else
    46→            echo -e "  ${RED}✗${NC} Log Server failed to start"
    47→        fi
    48→    fi
    49→
    50→    # Start claude-cli-server (port 9003)
    51→    if check_port $CLI_SERVER_PORT; then
    52→        echo -e "  ${GREEN}✓${NC} CLI Server (port $CLI_SERVER_PORT) already running"
    53→    else
    54→        cd /Users/neog
    55→        python3 claude-cli-server.py > /tmp/claude-cli-server.log 2>&1 &
    56→        sleep 2
    57→        if check_port $CLI_SERVER_PORT; then
    58→            echo -e "  ${GREEN}✓${NC} CLI Server started (port $CLI_SERVER_PORT)"
    59→        else
    60→            echo -e "  ${RED}✗${NC} CLI Server failed to start"
    61→        fi
    62→    fi
    63→
    64→    echo ""
    65→    echo -e "${GREEN}Services started!${NC}"
    66→    echo ""
    67→    echo "  ROI Dashboard:  http://localhost:9001/roi"
    68→    echo "  API Health:     http://localhost:9001/api/cc/health"
    69→    echo "  CLI Server:     http://localhost:9003"
    70→}
    71→
    72→stop_services() {
    73→    echo ""
    74→    echo -e "${YELLOW}Stopping services...${NC}"
    75→    echo ""
    76→
    77→    # Stop log-server
    78→    local pid=$(get_pid $LOG_SERVER_PORT)
    79→    if [ -n "$pid" ]; then
    80→        kill -9 $pid 2>/dev/null
    81→        echo -e "  ${GREEN}✓${NC} Log Server stopped (PID $pid)"
    82→    else
    83→        echo -e "  ${YELLOW}○${NC} Log Server not running"
    84→    fi
    85→
    86→    # Stop CLI server
    87→    pid=$(get_pid $CLI_SERVER_PORT)
    88→    if [ -n "$pid" ]; then
    89→        kill -9 $pid 2>/dev/null
    90→        echo -e "  ${GREEN}✓${NC} CLI Server stopped (PID $pid)"
    91→    else
    92→        echo -e "  ${YELLOW}○${NC} CLI Server not running"
    93→    fi
    94→
    95→    echo ""
    96→    echo -e "${GREEN}Services stopped.${NC}"
    97→}
    98→
    99→status_services() {
   100→    echo ""
   101→    echo -e "${YELLOW}Service Status:${NC}"
   102→    echo ""
   103→
   104→    # Log Server status
   105→    if check_port $LOG_SERVER_PORT; then
   106→        local pid=$(get_pid $LOG_SERVER_PORT)
   107→        echo -e "  ${GREEN}●${NC} Log Server     : Running (PID $pid, port $LOG_SERVER_PORT)"
   108→
   109→        # Get health info
   110→        local health=$(curl -s http://localhost:$LOG_SERVER_PORT/api/cc/health 2>/dev/null)
   111→        if [ -n "$health" ]; then
   112→            local budget_pct=$(echo "$health" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('gates',{}).get('budget',{}).get('used_pct',0):.1f}\")" 2>/dev/null)
   113→            local guardrails=$(echo "$health" | python3 -c "import sys,json; print(json.load(sys.stdin).get('gates',{}).get('guardrails',{}).get('active_rules',0))" 2>/dev/null)
   114→            echo -e "                   Budget: ${budget_pct}% used | Guardrails: ${guardrails} active"
   115→        fi
   116→    else
   117→        echo -e "  ${RED}○${NC} Log Server     : Stopped"
   118→    fi
   119→
   120→    # CLI Server status
   121→    if check_port $CLI_SERVER_PORT; then
   122→        local pid=$(get_pid $CLI_SERVER_PORT)
   123→        echo -e "  ${GREEN}●${NC} CLI Server     : Running (PID $pid, port $CLI_SERVER_PORT)"
   124→    else
   125→        echo -e "  ${RED}○${NC} CLI Server     : Stopped"
   126→    fi
   127→
   128→    echo ""
   129→
   130→    # Quick stats
   131→    if check_port $LOG_SERVER_PORT; then
   132→        echo -e "${YELLOW}Today's Stats:${NC}"
   133→        local summary=$(curl -s http://localhost:$LOG_SERVER_PORT/api/cc/roi/summary 2>/dev/null)
   134→        if [ -n "$summary" ]; then
   135→            echo "$summary" | python3 -c "
   136→import sys,json
   137→d=json.load(sys.stdin)
   138→print(f\"  Cost:    \${d.get('today_cost', 0):.4f}\")
   139→print(f\"  Revenue: \${d.get('today_revenue', 0):.2f}\")
   140→print(f\"  Runs:    {d.get('today_runs', 0)}\")
   141→" 2>/dev/null
   142→        fi
   143→    fi
   144→}
   145→
   146→print_header
   147→
   148→case "${1:-status}" in
   149→    start)
   150→        start_services
   151→        ;;
   152→    stop)
   153→        stop_services
   154→        ;;
   155→    restart)
   156→        stop_services
   157→        sleep 1
   158→        start_services
   159→        ;;
   160→    status|*)
   161→        status_services
   162→        ;;
   163→esac
   164→
   165→echo ""
   166→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

#!/bin/bash
# cc-services.sh - Manage Claude Code automation services
# Usage: ./cc-services.sh [start|stop|status|restart]

LOG_SERVER_PORT=9001
CLI_SERVER_PORT=9003

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

print_header() {
    echo ""
    echo -e "${CYAN}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${CYAN}  CC Automation Services Manager${NC}"
    echo -e "${CYAN}═══════════════════════════════════════════════════════════${NC}"
}

check_port() {
    local port=$1
    lsof -ti :$port > /dev/null 2>&1
}

get_pid() {
    local port=$1
    lsof -ti :$port 2>/dev/null
}

start_services() {
    echo ""
    echo -e "${YELLOW}Starting services...${NC}"
    echo ""

    # Start log-server (port 9001)
    if check_port $LOG_SERVER_PORT; then
        echo -e "  ${GREEN}✓${NC} Log Server (port $LOG_SERVER_PORT) already running"
    else
        cd /Users/neog
        python3 log-server.py > /tmp/log-server.log 2>&1 &
        sleep 2
        if check_port $LOG_SERVER_PORT; then
            echo -e "  ${GREEN}✓${NC} Log Server started (port $LOG_SERVER_PORT)"
        else
            echo -e "  ${RED}✗${NC} Log Server failed to start"
        fi
    fi

    # Start claude-cli-server (port 9003)
    if check_port $CLI_SERVER_PORT; then
        echo -e "  ${GREEN}✓${NC} CLI Server (port $CLI_SERVER_PORT) already running"
    else
        cd /Users/neog
        python3 claude-cli-server.py > /tmp/claude-cli-server.log 2>&1 &
        sleep 2
        if check_port $CLI_SERVER_PORT; then
            echo -e "  ${GREEN}✓${NC} CLI Server started (port $CLI_SERVER_PORT)"
        else
            echo -e "  ${RED}✗${NC} CLI Server failed to start"
        fi
    fi

    echo ""
    echo -e "${GREEN}Services started!${NC}"
    echo ""
    echo "  ROI Dashboard:  http://localhost:9001/roi"
    echo "  API Health:     http://localhost:9001/api/cc/health"
    echo "  CLI Server:     http://localhost:9003"
}

stop_services() {
    echo ""
    echo -e "${YELLOW}Stopping services...${NC}"
    echo ""

    # Stop log-server
    local pid=$(get_pid $LOG_SERVER_PORT)
    if [ -n "$pid" ]; then
        kill -9 $pid 2>/dev/null
        echo -e "  ${GREEN}✓${NC} Log Server stopped (PID $pid)"
    else
        echo -e "  ${YELLOW}○${NC} Log Server not running"
    fi

    # Stop CLI server
    pid=$(get_pid $CLI_SERVER_PORT)
    if [ -n "$pid" ]; then
        kill -9 $pid 2>/dev/null
        echo -e "  ${GREEN}✓${NC} CLI Server stopped (PID $pid)"
    else
        echo -e "  ${YELLOW}○${NC} CLI Server not running"
    fi

    echo ""
    echo -e "${GREEN}Services stopped.${NC}"
}

status_services() {
    echo ""
    echo -e "${YELLOW}Service Status:${NC}"
    echo ""

    # Log Server status
    if check_port $LOG_SERVER_PORT; then
        local pid=$(get_pid $LOG_SERVER_PORT)
        echo -e "  ${GREEN}●${NC} Log Server     : Running (PID $pid, port $LOG_SERVER_PORT)"

        # Get health info
        local health=$(curl -s http://localhost:$LOG_SERVER_PORT/api/cc/health 2>/dev/null)
        if [ -n "$health" ]; then
            local budget_pct=$(echo "$health" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('gates',{}).get('budget',{}).get('used_pct',0):.1f}\")" 2>/dev/null)
            local guardrails=$(echo "$health" | python3 -c "import sys,json; print(json.load(sys.stdin).get('gates',{}).get('guardrails',{}).get('active_rules',0))" 2>/dev/null)
            echo -e "                   Budget: ${budget_pct}% used | Guardrails: ${guardrails} active"
        fi
    else
        echo -e "  ${RED}○${NC} Log Server     : Stopped"
    fi

    # CLI Server status
    if check_port $CLI_SERVER_PORT; then
        local pid=$(get_pid $CLI_SERVER_PORT)
        echo -e "  ${GREEN}●${NC} CLI Server     : Running (PID $pid, port $CLI_SERVER_PORT)"
    else
        echo -e "  ${RED}○${NC} CLI Server     : Stopped"
    fi

    echo ""

    # Quick stats
    if check_port $LOG_SERVER_PORT; then
        echo -e "${YELLOW}Today's Stats:${NC}"
        local summary=$(curl -s http://localhost:$LOG_SERVER_PORT/api/cc/roi/summary 2>/dev/null)
        if [ -n "$summary" ]; then
            echo "$summary" | python3 -c "
import sys,json
d=json.load(sys.stdin)
print(f\"  Cost:    \${d.get('today_cost', 0):.4f}\")
print(f\"  Revenue: \${d.get('today_revenue', 0):.2f}\")
print(f\"  Runs:    {d.get('today_runs', 0)}\")
" 2>/dev/null
        fi
    fi
}

print_header

case "${1:-status}" in
    start)
        start_services
        ;;
    stop)
        stop_services
        ;;
    restart)
        stop_services
        sleep 1
        start_services
        ;;
    status|*)
        status_services
        ;;
esac

echo ""


     1→#!/bin/bash
     2→# cc.sh - Unified Claude Code ROI Dashboard Control
     3→#
     4→# Usage:
     5→#   cc              # Quick status overview
     6→#   cc status       # Detailed status
     7→#   cc value        # Manage run values (interactive)
     8→#   cc watch        # Live monitoring
     9→#   cc action X     # Run automation action
    10→#   cc report       # Generate daily report
    11→#   cc help         # Show all commands
    12→
    13→SCRIPT_DIR="$HOME"
    14→API_BASE="http://localhost:9001/api/cc"
    15→
    16→RED='\033[0;31m'
    17→GREEN='\033[0;32m'
    18→YELLOW='\033[1;33m'
    19→CYAN='\033[0;36m'
    20→PURPLE='\033[0;35m'
    21→BOLD='\033[1m'
    22→DIM='\033[2m'
    23→NC='\033[0m'
    24→
    25→# Quick status - default command
    26→quick_status() {
    27→    # Check if server is running
    28→    local health
    29→    health=$(curl -s "$API_BASE/health" 2>/dev/null)
    30→
    31→    if [ -z "$health" ]; then
    32→        echo -e "${RED}⚠ CC Dashboard server is offline${NC}"
    33→        echo -e "${DIM}  Start with: python3 ~/log-server.py${NC}"
    34→        return 1
    35→    fi
    36→
    37→    # Get all data in parallel
    38→    local alltime roi_real
    39→    alltime=$(curl -s "$API_BASE/roi/all-time" 2>/dev/null)
    40→    roi_real=$(curl -s "$API_BASE/roi/real" 2>/dev/null)
    41→
    42→    # Parse with python
    43→    echo "$health" | python3 -c '
    44→import sys, json
    45→
    46→PURPLE = "\033[0;35m"
    47→GREEN = "\033[0;32m"
    48→YELLOW = "\033[1;33m"
    49→RED = "\033[0;31m"
    50→CYAN = "\033[0;36m"
    51→BOLD = "\033[1m"
    52→DIM = "\033[2m"
    53→NC = "\033[0m"
    54→
    55→try:
    56→    h = json.load(sys.stdin)
    57→    overall = h.get("overall", "unknown")
    58→    budget = h.get("gates", {}).get("budget", {})
    59→
    60→    status_icon = "●"
    61→    status_color = GREEN if overall == "ok" else YELLOW if overall == "warning" else RED
    62→
    63→    spent = budget.get("spent_usd", 0)
    64→    limit = budget.get("limit_usd", 10)
    65→    pct = budget.get("used_pct", 0)
    66→
    67→    print(f"{PURPLE}{BOLD}⚡ CC Dashboard{NC}")
    68→    print(f"  Status: {status_color}{status_icon} {overall.upper()}{NC}")
    69→    print(f"  Budget: ${spent:.2f}/${limit:.0f} ({pct:.1f}%)")
    70→except Exception as e:
    71→    print(f"Error: {e}")
    72→'
    73→
    74→    echo "$alltime" | python3 -c '
    75→import sys, json
    76→
    77→GREEN = "\033[0;32m"
    78→CYAN = "\033[0;36m"
    79→NC = "\033[0m"
    80→
    81→try:
    82→    d = json.load(sys.stdin)
    83→    profit = d.get("profit_usd", 0)
    84→    roi = d.get("roi_pct", 0)
    85→    runs = d.get("runs_total", 0)
    86→    success = d.get("success_rate_pct", 0)
    87→
    88→    print(f"  Profit: {GREEN}${profit:.2f}{NC} (+{roi:.0f}% ROI)")
    89→    print(f"  Runs:   {runs} total ({success:.0f}% success)")
    90→except Exception as e:
    91→    print(f"Error: {e}")
    92→'
    93→
    94→    echo "$roi_real" | python3 -c '
    95→import sys, json
    96→
    97→GREEN = "\033[0;32m"
    98→YELLOW = "\033[1;33m"
    99→DIM = "\033[2m"
   100→NC = "\033[0m"
   101→
   102→try:
   103→    d = json.load(sys.stdin)
   104→    real_pct = d.get("total", {}).get("real_pct", 0)
   105→    verified = d.get("real", {}).get("runs", 0)
   106→    estimated = d.get("estimated", {}).get("runs", 0)
   107→
   108→    if real_pct < 20:
   109→        color = YELLOW
   110→        msg = "needs verification"
   111→    else:
   112→        color = GREEN
   113→        msg = "good"
   114→
   115→    print(f"  Data:   {color}{real_pct:.0f}% verified{NC} {DIM}({verified} real, {estimated} estimated){NC}")
   116→except Exception as e:
   117→    print(f"Error: {e}")
   118→'
   119→
   120→    echo ""
   121→    echo -e "${DIM}Quick: cc value | cc watch | cc action report${NC}"
   122→}
   123→
   124→# Detailed status
   125→detailed_status() {
   126→    echo -e "${PURPLE}${BOLD}═══════════════════════════════════════════════════════${NC}"
   127→    echo -e "${PURPLE}${BOLD}  CC ROI Dashboard - Detailed Status${NC}"
   128→    echo -e "${PURPLE}${BOLD}═══════════════════════════════════════════════════════${NC}"
   129→    echo ""
   130→
   131→    # Health check
   132→    echo -e "${CYAN}Health Check:${NC}"
   133→    "$SCRIPT_DIR/cc-action.sh" health 2>/dev/null | grep -E "(✅|⚠|❌|Status)" | head -10
   134→    echo ""
   135→
   136→    # Value stats
   137→    echo -e "${CYAN}Value Statistics:${NC}"
   138→    "$SCRIPT_DIR/cc-value.sh" stats 2>/dev/null | tail -20
   139→    echo ""
   140→
   141→    # Recent runs
   142→    echo -e "${CYAN}Recent Runs:${NC}"
   143→    "$SCRIPT_DIR/cc-value.sh" list 2>/dev/null | head -12
   144→}
   145→
   146→# Morning report
   147→morning_report() {
   148→    echo -e "${PURPLE}${BOLD}☀  Good Morning! Here's your CC status:${NC}"
   149→    echo ""
   150→
   151→    local alltime roi_real
   152→    alltime=$(curl -s "$API_BASE/roi/all-time" 2>/dev/null)
   153→    roi_real=$(curl -s "$API_BASE/roi/real" 2>/dev/null)
   154→
   155→    if [ -z "$alltime" ]; then
   156→        echo -e "${RED}Server offline. Start with: python3 ~/log-server.py${NC}"
   157→        return 1
   158→    fi
   159→
   160→    # Process alltime data
   161→    echo "$alltime" | python3 -c '
   162→import sys, json
   163→
   164→GREEN = "\033[0;32m"
   165→CYAN = "\033[0;36m"
   166→NC = "\033[0m"
   167→
   168→try:
   169→    d = json.load(sys.stdin)
   170→    profit = d.get("profit_usd", 0)
   171→    roi = d.get("roi_pct", 0)
   172→    runs = d.get("runs_total", 0)
   173→    cost = d.get("cost_usd", 0)
   174→    days = d.get("active_days", 1)
   175→
   176→    print(f"{CYAN}All-Time Performance:{NC}")
   177→    print(f"  💰 Profit: {GREEN}${profit:.2f}{NC}")
   178→    print(f"  📈 ROI: {GREEN}+{roi:.0f}%{NC}")
   179→    print(f"  🔢 Runs: {runs} over {days} days")
   180→    print(f"  💸 Total Cost: ${cost:.2f}")
   181→    print()
   182→
   183→    daily_profit = profit / days if days > 0 else 0
   184→    daily_runs = runs / days if days > 0 else 0
   185→    print(f"{CYAN}Daily Averages:{NC}")
   186→    print(f"  📊 ${daily_profit:.2f}/day profit")
   187→    print(f"  🔄 {daily_runs:.1f} runs/day")
   188→except Exception as e:
   189→    print(f"Error: {e}")
   190→'
   191→
   192→    # Process roi_real data
   193→    echo "$roi_real" | python3 -c '
   194→import sys, json
   195→
   196→CYAN = "\033[0;36m"
   197→NC = "\033[0m"
   198→
   199→try:
   200→    d = json.load(sys.stdin)
   201→    real = d.get("real", {})
   202→    verified_runs = real.get("runs", 0)
   203→    verified_value = real.get("value_usd", 0)
   204→    time_saved = real.get("time_saved_minutes", 0)
   205→
   206→    print()
   207→    print(f"{CYAN}Verified Value:{NC}")
   208→    print(f"  ✅ {verified_runs} runs verified")
   209→    print(f"  💵 ${verified_value:.2f} confirmed value")
   210→    time_value = time_saved * 50 / 60
   211→    print(f"  ⏱  {time_saved} minutes saved (${time_value:.2f} @$50/hr)")
   212→except Exception as e:
   213→    print(f"Error: {e}")
   214→'
   215→
   216→    echo ""
   217→    echo -e "${YELLOW}Tip:${NC} Run ${CYAN}cc value${NC} to verify estimated values"
   218→}
   219→
   220→# Show help
   221→show_help() {
   222→    echo -e "${PURPLE}${BOLD}CC Dashboard - Command Reference${NC}"
   223→    echo ""
   224→    echo -e "${BOLD}Quick Commands:${NC}"
   225→    echo "  cc                  Quick status overview"
   226→    echo "  cc status           Detailed status report"
   227→    echo "  cc morning          Morning status summary"
   228→    echo ""
   229→    echo -e "${BOLD}Value Management:${NC}"
   230→    echo "  cc value            Interactive value editor"
   231→    echo "  cc value list       List runs with values"
   232→    echo "  cc value stats      Show real vs estimated stats"
   233→    echo "  cc value set ID $   Set verified value for run"
   234→    echo ""
   235→    echo -e "${BOLD}Monitoring:${NC}"
   236→    echo "  cc watch            Full-screen live monitor"
   237→    echo "  cc watch compact    Single-line status"
   238→    echo "  cc watch alerts     Alert-only mode"
   239→    echo ""
   240→    echo -e "${BOLD}Automation:${NC}"
   241→    echo "  cc action backup    Create backup"
   242→    echo "  cc action report    Generate daily report"
   243→    echo "  cc action health    Health check"
   244→    echo "  cc action optimize  Run optimization"
   245→    echo "  cc action review    Code review"
   246→    echo ""
   247→    echo -e "${BOLD}Scheduling:${NC}"
   248→    echo "  cc schedule list    List scheduled jobs"
   249→    echo "  cc schedule setup   Setup recommended schedule"
   250→    echo ""
   251→    echo -e "${BOLD}Services:${NC}"
   252→    echo "  cc server start     Start dashboard server"
   253→    echo "  cc server stop      Stop dashboard server"
   254→    echo "  cc server status    Check server status"
   255→    echo ""
   256→    echo -e "${BOLD}Dashboard:${NC}"
   257→    echo "  cc open             Open dashboard in browser"
   258→    echo ""
   259→    echo -e "${DIM}Dashboard URL: http://localhost:9001/roi${NC}"
   260→}
   261→
   262→# Open dashboard
   263→open_dashboard() {
   264→    echo -e "${CYAN}Opening CC ROI Dashboard...${NC}"
   265→    open "http://localhost:9001/roi"
   266→}
   267→
   268→# Server control
   269→server_control() {
   270→    local action="${1:-status}"
   271→
   272→    case "$action" in
   273→        start)
   274→            if curl -s "$API_BASE/health" >/dev/null 2>&1; then
   275→                echo -e "${YELLOW}Server already running${NC}"
   276→            else
   277→                echo -e "${CYAN}Starting log server...${NC}"
   278→                nohup python3 "$HOME/log-server.py" > /tmp/cc-log-server.log 2>&1 &
   279→                sleep 2
   280→                if curl -s "$API_BASE/health" >/dev/null 2>&1; then
   281→                    echo -e "${GREEN}✓ Server started${NC}"
   282→                else
   283→                    echo -e "${RED}✗ Failed to start server${NC}"
   284→                fi
   285→            fi
   286→            ;;
   287→        stop)
   288→            pkill -f "log-server.py" 2>/dev/null
   289→            echo -e "${GREEN}✓ Server stopped${NC}"
   290→            ;;
   291→        status)
   292→            if curl -s "$API_BASE/health" >/dev/null 2>&1; then
   293→                echo -e "${GREEN}● Server running${NC}"
   294→            else
   295→                echo -e "${RED}○ Server offline${NC}"
   296→            fi
   297→            ;;
   298→        restart)
   299→            server_control stop
   300→            sleep 1
   301→            server_control start
   302→            ;;
   303→        *)
   304→            echo "Usage: cc server [start|stop|status|restart]"
   305→            ;;
   306→    esac
   307→}
   308→
   309→# Main
   310→case "${1:-quick}" in
   311→    quick|"")
   312→        quick_status
   313→        ;;
   314→    status|full|detailed)
   315→        detailed_status
   316→        ;;
   317→    morning|am)
   318→        morning_report
   319→        ;;
   320→    value|v)
   321→        shift
   322→        "$SCRIPT_DIR/cc-value.sh" "$@"
   323→        ;;
   324→    watch|w|monitor)
   325→        shift
   326→        "$SCRIPT_DIR/cc-watch.sh" "$@"
   327→        ;;
   328→    action|a|run)
   329→        shift
   330→        "$SCRIPT_DIR/cc-action.sh" "$@"
   331→        ;;
   332→    schedule|sched|cron)
   333→        shift
   334→        "$SCRIPT_DIR/cc-scheduler.sh" "$@"
   335→        ;;
   336→    server|srv)
   337→        shift
   338→        server_control "$@"
   339→        ;;
   340→    open|dashboard|web)
   341→        open_dashboard
   342→        ;;
   343→    report)
   344→        "$SCRIPT_DIR/cc-action.sh" report
   345→        ;;
   346→    help|--help|-h)
   347→        show_help
   348→        ;;
   349→    *)
   350→        echo -e "${RED}Unknown command: $1${NC}"
   351→        echo "Run 'cc help' for usage"
   352→        exit 1
   353→        ;;
   354→esac
   355→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

#!/bin/bash
# cc.sh - Unified Claude Code ROI Dashboard Control
#
# Usage:
#   cc              # Quick status overview
#   cc status       # Detailed status
#   cc value        # Manage run values (interactive)
#   cc watch        # Live monitoring
#   cc action X     # Run automation action
#   cc report       # Generate daily report
#   cc help         # Show all commands

SCRIPT_DIR="$HOME"
API_BASE="http://localhost:9001/api/cc"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
PURPLE='\033[0;35m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'

# Quick status - default command
quick_status() {
    # Check if server is running
    local health
    health=$(curl -s "$API_BASE/health" 2>/dev/null)

    if [ -z "$health" ]; then
        echo -e "${RED}⚠ CC Dashboard server is offline${NC}"
        echo -e "${DIM}  Start with: python3 ~/log-server.py${NC}"
        return 1
    fi

    # Get all data in parallel
    local alltime roi_real
    alltime=$(curl -s "$API_BASE/roi/all-time" 2>/dev/null)
    roi_real=$(curl -s "$API_BASE/roi/real" 2>/dev/null)

    # Parse with python
    echo "$health" | python3 -c '
import sys, json

PURPLE = "\033[0;35m"
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
RED = "\033[0;31m"
CYAN = "\033[0;36m"
BOLD = "\033[1m"
DIM = "\033[2m"
NC = "\033[0m"

try:
    h = json.load(sys.stdin)
    overall = h.get("overall", "unknown")
    budget = h.get("gates", {}).get("budget", {})

    status_icon = "●"
    status_color = GREEN if overall == "ok" else YELLOW if overall == "warning" else RED

    spent = budget.get("spent_usd", 0)
    limit = budget.get("limit_usd", 10)
    pct = budget.get("used_pct", 0)

    print(f"{PURPLE}{BOLD}⚡ CC Dashboard{NC}")
    print(f"  Status: {status_color}{status_icon} {overall.upper()}{NC}")
    print(f"  Budget: ${spent:.2f}/${limit:.0f} ({pct:.1f}%)")
except Exception as e:
    print(f"Error: {e}")
'

    echo "$alltime" | python3 -c '
import sys, json

GREEN = "\033[0;32m"
CYAN = "\033[0;36m"
NC = "\033[0m"

try:
    d = json.load(sys.stdin)
    profit = d.get("profit_usd", 0)
    roi = d.get("roi_pct", 0)
    runs = d.get("runs_total", 0)
    success = d.get("success_rate_pct", 0)

    print(f"  Profit: {GREEN}${profit:.2f}{NC} (+{roi:.0f}% ROI)")
    print(f"  Runs:   {runs} total ({success:.0f}% success)")
except Exception as e:
    print(f"Error: {e}")
'

    echo "$roi_real" | python3 -c '
import sys, json

GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
DIM = "\033[2m"
NC = "\033[0m"

try:
    d = json.load(sys.stdin)
    real_pct = d.get("total", {}).get("real_pct", 0)
    verified = d.get("real", {}).get("runs", 0)
    estimated = d.get("estimated", {}).get("runs", 0)

    if real_pct < 20:
        color = YELLOW
        msg = "needs verification"
    else:
        color = GREEN
        msg = "good"

    print(f"  Data:   {color}{real_pct:.0f}% verified{NC} {DIM}({verified} real, {estimated} estimated){NC}")
except Exception as e:
    print(f"Error: {e}")
'

    echo ""
    echo -e "${DIM}Quick: cc value | cc watch | cc action report${NC}"
}

# Detailed status
detailed_status() {
    echo -e "${PURPLE}${BOLD}═══════════════════════════════════════════════════════${NC}"
    echo -e "${PURPLE}${BOLD}  CC ROI Dashboard - Detailed Status${NC}"
    echo -e "${PURPLE}${BOLD}═══════════════════════════════════════════════════════${NC}"
    echo ""

    # Health check
    echo -e "${CYAN}Health Check:${NC}"
    "$SCRIPT_DIR/cc-action.sh" health 2>/dev/null | grep -E "(✅|⚠|❌|Status)" | head -10
    echo ""

    # Value stats
    echo -e "${CYAN}Value Statistics:${NC}"
    "$SCRIPT_DIR/cc-value.sh" stats 2>/dev/null | tail -20
    echo ""

    # Recent runs
    echo -e "${CYAN}Recent Runs:${NC}"
    "$SCRIPT_DIR/cc-value.sh" list 2>/dev/null | head -12
}

# Morning report
morning_report() {
    echo -e "${PURPLE}${BOLD}☀  Good Morning! Here's your CC status:${NC}"
    echo ""

    local alltime roi_real
    alltime=$(curl -s "$API_BASE/roi/all-time" 2>/dev/null)
    roi_real=$(curl -s "$API_BASE/roi/real" 2>/dev/null)

    if [ -z "$alltime" ]; then
        echo -e "${RED}Server offline. Start with: python3 ~/log-server.py${NC}"
        return 1
    fi

    # Process alltime data
    echo "$alltime" | python3 -c '
import sys, json

GREEN = "\033[0;32m"
CYAN = "\033[0;36m"
NC = "\033[0m"

try:
    d = json.load(sys.stdin)
    profit = d.get("profit_usd", 0)
    roi = d.get("roi_pct", 0)
    runs = d.get("runs_total", 0)
    cost = d.get("cost_usd", 0)
    days = d.get("active_days", 1)

    print(f"{CYAN}All-Time Performance:{NC}")
    print(f"  💰 Profit: {GREEN}${profit:.2f}{NC}")
    print(f"  📈 ROI: {GREEN}+{roi:.0f}%{NC}")
    print(f"  🔢 Runs: {runs} over {days} days")
    print(f"  💸 Total Cost: ${cost:.2f}")
    print()

    daily_profit = profit / days if days > 0 else 0
    daily_runs = runs / days if days > 0 else 0
    print(f"{CYAN}Daily Averages:{NC}")
    print(f"  📊 ${daily_profit:.2f}/day profit")
    print(f"  🔄 {daily_runs:.1f} runs/day")
except Exception as e:
    print(f"Error: {e}")
'

    # Process roi_real data
    echo "$roi_real" | python3 -c '
import sys, json

CYAN = "\033[0;36m"
NC = "\033[0m"

try:
    d = json.load(sys.stdin)
    real = d.get("real", {})
    verified_runs = real.get("runs", 0)
    verified_value = real.get("value_usd", 0)
    time_saved = real.get("time_saved_minutes", 0)

    print()
    print(f"{CYAN}Verified Value:{NC}")
    print(f"  ✅ {verified_runs} runs verified")
    print(f"  💵 ${verified_value:.2f} confirmed value")
    time_value = time_saved * 50 / 60
    print(f"  ⏱  {time_saved} minutes saved (${time_value:.2f} @$50/hr)")
except Exception as e:
    print(f"Error: {e}")
'

    echo ""
    echo -e "${YELLOW}Tip:${NC} Run ${CYAN}cc value${NC} to verify estimated values"
}

# Show help
show_help() {
    echo -e "${PURPLE}${BOLD}CC Dashboard - Command Reference${NC}"
    echo ""
    echo -e "${BOLD}Quick Commands:${NC}"
    echo "  cc                  Quick status overview"
    echo "  cc status           Detailed status report"
    echo "  cc morning          Morning status summary"
    echo ""
    echo -e "${BOLD}Value Management:${NC}"
    echo "  cc value            Interactive value editor"
    echo "  cc value list       List runs with values"
    echo "  cc value stats      Show real vs estimated stats"
    echo "  cc value set ID $   Set verified value for run"
    echo ""
    echo -e "${BOLD}Monitoring:${NC}"
    echo "  cc watch            Full-screen live monitor"
    echo "  cc watch compact    Single-line status"
    echo "  cc watch alerts     Alert-only mode"
    echo ""
    echo -e "${BOLD}Automation:${NC}"
    echo "  cc action backup    Create backup"
    echo "  cc action report    Generate daily report"
    echo "  cc action health    Health check"
    echo "  cc action optimize  Run optimization"
    echo "  cc action review    Code review"
    echo ""
    echo -e "${BOLD}Scheduling:${NC}"
    echo "  cc schedule list    List scheduled jobs"
    echo "  cc schedule setup   Setup recommended schedule"
    echo ""
    echo -e "${BOLD}Services:${NC}"
    echo "  cc server start     Start dashboard server"
    echo "  cc server stop      Stop dashboard server"
    echo "  cc server status    Check server status"
    echo ""
    echo -e "${BOLD}Dashboard:${NC}"
    echo "  cc open             Open dashboard in browser"
    echo ""
    echo -e "${DIM}Dashboard URL: http://localhost:9001/roi${NC}"
}

# Open dashboard
open_dashboard() {
    echo -e "${CYAN}Opening CC ROI Dashboard...${NC}"
    open "http://localhost:9001/roi"
}

# Server control
server_control() {
    local action="${1:-status}"

    case "$action" in
        start)
            if curl -s "$API_BASE/health" >/dev/null 2>&1; then
                echo -e "${YELLOW}Server already running${NC}"
            else
                echo -e "${CYAN}Starting log server...${NC}"
                nohup python3 "$HOME/log-server.py" > /tmp/cc-log-server.log 2>&1 &
                sleep 2
                if curl -s "$API_BASE/health" >/dev/null 2>&1; then
                    echo -e "${GREEN}✓ Server started${NC}"
                else
                    echo -e "${RED}✗ Failed to start server${NC}"
                fi
            fi
            ;;
        stop)
            pkill -f "log-server.py" 2>/dev/null
            echo -e "${GREEN}✓ Server stopped${NC}"
            ;;
        status)
            if curl -s "$API_BASE/health" >/dev/null 2>&1; then
                echo -e "${GREEN}● Server running${NC}"
            else
                echo -e "${RED}○ Server offline${NC}"
            fi
            ;;
        restart)
            server_control stop
            sleep 1
            server_control start
            ;;
        *)
            echo "Usage: cc server [start|stop|status|restart]"
            ;;
    esac
}

# Main
case "${1:-quick}" in
    quick|"")
        quick_status
        ;;
    status|full|detailed)
        detailed_status
        ;;
    morning|am)
        morning_report
        ;;
    value|v)
        shift
        "$SCRIPT_DIR/cc-value.sh" "$@"
        ;;
    watch|w|monitor)
        shift
        "$SCRIPT_DIR/cc-watch.sh" "$@"
        ;;
    action|a|run)
        shift
        "$SCRIPT_DIR/cc-action.sh" "$@"
        ;;
    schedule|sched|cron)
        shift
        "$SCRIPT_DIR/cc-scheduler.sh" "$@"
        ;;
    server|srv)
        shift
        server_control "$@"
        ;;
    open|dashboard|web)
        open_dashboard
        ;;
    report)
        "$SCRIPT_DIR/cc-action.sh" report
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        echo -e "${RED}Unknown command: $1${NC}"
        echo "Run 'cc help' for usage"
        exit 1
        ;;
esac


Now let me read the actual backend servers that power the ROI system:


ls -la /Users/neog/*.py | grep -i "log\|cc\|roi"

Find Python ROI tracking servers in home directory


     1→#!/usr/bin/env python3
     2→"""
     3→CC Live Tracker - Real-time Claude Code Session Monitoring
     4→Monitors ~/.claude/stats-cache.json for changes and sends deltas to the CC ROI API.
     5→"""
     6→
     7→import json
     8→import time
     9→import os
    10→import sys
    11→import requests
    12→from datetime import datetime
    13→from pathlib import Path
    14→
    15→# Try to import watchdog, install if not available
    16→try:
    17→    from watchdog.observers import Observer
    18→    from watchdog.events import FileSystemEventHandler
    19→except ImportError:
    20→    print("Installing watchdog...")
    21→    os.system("pip3 install watchdog")
    22→    from watchdog.observers import Observer
    23→    from watchdog.events import FileSystemEventHandler
    24→
    25→# Configuration
    26→STATS_FILE = os.path.expanduser("~/.claude/stats-cache.json")
    27→API_BASE_URL = "http://localhost:9001"
    28→POLL_INTERVAL = 1  # seconds
    29→
    30→# Token pricing (USD per 1M tokens) - Opus 4.5
    31→PRICING = {
    32→    "claude-opus-4-5-20251101": {
    33→        "input": 15.00,
    34→        "output": 75.00,
    35→        "cacheRead": 1.875,
    36→        "cacheCreation": 18.75
    37→    },
    38→    "claude-sonnet-4-5-20250929": {
    39→        "input": 3.00,
    40→        "output": 15.00,
    41→        "cacheRead": 0.30,
    42→        "cacheCreation": 3.75
    43→    }
    44→}
    45→
    46→class SessionTracker:
    47→    """Tracks session statistics and calculates costs."""
    48→
    49→    def __init__(self):
    50→        self.session_start = datetime.now()
    51→        self.last_stats = None
    52→        self.session_id = f"live-{int(time.time())}"
    53→        self.cumulative_cost = 0.0
    54→        self.cumulative_tokens = {
    55→            "input": 0,
    56→            "output": 0,
    57→            "cacheRead": 0,
    58→            "cacheCreation": 0
    59→        }
    60→
    61→    def load_stats(self) -> dict:
    62→        """Load current stats from file."""
    63→        try:
    64→            with open(STATS_FILE, 'r') as f:
    65→                return json.load(f)
    66→        except Exception as e:
    67→            print(f"[ERROR] Failed to load stats: {e}")
    68→            return None
    69→
    70→    def calculate_cost(self, tokens: dict, model: str) -> float:
    71→        """Calculate cost for given tokens and model."""
    72→        if model not in PRICING:
    73→            return 0.0
    74→
    75→        prices = PRICING[model]
    76→        cost = 0.0
    77→
    78→        for token_type, count in tokens.items():
    79→            if token_type in prices and count > 0:
    80→                cost += (count / 1_000_000) * prices[token_type]
    81→
    82→        return cost
    83→
    84→    def calculate_deltas(self, current_stats: dict) -> dict:
    85→        """Calculate token deltas from last known state."""
    86→        if not self.last_stats or not current_stats:
    87→            return None
    88→
    89→        deltas = {"models": {}, "total_cost": 0.0, "total_tokens": {}}
    90→
    91→        current_usage = current_stats.get("modelUsage", {})
    92→        last_usage = self.last_stats.get("modelUsage", {})
    93→
    94→        total_input_delta = 0
    95→        total_output_delta = 0
    96→        total_cache_read_delta = 0
    97→        total_cache_creation_delta = 0
    98→
    99→        for model, current in current_usage.items():
   100→            last = last_usage.get(model, {})
   101→
   102→            input_delta = current.get("inputTokens", 0) - last.get("inputTokens", 0)
   103→            output_delta = current.get("outputTokens", 0) - last.get("outputTokens", 0)
   104→            cache_read_delta = current.get("cacheReadInputTokens", 0) - last.get("cacheReadInputTokens", 0)
   105→            cache_creation_delta = current.get("cacheCreationInputTokens", 0) - last.get("cacheCreationInputTokens", 0)
   106→
   107→            # Only process if there are actual changes
   108→            if any([input_delta, output_delta, cache_read_delta, cache_creation_delta]):
   109→                tokens = {
   110→                    "input": max(0, input_delta),
   111→                    "output": max(0, output_delta),
   112→                    "cacheRead": max(0, cache_read_delta),
   113→                    "cacheCreation": max(0, cache_creation_delta)
   114→                }
   115→
   116→                cost = self.calculate_cost(tokens, model)
   117→
   118→                deltas["models"][model] = {
   119→                    "tokens": tokens,
   120→                    "cost": cost
   121→                }
   122→
   123→                total_input_delta += tokens["input"]
   124→                total_output_delta += tokens["output"]
   125→                total_cache_read_delta += tokens["cacheRead"]
   126→                total_cache_creation_delta += tokens["cacheCreation"]
   127→                deltas["total_cost"] += cost
   128→
   129→        deltas["total_tokens"] = {
   130→            "input": total_input_delta,
   131→            "output": total_output_delta,
   132→            "cacheRead": total_cache_read_delta,
   133→            "cacheCreation": total_cache_creation_delta
   134→        }
   135→
   136→        return deltas if deltas["models"] else None
   137→
   138→    def send_update(self, deltas: dict):
   139→        """Send update to the CC ROI API."""
   140→        if not deltas:
   141→            return
   142→
   143→        # Update cumulative totals
   144→        self.cumulative_cost += deltas["total_cost"]
   145→        for key, value in deltas["total_tokens"].items():
   146→            self.cumulative_tokens[key] += value
   147→
   148→        payload = {
   149→            "session_id": self.session_id,
   150→            "timestamp": datetime.now().isoformat(),
   151→            "deltas": deltas,
   152→            "cumulative": {
   153→                "cost": self.cumulative_cost,
   154→                "tokens": self.cumulative_tokens,
   155→                "duration_seconds": (datetime.now() - self.session_start).total_seconds()
   156→            }
   157→        }
   158→
   159→        try:
   160→            response = requests.post(
   161→                f"{API_BASE_URL}/api/cc/session/update",
   162→                json=payload,
   163→                timeout=5
   164→            )
   165→            if response.status_code == 200:
   166→                print(f"[{datetime.now().strftime('%H:%M:%S')}] "
   167→                      f"Update sent: +${deltas['total_cost']:.4f} "
   168→                      f"(Total: ${self.cumulative_cost:.4f})")
   169→            else:
   170→                print(f"[WARN] API returned {response.status_code}")
   171→        except requests.exceptions.ConnectionError:
   172→            # API not available, just log locally
   173→            print(f"[{datetime.now().strftime('%H:%M:%S')}] "
   174→                  f"[LOCAL] +${deltas['total_cost']:.4f} "
   175→                  f"(Total: ${self.cumulative_cost:.4f}) "
   176→                  f"- In:{deltas['total_tokens']['input']:,} "
   177→                  f"Out:{deltas['total_tokens']['output']:,}")
   178→        except Exception as e:
   179→            print(f"[ERROR] Failed to send update: {e}")
   180→
   181→    def process_change(self):
   182→        """Process a change in the stats file."""
   183→        current_stats = self.load_stats()
   184→        if not current_stats:
   185→            return
   186→
   187→        if self.last_stats:
   188→            deltas = self.calculate_deltas(current_stats)
   189→            if deltas:
   190→                self.send_update(deltas)
   191→        else:
   192→            print(f"[{datetime.now().strftime('%H:%M:%S')}] Initial stats loaded")
   193→
   194→        self.last_stats = current_stats
   195→
   196→
   197→class StatsFileHandler(FileSystemEventHandler):
   198→    """Handles file system events for the stats file."""
   199→
   200→    def __init__(self, tracker: SessionTracker):
   201→        self.tracker = tracker
   202→        self.last_modified = 0
   203→
   204→    def on_modified(self, event):
   205→        if event.src_path == STATS_FILE:
   206→            # Debounce rapid changes
   207→            current_time = time.time()
   208→            if current_time - self.last_modified > 0.5:
   209→                self.last_modified = current_time
   210→                self.tracker.process_change()
   211→
   212→
   213→def print_banner():
   214→    """Print startup banner."""
   215→    print("""
   216→╔══════════════════════════════════════════════════════════════╗
   217→║        CC Live Tracker - Real-time Cost Monitoring           ║
   218→╠══════════════════════════════════════════════════════════════╣
   219→║  Monitoring: ~/.claude/stats-cache.json                      ║
   220→║  API: http://localhost:9001                                  ║
   221→║                                                              ║
   222→║  Pricing (per 1M tokens):                                    ║
   223→║  • Opus 4.5: $15 input, $75 output, $1.875 cache read       ║
   224→║  • Sonnet 4.5: $3 input, $15 output, $0.30 cache read       ║
   225→╚══════════════════════════════════════════════════════════════╝
   226→""")
   227→
   228→
   229→def main():
   230→    print_banner()
   231→
   232→    # Check if stats file exists
   233→    if not os.path.exists(STATS_FILE):
   234→        print(f"[ERROR] Stats file not found: {STATS_FILE}")
   235→        print("Make sure Claude Code CLI is installed and has been used at least once.")
   236→        sys.exit(1)
   237→
   238→    tracker = SessionTracker()
   239→    handler = StatsFileHandler(tracker)
   240→
   241→    # Load initial stats
   242→    tracker.process_change()
   243→
   244→    # Set up file watcher
   245→    observer = Observer()
   246→    observer.schedule(handler, path=os.path.dirname(STATS_FILE), recursive=False)
   247→    observer.start()
   248→
   249→    print(f"\n[{datetime.now().strftime('%H:%M:%S')}] Watching for changes... (Ctrl+C to stop)\n")
   250→
   251→    try:
   252→        while True:
   253→            time.sleep(POLL_INTERVAL)
   254→    except KeyboardInterrupt:
   255→        observer.stop()
   256→        print(f"\n\n[Session Summary]")
   257→        print(f"Duration: {(datetime.now() - tracker.session_start).total_seconds():.0f} seconds")
   258→        print(f"Total Cost: ${tracker.cumulative_cost:.4f}")
   259→        print(f"Tokens - Input: {tracker.cumulative_tokens['input']:,}, "
   260→              f"Output: {tracker.cumulative_tokens['output']:,}")
   261→
   262→    observer.join()
   263→
   264→
   265→if __name__ == "__main__":
   266→    main()
   267→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

#!/usr/bin/env python3
"""
CC Live Tracker - Real-time Claude Code Session Monitoring
Monitors ~/.claude/stats-cache.json for changes and sends deltas to the CC ROI API.
"""

import json
import time
import os
import sys
import requests
from datetime import datetime
from pathlib import Path

# Try to import watchdog, install if not available
try:
    from watchdog.observers import Observer
    from watchdog.events import FileSystemEventHandler
except ImportError:
    print("Installing watchdog...")
    os.system("pip3 install watchdog")
    from watchdog.observers import Observer
    from watchdog.events import FileSystemEventHandler

# Configuration
STATS_FILE = os.path.expanduser("~/.claude/stats-cache.json")
API_BASE_URL = "http://localhost:9001"
POLL_INTERVAL = 1  # seconds

# Token pricing (USD per 1M tokens) - Opus 4.5
PRICING = {
    "claude-opus-4-5-20251101": {
        "input": 15.00,
        "output": 75.00,
        "cacheRead": 1.875,
        "cacheCreation": 18.75
    },
    "claude-sonnet-4-5-20250929": {
        "input": 3.00,
        "output": 15.00,
        "cacheRead": 0.30,
        "cacheCreation": 3.75
    }
}

class SessionTracker:
    """Tracks session statistics and calculates costs."""

    def __init__(self):
        self.session_start = datetime.now()
        self.last_stats = None
        self.session_id = f"live-{int(time.time())}"
        self.cumulative_cost = 0.0
        self.cumulative_tokens = {
            "input": 0,
            "output": 0,
            "cacheRead": 0,
            "cacheCreation": 0
        }

    def load_stats(self) -> dict:
        """Load current stats from file."""
        try:
            with open(STATS_FILE, 'r') as f:
                return json.load(f)
        except Exception as e:
            print(f"[ERROR] Failed to load stats: {e}")
            return None

    def calculate_cost(self, tokens: dict, model: str) -> float:
        """Calculate cost for given tokens and model."""
        if model not in PRICING:
            return 0.0

        prices = PRICING[model]
        cost = 0.0

        for token_type, count in tokens.items():
            if token_type in prices and count > 0:
                cost += (count / 1_000_000) * prices[token_type]

        return cost

    def calculate_deltas(self, current_stats: dict) -> dict:
        """Calculate token deltas from last known state."""
        if not self.last_stats or not current_stats:
            return None

        deltas = {"models": {}, "total_cost": 0.0, "total_tokens": {}}

        current_usage = current_stats.get("modelUsage", {})
        last_usage = self.last_stats.get("modelUsage", {})

        total_input_delta = 0
        total_output_delta = 0
        total_cache_read_delta = 0
        total_cache_creation_delta = 0

        for model, current in current_usage.items():
            last = last_usage.get(model, {})

            input_delta = current.get("inputTokens", 0) - last.get("inputTokens", 0)
            output_delta = current.get("outputTokens", 0) - last.get("outputTokens", 0)
            cache_read_delta = current.get("cacheReadInputTokens", 0) - last.get("cacheReadInputTokens", 0)
            cache_creation_delta = current.get("cacheCreationInputTokens", 0) - last.get("cacheCreationInputTokens", 0)

            # Only process if there are actual changes
            if any([input_delta, output_delta, cache_read_delta, cache_creation_delta]):
                tokens = {
                    "input": max(0, input_delta),
                    "output": max(0, output_delta),
                    "cacheRead": max(0, cache_read_delta),
                    "cacheCreation": max(0, cache_creation_delta)
                }

                cost = self.calculate_cost(tokens, model)

                deltas["models"][model] = {
                    "tokens": tokens,
                    "cost": cost
                }

                total_input_delta += tokens["input"]
                total_output_delta += tokens["output"]
                total_cache_read_delta += tokens["cacheRead"]
                total_cache_creation_delta += tokens["cacheCreation"]
                deltas["total_cost"] += cost

        deltas["total_tokens"] = {
            "input": total_input_delta,
            "output": total_output_delta,
            "cacheRead": total_cache_read_delta,
            "cacheCreation": total_cache_creation_delta
        }

        return deltas if deltas["models"] else None

    def send_update(self, deltas: dict):
        """Send update to the CC ROI API."""
        if not deltas:
            return

        # Update cumulative totals
        self.cumulative_cost += deltas["total_cost"]
        for key, value in deltas["total_tokens"].items():
            self.cumulative_tokens[key] += value

        payload = {
            "session_id": self.session_id,
            "timestamp": datetime.now().isoformat(),
            "deltas": deltas,
            "cumulative": {
                "cost": self.cumulative_cost,
                "tokens": self.cumulative_tokens,
                "duration_seconds": (datetime.now() - self.session_start).total_seconds()
            }
        }

        try:
            response = requests.post(
                f"{API_BASE_URL}/api/cc/session/update",
                json=payload,
                timeout=5
            )
            if response.status_code == 200:
                print(f"[{datetime.now().strftime('%H:%M:%S')}] "
                      f"Update sent: +${deltas['total_cost']:.4f} "
                      f"(Total: ${self.cumulative_cost:.4f})")
            else:
                print(f"[WARN] API returned {response.status_code}")
        except requests.exceptions.ConnectionError:
            # API not available, just log locally
            print(f"[{datetime.now().strftime('%H:%M:%S')}] "
                  f"[LOCAL] +${deltas['total_cost']:.4f} "
                  f"(Total: ${self.cumulative_cost:.4f}) "
                  f"- In:{deltas['total_tokens']['input']:,} "
                  f"Out:{deltas['total_tokens']['output']:,}")
        except Exception as e:
            print(f"[ERROR] Failed to send update: {e}")

    def process_change(self):
        """Process a change in the stats file."""
        current_stats = self.load_stats()
        if not current_stats:
            return

        if self.last_stats:
            deltas = self.calculate_deltas(current_stats)
            if deltas:
                self.send_update(deltas)
        else:
            print(f"[{datetime.now().strftime('%H:%M:%S')}] Initial stats loaded")

        self.last_stats = current_stats

class StatsFileHandler(FileSystemEventHandler):
    """Handles file system events for the stats file."""

    def __init__(self, tracker: SessionTracker):
        self.tracker = tracker
        self.last_modified = 0

    def on_modified(self, event):
        if event.src_path == STATS_FILE:
            # Debounce rapid changes
            current_time = time.time()
            if current_time - self.last_modified > 0.5:
                self.last_modified = current_time
                self.tracker.process_change()

def print_banner():
    """Print startup banner."""
    print("""
╔══════════════════════════════════════════════════════════════╗
║        CC Live Tracker - Real-time Cost Monitoring           ║
╠══════════════════════════════════════════════════════════════╣
║  Monitoring: ~/.claude/stats-cache.json                      ║
║  API: http://localhost:9001                                  ║
║                                                              ║
║  Pricing (per 1M tokens):                                    ║
║  • Opus 4.5: $15 input, $75 output, $1.875 cache read       ║
║  • Sonnet 4.5: $3 input, $15 output, $0.30 cache read       ║
╚══════════════════════════════════════════════════════════════╝
""")

def main():
    print_banner()

    # Check if stats file exists
    if not os.path.exists(STATS_FILE):
        print(f"[ERROR] Stats file not found: {STATS_FILE}")
        print("Make sure Claude Code CLI is installed and has been used at least once.")
        sys.exit(1)

    tracker = SessionTracker()
    handler = StatsFileHandler(tracker)

    # Load initial stats
    tracker.process_change()

    # Set up file watcher
    observer = Observer()
    observer.schedule(handler, path=os.path.dirname(STATS_FILE), recursive=False)
    observer.start()

    print(f"\n[{datetime.now().strftime('%H:%M:%S')}] Watching for changes... (Ctrl+C to stop)\n")

    try:
        while True:
            time.sleep(POLL_INTERVAL)
    except KeyboardInterrupt:
        observer.stop()
        print(f"\n\n[Session Summary]")
        print(f"Duration: {(datetime.now() - tracker.session_start).total_seconds():.0f} seconds")
        print(f"Total Cost: ${tracker.cumulative_cost:.4f}")
        print(f"Tokens - Input: {tracker.cumulative_tokens['input']:,}, "
              f"Output: {tracker.cumulative_tokens['output']:,}")

    observer.join()

if __name__ == "__main__":
    main()


Error: File content (32645 tokens) exceeds maximum allowed tokens (25000). Please use offset and limit parameters to read specific portions of the file, or use the GrepTool to search for specific content.


lrwxr-xr-x@ 1 neog  staff  44 Dec 25 04:48 /Users/neog/log-server.py -> /Users/neog/Services/servers/neog-gateway.py


Let me check the actual log-server implementation: