smart-tree 8.0.1

Smart Tree - An intelligent, AI-friendly directory visualization tool
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! STD - Smart Tree Daemon
//!
//! Persistent daemon providing context, security, and API services.
//! Listens on Unix socket using the ST binary protocol.
//!
//! ## Usage
//!
//! ```bash
//! std start              # Start daemon
//! std stop               # Stop daemon
//! std status             # Health check
//! ```

use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{UnixListener, UnixStream};
use tokio::sync::RwLock;
use tracing::{debug, error, info};

use st::formatters::{
    ai::AiFormatter, classic::ClassicFormatter, digest::DigestFormatter, hex::HexFormatter,
    json::JsonFormatter, quantum::QuantumFormatter, stats::StatsFormatter, Formatter,
    PathDisplayMode,
};
use st::mcp::wave_memory::{MemoryType, WaveMemoryManager};
use st::scanner::{Scanner, ScannerConfig};
use st_protocol::{Address, AuthLevel, Frame, Payload, PayloadDecoder, SecurityContext, Verb};

/// Daemon configuration
#[derive(Debug, Clone)]
pub struct DaemonConfig {
    /// Socket path
    pub socket_path: PathBuf,
    /// PID file path
    pub pid_path: PathBuf,
    /// Log level
    pub log_level: String,
}

impl Default for DaemonConfig {
    fn default() -> Self {
        let runtime_dir = std::env::var("XDG_RUNTIME_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| PathBuf::from("/tmp"));

        DaemonConfig {
            socket_path: runtime_dir.join("st.sock"),
            pid_path: runtime_dir.join("st.pid"),
            log_level: "info".to_string(),
        }
    }
}

/// Session state for a connected client
#[derive(Debug)]
#[allow(dead_code)]
struct ClientSession {
    security: SecurityContext,
    address: Address,
}

impl Default for ClientSession {
    fn default() -> Self {
        ClientSession {
            security: SecurityContext::new(),
            address: Address::Local,
        }
    }
}

/// Daemon state shared across connections
#[allow(dead_code)]
struct DaemonState {
    config: DaemonConfig,
    memory: WaveMemoryManager,
}

impl DaemonState {
    fn new(config: DaemonConfig) -> Self {
        DaemonState {
            config,
            memory: WaveMemoryManager::new_compact(None), // Use compact grid for daemon
        }
    }
}

/// Handle a single client connection
async fn handle_client(
    mut stream: UnixStream,
    state: Arc<RwLock<DaemonState>>,
) -> Result<()> {
    let mut session = ClientSession::default();
    let mut buf = vec![0u8; 65536]; // Max frame size

    loop {
        // Read frame header (at least verb + END = 2 bytes)
        let n = stream.read(&mut buf).await?;
        if n == 0 {
            debug!("Client disconnected");
            return Ok(());
        }

        // Find frame end
        let frame_end = match Frame::find_end(&buf[..n]) {
            Some(end) => end,
            None => {
                // Incomplete frame - need more data (simplified: error for now)
                let response = Frame::error("Incomplete frame");
                stream.write_all(&response.encode()).await?;
                continue;
            }
        };

        // Decode frame
        let frame = match Frame::decode(&buf[..frame_end]) {
            Ok(f) => f,
            Err(e) => {
                let response = Frame::error(&format!("Decode error: {e:?}"));
                stream.write_all(&response.encode()).await?;
                continue;
            }
        };

        debug!("Received {:?}", frame.verb());

        // Check security level
        let required_level = frame.verb().security_level();
        if (session.security.level() as u8) < required_level {
            let response = Frame::error(&format!(
                "Requires auth level {}",
                AuthLevel::from_byte(required_level)
                    .map(|l| l.name())
                    .unwrap_or("unknown")
            ));
            stream.write_all(&response.encode()).await?;
            continue;
        }

        // Handle verb
        let response = handle_verb(frame, &mut session, &state).await;
        stream.write_all(&response.encode()).await?;

        // Check for EndStream
        if response.verb() == Verb::EndStream {
            break;
        }
    }

    Ok(())
}

/// Handle a single verb and return response frame
async fn handle_verb(
    frame: Frame,
    session: &mut ClientSession,
    state: &Arc<RwLock<DaemonState>>,
) -> Frame {
    match frame.verb() {
        Verb::Ping => Frame::ok(),

        Verb::Scan => handle_scan(frame.into_payload(), state).await,

        Verb::Format => handle_format(frame.into_payload(), state).await,

        Verb::Search => handle_search(frame.into_payload(), state).await,

        Verb::Stats => handle_stats(state).await,

        Verb::Context => handle_context(frame.into_payload(), state).await,

        Verb::Session => {
            // Return session info
            let mut payload = Payload::new();
            payload.push_byte(session.security.level() as u8);
            Frame::new(Verb::Ok, payload)
        }

        Verb::EndStream => Frame::simple(Verb::EndStream),

        Verb::Subscribe => {
            // TODO: implement file watching
            Frame::error("Subscribe not yet implemented")
        }

        Verb::Unsubscribe => {
            // TODO: implement file watching
            Frame::error("Unsubscribe not yet implemented")
        }

        // Auth verbs
        Verb::AuthStart | Verb::AuthEnd => {
            Frame::error("Auth block expected, not standalone verb")
        }

        Verb::Elevate => {
            // TODO: FIDO2 integration
            Frame::error("Elevate not yet implemented")
        }

        // Memory verbs
        Verb::Remember => handle_remember(frame.into_payload(), state).await,
        Verb::Recall => handle_recall(frame.into_payload(), state).await,
        Verb::Forget => handle_forget(frame.into_payload(), state).await,

        // Audio/Media verbs
        Verb::Audio => handle_audio(frame.into_payload(), state).await,
        Verb::M8Wave => {
            // Return current wave state
            let state = state.read().await;
            let stats = state.memory.stats();
            Frame::new(Verb::Ok, Payload::from_string(&stats.to_string()))
        }

        // Admin verbs
        Verb::Permit | Verb::Deny | Verb::Audit => {
            Frame::error("Admin operations not yet implemented")
        }

        // Misc
        Verb::Ok | Verb::Error | Verb::Alert => {
            // These are response verbs, not request verbs
            Frame::error("Invalid request verb")
        }

        Verb::Back | Verb::Next | Verb::Clear | Verb::Complete | Verb::User | Verb::Cancel => {
            Frame::error("Not implemented")
        }
    }
}

/// Handle SCAN verb
async fn handle_scan(payload: Payload, _state: &Arc<RwLock<DaemonState>>) -> Frame {
    let mut decoder = PayloadDecoder::new(&payload);

    // Parse path (length-prefixed string)
    let path = match decoder.string() {
        Some(p) => p.to_string(),
        None => ".".to_string(),
    };

    // Parse depth
    let depth = decoder.byte().unwrap_or(3);

    debug!("SCAN path={} depth={}", path, depth);

    // Use st scanner with config
    let config = ScannerConfig {
        max_depth: depth as usize,
        ..ScannerConfig::default()
    };

    let path = Path::new(&path);
    match Scanner::new(path, config).and_then(|s| s.scan()) {
        Ok((nodes, stats)) => {
            // Encode result as JSON for now (will optimize later)
            let result = serde_json::json!({
                "files": stats.total_files,
                "dirs": stats.total_dirs,
                "total_size": stats.total_size,
                "nodes": nodes,
            });
            Frame::new(Verb::Ok, Payload::from_string(&result.to_string()))
        }
        Err(e) => Frame::error(&format!("Scan failed: {e}")),
    }
}

/// Handle FORMAT verb - scan and format in one operation
/// Payload: [mode string][path string][depth byte]
async fn handle_format(payload: Payload, _state: &Arc<RwLock<DaemonState>>) -> Frame {
    let mut decoder = PayloadDecoder::new(&payload);

    // Parse mode (length-prefixed string)
    let mode = decoder.string().unwrap_or("classic");

    // Parse path (length-prefixed string)
    let path_str = decoder.string().unwrap_or(".");

    // Parse depth
    let depth = decoder.byte().unwrap_or(3);

    debug!("FORMAT mode={} path={} depth={}", mode, path_str, depth);

    // Scan the directory
    let config = ScannerConfig {
        max_depth: depth as usize,
        ..ScannerConfig::default()
    };

    let path = Path::new(path_str);
    let (nodes, stats) = match Scanner::new(path, config).and_then(|s| s.scan()) {
        Ok(result) => result,
        Err(e) => return Frame::error(&format!("Scan failed: {e}")),
    };

    // Get the appropriate formatter
    let formatter: Box<dyn Formatter> = match mode {
        "classic" => Box::new(ClassicFormatter::new(false, false, PathDisplayMode::Relative)),
        "ai" => Box::new(AiFormatter::new(false, PathDisplayMode::Relative)),
        "json" => Box::new(JsonFormatter::new(false)),
        "hex" => Box::new(HexFormatter::new(false, false, false, PathDisplayMode::Relative, false)),
        "quantum" => Box::new(QuantumFormatter::new()),
        "stats" => Box::new(StatsFormatter::new()),
        "digest" => Box::new(DigestFormatter::new()),
        _ => return Frame::error(&format!("Unknown format mode: {mode}")),
    };

    // Format to a buffer
    let mut output = Vec::new();
    if let Err(e) = formatter.format(&mut output, &nodes, &stats, path) {
        return Frame::error(&format!("Format failed: {e}"));
    }

    // Return formatted output
    let output_str = String::from_utf8_lossy(&output);
    Frame::new(Verb::Ok, Payload::from_string(&output_str))
}

/// Handle SEARCH verb
/// Payload: [path string][pattern string][max_results byte]
async fn handle_search(payload: Payload, _state: &Arc<RwLock<DaemonState>>) -> Frame {
    let mut decoder = PayloadDecoder::new(&payload);

    // Parse path (length-prefixed string)
    let path_str = decoder.string().unwrap_or(".");

    // Parse pattern (length-prefixed string)
    let pattern = decoder.string().unwrap_or("");

    // Parse max results
    let max_results = decoder.byte().unwrap_or(50) as usize;

    debug!("SEARCH path={} pattern={} max={}", path_str, pattern, max_results);

    if pattern.is_empty() {
        return Frame::error("Search pattern required");
    }

    let path = Path::new(path_str);

    // Use scanner with search_keyword for content search
    let config = ScannerConfig {
        max_depth: 10,
        search_keyword: Some(pattern.to_string()),
        include_line_content: true,
        ..ScannerConfig::default()
    };

    let (nodes, _stats) = match Scanner::new(path, config).and_then(|s| s.scan()) {
        Ok(result) => result,
        Err(e) => return Frame::error(&format!("Search failed: {e}")),
    };

    // Collect files with matches
    let mut results: Vec<_> = nodes
        .iter()
        .filter_map(|node| {
            let matches = node.search_matches.as_ref()?;
            if matches.total_count == 0 {
                return None;
            }

            let mut match_info = serde_json::json!({
                "path": node.path.display().to_string(),
                "matches": matches.total_count,
                "truncated": matches.truncated
            });

            // Include line content if available
            if let Some(ref lines) = matches.line_content {
                let line_results: Vec<_> = lines
                    .iter()
                    .take(10) // Limit lines per file
                    .map(|(line_num, content, col)| serde_json::json!({
                        "line": line_num,
                        "content": content,
                        "col": col
                    }))
                    .collect();
                match_info["lines"] = serde_json::json!(line_results);
            }

            Some((matches.total_count, match_info))
        })
        .collect();

    // Sort by match count descending, limit results
    results.sort_by(|a, b| b.0.cmp(&a.0));
    results.truncate(max_results);

    let results: Vec<_> = results.into_iter().map(|(_, info)| info).collect();

    let response = serde_json::json!({
        "pattern": pattern,
        "count": results.len(),
        "results": results
    });

    Frame::new(Verb::Ok, Payload::from_string(&response.to_string()))
}

/// Handle STATS verb
async fn handle_stats(state: &Arc<RwLock<DaemonState>>) -> Frame {
    let state = state.read().await;
    let mem_stats = state.memory.stats();

    let stats = serde_json::json!({
        "version": env!("CARGO_PKG_VERSION"),
        "protocol": format!("v{}", st_protocol::VERSION),
        "memories": mem_stats["total_memories"],
        "active_waves": mem_stats["active_waves"],
        "keywords": mem_stats["unique_keywords"],
    });
    Frame::new(Verb::Ok, Payload::from_string(&stats.to_string()))
}

/// Handle CONTEXT verb
async fn handle_context(payload: Payload, _state: &Arc<RwLock<DaemonState>>) -> Frame {
    let path = payload.as_str().unwrap_or(".");
    debug!("CONTEXT path={}", path);

    // TODO: integrate with MCP context gathering
    Frame::error("Context gathering not yet implemented")
}

/// Handle REMEMBER verb - Store a memory
/// Payload: [content string][keywords string (comma-separated)][type string][valence f32][arousal f32]
async fn handle_remember(payload: Payload, state: &Arc<RwLock<DaemonState>>) -> Frame {
    let mut decoder = PayloadDecoder::new(&payload);

    // Parse content (required)
    let content = match decoder.string() {
        Some(c) if !c.is_empty() => c.to_string(),
        _ => return Frame::error("Content required for remember"),
    };

    // Parse keywords (comma-separated)
    let keywords_str = decoder.string().unwrap_or("");
    let keywords: Vec<String> = keywords_str
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    // Parse memory type
    let type_str = decoder.string().unwrap_or("technical");
    let memory_type = MemoryType::parse(type_str);

    // Parse emotional state (defaults: neutral valence, medium arousal)
    let valence = decoder.byte().map(|b| (b as f32 - 128.0) / 128.0).unwrap_or(0.0);
    let arousal = decoder.byte().map(|b| b as f32 / 255.0).unwrap_or(0.5);

    debug!(
        "REMEMBER content_len={} keywords={:?} type={:?}",
        content.len(),
        keywords,
        memory_type
    );

    let mut state = state.write().await;
    match state.memory.anchor(
        content,
        keywords,
        memory_type,
        valence,
        arousal,
        "daemon".to_string(),
        None,
    ) {
        Ok(id) => {
            // Save to disk
            let _ = state.memory.save();
            let response = serde_json::json!({
                "id": id,
                "status": "anchored"
            });
            Frame::new(Verb::Ok, Payload::from_string(&response.to_string()))
        }
        Err(e) => Frame::error(&format!("Remember failed: {e}")),
    }
}

/// Handle RECALL verb - Find memories
/// Payload: [keywords string (comma-separated)][max_results byte]
async fn handle_recall(payload: Payload, state: &Arc<RwLock<DaemonState>>) -> Frame {
    let mut decoder = PayloadDecoder::new(&payload);

    // Parse keywords (comma-separated)
    let keywords_str = decoder.string().unwrap_or("");
    let keywords: Vec<String> = keywords_str
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    if keywords.is_empty() {
        return Frame::error("Keywords required for recall");
    }

    let max_results = decoder.byte().unwrap_or(10) as usize;

    debug!("RECALL keywords={:?} max={}", keywords, max_results);

    let mut state = state.write().await;
    let memories = state.memory.find_by_keywords(&keywords, max_results);

    let results: Vec<_> = memories
        .iter()
        .map(|m| {
            serde_json::json!({
                "id": m.id,
                "content": m.content,
                "keywords": m.keywords,
                "type": format!("{:?}", m.memory_type),
                "access_count": m.access_count
            })
        })
        .collect();

    let response = serde_json::json!({
        "count": results.len(),
        "memories": results
    });

    Frame::new(Verb::Ok, Payload::from_string(&response.to_string()))
}

/// Handle FORGET verb - Delete a memory
/// Payload: [memory_id string]
async fn handle_forget(payload: Payload, state: &Arc<RwLock<DaemonState>>) -> Frame {
    let id = match payload.as_str() {
        Some(id) if !id.is_empty() => id,
        _ => return Frame::error("Memory ID required for forget"),
    };

    debug!("FORGET id={}", id);

    let mut state = state.write().await;
    if state.memory.delete(id) {
        let _ = state.memory.save();
        let response = serde_json::json!({
            "id": id,
            "status": "forgotten"
        });
        Frame::new(Verb::Ok, Payload::from_string(&response.to_string()))
    } else {
        Frame::error(&format!("Memory not found: {id}"))
    }
}

/// Handle AUDIO verb - Store acoustic memory from liquid-rust
/// Payload format 1 (full AcousticMemory): [AYE8 magic][serialized bytes]
/// Payload format 2 (simple): [text string][valence byte][arousal byte]
async fn handle_audio(payload: Payload, state: &Arc<RwLock<DaemonState>>) -> Frame {
    let data = payload.as_bytes();

    // Check for AYE8 magic (full AcousticMemory from liquid-rust)
    if data.len() > 4 && &data[0..4] == b"AYE8" {
        // Full acoustic memory format - extract text and emotion
        // Parse: magic(4) + version(1) + emotion(12) + salience(4) + voice_conf(4) + duration(4) + f0(4) + text_len(4) + text
        if data.len() < 37 {
            return Frame::error("AYE8 payload too short");
        }

        let valence = f32::from_le_bytes(data[5..9].try_into().unwrap_or([0; 4]));
        let arousal = f32::from_le_bytes(data[9..13].try_into().unwrap_or([0; 4]));
        let salience = f32::from_le_bytes(data[17..21].try_into().unwrap_or([0; 4]));
        let voice_conf = f32::from_le_bytes(data[21..25].try_into().unwrap_or([0; 4]));

        let text_len = u32::from_le_bytes(data[33..37].try_into().unwrap_or([0; 4])) as usize;
        if data.len() < 37 + text_len {
            return Frame::error("AYE8 text truncated");
        }

        let text = match String::from_utf8(data[37..37 + text_len].to_vec()) {
            Ok(t) => t,
            Err(_) => return Frame::error("Invalid UTF-8 in audio text"),
        };

        debug!(
            "AUDIO (AYE8) text_len={} valence={:.2} arousal={:.2} salience={:.2}",
            text.len(),
            valence,
            arousal,
            salience
        );

        // Store as memory with acoustic keywords
        let keywords = vec![
            "audio".to_string(),
            "voice".to_string(),
            if voice_conf > 0.7 { "clear" } else { "unclear" }.to_string(),
            if arousal > 0.7 { "excited" } else if arousal < 0.3 { "calm" } else { "neutral" }.to_string(),
        ];

        let mut state = state.write().await;
        match state.memory.anchor(
            text,
            keywords,
            MemoryType::Learning, // Audio insights are valuable
            valence,
            arousal,
            "audio".to_string(),
            None,
        ) {
            Ok(id) => {
                let _ = state.memory.save();
                let response = serde_json::json!({
                    "id": id,
                    "status": "anchored",
                    "source": "acoustic",
                    "salience": salience
                });
                Frame::new(Verb::Ok, Payload::from_string(&response.to_string()))
            }
            Err(e) => Frame::error(&format!("Audio store failed: {e}")),
        }
    } else {
        // Simple format: [text string][valence byte][arousal byte]
        let mut decoder = PayloadDecoder::new(&payload);

        let text = match decoder.string() {
            Some(t) if !t.is_empty() => t.to_string(),
            _ => return Frame::error("Text required for audio"),
        };

        let valence = decoder.byte().map(|b| (b as f32 - 127.5) / 127.5).unwrap_or(0.0);
        let arousal = decoder.byte().map(|b| b as f32 / 255.0).unwrap_or(0.5);

        debug!(
            "AUDIO (simple) text_len={} valence={:.2} arousal={:.2}",
            text.len(),
            valence,
            arousal
        );

        let keywords = vec!["audio".to_string(), "voice".to_string()];

        let mut state = state.write().await;
        match state.memory.anchor(
            text,
            keywords,
            MemoryType::Learning,
            valence,
            arousal,
            "audio".to_string(),
            None,
        ) {
            Ok(id) => {
                let _ = state.memory.save();
                let response = serde_json::json!({
                    "id": id,
                    "status": "anchored",
                    "source": "audio_simple"
                });
                Frame::new(Verb::Ok, Payload::from_string(&response.to_string()))
            }
            Err(e) => Frame::error(&format!("Audio store failed: {e}")),
        }
    }
}

/// Start the daemon
async fn start_daemon(config: DaemonConfig) -> Result<()> {
    // Remove stale socket
    if config.socket_path.exists() {
        std::fs::remove_file(&config.socket_path)
            .context("Failed to remove stale socket")?;
    }

    // Create listener
    let listener = UnixListener::bind(&config.socket_path)
        .context("Failed to bind socket")?;

    info!("STD listening on {:?}", config.socket_path);

    // Write PID file
    let pid = std::process::id();
    std::fs::write(&config.pid_path, pid.to_string())
        .context("Failed to write PID file")?;

    // Shared state
    let state = Arc::new(RwLock::new(DaemonState::new(config.clone())));

    // Accept connections
    loop {
        match listener.accept().await {
            Ok((stream, _addr)) => {
                let state = state.clone();
                tokio::spawn(async move {
                    if let Err(e) = handle_client(stream, state).await {
                        error!("Client error: {e}");
                    }
                });
            }
            Err(e) => {
                error!("Accept error: {e}");
            }
        }
    }
}

/// Check daemon status
fn check_status(config: &DaemonConfig) -> Result<bool> {
    if !config.pid_path.exists() {
        println!("STD is not running");
        return Ok(false);
    }

    let pid_str = std::fs::read_to_string(&config.pid_path)?;
    let pid: u32 = pid_str.trim().parse()?;

    // Check if process exists
    let proc_path = format!("/proc/{}", pid);
    if std::path::Path::new(&proc_path).exists() {
        println!("STD is running (PID {})", pid);
        Ok(true)
    } else {
        println!("STD is not running (stale PID file)");
        // Clean up stale files
        let _ = std::fs::remove_file(&config.pid_path);
        let _ = std::fs::remove_file(&config.socket_path);
        Ok(false)
    }
}

/// Stop the daemon
fn stop_daemon(config: &DaemonConfig) -> Result<()> {
    if !config.pid_path.exists() {
        println!("STD is not running");
        return Ok(());
    }

    let pid_str = std::fs::read_to_string(&config.pid_path)?;
    let pid: i32 = pid_str.trim().parse()?;

    // Send SIGTERM
    unsafe {
        libc::kill(pid, libc::SIGTERM);
    }

    // Wait a moment
    std::thread::sleep(std::time::Duration::from_millis(100));

    // Clean up
    let _ = std::fs::remove_file(&config.pid_path);
    let _ = std::fs::remove_file(&config.socket_path);

    println!("STD stopped");
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    // Parse command
    let args: Vec<String> = std::env::args().collect();
    let command = args.get(1).map(|s| s.as_str()).unwrap_or("start");

    let config = DaemonConfig::default();

    // Initialize logging
    tracing_subscriber::fmt()
        .with_env_filter(&config.log_level)
        .init();

    match command {
        "start" => {
            // Check if already running
            if check_status(&config)? {
                println!("STD is already running");
                return Ok(());
            }
            start_unified_daemon(config).await
        }
        "stop" => stop_daemon(&config),
        "status" => {
            check_status(&config)?;
            Ok(())
        }
        "restart" => {
            stop_daemon(&config)?;
            std::thread::sleep(std::time::Duration::from_millis(200));
            start_unified_daemon(config).await
        }
        "--help" | "-h" => {
            println!("STD - Smart Tree Daemon (Unified)");
            println!();
            println!("Usage: std <command>");
            println!();
            println!("Commands:");
            println!("  start    Start the daemon (HTTP + Unix socket)");
            println!("  stop     Stop the daemon");
            println!("  status   Check daemon status");
            println!("  restart  Restart the daemon");
            println!();
            println!("HTTP Endpoints (port 28428):");
            println!("  /cli/scan   - CLI thin-client scanning");
            println!("  /v1/*       - LLM Proxy (OpenAI-compatible)");
            println!("  /mcp/*      - HTTP MCP protocol");
            println!("  /dash       - Web dashboard");
            Ok(())
        }
        _ => {
            eprintln!("Unknown command: {}", command);
            eprintln!("Run 'std --help' for usage");
            std::process::exit(1);
        }
    }
}

/// Start unified daemon with both HTTP and Unix socket
async fn start_unified_daemon(socket_config: DaemonConfig) -> Result<()> {
    // Start HTTP daemon in background task
    let http_config = st::daemon::DaemonConfig {
        port: 28428,
        watch_paths: vec![std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))],
        orchestrator_url: None, // Foken credits disabled for now
        enable_credits: false,
        allow_external: false,
    };

    tokio::spawn(async move {
        if let Err(e) = st::daemon::start_daemon(http_config).await {
            error!("HTTP daemon error: {}", e);
        }
    });

    // Give HTTP daemon a moment to start
    tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;

    // Start Unix socket daemon (this blocks)
    start_daemon(socket_config).await
}