File size: 10,004 Bytes
bbbc03f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d79c1a
bbbc03f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#!/bin/bash

# Mission Control Phase 3: Notification Delivery Daemon
# Polls undelivered notifications and sends them to agent sessions via OpenClaw
#
# Usage:
#   scripts/notification-daemon.sh [options]
#
# Options:
#   --agent AGENT_NAME    Only deliver notifications to specific agent
#   --limit N             Max notifications to process per batch (default: 50)
#   --dry-run            Test mode - don't actually deliver notifications
#   --daemon             Run in daemon mode (continuous polling)
#   --interval SECONDS   Polling interval in daemon mode (default: 60)

set -e

# Configuration
MISSION_CONTROL_URL="${MISSION_CONTROL_URL:-http://localhost:3000}"
LOG_DIR="${LOG_DIR:-$HOME/.mission-control/logs}"
LOG_FILE="$LOG_DIR/notification-daemon-$(date +%Y-%m-%d).log"
PID_FILE="/tmp/notification-daemon.pid"
DEFAULT_INTERVAL=60
DEFAULT_LIMIT=50

# Command line options
AGENT_FILTER=""
LIMIT=$DEFAULT_LIMIT
DRY_RUN=false
DAEMON_MODE=false
INTERVAL=$DEFAULT_INTERVAL

# Ensure log directory exists
mkdir -p "$LOG_DIR"

# Logging function
log() {
    local level="$1"
    shift
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*" | tee -a "$LOG_FILE"
}

# Check if Mission Control is running
check_mission_control() {
    if ! curl -s "$MISSION_CONTROL_URL/api/status" > /dev/null 2>&1; then
        log "ERROR" "Mission Control not accessible at $MISSION_CONTROL_URL"
        return 1
    fi
    return 0
}

# Process and deliver notifications
deliver_notifications() {
    log "INFO" "Starting notification delivery batch"
    
    # Build API request
    local api_payload="{\"limit\": $LIMIT"
    
    if [[ -n "$AGENT_FILTER" ]]; then
        api_payload+=", \"agent_filter\": \"$AGENT_FILTER\""
    fi
    
    if [[ "$DRY_RUN" == "true" ]]; then
        api_payload+=", \"dry_run\": true"
    fi
    
    api_payload+="}"
    
    # Call notification delivery endpoint
    local response
    response=$(curl -s -w "HTTP_STATUS:%{http_code}" \
        -X POST \
        -H "Content-Type: application/json" \
        -d "$api_payload" \
        "$MISSION_CONTROL_URL/api/notifications/deliver" 2>/dev/null)
    
    local http_code
    http_code=$(echo "$response" | grep -o "HTTP_STATUS:[0-9]*" | cut -d: -f2)
    local body
    body=$(echo "$response" | sed 's/HTTP_STATUS:[0-9]*$//')
    
    if [[ "$http_code" != "200" ]]; then
        log "ERROR" "Notification delivery failed: HTTP $http_code"
        log "ERROR" "Response: $body"
        return 1
    fi
    
    # Parse results
    local status delivered errors total_processed
    status=$(echo "$body" | jq -r '.status // "unknown"' 2>/dev/null || echo "parse_error")
    delivered=$(echo "$body" | jq -r '.delivered // 0' 2>/dev/null || echo "0")
    errors=$(echo "$body" | jq -r '.errors // 0' 2>/dev/null || echo "0")
    total_processed=$(echo "$body" | jq -r '.total_processed // 0' 2>/dev/null || echo "0")
    
    if [[ "$status" == "success" ]]; then
        if [[ "$total_processed" -gt 0 ]]; then
            log "INFO" "Batch completed: $total_processed processed, $delivered delivered, $errors failed"
            
            # Log detailed errors if any
            if [[ "$errors" -gt 0 ]]; then
                local error_details
                error_details=$(echo "$body" | jq -r '.error_details[]? | "- \(.recipient): \(.error)"' 2>/dev/null || echo "")
                if [[ -n "$error_details" ]]; then
                    log "WARN" "Error details:"
                    echo "$error_details" | while read -r line; do
                        log "WARN" "  $line"
                    done
                fi
            fi
        else
            log "INFO" "No notifications to deliver"
        fi
        
        return 0
    else
        log "ERROR" "Unexpected delivery response: $status"
        return 1
    fi
}

# Get delivery statistics
get_delivery_stats() {
    local stats_url="$MISSION_CONTROL_URL/api/notifications/deliver"
    
    if [[ -n "$AGENT_FILTER" ]]; then
        stats_url+="?agent=$AGENT_FILTER"
    fi
    
    local response
    response=$(curl -s "$stats_url" 2>/dev/null)
    
    if [[ $? -eq 0 ]]; then
        echo "$response" | jq -r '
            "Delivery Statistics:",
            "  Total notifications: \(.statistics.total)",
            "  Delivered: \(.statistics.delivered)",
            "  Undelivered: \(.statistics.undelivered)",
            "  Delivery rate: \(.statistics.delivery_rate)%",
            "",
            "Agents with pending notifications:",
            (.agents_with_pending[] | "  \(.recipient): \(.pending_count) pending\(if .session_key then "" else " (no session key)" end)")
        ' 2>/dev/null || echo "Failed to parse statistics"
    else
        echo "Failed to fetch delivery statistics"
    fi
}

# Daemon mode signal handlers
cleanup() {
    log "INFO" "Received shutdown signal, stopping daemon"
    rm -f "$PID_FILE"
    exit 0
}

# Check if daemon is already running
check_daemon() {
    if [[ -f "$PID_FILE" ]]; then
        local old_pid
        old_pid=$(cat "$PID_FILE" 2>/dev/null || echo "")
        
        if [[ -n "$old_pid" ]] && kill -0 "$old_pid" 2>/dev/null; then
            log "ERROR" "Notification daemon already running with PID $old_pid"
            exit 1
        else
            log "WARN" "Stale PID file found, removing"
            rm -f "$PID_FILE"
        fi
    fi
}

# Run in daemon mode
run_daemon() {
    log "INFO" "Starting notification daemon (PID: $$)"
    
    # Check if already running
    check_daemon
    
    # Write PID file
    echo $$ > "$PID_FILE"
    
    # Set up signal handlers
    trap cleanup SIGTERM SIGINT SIGQUIT
    
    # Main daemon loop
    while true; do
        if ! check_mission_control; then
            log "WARN" "Mission Control not accessible, sleeping $INTERVAL seconds"
            sleep "$INTERVAL"
            continue
        fi
        
        # Process notifications
        if deliver_notifications; then
            log "DEBUG" "Delivery batch completed successfully"
        else
            log "WARN" "Delivery batch had errors"
        fi
        
        # Sleep until next cycle
        sleep "$INTERVAL"
    done
}

# Parse command line arguments
parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            --agent)
                AGENT_FILTER="$2"
                shift 2
                ;;
            --limit)
                LIMIT="$2"
                shift 2
                ;;
            --dry-run)
                DRY_RUN=true
                shift
                ;;
            --daemon)
                DAEMON_MODE=true
                shift
                ;;
            --interval)
                INTERVAL="$2"
                shift 2
                ;;
            --stats)
                get_delivery_stats
                exit 0
                ;;
            --stop)
                if [[ -f "$PID_FILE" ]]; then
                    local pid
                    pid=$(cat "$PID_FILE" 2>/dev/null || echo "")
                    if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
                        kill -TERM "$pid"
                        log "INFO" "Sent stop signal to daemon (PID: $pid)"
                        exit 0
                    else
                        log "WARN" "No running daemon found"
                        rm -f "$PID_FILE"
                        exit 1
                    fi
                else
                    log "WARN" "No daemon PID file found"
                    exit 1
                fi
                ;;
            --help|-h)
                show_help
                exit 0
                ;;
            *)
                echo "Unknown option: $1" >&2
                show_help
                exit 1
                ;;
        esac
    done
}

# Show help
show_help() {
    cat << 'EOF'
Mission Control Notification Delivery Daemon

Usage: notification-daemon.sh [options]

Options:
  --agent AGENT_NAME      Only deliver notifications to specific agent
  --limit N              Max notifications to process per batch (default: 50)
  --dry-run              Test mode - don't actually deliver notifications
  --daemon               Run in daemon mode (continuous polling)
  --interval SECONDS     Polling interval in daemon mode (default: 60)
  --stats                Show delivery statistics and exit
  --stop                 Stop running daemon
  --help, -h             Show this help message

Examples:
  # Single batch delivery
  ./notification-daemon.sh

  # Dry run to test
  ./notification-daemon.sh --dry-run

  # Deliver only to specific agent
  ./notification-daemon.sh --agent "coordinator"

  # Run as daemon
  ./notification-daemon.sh --daemon --interval 30

  # Show statistics
  ./notification-daemon.sh --stats

  # Stop daemon
  ./notification-daemon.sh --stop

Environment variables:
  MISSION_CONTROL_URL    Mission Control base URL (default: http://localhost:3005)

Log files:
  $LOG_DIR/notification-daemon-YYYY-MM-DD.log
EOF
}

# Validate arguments
validate_args() {
    if ! [[ "$LIMIT" =~ ^[1-9][0-9]*$ ]]; then
        log "ERROR" "Invalid limit: $LIMIT (must be positive integer)"
        exit 1
    fi
    
    if ! [[ "$INTERVAL" =~ ^[1-9][0-9]*$ ]]; then
        log "ERROR" "Invalid interval: $INTERVAL (must be positive integer)"
        exit 1
    fi
}

# Main execution
main() {
    parse_args "$@"
    validate_args
    
    if [[ "$DAEMON_MODE" == "true" ]]; then
        run_daemon
    else
        # Single run mode
        log "INFO" "Starting single notification delivery run"
        
        if ! check_mission_control; then
            log "ERROR" "Aborting: Mission Control not accessible"
            exit 1
        fi
        
        if deliver_notifications; then
            log "INFO" "Notification delivery completed successfully"
            exit 0
        else
            log "ERROR" "Notification delivery failed"
            exit 1
        fi
    fi
}

# Run main function
main "$@"