     1→#!/bin/bash
     2→# cc-value.sh - Quick value update tool for CC ROI Dashboard
     3→#
     4→# Usage:
     5→#   ./cc-value.sh                    # Interactive: list recent runs and update
     6→#   ./cc-value.sh list               # List recent runs with values
     7→#   ./cc-value.sh set <run_id> <value> [time_saved]  # Set value for run
     8→#   ./cc-value.sh bulk <value> [time_saved]          # Set value for all estimated runs
     9→#   ./cc-value.sh stats              # Show real vs estimated stats
    10→#   ./cc-value.sh clear              # Clear all estimates (set to $0)
    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→PURPLE='\033[0;35m'
    19→BOLD='\033[1m'
    20→DIM='\033[2m'
    21→NC='\033[0m'
    22→
    23→# List recent runs
    24→list_runs() {
    25→    echo -e "${PURPLE}${BOLD}Recent Runs${NC}"
    26→    echo ""
    27→
    28→    # Fetch data and process with python
    29→    local data
    30→    data=$(curl -s "http://localhost:9001/api/cc/runs?limit=20" 2>/dev/null)
    31→
    32→    if [ -z "$data" ]; then
    33→        echo -e "${RED}  Server not responding${NC}"
    34→        return 1
    35→    fi
    36→
    37→    echo "$data" | python3 -c '
    38→import sys, json
    39→try:
    40→    runs = json.load(sys.stdin)
    41→    hdr = "{:<8} {:<12} {:<10} {:<10} {}".format("ID", "Value", "Cost", "Source", "Prompt")
    42→    print(hdr)
    43→    print("-" * 80)
    44→    for r in runs:
    45→        run_id = r.get("run_id", "")[:8]
    46→        value = r.get("value_generated_usd", 0) or 0
    47→        is_est = r.get("value_is_estimated", 1)
    48→        cost = r.get("cost_usd", 0) or 0
    49→        source = r.get("source", "?")[:10]
    50→        prompt = r.get("prompt", "")
    51→        prompt = (prompt[:35] + "...") if len(prompt) > 35 else prompt
    52→        marker = "~" if is_est else "✓"
    53→        color = "\033[1;33m" if is_est else "\033[0;32m"
    54→        nc = "\033[0m"
    55→        print("{:<8} {}${:<7.2f}{}{:<3} ${:<9.4f} {:<10} {}".format(
    56→            run_id, color, value, marker, nc, cost, source, prompt))
    57→except Exception as e:
    58→    print("Error: " + str(e))
    59→'
    60→    echo ""
    61→    echo -e "${DIM}~ = estimated, ✓ = verified${NC}"
    62→}
    63→
    64→# Set value for a run
    65→set_value() {
    66→    local run_id="$1"
    67→    local value="$2"
    68→    local time_saved="${3:-0}"
    69→
    70→    if [ -z "$run_id" ] || [ -z "$value" ]; then
    71→        echo -e "${RED}Usage: ./cc-value.sh set <run_id> <value> [time_saved_minutes]${NC}"
    72→        exit 1
    73→    fi
    74→
    75→    # Find full run_id if partial
    76→    if [ ${#run_id} -lt 36 ]; then
    77→        full_id=$(curl -s "$API_BASE/runs?limit=50" 2>/dev/null | python3 -c "
    78→import sys, json
    79→runs = json.load(sys.stdin)
    80→for r in runs:
    81→    if r.get('run_id', '').startswith('$run_id'):
    82→        print(r['run_id'])
    83→        break
    84→" 2>/dev/null)
    85→        if [ -n "$full_id" ]; then
    86→            run_id="$full_id"
    87→        fi
    88→    fi
    89→
    90→    result=$(curl -s -X POST "$API_BASE/run/$run_id/value" \
    91→        -H "Content-Type: application/json" \
    92→        -d "{\"value_usd\": $value, \"time_saved_minutes\": $time_saved}" 2>/dev/null)
    93→
    94→    status=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status','error'))" 2>/dev/null)
    95→
    96→    if [ "$status" = "ok" ]; then
    97→        echo -e "${GREEN}✓ Updated: \$$value (${time_saved}min saved)${NC}"
    98→    else
    99→        echo -e "${RED}✗ Failed to update${NC}"
   100→        echo "$result"
   101→    fi
   102→}
   103→
   104→# Bulk update all estimated runs
   105→bulk_update() {
   106→    local value="$1"
   107→    local time_saved="${2:-0}"
   108→
   109→    if [ -z "$value" ]; then
   110→        echo -e "${RED}Usage: ./cc-value.sh bulk <value> [time_saved_minutes]${NC}"
   111→        exit 1
   112→    fi
   113→
   114→    echo -e "${YELLOW}This will set ALL estimated runs to \$$value...${NC}"
   115→    read -p "Continue? (y/N) " confirm
   116→
   117→    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
   118→        echo "Cancelled."
   119→        exit 0
   120→    fi
   121→
   122→    # Get all estimated runs
   123→    run_ids=$(curl -s "$API_BASE/runs?limit=100" 2>/dev/null | python3 -c "
   124→import sys, json
   125→runs = json.load(sys.stdin)
   126→for r in runs:
   127→    if r.get('value_is_estimated', 1):
   128→        print(r['run_id'])
   129→" 2>/dev/null)
   130→
   131→    count=0
   132→    for run_id in $run_ids; do
   133→        result=$(curl -s -X POST "$API_BASE/run/$run_id/value" \
   134→            -H "Content-Type: application/json" \
   135→            -d "{\"value_usd\": $value, \"time_saved_minutes\": $time_saved}" 2>/dev/null)
   136→        status=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status','error'))" 2>/dev/null)
   137→        if [ "$status" = "ok" ]; then
   138→            ((count++))
   139→            echo -ne "\r  Updated $count runs..."
   140→        fi
   141→    done
   142→
   143→    echo ""
   144→    echo -e "${GREEN}✓ Updated $count runs to \$$value each${NC}"
   145→}
   146→
   147→# Show stats
   148→show_stats() {
   149→    echo -e "${PURPLE}${BOLD}Value Statistics${NC}"
   150→    echo ""
   151→
   152→    local data
   153→    data=$(curl -s "$API_BASE/roi/real" 2>/dev/null)
   154→
   155→    if [ -z "$data" ]; then
   156→        echo -e "${RED}  Server not responding${NC}"
   157→        return 1
   158→    fi
   159→
   160→    echo "$data" | python3 -c '
   161→import sys, json
   162→GREEN = "\033[0;32m"
   163→YELLOW = "\033[1;33m"
   164→CYAN = "\033[0;36m"
   165→NC = "\033[0m"
   166→
   167→try:
   168→    d = json.load(sys.stdin)
   169→    real = d.get("real", {})
   170→    est = d.get("estimated", {})
   171→    total = d.get("total", {})
   172→
   173→    runs_r = real.get("runs", 0)
   174→    value_r = real.get("value_usd", 0)
   175→    time_r = real.get("time_saved_minutes", 0)
   176→    time_val_r = real.get("time_value_usd", 0)
   177→    roi_r = real.get("roi_pct", 0)
   178→
   179→    runs_e = est.get("runs", 0)
   180→    value_e = est.get("value_usd", 0)
   181→    roi_e = est.get("roi_pct", 0)
   182→
   183→    runs_t = total.get("runs", 0)
   184→    cost_t = total.get("cost_usd", 0)
   185→    value_t = total.get("value_usd", 0)
   186→    verified_t = total.get("real_pct", 0)
   187→
   188→    print(f"{GREEN}Verified (Real):{NC}")
   189→    print(f"  Runs:       {runs_r}")
   190→    print(f"  Value:      ${value_r:.2f}")
   191→    print(f"  Time Saved: {time_r} min (= ${time_val_r:.2f})")
   192→    print(f"  ROI:        {roi_r:.0f}%")
   193→    print()
   194→    print(f"{YELLOW}Estimated:{NC}")
   195→    print(f"  Runs:       {runs_e}")
   196→    print(f"  Value:      ${value_e:.2f}")
   197→    print(f"  ROI:        {roi_e:.0f}%")
   198→    print()
   199→    print(f"{CYAN}Total:{NC}")
   200→    print(f"  Runs:       {runs_t}")
   201→    print(f"  Cost:       ${cost_t:.4f}")
   202→    print(f"  Value:      ${value_t:.2f}")
   203→    print(f"  Verified:   {verified_t:.0f}%")
   204→except Exception as e:
   205→    print(f"Error: {e}")
   206→'
   207→}
   208→
   209→# Clear all estimates
   210→clear_estimates() {
   211→    echo -e "${YELLOW}This will set ALL estimated values to \$0...${NC}"
   212→    read -p "Continue? (y/N) " confirm
   213→
   214→    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
   215→        echo "Cancelled."
   216→        exit 0
   217→    fi
   218→
   219→    result=$(curl -s -X POST "$API_BASE/runs/clear-estimates" \
   220→        -H "Content-Type: application/json" -d '{}' 2>/dev/null)
   221→
   222→    updated=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('updated',0))" 2>/dev/null)
   223→
   224→    echo -e "${GREEN}✓ Cleared $updated estimated values${NC}"
   225→}
   226→
   227→# Interactive mode
   228→interactive_mode() {
   229→    echo -e "${PURPLE}${BOLD}CC Value Editor${NC}"
   230→    echo ""
   231→
   232→    list_runs
   233→
   234→    echo ""
   235→    echo -e "Enter run ID (first 8 chars) to update, or:"
   236→    echo -e "  ${CYAN}s${NC} - Show stats"
   237→    echo -e "  ${CYAN}b${NC} - Bulk update"
   238→    echo -e "  ${CYAN}c${NC} - Clear estimates"
   239→    echo -e "  ${CYAN}q${NC} - Quit"
   240→    echo ""
   241→
   242→    while true; do
   243→        read -p "$(echo -e ${CYAN}Enter run ID or command: ${NC})" input
   244→
   245→        case "$input" in
   246→            s|stats) show_stats ;;
   247→            b|bulk)
   248→                read -p "Value per run: \$" value
   249→                read -p "Time saved (min): " time
   250→                bulk_update "$value" "$time"
   251→                ;;
   252→            c|clear) clear_estimates ;;
   253→            q|quit|exit) exit 0 ;;
   254→            "")
   255→                continue
   256→                ;;
   257→            *)
   258→                # Assume it's a run ID
   259→                read -p "Value for this run: \$" value
   260→                read -p "Time saved (min): " time
   261→                set_value "$input" "$value" "$time"
   262→                ;;
   263→        esac
   264→        echo ""
   265→    done
   266→}
   267→
   268→# Main
   269→case "${1:-interactive}" in
   270→    list|ls)
   271→        list_runs
   272→        ;;
   273→    set)
   274→        set_value "$2" "$3" "$4"
   275→        ;;
   276→    bulk)
   277→        bulk_update "$2" "$3"
   278→        ;;
   279→    stats)
   280→        show_stats
   281→        ;;
   282→    clear)
   283→        clear_estimates
   284→        ;;
   285→    interactive|i)
   286→        interactive_mode
   287→        ;;
   288→    help|--help|-h)
   289→        echo "Usage: ./cc-value.sh [command]"
   290→        echo ""
   291→        echo "Commands:"
   292→        echo "  list                           List recent runs with values"
   293→        echo "  set <run_id> <value> [time]    Set value for specific run"
   294→        echo "  bulk <value> [time]            Set value for all estimated runs"
   295→        echo "  stats                          Show real vs estimated stats"
   296→        echo "  clear                          Clear all estimates (set to \$0)"
   297→        echo "  interactive                    Interactive mode (default)"
   298→        echo ""
   299→        echo "Examples:"
   300→        echo "  ./cc-value.sh set abc123 25.00 30    # Set run abc123... to \$25, 30min saved"
   301→        echo "  ./cc-value.sh bulk 5.00 10           # Set all estimated to \$5, 10min each"
   302→        echo "  ./cc-value.sh stats                  # Show verification stats"
   303→        ;;
   304→    *)
   305→        echo -e "${RED}Unknown command: $1${NC}"
   306→        echo "Run './cc-value.sh help' for usage"
   307→        exit 1
   308→        ;;
   309→esac
   310→

<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-value.sh - Quick value update tool for CC ROI Dashboard
#
# Usage:
#   ./cc-value.sh                    # Interactive: list recent runs and update
#   ./cc-value.sh list               # List recent runs with values
#   ./cc-value.sh set <run_id> <value> [time_saved]  # Set value for run
#   ./cc-value.sh bulk <value> [time_saved]          # Set value for all estimated runs
#   ./cc-value.sh stats              # Show real vs estimated stats
#   ./cc-value.sh clear              # Clear all estimates (set to $0)

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'

# List recent runs
list_runs() {
    echo -e "${PURPLE}${BOLD}Recent Runs${NC}"
    echo ""

    # Fetch data and process with python
    local data
    data=$(curl -s "http://localhost:9001/api/cc/runs?limit=20" 2>/dev/null)

    if [ -z "$data" ]; then
        echo -e "${RED}  Server not responding${NC}"
        return 1
    fi

    echo "$data" | python3 -c '
import sys, json
try:
    runs = json.load(sys.stdin)
    hdr = "{:<8} {:<12} {:<10} {:<10} {}".format("ID", "Value", "Cost", "Source", "Prompt")
    print(hdr)
    print("-" * 80)
    for r in runs:
        run_id = r.get("run_id", "")[:8]
        value = r.get("value_generated_usd", 0) or 0
        is_est = r.get("value_is_estimated", 1)
        cost = r.get("cost_usd", 0) or 0
        source = r.get("source", "?")[:10]
        prompt = r.get("prompt", "")
        prompt = (prompt[:35] + "...") if len(prompt) > 35 else prompt
        marker = "~" if is_est else "✓"
        color = "\033[1;33m" if is_est else "\033[0;32m"
        nc = "\033[0m"
        print("{:<8} {}${:<7.2f}{}{:<3} ${:<9.4f} {:<10} {}".format(
            run_id, color, value, marker, nc, cost, source, prompt))
except Exception as e:
    print("Error: " + str(e))
'
    echo ""
    echo -e "${DIM}~ = estimated, ✓ = verified${NC}"
}

# Set value for a run
set_value() {
    local run_id="$1"
    local value="$2"
    local time_saved="${3:-0}"

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

    # Find full run_id if partial
    if [ ${#run_id} -lt 36 ]; then
        full_id=$(curl -s "$API_BASE/runs?limit=50" 2>/dev/null | python3 -c "
import sys, json
runs = json.load(sys.stdin)
for r in runs:
    if r.get('run_id', '').startswith('$run_id'):
        print(r['run_id'])
        break
" 2>/dev/null)
        if [ -n "$full_id" ]; then
            run_id="$full_id"
        fi
    fi

    result=$(curl -s -X POST "$API_BASE/run/$run_id/value" \
        -H "Content-Type: application/json" \
        -d "{\"value_usd\": $value, \"time_saved_minutes\": $time_saved}" 2>/dev/null)

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

    if [ "$status" = "ok" ]; then
        echo -e "${GREEN}✓ Updated: \$$value (${time_saved}min saved)${NC}"
    else
        echo -e "${RED}✗ Failed to update${NC}"
        echo "$result"
    fi
}

# Bulk update all estimated runs
bulk_update() {
    local value="$1"
    local time_saved="${2:-0}"

    if [ -z "$value" ]; then
        echo -e "${RED}Usage: ./cc-value.sh bulk <value> [time_saved_minutes]${NC}"
        exit 1
    fi

    echo -e "${YELLOW}This will set ALL estimated runs to \$$value...${NC}"
    read -p "Continue? (y/N) " confirm

    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        echo "Cancelled."
        exit 0
    fi

    # Get all estimated runs
    run_ids=$(curl -s "$API_BASE/runs?limit=100" 2>/dev/null | python3 -c "
import sys, json
runs = json.load(sys.stdin)
for r in runs:
    if r.get('value_is_estimated', 1):
        print(r['run_id'])
" 2>/dev/null)

    count=0
    for run_id in $run_ids; do
        result=$(curl -s -X POST "$API_BASE/run/$run_id/value" \
            -H "Content-Type: application/json" \
            -d "{\"value_usd\": $value, \"time_saved_minutes\": $time_saved}" 2>/dev/null)
        status=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status','error'))" 2>/dev/null)
        if [ "$status" = "ok" ]; then
            ((count++))
            echo -ne "\r  Updated $count runs..."
        fi
    done

    echo ""
    echo -e "${GREEN}✓ Updated $count runs to \$$value each${NC}"
}

# Show stats
show_stats() {
    echo -e "${PURPLE}${BOLD}Value Statistics${NC}"
    echo ""

    local data
    data=$(curl -s "$API_BASE/roi/real" 2>/dev/null)

    if [ -z "$data" ]; then
        echo -e "${RED}  Server not responding${NC}"
        return 1
    fi

    echo "$data" | python3 -c '
import sys, json
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
CYAN = "\033[0;36m"
NC = "\033[0m"

try:
    d = json.load(sys.stdin)
    real = d.get("real", {})
    est = d.get("estimated", {})
    total = d.get("total", {})

    runs_r = real.get("runs", 0)
    value_r = real.get("value_usd", 0)
    time_r = real.get("time_saved_minutes", 0)
    time_val_r = real.get("time_value_usd", 0)
    roi_r = real.get("roi_pct", 0)

    runs_e = est.get("runs", 0)
    value_e = est.get("value_usd", 0)
    roi_e = est.get("roi_pct", 0)

    runs_t = total.get("runs", 0)
    cost_t = total.get("cost_usd", 0)
    value_t = total.get("value_usd", 0)
    verified_t = total.get("real_pct", 0)

    print(f"{GREEN}Verified (Real):{NC}")
    print(f"  Runs:       {runs_r}")
    print(f"  Value:      ${value_r:.2f}")
    print(f"  Time Saved: {time_r} min (= ${time_val_r:.2f})")
    print(f"  ROI:        {roi_r:.0f}%")
    print()
    print(f"{YELLOW}Estimated:{NC}")
    print(f"  Runs:       {runs_e}")
    print(f"  Value:      ${value_e:.2f}")
    print(f"  ROI:        {roi_e:.0f}%")
    print()
    print(f"{CYAN}Total:{NC}")
    print(f"  Runs:       {runs_t}")
    print(f"  Cost:       ${cost_t:.4f}")
    print(f"  Value:      ${value_t:.2f}")
    print(f"  Verified:   {verified_t:.0f}%")
except Exception as e:
    print(f"Error: {e}")
'
}

# Clear all estimates
clear_estimates() {
    echo -e "${YELLOW}This will set ALL estimated values to \$0...${NC}"
    read -p "Continue? (y/N) " confirm

    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        echo "Cancelled."
        exit 0
    fi

    result=$(curl -s -X POST "$API_BASE/runs/clear-estimates" \
        -H "Content-Type: application/json" -d '{}' 2>/dev/null)

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

    echo -e "${GREEN}✓ Cleared $updated estimated values${NC}"
}

# Interactive mode
interactive_mode() {
    echo -e "${PURPLE}${BOLD}CC Value Editor${NC}"
    echo ""

    list_runs

    echo ""
    echo -e "Enter run ID (first 8 chars) to update, or:"
    echo -e "  ${CYAN}s${NC} - Show stats"
    echo -e "  ${CYAN}b${NC} - Bulk update"
    echo -e "  ${CYAN}c${NC} - Clear estimates"
    echo -e "  ${CYAN}q${NC} - Quit"
    echo ""

    while true; do
        read -p "$(echo -e ${CYAN}Enter run ID or command: ${NC})" input

        case "$input" in
            s|stats) show_stats ;;
            b|bulk)
                read -p "Value per run: \$" value
                read -p "Time saved (min): " time
                bulk_update "$value" "$time"
                ;;
            c|clear) clear_estimates ;;
            q|quit|exit) exit 0 ;;
            "")
                continue
                ;;
            *)
                # Assume it's a run ID
                read -p "Value for this run: \$" value
                read -p "Time saved (min): " time
                set_value "$input" "$value" "$time"
                ;;
        esac
        echo ""
    done
}

# Main
case "${1:-interactive}" in
    list|ls)
        list_runs
        ;;
    set)
        set_value "$2" "$3" "$4"
        ;;
    bulk)
        bulk_update "$2" "$3"
        ;;
    stats)
        show_stats
        ;;
    clear)
        clear_estimates
        ;;
    interactive|i)
        interactive_mode
        ;;
    help|--help|-h)
        echo "Usage: ./cc-value.sh [command]"
        echo ""
        echo "Commands:"
        echo "  list                           List recent runs with values"
        echo "  set <run_id> <value> [time]    Set value for specific run"
        echo "  bulk <value> [time]            Set value for all estimated runs"
        echo "  stats                          Show real vs estimated stats"
        echo "  clear                          Clear all estimates (set to \$0)"
        echo "  interactive                    Interactive mode (default)"
        echo ""
        echo "Examples:"
        echo "  ./cc-value.sh set abc123 25.00 30    # Set run abc123... to \$25, 30min saved"
        echo "  ./cc-value.sh bulk 5.00 10           # Set all estimated to \$5, 10min each"
        echo "  ./cc-value.sh stats                  # Show verification stats"
        ;;
    *)
        echo -e "${RED}Unknown command: $1${NC}"
        echo "Run './cc-value.sh help' for usage"
        exit 1
        ;;
esac


     1→#!/bin/bash
     2→# cc-watch.sh - Live terminal monitoring for CC ROI Dashboard
     3→#
     4→# Usage:
     5→#   ./cc-watch.sh              # Live monitoring mode
     6→#   ./cc-watch.sh compact      # Compact single-line mode
     7→#   ./cc-watch.sh alerts       # Only show alerts and completed runs
     8→
     9→API_BASE="http://localhost:9001/api/cc"
    10→
    11→RED='\033[0;31m'
    12→GREEN='\033[0;32m'
    13→YELLOW='\033[1;33m'
    14→CYAN='\033[0;36m'
    15→PURPLE='\033[0;35m'
    16→BOLD='\033[1m'
    17→DIM='\033[2m'
    18→NC='\033[0m'
    19→
    20→# Clear screen and move cursor
    21→clear_screen() {
    22→    printf "\033[2J\033[H"
    23→}
    24→
    25→# Draw header
    26→draw_header() {
    27→    local cols=$(tput cols)
    28→    local line=$(printf '═%.0s' $(seq 1 $cols))
    29→
    30→    echo -e "${PURPLE}${BOLD}"
    31→    echo "$line"
    32→    echo "  ⚡ CC ROI DASHBOARD - LIVE MONITOR                    $(date '+%H:%M:%S')"
    33→    echo "$line"
    34→    echo -e "${NC}"
    35→}
    36→
    37→# Get and display stats
    38→show_stats() {
    39→    local health=$(curl -s "$API_BASE/health" 2>/dev/null)
    40→    local alltime=$(curl -s "$API_BASE/roi/all-time" 2>/dev/null)
    41→    local summary=$(curl -s "$API_BASE/roi/summary" 2>/dev/null)
    42→
    43→    if [ -z "$health" ]; then
    44→        echo -e "${RED}  ⚠  Server offline - waiting for connection...${NC}"
    45→        return 1
    46→    fi
    47→
    48→    # Parse data
    49→    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)
    50→    local budget_spent=$(echo "$health" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('gates',{}).get('budget',{}).get('spent_usd',0):.2f}\")" 2>/dev/null)
    51→    local budget_limit=$(echo "$health" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('gates',{}).get('budget',{}).get('limit_usd',10):.0f}\")" 2>/dev/null)
    52→    local overall=$(echo "$health" | python3 -c "import sys,json; print(json.load(sys.stdin).get('overall','?'))" 2>/dev/null)
    53→    local active_runs=$(echo "$health" | python3 -c "import sys,json; print(json.load(sys.stdin).get('gates',{}).get('heartbeat',{}).get('active_runs',0))" 2>/dev/null)
    54→
    55→    local profit=$(echo "$alltime" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('profit_usd',0):.2f}\")" 2>/dev/null)
    56→    local roi=$(echo "$alltime" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('roi_pct',0):.0f}\")" 2>/dev/null)
    57→    local total_runs=$(echo "$alltime" | python3 -c "import sys,json; print(json.load(sys.stdin).get('runs_total',0))" 2>/dev/null)
    58→    local success_rate=$(echo "$alltime" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('success_rate_pct',0):.0f}\")" 2>/dev/null)
    59→
    60→    local today_profit=$(echo "$summary" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('profit_usd',0):.2f}\")" 2>/dev/null)
    61→    local today_runs=$(echo "$summary" | python3 -c "import sys,json; print(json.load(sys.stdin).get('runs_total',0))" 2>/dev/null)
    62→
    63→    # Status color
    64→    local status_color=$GREEN
    65→    if [ "$overall" = "warning" ]; then status_color=$YELLOW; fi
    66→    if [ "$overall" = "critical" ]; then status_color=$RED; fi
    67→
    68→    # Budget bar
    69→    local bar_width=20
    70→    local filled=$(echo "$budget_pct * $bar_width / 100" | bc 2>/dev/null || echo "0")
    71→    local empty=$((bar_width - filled))
    72→    local bar_color=$GREEN
    73→    if [ $(echo "$budget_pct > 60" | bc 2>/dev/null) -eq 1 ]; then bar_color=$YELLOW; fi
    74→    if [ $(echo "$budget_pct > 80" | bc 2>/dev/null) -eq 1 ]; then bar_color=$RED; fi
    75→
    76→    local bar="${bar_color}$(printf '█%.0s' $(seq 1 $filled 2>/dev/null) 2>/dev/null)${DIM}$(printf '░%.0s' $(seq 1 $empty 2>/dev/null) 2>/dev/null)${NC}"
    77→
    78→    echo -e "  ${BOLD}STATUS${NC}  ${status_color}●${NC} ${overall^^}     ${BOLD}ACTIVE${NC} ${active_runs} runs"
    79→    echo ""
    80→    echo -e "  ${CYAN}╭─────────────────────────────────────────────────────────╮${NC}"
    81→    echo -e "  ${CYAN}│${NC}  ${BOLD}ALL-TIME${NC}                      ${BOLD}TODAY${NC}                  ${CYAN}│${NC}"
    82→    echo -e "  ${CYAN}│${NC}  ${GREEN}💰 \$${profit}${NC} profit             ${GREEN}💰 \$${today_profit}${NC} profit       ${CYAN}│${NC}"
    83→    echo -e "  ${CYAN}│${NC}  ${GREEN}📈 +${roi}%${NC} ROI                  📊 ${today_runs} runs            ${CYAN}│${NC}"
    84→    echo -e "  ${CYAN}│${NC}  🔢 ${total_runs} runs                   ✅ ${success_rate}% success       ${CYAN}│${NC}"
    85→    echo -e "  ${CYAN}╰─────────────────────────────────────────────────────────╯${NC}"
    86→    echo ""
    87→    echo -e "  ${BOLD}BUDGET${NC}  \$${budget_spent}/\$${budget_limit}  [${bar}]  ${budget_pct}%"
    88→    echo ""
    89→}
    90→
    91→# Show recent runs
    92→show_recent_runs() {
    93→    echo -e "  ${BOLD}RECENT RUNS${NC}"
    94→    echo -e "  ${DIM}─────────────────────────────────────────────────────────${NC}"
    95→
    96→    curl -s "$API_BASE/runs?limit=5" 2>/dev/null | python3 -c "
    97→import sys,json
    98→try:
    99→    runs = json.load(sys.stdin)
   100→    for r in runs:
   101→        status = '✅' if r.get('status') == 'completed' else '⏳' if r.get('status') == 'running' else '❌'
   102→        prompt = (r.get('prompt','')[:30] + '...') if len(r.get('prompt','')) > 30 else r.get('prompt','')
   103→        cost = r.get('cost_usd', 0)
   104→        value = r.get('value_generated_usd', 0) or 0
   105→        source = r.get('source', '?')[:8]
   106→        print(f'  {status} {source:8} \${cost:.3f}→\${value:.2f}  {prompt}')
   107→except:
   108→    print('  No runs available')
   109→" 2>/dev/null
   110→    echo ""
   111→}
   112→
   113→# Show quick action buttons hint
   114→show_actions_hint() {
   115→    echo -e "  ${DIM}Press: ${NC}${CYAN}1${NC}${DIM}-Backup ${NC}${CYAN}2${NC}${DIM}-Review ${NC}${CYAN}3${NC}${DIM}-Report ${NC}${CYAN}4${NC}${DIM}-Health ${NC}${CYAN}5${NC}${DIM}-Optimize ${NC}${CYAN}q${NC}${DIM}-Quit${NC}"
   116→}
   117→
   118→# Compact mode - single line
   119→compact_mode() {
   120→    while true; do
   121→        local health=$(curl -s "$API_BASE/health" 2>/dev/null)
   122→        local alltime=$(curl -s "$API_BASE/roi/all-time" 2>/dev/null)
   123→
   124→        if [ -z "$health" ]; then
   125→            echo -ne "\r${RED}CC: Offline${NC}                              "
   126→            sleep 2
   127→            continue
   128→        fi
   129→
   130→        local budget_pct=$(echo "$health" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('gates',{}).get('budget',{}).get('used_pct',0):.0f}\")" 2>/dev/null)
   131→        local overall=$(echo "$health" | python3 -c "import sys,json; print(json.load(sys.stdin).get('overall','?'))" 2>/dev/null)
   132→        local profit=$(echo "$alltime" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('profit_usd',0):.0f}\")" 2>/dev/null)
   133→        local roi=$(echo "$alltime" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('roi_pct',0):.0f}\")" 2>/dev/null)
   134→
   135→        local status_icon="●"
   136→        local status_color=$GREEN
   137→        if [ "$overall" = "warning" ]; then status_color=$YELLOW; fi
   138→        if [ "$overall" = "critical" ]; then status_color=$RED; fi
   139→
   140→        echo -ne "\r${status_color}${status_icon}${NC} CC: \$${profit} (+${roi}%) | Budget: ${budget_pct}% | $(date '+%H:%M:%S')    "
   141→
   142→        sleep 5
   143→    done
   144→}
   145→
   146→# Full live mode
   147→live_mode() {
   148→    # Check for input in background
   149→    while true; do
   150→        clear_screen
   151→        draw_header
   152→
   153→        if show_stats; then
   154→            show_recent_runs
   155→        fi
   156→
   157→        show_actions_hint
   158→
   159→        # Wait with timeout for input
   160→        read -t 3 -n 1 key 2>/dev/null
   161→
   162→        case "$key" in
   163→            1) ./cc-action.sh backup 2>/dev/null ;;
   164→            2) ./cc-action.sh review 2>/dev/null ;;
   165→            3) ./cc-action.sh report 2>/dev/null ;;
   166→            4) ./cc-action.sh health 2>/dev/null ;;
   167→            5) ./cc-action.sh optimize 2>/dev/null ;;
   168→            q|Q)
   169→                clear_screen
   170→                echo "Bye!"
   171→                exit 0
   172→                ;;
   173→        esac
   174→    done
   175→}
   176→
   177→# Alerts mode - only show when something happens
   178→alerts_mode() {
   179→    echo -e "${PURPLE}⚡ CC Alert Monitor${NC} - Watching for activity..."
   180→    echo ""
   181→
   182→    local last_runs=""
   183→
   184→    while true; do
   185→        local runs=$(curl -s "$API_BASE/runs?limit=1" 2>/dev/null)
   186→        local current_run=$(echo "$runs" | python3 -c "import sys,json; r=json.load(sys.stdin); print(r[0].get('id','') if r else '')" 2>/dev/null)
   187→
   188→        if [ -n "$current_run" ] && [ "$current_run" != "$last_runs" ]; then
   189→            local run_data=$(echo "$runs" | python3 -c "
   190→import sys,json
   191→r = json.load(sys.stdin)[0]
   192→status = '✅' if r.get('status') == 'completed' else '⏳' if r.get('status') == 'running' else '❌'
   193→print(f\"{status} {r.get('source','?')} | \${r.get('cost_usd',0):.3f} | {r.get('prompt','')[:40]}\")
   194→" 2>/dev/null)
   195→
   196→            echo -e "[$(date '+%H:%M:%S')] $run_data"
   197→            last_runs="$current_run"
   198→
   199→            # macOS notification
   200→            if command -v osascript &> /dev/null; then
   201→                local status=$(echo "$runs" | python3 -c "import sys,json; print(json.load(sys.stdin)[0].get('status',''))" 2>/dev/null)
   202→                if [ "$status" = "completed" ]; then
   203→                    osascript -e "display notification \"Run completed\" with title \"CC Dashboard\"" 2>/dev/null
   204→                fi
   205→            fi
   206→        fi
   207→
   208→        sleep 5
   209→    done
   210→}
   211→
   212→# Main
   213→case "${1:-live}" in
   214→    live|watch)
   215→        live_mode
   216→        ;;
   217→    compact|mini)
   218→        compact_mode
   219→        ;;
   220→    alerts|notify)
   221→        alerts_mode
   222→        ;;
   223→    help|--help|-h)
   224→        echo "Usage: ./cc-watch.sh [mode]"
   225→        echo ""
   226→        echo "Modes:"
   227→        echo "  live      Full-screen live monitoring (default)"
   228→        echo "  compact   Single-line status updates"
   229→        echo "  alerts    Only show new activity"
   230→        echo ""
   231→        echo "In live mode:"
   232→        echo "  1-5  Trigger quick actions"
   233→        echo "  q    Quit"
   234→        ;;
   235→    *)
   236→        echo "Unknown mode: $1"
   237→        echo "Run './cc-watch.sh help' for usage"
   238→        exit 1
   239→        ;;
   240→esac
   241→

<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-watch.sh - Live terminal monitoring for CC ROI Dashboard
#
# Usage:
#   ./cc-watch.sh              # Live monitoring mode
#   ./cc-watch.sh compact      # Compact single-line mode
#   ./cc-watch.sh alerts       # Only show alerts and completed runs

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'

# Clear screen and move cursor
clear_screen() {
    printf "\033[2J\033[H"
}

# Draw header
draw_header() {
    local cols=$(tput cols)
    local line=$(printf '═%.0s' $(seq 1 $cols))

    echo -e "${PURPLE}${BOLD}"
    echo "$line"
    echo "  ⚡ CC ROI DASHBOARD - LIVE MONITOR                    $(date '+%H:%M:%S')"
    echo "$line"
    echo -e "${NC}"
}

# Get and display stats
show_stats() {
    local health=$(curl -s "$API_BASE/health" 2>/dev/null)
    local alltime=$(curl -s "$API_BASE/roi/all-time" 2>/dev/null)
    local summary=$(curl -s "$API_BASE/roi/summary" 2>/dev/null)

    if [ -z "$health" ]; then
        echo -e "${RED}  ⚠  Server offline - waiting for connection...${NC}"
        return 1
    fi

    # Parse data
    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 budget_spent=$(echo "$health" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('gates',{}).get('budget',{}).get('spent_usd',0):.2f}\")" 2>/dev/null)
    local budget_limit=$(echo "$health" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('gates',{}).get('budget',{}).get('limit_usd',10):.0f}\")" 2>/dev/null)
    local overall=$(echo "$health" | python3 -c "import sys,json; print(json.load(sys.stdin).get('overall','?'))" 2>/dev/null)
    local active_runs=$(echo "$health" | python3 -c "import sys,json; print(json.load(sys.stdin).get('gates',{}).get('heartbeat',{}).get('active_runs',0))" 2>/dev/null)

    local profit=$(echo "$alltime" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('profit_usd',0):.2f}\")" 2>/dev/null)
    local roi=$(echo "$alltime" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('roi_pct',0):.0f}\")" 2>/dev/null)
    local total_runs=$(echo "$alltime" | python3 -c "import sys,json; print(json.load(sys.stdin).get('runs_total',0))" 2>/dev/null)
    local success_rate=$(echo "$alltime" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('success_rate_pct',0):.0f}\")" 2>/dev/null)

    local today_profit=$(echo "$summary" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('profit_usd',0):.2f}\")" 2>/dev/null)
    local today_runs=$(echo "$summary" | python3 -c "import sys,json; print(json.load(sys.stdin).get('runs_total',0))" 2>/dev/null)

    # Status color
    local status_color=$GREEN
    if [ "$overall" = "warning" ]; then status_color=$YELLOW; fi
    if [ "$overall" = "critical" ]; then status_color=$RED; fi

    # Budget bar
    local bar_width=20
    local filled=$(echo "$budget_pct * $bar_width / 100" | bc 2>/dev/null || echo "0")
    local empty=$((bar_width - filled))
    local bar_color=$GREEN
    if [ $(echo "$budget_pct > 60" | bc 2>/dev/null) -eq 1 ]; then bar_color=$YELLOW; fi
    if [ $(echo "$budget_pct > 80" | bc 2>/dev/null) -eq 1 ]; then bar_color=$RED; fi

    local bar="${bar_color}$(printf '█%.0s' $(seq 1 $filled 2>/dev/null) 2>/dev/null)${DIM}$(printf '░%.0s' $(seq 1 $empty 2>/dev/null) 2>/dev/null)${NC}"

    echo -e "  ${BOLD}STATUS${NC}  ${status_color}●${NC} ${overall^^}     ${BOLD}ACTIVE${NC} ${active_runs} runs"
    echo ""
    echo -e "  ${CYAN}╭─────────────────────────────────────────────────────────╮${NC}"
    echo -e "  ${CYAN}│${NC}  ${BOLD}ALL-TIME${NC}                      ${BOLD}TODAY${NC}                  ${CYAN}│${NC}"
    echo -e "  ${CYAN}│${NC}  ${GREEN}💰 \$${profit}${NC} profit             ${GREEN}💰 \$${today_profit}${NC} profit       ${CYAN}│${NC}"
    echo -e "  ${CYAN}│${NC}  ${GREEN}📈 +${roi}%${NC} ROI                  📊 ${today_runs} runs            ${CYAN}│${NC}"
    echo -e "  ${CYAN}│${NC}  🔢 ${total_runs} runs                   ✅ ${success_rate}% success       ${CYAN}│${NC}"
    echo -e "  ${CYAN}╰─────────────────────────────────────────────────────────╯${NC}"
    echo ""
    echo -e "  ${BOLD}BUDGET${NC}  \$${budget_spent}/\$${budget_limit}  [${bar}]  ${budget_pct}%"
    echo ""
}

# Show recent runs
show_recent_runs() {
    echo -e "  ${BOLD}RECENT RUNS${NC}"
    echo -e "  ${DIM}─────────────────────────────────────────────────────────${NC}"

    curl -s "$API_BASE/runs?limit=5" 2>/dev/null | python3 -c "
import sys,json
try:
    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','')[:30] + '...') if len(r.get('prompt','')) > 30 else r.get('prompt','')
        cost = r.get('cost_usd', 0)
        value = r.get('value_generated_usd', 0) or 0
        source = r.get('source', '?')[:8]
        print(f'  {status} {source:8} \${cost:.3f}→\${value:.2f}  {prompt}')
except:
    print('  No runs available')
" 2>/dev/null
    echo ""
}

# Show quick action buttons hint
show_actions_hint() {
    echo -e "  ${DIM}Press: ${NC}${CYAN}1${NC}${DIM}-Backup ${NC}${CYAN}2${NC}${DIM}-Review ${NC}${CYAN}3${NC}${DIM}-Report ${NC}${CYAN}4${NC}${DIM}-Health ${NC}${CYAN}5${NC}${DIM}-Optimize ${NC}${CYAN}q${NC}${DIM}-Quit${NC}"
}

# Compact mode - single line
compact_mode() {
    while true; do
        local health=$(curl -s "$API_BASE/health" 2>/dev/null)
        local alltime=$(curl -s "$API_BASE/roi/all-time" 2>/dev/null)

        if [ -z "$health" ]; then
            echo -ne "\r${RED}CC: Offline${NC}                              "
            sleep 2
            continue
        fi

        local budget_pct=$(echo "$health" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('gates',{}).get('budget',{}).get('used_pct',0):.0f}\")" 2>/dev/null)
        local overall=$(echo "$health" | python3 -c "import sys,json; print(json.load(sys.stdin).get('overall','?'))" 2>/dev/null)
        local profit=$(echo "$alltime" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('profit_usd',0):.0f}\")" 2>/dev/null)
        local roi=$(echo "$alltime" | python3 -c "import sys,json; print(f\"{json.load(sys.stdin).get('roi_pct',0):.0f}\")" 2>/dev/null)

        local status_icon="●"
        local status_color=$GREEN
        if [ "$overall" = "warning" ]; then status_color=$YELLOW; fi
        if [ "$overall" = "critical" ]; then status_color=$RED; fi

        echo -ne "\r${status_color}${status_icon}${NC} CC: \$${profit} (+${roi}%) | Budget: ${budget_pct}% | $(date '+%H:%M:%S')    "

        sleep 5
    done
}

# Full live mode
live_mode() {
    # Check for input in background
    while true; do
        clear_screen
        draw_header

        if show_stats; then
            show_recent_runs
        fi

        show_actions_hint

        # Wait with timeout for input
        read -t 3 -n 1 key 2>/dev/null

        case "$key" in
            1) ./cc-action.sh backup 2>/dev/null ;;
            2) ./cc-action.sh review 2>/dev/null ;;
            3) ./cc-action.sh report 2>/dev/null ;;
            4) ./cc-action.sh health 2>/dev/null ;;
            5) ./cc-action.sh optimize 2>/dev/null ;;
            q|Q)
                clear_screen
                echo "Bye!"
                exit 0
                ;;
        esac
    done
}

# Alerts mode - only show when something happens
alerts_mode() {
    echo -e "${PURPLE}⚡ CC Alert Monitor${NC} - Watching for activity..."
    echo ""

    local last_runs=""

    while true; do
        local runs=$(curl -s "$API_BASE/runs?limit=1" 2>/dev/null)
        local current_run=$(echo "$runs" | python3 -c "import sys,json; r=json.load(sys.stdin); print(r[0].get('id','') if r else '')" 2>/dev/null)

        if [ -n "$current_run" ] && [ "$current_run" != "$last_runs" ]; then
            local run_data=$(echo "$runs" | python3 -c "
import sys,json
r = json.load(sys.stdin)[0]
status = '✅' if r.get('status') == 'completed' else '⏳' if r.get('status') == 'running' else '❌'
print(f\"{status} {r.get('source','?')} | \${r.get('cost_usd',0):.3f} | {r.get('prompt','')[:40]}\")
" 2>/dev/null)

            echo -e "[$(date '+%H:%M:%S')] $run_data"
            last_runs="$current_run"

            # macOS notification
            if command -v osascript &> /dev/null; then
                local status=$(echo "$runs" | python3 -c "import sys,json; print(json.load(sys.stdin)[0].get('status',''))" 2>/dev/null)
                if [ "$status" = "completed" ]; then
                    osascript -e "display notification \"Run completed\" with title \"CC Dashboard\"" 2>/dev/null
                fi
            fi
        fi

        sleep 5
    done
}

# Main
case "${1:-live}" in
    live|watch)
        live_mode
        ;;
    compact|mini)
        compact_mode
        ;;
    alerts|notify)
        alerts_mode
        ;;
    help|--help|-h)
        echo "Usage: ./cc-watch.sh [mode]"
        echo ""
        echo "Modes:"
        echo "  live      Full-screen live monitoring (default)"
        echo "  compact   Single-line status updates"
        echo "  alerts    Only show new activity"
        echo ""
        echo "In live mode:"
        echo "  1-5  Trigger quick actions"
        echo "  q    Quit"
        ;;
    *)
        echo "Unknown mode: $1"
        echo "Run './cc-watch.sh help' for usage"
        exit 1
        ;;
esac


Perfect! Let me also check the log-server.py directly to see the full API:


Bash

Check log-server.py size


sqlite3 /Users/neog/logs.db "SELECT COUNT(*) as event_count FROM cc_events;" 2>/dev/null

Check number of events in database


sqlite3 /Users/neog/logs.db "SELECT DATE(started_at) as date, COUNT(*) as runs, COALESCE(SUM(cost_usd), 0) as cost, COALESCE(SUM(value_generated_usd), 0) as revenue FROM cc_runs GROUP BY DATE(started_at) ORDER BY date DESC;" 2>/dev/null

Get daily breakdown of runs


3007 /Users/neog/Services/servers/log-server.py


Perfect! Now I have comprehensive information. Let me create a detailed summary of the CC ROI Dashboard system.

## Comprehensive Summary: CC ROI Dashboard Infrastructure

I've thoroughly explored the CC ROI tracking system in your workspace. Here's what I found:

---

### 1. SYSTEM ARCHITECTURE

**Backend Stack:**
- **Primary Server**: `neog-gateway.py` (symlinked as `log-server.py`) - Flask + Flask-SocketIO on **port 9001**
- **CLI Server**: `claude-cli-server.py` on port 9003
- **Live Tracker**: `cc-live-tracker.py` - File watcher for `~/.claude/stats-cache.json`
- **Database**: SQLite at `/Users/neog/logs.db`

**Frontend:**
- Web dashboard at `http://localhost:9001/roi`
- Embedded in gateway (Flask serves HTML)
- Real-time updates via WebSocket (SocketIO)

---

### 2. DATABASE SCHEMA

**Primary Tables:**

**`cc_runs`** - Automation execution sessions
```
run_id (PK)              UUID primary key
session_id               Session identifier
prompt                   Automation prompt/description
source                   Origin (ios_app, macos_app, web, terminal, manual, cron, test)
device_ip                Device IP address
status                   pending|running|completed|failed|halted
model                    Default: claude-opus-4-5-20251101
input_tokens             Integer count
output_tokens            Integer count
cache_read_tokens        Cache read token count
cost_usd                 Calculated cost (REAL)
value_generated_usd      Revenue/value generated
value_is_estimated       Boolean (1=estimated, 0=verified/real)
gate_guardrails_ok       Safety gate status
gate_budget_ok           Budget gate status
gate_heartbeat_ok        Health gate status
halt_reason              If halted
started_at               Timestamp
completed_at             Timestamp
duration_ms              Runtime duration
tools_used               JSON array
files_modified           JSON array
error_message            Error details if failed
tags                     JSON tags
```

**`cc_events`** - Granular events within runs (currently empty: 0 records)
```
id (PK)                  Auto-increment
run_id (FK)              Links to cc_runs
event_type               Event classification
event_subtype            Sub-classification
input_tokens             Token count
output_tokens            Token count
cost_usd                 Cost for event
input_data               JSON input data
output_data              JSON output data
duration_ms              Event duration
success                  Boolean success flag
created_at               Timestamp
```

**`budget_config`** - 3-Gate budget limits
```
id (PK)
name                     "default"
daily_limit_usd          Default: $10.00
monthly_limit_usd        Default: $200.00
max_tokens_per_run       Default: 100,000
max_cost_per_run_usd     Default: $2.00
alert_threshold_pct      Default: 80%
is_active                Boolean
updated_at               Timestamp
```

**`guardrails`** - Safety rules
```
id (PK)
name                     Rule name
rule_type                blocked_command|blocked_path
pattern                  Pattern to match
action                   block|warn
is_active                Boolean
created_at               Timestamp
```

**`cc_tags`** - Tag management
```
id (PK)
name                     Tag name (unique)
color                    Hex color (default: #00d4ff)
description              Tag description
created_at               Timestamp
```

---

### 3. TOKEN PRICING & COST CALCULATION

**Current Rates (per 1M tokens):**

| Model | Input | Output | Cache Read |
|-------|-------|--------|-----------|
| Claude Opus 4.5 | $15.00 | $75.00 | $1.50 |
| Claude Sonnet 4.5 | $3.00 | $15.00 | $0.30 |
| Default | $3.00 | $15.00 | $0.30 |

**Cost Formula:**
```
cost = (input_tokens / 1M * input_rate) +
       (output_tokens / 1M * output_rate) +
       (cache_read_tokens / 1M * cache_read_rate)
```

---

### 4. API ENDPOINTS (Port 9001)

**Run Management:**
- `POST /api/cc/run` - Create new run
- `GET /api/cc/run/<run_id>` - Get single run with events
- `PATCH /api/cc/run/<run_id>` - Update run (auto-calculates cost from tokens)
- `POST /api/cc/run/<run_id>/complete` - Mark run as completed
- `POST /api/cc/run/<run_id>/value` - Update real value (verified)
- `GET /api/cc/runs` - List runs (limit, offset, status, source filters)

**ROI Statistics:**
- `GET /api/cc/roi/summary` - Today's cost/revenue/profit/ROI/runs
- `GET /api/cc/roi/all-time` - All-time stats (profit, ROI%, success rate, active days)
- `GET /api/cc/roi/daily` - Daily breakdown (last 30 days)
- `GET /api/cc/roi/real` - Verified vs estimated value comparison

**Events:**
- `POST /api/cc/event` - Log event for a run
- `GET /api/cc/events` - List events

**Budget & Gates:**
- `GET /api/cc/budget` - Get budget config & usage
- `POST /api/cc/budget` - Update budget limits
- `POST /api/cc/gate/check` - Pre-flight safety gate check
- `GET /api/cc/guardrails` - List active safety rules
- `GET /api/cc/health` - 3-Gate health status (guardrails, budget, heartbeat)

**System:**
- `GET /api/gateway/status` - Gateway uptime & database info
- `GET /api/gateway/services` - Available services list
- `POST /api/cc/export` - Export runs as JSON/CSV

---

### 5. COMMAND-LINE TOOLS

**Main Control Scripts:**

**`cc-services.sh`** - Service manager
```bash
./cc-services.sh start   # Start log-server & CLI server
./cc-services.sh stop    # Stop services
./cc-services.sh status  # Check status & health
./cc-services.sh restart
```

**`cc-track.sh`** - Primary tracking tool
```bash
./cc-track.sh start "prompt" [source]     # Create run
./cc-track.sh complete <run_id> [value]   # Finish run with optional revenue
./cc-track.sh value <run_id> <value>      # Add revenue to existing run
./cc-track.sh status                      # Show today's stats
./cc-track.sh runs [limit]                # List recent runs
./cc-track.sh gate "prompt" [tokens]      # Pre-flight gate check
./cc-track.sh budget status|set <limit>   # Manage budget
./cc-track.sh export [json|csv|summary] [days] # Export data
```

**`cc-value.sh`** - Value verification
```bash
./cc-value.sh list              # List runs with values (~=estimated, ✓=verified)
./cc-value.sh set <id> <value> # Mark run value as verified
./cc-value.sh bulk <value>      # Set all estimated runs to specific value
./cc-value.sh stats             # Show real vs estimated comparison
./cc-value.sh clear             # Reset all estimated values to $0
./cc-value.sh interactive       # Interactive mode (default)
```

**`cc-watch.sh`** - Live monitoring
```bash
./cc-watch.sh                   # Full-screen live monitor
./cc-watch.sh compact           # Single-line status updates
./cc-watch.sh alerts            # Alert-only mode (new activity)
```

**`cc.sh`** - Unified dashboard control
```bash
cc                              # Quick status
cc status|full|detailed         # Detailed report
cc morning|am                   # Morning report
cc value|v [subcommand]         # Value editor
cc watch|w [mode]               # Live monitor
cc action|a [action]            # Run automation
cc server [start|stop|restart]  # Service control
cc open|dashboard|web           # Open web UI
cc report                       # Daily report
```

---

### 6. CURRENT STATISTICS

**Database State (as of 2025-12-25):**
- **Total Runs**: 3 runs
- **Total Cost**: $0.654 USD
- **Total Revenue**: $45.00 USD
- **Profit**: $44.35 USD
- **Overall ROI**: 6,782%
- **Events**: 0 (event tracking not yet used)

**Run Breakdown by Date:**
```
2025-12-25: 3 runs, $0.654 cost, $45.00 revenue
```

---

### 7. 3-GATE AUTONOMY SYSTEM

The system implements 3 security/control gates:

**Gate 1: Guardrails**
- Pattern matching for dangerous commands
- Default rules block: `rm -rf /`, `rm -rf ~`, `sudo`, `git push --force`
- Default rules warn: `.env`, `.ssh` files
- Customizable patterns and actions (block/warn)

**Gate 2: Budget**
- Daily limit: $10.00 (default, configurable)
- Monthly limit: $200.00 (default, configurable)
- Per-run max: $2.00 (default, configurable)
- Alert at 80% threshold (macOS notification)
- Blocks when 100% exceeded

**Gate 3: Heartbeat**
- Monitors active run health
- Tracks run duration
- Validates gateway connectivity

**Gate Check Endpoint:**
Returns: `can_proceed` (boolean), detailed violations, budget remaining

---

### 8. VALUE ESTIMATION & VERIFICATION

**Automatic Value Estimation** (when no manual value provided):
- Base value calculation using source multipliers
- Keywords detection (deploy, release, fix bug, feature, etc.)
- Token-based fallback
- Minimum value = 2x cost (ensures positive ROI estimate)

**Source Multipliers:**
- iOS/macOS apps: 3.0x
- Web: 2.5x
- Dashboard: 2.0x
- Terminal: 1.5x
- Cron jobs: 1.2x
- Manual: 1.0x
- Tests: 0.5x

**Value States:**
- `value_is_estimated = 1` (automatically calculated)
- `value_is_estimated = 0` (user-verified/real value)

---

### 9. KEY FEATURES

**Cost Tracking:**
- Auto-calculates from token counts
- Supports multiple models with different rates
- Cache read token pricing
- Per-run cost accumulation

**Real-time Updates:**
- WebSocket events for run creation/completion
- Live cost streaming from Claude Code CLI
- Dashboard updates without refresh

**Data Export:**
- CSV format for spreadsheet analysis
- JSON for programmatic access
- Configurable date ranges (1-365 days)

**macOS Integration:**
- Budget alert notifications at 80% and 100%
- Timestamp integration with system

**Value Verification Workflow:**
- Automatic estimation for all runs
- Interactive editor to mark values as verified
- Bulk updates for multiple runs
- Real vs estimated statistics tracking

---

### 10. INTEGRATION POINTS

**Input Sources:**
- Manual CLI tracking (`cc-track.sh`)
- Claude Code CLI (via `claude-cli-server.py` on port 9003)
- Live stats monitoring (file watcher on `~/.claude/stats-cache.json`)
- Direct API calls

**Related Services:**
- LM Studio (inference, not directly integrated into ROI)
- Workspace Manager API (port 9004, separate)
- System Monitor Server (port 5555, separate)

---

### 11. DOCUMENTATION

**Primary Docs:**
- `/Users/neog/Docs/archive/CC-ROI-QUICKSTART.md` - Quick start guide
- `/Users/neog/CLAUDE.md` - Master workspace guide (references CC ROI)
- Inline help in all shell scripts

---

### Summary

You have a **sophisticated ROI tracking system** with:
- Dual backend (NEOG Gateway + Live Tracker)
- **6-table SQLite database** with proper relationships
- **20+ API endpoints** for comprehensive tracking
- **5+ CLI tools** for easy interaction
- **3-gate security/control system**
- Automatic value estimation with manual verification
- Real-time WebSocket updates
- Full export capabilities
- macOS integration for alerts

Currently, the system is lightly used (3 runs total) but fully functional and ready for scaling.