netsky 0.1.7

netsky CLI: the viable system launcher and subcommand dispatcher
Documentation
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use std::cell::RefCell;
use std::ffi::OsString;
use std::fs;
use std::time::Duration;

use chrono::{DateTime, Utc};

use netsky_db::{
    CloneDispatchRecord, CommunicationEventRecord, Db, GitOperationRecord, HarvestEventRecord,
    IrohEventRecord, IrohEventType, McpToolCallRecord, OwnerDirectiveRecord, SessionEvent,
    SourceErrorClass, SourceErrorRecord, TokenUsageRecord, WatchdogEventRecord,
};

thread_local! {
    static DB: RefCell<Option<Db>> = const { RefCell::new(None) };
}

pub fn record_cli_invocation(argv: &[OsString], exit_code: Option<i64>, duration: Duration) {
    let Some((bin, argv_json)) = cli_args(argv) else {
        return;
    };
    let duration_ms = duration.as_millis().try_into().ok();
    write_with_fallback(
        "cli_invocations",
        serde_json::json!({
            "bin": bin,
            "argv_json": argv_json,
            "exit_code": exit_code,
            "duration_ms": duration_ms,
            "host": host(),
        }),
        |db| {
            db.record_cli(
                Utc::now(),
                &bin,
                &argv_json,
                exit_code,
                duration_ms,
                &host(),
            )
        },
    );
}

pub fn record_session(agent: &str, session_num: i64, event: SessionEvent) {
    write_with_fallback(
        "sessions",
        serde_json::json!({
            "ts_utc": Utc::now().to_rfc3339(),
            "agent": agent,
            "session_num": session_num,
            "event": session_event_label(event),
        }),
        |db| db.record_session(Utc::now(), agent, session_num, event),
    );
}

pub fn record_tick(source: &str, detail: serde_json::Value) {
    let detail_json = detail.to_string();
    write_with_fallback(
        "ticks",
        serde_json::json!({
            "ts_utc": Utc::now().to_rfc3339(),
            "source": source,
            "detail_json": detail_json,
        }),
        |db| db.record_tick(Utc::now(), source, &detail_json),
    );
}

pub fn record_clone_dispatch(record: CloneDispatchRecord<'_>) {
    write_with_fallback(
        "clone_dispatches",
        serde_json::json!({
            "ts_utc_start": record.ts_utc_start.to_rfc3339(),
            "ts_utc_end": record.ts_utc_end.map(|ts| ts.to_rfc3339()),
            "agent_id": record.agent_id,
            "runtime": record.runtime,
            "brief_path": record.brief_path,
            "brief": record.brief,
            "workspace": record.workspace,
            "branch": record.branch,
            "status": record.status,
            "exit_code": record.exit_code,
            "detail_json": record.detail_json,
        }),
        |db| db.record_clone_dispatch(record),
    );
}

pub fn record_harvest_event(record: HarvestEventRecord<'_>) {
    write_with_fallback(
        "harvest_events",
        serde_json::json!({
            "ts_utc": record.ts_utc.to_rfc3339(),
            "source_branch": record.source_branch,
            "target_branch": record.target_branch,
            "commit_sha": record.commit_sha,
            "status": record.status,
            "conflicts": record.conflicts,
            "detail_json": record.detail_json,
        }),
        |db| db.record_harvest_event(record),
    );
}

pub fn record_communication_event(record: CommunicationEventRecord<'_>) {
    write_with_fallback(
        "communication_events",
        serde_json::json!({
            "ts_utc": record.ts_utc.to_rfc3339(),
            "source": record.source,
            "tool": record.tool,
            "direction": direction_label(record.direction),
            "chat_id": record.chat_id,
            "message_id": record.message_id,
            "handle": record.handle,
            "agent": record.agent,
            "body": record.body,
            "status": record.status,
            "detail_json": record.detail_json,
        }),
        |db| db.record_communication_event(record),
    );
}

pub fn record_mcp_tool_call(record: McpToolCallRecord<'_>) {
    write_with_fallback(
        "mcp_tool_calls",
        serde_json::json!({
            "ts_utc_start": record.ts_utc_start.to_rfc3339(),
            "ts_utc_end": record.ts_utc_end.map(|ts| ts.to_rfc3339()),
            "source": record.source,
            "tool": record.tool,
            "agent": record.agent,
            "duration_ms": record.duration_ms,
            "success": record.success,
            "error": record.error,
            "timeout_race": record.timeout_race,
            "request_json": record.request_json,
            "response_json": record.response_json,
        }),
        |db| db.record_mcp_tool_call(record),
    );
}

pub fn record_git_operation(record: GitOperationRecord<'_>) {
    write_with_fallback(
        "git_operations",
        serde_json::json!({
            "ts_utc": record.ts_utc.to_rfc3339(),
            "operation": record.operation,
            "repo": record.repo,
            "branch": record.branch,
            "remote": record.remote,
            "from_sha": record.from_sha,
            "to_sha": record.to_sha,
            "status": record.status,
            "detail_json": record.detail_json,
        }),
        |db| db.record_git_operation(record),
    );
}

pub fn record_owner_directive(record: OwnerDirectiveRecord<'_>) {
    write_with_fallback(
        "owner_directives",
        serde_json::json!({
            "ts_utc": record.ts_utc.to_rfc3339(),
            "source": record.source,
            "chat_id": record.chat_id,
            "raw_text": record.raw_text,
            "resolved_action": record.resolved_action,
            "agent": record.agent,
            "status": record.status,
            "detail_json": record.detail_json,
        }),
        |db| db.record_owner_directive(record),
    );
}

pub fn record_token_usage(record: TokenUsageRecord<'_>) {
    write_with_fallback(
        "token_usage",
        serde_json::json!({
            "ts_utc": record.ts_utc.to_rfc3339(),
            "session_id": record.session_id,
            "agent": record.agent,
            "runtime": record.runtime,
            "model": record.model,
            "input_tokens": record.input_tokens,
            "output_tokens": record.output_tokens,
            "cached_input_tokens": record.cached_input_tokens,
            "cost_usd_micros": record.cost_usd_micros,
            "detail_json": record.detail_json,
        }),
        |db| db.record_token_usage(record),
    );
}

pub fn record_watchdog_event(record: WatchdogEventRecord<'_>) {
    write_with_fallback(
        "watchdog_events",
        serde_json::json!({
            "ts_utc": record.ts_utc.to_rfc3339(),
            "event": record.event,
            "agent": record.agent,
            "severity": record.severity,
            "status": record.status,
            "detail_json": record.detail_json,
        }),
        |db| db.record_watchdog_event(record),
    );
}

pub fn record_source_error(record: SourceErrorRecord<'_>) {
    write_with_fallback(
        "source_errors",
        serde_json::json!({
            "ts_utc": record.ts_utc.to_rfc3339(),
            "source": record.source,
            "error_class": record.error_class.as_str(),
            "count": record.count,
            "detail_json": record.detail_json,
        }),
        |db| db.record_source_error(record),
    );
}

pub fn record_iroh_event(record: IrohEventRecord<'_>) {
    write_with_fallback(
        "iroh_events",
        serde_json::json!({
            "ts_utc": record.ts_utc.to_rfc3339(),
            "event_type": record.event_type.as_str(),
            "peer_id_hash": record.peer_id_hash,
            "peer_label": record.peer_label,
            "detail_json": record.detail_json,
        }),
        |db| db.record_iroh_event(record),
    );
}

/// Convenience wrapper for a single-event source error.
/// Phase 2 may introduce in-process bucketing that flushes a
/// rolled-up `count` on interval; for now every call records one row.
pub fn record_source_err(source: &str, error_class: SourceErrorClass, detail: Option<&str>) {
    record_source_error(SourceErrorRecord {
        ts_utc: Utc::now(),
        source,
        error_class,
        count: 1,
        detail_json: detail,
    });
}

/// Convenience wrapper for an iroh event. The raw NodeId is hashed at
/// the boundary so call sites do not need to import sha2.
pub fn record_iroh(
    event_type: IrohEventType,
    raw_peer_id: &str,
    peer_label: Option<&str>,
    detail: Option<&str>,
) {
    let hash = netsky_db::hash_peer_id(raw_peer_id);
    record_iroh_event(IrohEventRecord {
        ts_utc: Utc::now(),
        event_type,
        peer_id_hash: &hash,
        peer_label,
        detail_json: detail,
    });
}

#[allow(clippy::too_many_arguments)]
pub fn record_watchdog(
    event: &str,
    agent: Option<&str>,
    severity: Option<&str>,
    status: Option<&str>,
    detail: serde_json::Value,
) {
    let detail_json = detail.to_string();
    record_watchdog_event(WatchdogEventRecord {
        ts_utc: Utc::now(),
        event,
        agent,
        severity,
        status,
        detail_json: Some(&detail_json),
    });
}

#[allow(clippy::too_many_arguments)]
pub fn record_directive(
    source: &str,
    chat_id: Option<&str>,
    raw_text: &str,
    resolved_action: Option<&str>,
    agent: Option<&str>,
    status: Option<&str>,
    detail: serde_json::Value,
) {
    let detail_json = detail.to_string();
    record_owner_directive(OwnerDirectiveRecord {
        ts_utc: Utc::now(),
        source,
        chat_id,
        raw_text,
        resolved_action,
        agent,
        status,
        detail_json: Some(&detail_json),
    });
}

#[allow(clippy::too_many_arguments)]
pub fn record_mcp_call(
    source: &str,
    tool: &str,
    agent: Option<&str>,
    started: DateTime<Utc>,
    duration: Duration,
    success: bool,
    error: Option<&str>,
    timeout_race: bool,
    request_json: Option<&str>,
    response_json: Option<&str>,
) {
    let duration_ms = duration.as_millis().try_into().ok();
    record_mcp_tool_call(McpToolCallRecord {
        ts_utc_start: started,
        ts_utc_end: Some(Utc::now()),
        source,
        tool,
        agent,
        duration_ms,
        success,
        error,
        timeout_race,
        request_json,
        response_json,
    });
}

fn with_db<F, T>(f: F) -> netsky_db::Result<T>
where
    F: FnOnce(&Db) -> netsky_db::Result<T>,
{
    DB.with(|cell| {
        if cell.borrow().is_none() {
            let db = Db::open()?;
            db.migrate()?;
            cell.replace(Some(db));
        }

        let borrow = cell.borrow();
        let Some(db) = borrow.as_ref() else {
            unreachable!("db was initialized above")
        };
        f(db)
    })
}

fn write_with_fallback<T, F>(table: &str, record: serde_json::Value, f: F)
where
    F: FnOnce(&Db) -> netsky_db::Result<T>,
{
    if let Err(error) = with_db(f)
        && let Err(spool_error) = spool_meta_db_error(table, &error, record)
    {
        eprintln!("meta-db fallback failed for {table}: {spool_error}");
    }
}

fn cli_args(argv: &[OsString]) -> Option<(String, String)> {
    let bin = argv.first()?.to_string_lossy().into_owned();
    let args: Vec<String> = argv
        .iter()
        .skip(1)
        .map(|s| s.to_string_lossy().into_owned())
        .collect();
    let argv_json = serde_json::to_string(&args).ok()?;
    Some((bin, argv_json))
}

fn host() -> String {
    std::env::var("HOSTNAME")
        .or_else(|_| std::env::var("COMPUTERNAME"))
        .unwrap_or_else(|_| "unknown".to_string())
}

fn direction_label(direction: netsky_db::Direction) -> &'static str {
    match direction {
        netsky_db::Direction::Inbound => "inbound",
        netsky_db::Direction::Outbound => "outbound",
    }
}

fn session_event_label(event: SessionEvent) -> &'static str {
    match event {
        SessionEvent::Up => "up",
        SessionEvent::Down => "down",
        SessionEvent::Note => "note",
    }
}

fn spool_meta_db_error(
    table: &str,
    error: &netsky_db::Error,
    record: serde_json::Value,
) -> std::io::Result<()> {
    let home = dirs::home_dir().ok_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::NotFound, "home directory not found")
    })?;
    let dir = home.join(".netsky").join("logs");
    fs::create_dir_all(&dir)?;
    let value = serde_json::json!({
        "ts_utc": Utc::now().to_rfc3339(),
        "table": table,
        "error": error.to_string(),
        "record": record,
    });
    let path = dir.join(format!(
        "meta-db-errors-{}.jsonl",
        Utc::now().format("%Y-%m-%d")
    ));
    if let Err(spool_error) = netsky_core::jsonl::append_json_line(&path, &value) {
        write_spool_failure_marker(table, error, &spool_error, &value)?;
    }
    Ok(())
}

fn write_spool_failure_marker(
    table: &str,
    db_error: &netsky_db::Error,
    spool_error: &std::io::Error,
    record: &serde_json::Value,
) -> std::io::Result<()> {
    let home = dirs::home_dir().ok_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::NotFound, "home directory not found")
    })?;
    let dir = home.join(".netsky").join("state");
    fs::create_dir_all(&dir)?;
    let path = dir.join("meta-db-spool-failed");
    let body = serde_json::json!({
        "ts_utc": Utc::now().to_rfc3339(),
        "table": table,
        "db_error": db_error.to_string(),
        "spool_error": spool_error.to_string(),
        "record": record,
    });
    fs::write(path, serde_json::to_vec_pretty(&body)?)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cli_args_serializes_tail() {
        let argv = vec![
            OsString::from("netsky"),
            OsString::from("up"),
            OsString::from("2"),
        ];
        let (bin, json) = cli_args(&argv).expect("cli args");
        assert_eq!(bin, "netsky");
        assert_eq!(json, "[\"up\",\"2\"]");
    }
}