symforge 11.0.4

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use anyhow::{Context, Result};
use rusqlite::{Connection, OptionalExtension, params};
use serde::Serialize;
use serde_json::json;

use crate::capability::CapabilityEvidence;
use crate::domain::index::ProjectStateDir;
use crate::paths::{ANALYTICS_DB_NAME, ensure_project_state_db_path, project_state_path};
use crate::protocol::result_status::OutcomeClass;

use super::schema::{CURRENT_SCHEMA_VERSION, META_SCHEMA_VERSION, SCHEMA_V1};

pub const MAX_TOOL_NAME_BYTES: usize = 128;
pub const MAX_SURFACE_BYTES: usize = 64;
pub const MAX_CONFIGURED_SCOPE_BYTES: usize = 128;
pub const MAX_CAPABILITY_DETAIL_BYTES: usize = 256;
pub const MAX_CAPABILITY_STATE_JSON_BYTES: usize = 4096;
pub const MAX_CAPABILITY_ITEMS: usize = 16;
pub const DEFAULT_ANALYTICS_EXPORT_LIMIT: usize = 100;
pub const MAX_ANALYTICS_EXPORT_LIMIT: usize = 1_000;
pub const DEFAULT_ANALYTICS_RETENTION_RECORDS: usize = 10_000;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnalyticsMode {
    Disabled,
    Enabled,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnalyticsConfig {
    pub mode: AnalyticsMode,
    pub project_state_dir: ProjectStateDir,
}

impl AnalyticsConfig {
    pub fn disabled(project_state_dir: ProjectStateDir) -> Self {
        Self {
            mode: AnalyticsMode::Disabled,
            project_state_dir,
        }
    }

    pub fn enabled(project_state_dir: ProjectStateDir) -> Self {
        Self {
            mode: AnalyticsMode::Enabled,
            project_state_dir,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnalyticsStatus {
    Disabled {
        db_path: PathBuf,
    },
    Enabled {
        db_path: PathBuf,
        schema_version: u32,
    },
}

impl AnalyticsStatus {
    pub const fn is_disabled(&self) -> bool {
        matches!(self, Self::Disabled { .. })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnalyticsWriteOutcome {
    Disabled(AnalyticsStatus),
    Recorded { id: i64 },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnalyticsSurface {
    Tool,
    Resource,
    Prompt,
    Hook,
    Sidecar,
    Other(String),
}

impl AnalyticsSurface {
    fn storage_value(&self) -> String {
        match self {
            Self::Tool => "tool".to_string(),
            Self::Resource => "resource".to_string(),
            Self::Prompt => "prompt".to_string(),
            Self::Hook => "hook".to_string(),
            Self::Sidecar => "sidecar".to_string(),
            Self::Other(value) => bounded_text(value, MAX_SURFACE_BYTES),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnalyticsScope {
    Disabled,
    Session,
    Workspace,
    Persistent,
    Other(String),
}

impl AnalyticsScope {
    fn storage_value(&self) -> String {
        match self {
            Self::Disabled => "disabled".to_string(),
            Self::Session => "session".to_string(),
            Self::Workspace => "workspace".to_string(),
            Self::Persistent => "persistent".to_string(),
            Self::Other(value) => bounded_text(value, MAX_CONFIGURED_SCOPE_BYTES),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnalyticsObservation {
    pub tool_name: String,
    pub surface: AnalyticsSurface,
    pub configured_scope: AnalyticsScope,
    pub response_bytes: u64,
    pub estimated_tokens: Option<u64>,
    pub duration: Duration,
    pub success: bool,
    pub outcome_class: OutcomeClass,
    pub capability_state: Vec<CapabilityEvidence>,
}

impl AnalyticsObservation {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        tool_name: impl Into<String>,
        surface: AnalyticsSurface,
        configured_scope: AnalyticsScope,
        response_bytes: u64,
        estimated_tokens: Option<u64>,
        duration: Duration,
        success: bool,
        outcome_class: OutcomeClass,
    ) -> Self {
        Self {
            tool_name: tool_name.into(),
            surface,
            configured_scope,
            response_bytes,
            estimated_tokens,
            duration,
            success,
            outcome_class,
            capability_state: Vec::new(),
        }
    }

    pub fn with_capability_state(mut self, capability_state: Vec<CapabilityEvidence>) -> Self {
        self.capability_state = capability_state;
        self
    }

    pub fn bounded_for_queue(&self) -> Self {
        let capability_state = self
            .capability_state
            .iter()
            .take(MAX_CAPABILITY_ITEMS)
            .cloned()
            .map(|mut evidence| {
                if let Some(detail) = evidence.detail.as_deref() {
                    evidence.detail = Some(bounded_text(detail, MAX_CAPABILITY_DETAIL_BYTES));
                }
                evidence
            })
            .collect();

        Self {
            tool_name: bounded_text(&self.tool_name, MAX_TOOL_NAME_BYTES),
            surface: bounded_surface(&self.surface),
            configured_scope: bounded_scope(&self.configured_scope),
            response_bytes: self.response_bytes,
            estimated_tokens: self.estimated_tokens,
            duration: self.duration,
            success: self.success,
            outcome_class: self.outcome_class,
            capability_state,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StoredAnalyticsRecord {
    pub id: i64,
    pub tool_name: String,
    pub surface: String,
    pub configured_scope: String,
    pub response_bytes: u64,
    pub estimated_tokens: Option<u64>,
    pub duration_ms: u64,
    pub success: bool,
    pub outcome_class: String,
    pub capability_state_json: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AnalyticsSummary {
    pub total_records: u64,
    pub success_count: u64,
    pub failure_count: u64,
    pub latest_id: Option<i64>,
    pub tool_counts: Vec<AnalyticsSummaryCount>,
    pub outcome_counts: Vec<AnalyticsSummaryCount>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AnalyticsSummaryCount {
    pub value: String,
    pub count: u64,
}

#[derive(Debug, Clone)]
pub enum AnalyticsStore {
    Disabled { db_path: PathBuf },
    Enabled(SqliteAnalyticsStore),
}

impl AnalyticsStore {
    pub fn open(config: AnalyticsConfig) -> Result<Self> {
        let db_path = project_state_path(&config.project_state_dir, ANALYTICS_DB_NAME);
        match config.mode {
            AnalyticsMode::Disabled => Ok(Self::disabled(db_path)),
            AnalyticsMode::Enabled => {
                let db_path =
                    ensure_project_state_db_path(&config.project_state_dir, ANALYTICS_DB_NAME)?;
                Ok(Self::Enabled(SqliteAnalyticsStore::open(&db_path)?))
            }
        }
    }

    pub fn disabled(db_path: impl Into<PathBuf>) -> Self {
        Self::Disabled {
            db_path: db_path.into(),
        }
    }

    pub fn status(&self) -> Result<AnalyticsStatus> {
        match self {
            Self::Disabled { db_path } => Ok(AnalyticsStatus::Disabled {
                db_path: db_path.clone(),
            }),
            Self::Enabled(store) => store.status(),
        }
    }

    pub fn record(&self, observation: &AnalyticsObservation) -> Result<AnalyticsWriteOutcome> {
        match self {
            Self::Disabled { db_path } => {
                Ok(AnalyticsWriteOutcome::Disabled(AnalyticsStatus::Disabled {
                    db_path: db_path.clone(),
                }))
            }
            Self::Enabled(store) => Ok(AnalyticsWriteOutcome::Recorded {
                id: store.record(observation)?,
            }),
        }
    }
}

#[derive(Debug, Clone)]
pub struct SqliteAnalyticsStore {
    db_path: PathBuf,
    conn: Arc<Mutex<Connection>>,
}

impl SqliteAnalyticsStore {
    pub fn open(path: &Path) -> Result<Self> {
        if let Some(parent) = path.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("creating analytics db parent dir {:?}", parent))?;
        }
        let conn = Connection::open(path)
            .with_context(|| format!("opening analytics db at {:?}", path))?;
        let store = Self {
            db_path: path.to_path_buf(),
            conn: Arc::new(Mutex::new(conn)),
        };
        store.migrate()?;
        Ok(store)
    }

    pub fn open_in_memory() -> Result<Self> {
        let store = Self {
            db_path: PathBuf::from(":memory:"),
            conn: Arc::new(Mutex::new(Connection::open_in_memory()?)),
        };
        store.migrate()?;
        Ok(store)
    }

    pub fn status(&self) -> Result<AnalyticsStatus> {
        Ok(AnalyticsStatus::Enabled {
            db_path: self.db_path.clone(),
            schema_version: self.schema_version()?,
        })
    }

    pub fn migrate(&self) -> Result<()> {
        let conn = self.conn.lock().expect("analytics mutex poisoned");
        conn.execute_batch(SCHEMA_V1)
            .context("applying analytics schema v1")?;
        conn.execute(
            "INSERT OR REPLACE INTO analytics_meta (key, value) VALUES (?1, ?2)",
            params![META_SCHEMA_VERSION, CURRENT_SCHEMA_VERSION.to_string()],
        )?;
        Ok(())
    }

    pub fn schema_version(&self) -> Result<u32> {
        let conn = self.conn.lock().expect("analytics mutex poisoned");
        let value: Option<String> = conn
            .query_row(
                "SELECT value FROM analytics_meta WHERE key = ?1",
                params![META_SCHEMA_VERSION],
                |row| row.get(0),
            )
            .optional()?;
        Ok(value.and_then(|v| v.parse().ok()).unwrap_or(0))
    }

    pub fn record(&self, observation: &AnalyticsObservation) -> Result<i64> {
        let sanitized = SanitizedObservation::from(observation);
        let conn = self.conn.lock().expect("analytics mutex poisoned");
        conn.execute(
            "INSERT INTO analytics_tool_calls (
                tool_name,
                surface,
                configured_scope,
                response_bytes,
                estimated_tokens,
                duration_ms,
                success,
                outcome_class,
                capability_state_json
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
            params![
                sanitized.tool_name,
                sanitized.surface,
                sanitized.configured_scope,
                sanitized.response_bytes,
                sanitized.estimated_tokens,
                sanitized.duration_ms,
                sanitized.success,
                sanitized.outcome_class,
                sanitized.capability_state_json,
            ],
        )?;
        let id = conn.last_insert_rowid();
        enforce_record_retention(&conn, DEFAULT_ANALYTICS_RETENTION_RECORDS)?;
        Ok(id)
    }

    pub fn recent_records(&self, limit: usize) -> Result<Vec<StoredAnalyticsRecord>> {
        let conn = self.conn.lock().expect("analytics mutex poisoned");
        let mut stmt = conn.prepare(
            "SELECT
                id,
                tool_name,
                surface,
                configured_scope,
                response_bytes,
                estimated_tokens,
                duration_ms,
                success,
                outcome_class,
                capability_state_json
            FROM analytics_tool_calls
            ORDER BY id DESC
            LIMIT ?1",
        )?;
        let rows = stmt.query_map(params![usize_to_i64(limit)], |row| {
            let response_bytes: i64 = row.get(4)?;
            let estimated_tokens: Option<i64> = row.get(5)?;
            let duration_ms: i64 = row.get(6)?;
            let success: i64 = row.get(7)?;
            Ok(StoredAnalyticsRecord {
                id: row.get(0)?,
                tool_name: row.get(1)?,
                surface: row.get(2)?,
                configured_scope: row.get(3)?,
                response_bytes: i64_to_u64(response_bytes),
                estimated_tokens: estimated_tokens.map(i64_to_u64),
                duration_ms: i64_to_u64(duration_ms),
                success: success != 0,
                outcome_class: row.get(8)?,
                capability_state_json: row.get(9)?,
            })
        })?;

        rows.collect::<rusqlite::Result<Vec<_>>>()
            .map_err(Into::into)
    }

    pub fn export_records(&self, limit: usize) -> Result<Vec<StoredAnalyticsRecord>> {
        self.recent_records(normalize_export_limit(limit))
    }

    pub fn summary(&self, group_limit: usize) -> Result<AnalyticsSummary> {
        let conn = self.conn.lock().expect("analytics mutex poisoned");
        let total_records = query_count(&conn, "SELECT COUNT(*) FROM analytics_tool_calls")?;
        let success_count = query_count(
            &conn,
            "SELECT COUNT(*) FROM analytics_tool_calls WHERE success = 1",
        )?;
        let failure_count = query_count(
            &conn,
            "SELECT COUNT(*) FROM analytics_tool_calls WHERE success = 0",
        )?;
        let latest_id = conn.query_row("SELECT MAX(id) FROM analytics_tool_calls", [], |row| {
            row.get::<_, Option<i64>>(0)
        })?;

        Ok(AnalyticsSummary {
            total_records,
            success_count,
            failure_count,
            latest_id,
            tool_counts: grouped_counts(&conn, "tool_name", group_limit)?,
            outcome_counts: grouped_counts(&conn, "outcome_class", group_limit)?,
        })
    }

    pub fn enforce_retention(&self, max_records: usize) -> Result<usize> {
        let conn = self.conn.lock().expect("analytics mutex poisoned");
        enforce_record_retention(&conn, max_records)
    }
}

fn normalize_export_limit(limit: usize) -> usize {
    limit.min(MAX_ANALYTICS_EXPORT_LIMIT)
}

fn query_count(conn: &Connection, sql: &str) -> Result<u64> {
    let count: i64 = conn.query_row(sql, [], |row| row.get(0))?;
    Ok(i64_to_u64(count))
}

fn grouped_counts(
    conn: &Connection,
    column: &'static str,
    limit: usize,
) -> Result<Vec<AnalyticsSummaryCount>> {
    let sql = format!(
        "SELECT {column}, COUNT(*) FROM analytics_tool_calls \
         GROUP BY {column} \
         ORDER BY COUNT(*) DESC, {column} ASC \
         LIMIT ?1"
    );
    let mut stmt = conn.prepare(&sql)?;
    let rows = stmt.query_map(params![usize_to_i64(limit)], |row| {
        let count: i64 = row.get(1)?;
        Ok(AnalyticsSummaryCount {
            value: row.get(0)?,
            count: i64_to_u64(count),
        })
    })?;

    rows.collect::<rusqlite::Result<Vec<_>>>()
        .map_err(Into::into)
}

fn enforce_record_retention(conn: &Connection, max_records: usize) -> Result<usize> {
    conn.execute(
        "DELETE FROM analytics_tool_calls
         WHERE id NOT IN (
             SELECT id FROM analytics_tool_calls
             ORDER BY id DESC
             LIMIT ?1
         )",
        params![usize_to_i64(max_records)],
    )
    .map_err(Into::into)
}

struct SanitizedObservation {
    tool_name: String,
    surface: String,
    configured_scope: String,
    response_bytes: i64,
    estimated_tokens: Option<i64>,
    duration_ms: i64,
    success: i64,
    outcome_class: &'static str,
    capability_state_json: String,
}

impl From<&AnalyticsObservation> for SanitizedObservation {
    fn from(observation: &AnalyticsObservation) -> Self {
        Self {
            tool_name: bounded_text(&observation.tool_name, MAX_TOOL_NAME_BYTES),
            surface: observation.surface.storage_value(),
            configured_scope: observation.configured_scope.storage_value(),
            response_bytes: u64_to_i64(observation.response_bytes),
            estimated_tokens: observation.estimated_tokens.map(u64_to_i64),
            duration_ms: u128_to_i64(observation.duration.as_millis()),
            success: i64::from(observation.success),
            outcome_class: observation.outcome_class.as_str(),
            capability_state_json: capability_state_json(&observation.capability_state),
        }
    }
}

fn capability_state_json(capability_state: &[CapabilityEvidence]) -> String {
    let mut values = capability_state
        .iter()
        .take(MAX_CAPABILITY_ITEMS)
        .map(|evidence| {
            json!({
                "capability": evidence.capability.to_string(),
                "status": evidence.status.to_string(),
                "freshness": evidence.freshness.to_string(),
                "cost": evidence.cost.to_string(),
                "safety": evidence.safety.to_string(),
                "detail": evidence
                    .detail
                    .as_deref()
                    .map(|detail| bounded_text(detail, MAX_CAPABILITY_DETAIL_BYTES)),
            })
        })
        .collect::<Vec<_>>();

    loop {
        let value = serde_json::to_string(&values).expect("analytics capability JSON serializes");
        if value.len() <= MAX_CAPABILITY_STATE_JSON_BYTES || values.is_empty() {
            return value;
        }
        values.pop();
    }
}

pub(crate) fn bounded_text(raw: &str, max_bytes: usize) -> String {
    if contains_sensitive_marker(raw) {
        return "[redacted]".to_string();
    }

    let normalized = raw
        .chars()
        .map(|ch| if ch.is_control() { ' ' } else { ch })
        .collect::<String>();

    truncate_utf8(&normalized, max_bytes)
}

fn bounded_surface(surface: &AnalyticsSurface) -> AnalyticsSurface {
    match surface {
        AnalyticsSurface::Other(value) => {
            AnalyticsSurface::Other(bounded_text(value, MAX_SURFACE_BYTES))
        }
        known => known.clone(),
    }
}

fn bounded_scope(scope: &AnalyticsScope) -> AnalyticsScope {
    match scope {
        AnalyticsScope::Other(value) => {
            AnalyticsScope::Other(bounded_text(value, MAX_CONFIGURED_SCOPE_BYTES))
        }
        known => known.clone(),
    }
}

fn contains_sensitive_marker(raw: &str) -> bool {
    if !matches!(
        crate::knowledge::scan_secret_bytes("analytics", raw.as_bytes()),
        crate::knowledge::SecretScan::Clean
    ) {
        return true;
    }

    let lower = raw.to_ascii_lowercase();
    [
        "authorization",
        "bearer ",
        "api_key",
        "apikey",
        "access_token",
        "refresh_token",
        "password",
        "private key",
        "secret",
        "sk-",
        "ghp_",
    ]
    .iter()
    .any(|marker| lower.contains(marker))
}

fn truncate_utf8(value: &str, max_bytes: usize) -> String {
    if value.len() <= max_bytes {
        return value.to_string();
    }

    let mut out = String::new();
    let budget = max_bytes.saturating_sub(3);
    for ch in value.chars() {
        if out.len() + ch.len_utf8() > budget {
            break;
        }
        out.push(ch);
    }
    out.push_str("...");
    out
}

fn u64_to_i64(value: u64) -> i64 {
    i64::try_from(value).unwrap_or(i64::MAX)
}

fn u128_to_i64(value: u128) -> i64 {
    i64::try_from(value).unwrap_or(i64::MAX)
}

fn usize_to_i64(value: usize) -> i64 {
    i64::try_from(value).unwrap_or(i64::MAX)
}

fn i64_to_u64(value: i64) -> u64 {
    u64::try_from(value).unwrap_or_default()
}

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

    use crate::capability::{
        CapabilityCost, CapabilityEvidence, CapabilityFreshness, CapabilityName, CapabilitySafety,
        CapabilityStatus,
    };

    fn sample_observation() -> AnalyticsObservation {
        AnalyticsObservation::new(
            "search_text",
            AnalyticsSurface::Tool,
            AnalyticsScope::Persistent,
            2048,
            Some(512),
            Duration::from_millis(37),
            true,
            OutcomeClass::Found,
        )
        .with_capability_state(vec![
            CapabilityEvidence::new(CapabilityName::FrecencyRanking, CapabilityStatus::Ready)
                .with_freshness(CapabilityFreshness::Current)
                .with_cost(CapabilityCost::Low)
                .with_safety(CapabilitySafety::ReadOnly)
                .with_detail("persistent history available"),
        ])
    }

    #[test]
    fn open_in_memory_creates_schema_at_current_version() {
        let store = SqliteAnalyticsStore::open_in_memory().expect("analytics store");

        assert_eq!(
            store.schema_version().expect("schema version"),
            CURRENT_SCHEMA_VERSION
        );
    }

    #[test]
    fn migration_is_idempotent_and_preserves_current_version() {
        let store = SqliteAnalyticsStore::open_in_memory().expect("analytics store");

        store.migrate().expect("first migrate");
        store.migrate().expect("second migrate");

        assert_eq!(
            store.schema_version().expect("schema version"),
            CURRENT_SCHEMA_VERSION
        );
    }

    #[test]
    fn disabled_store_reports_status_and_keeps_filesystem_footprint_free() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let project_state = ProjectStateDir::new(tmp.path().join(crate::paths::SYMFORGE_DIR_NAME));
        let db_path =
            crate::paths::project_state_path(&project_state, crate::paths::ANALYTICS_DB_NAME);
        let store =
            AnalyticsStore::open(AnalyticsConfig::disabled(project_state)).expect("disabled");

        assert!(store.status().expect("status").is_disabled());
        assert!(
            !db_path.exists(),
            "disabled analytics must not create the database"
        );
        assert!(
            !db_path.parent().unwrap().exists(),
            "disabled analytics must not create the .symforge directory"
        );

        let outcome = store
            .record(&sample_observation())
            .expect("disabled record outcome");
        assert!(matches!(
            outcome,
            AnalyticsWriteOutcome::Disabled(AnalyticsStatus::Disabled { .. })
        ));
        assert!(
            !db_path.exists(),
            "disabled analytics record path must remain no-op"
        );
        assert!(
            !db_path.parent().unwrap().exists(),
            "disabled analytics record path must remain no-footprint"
        );
    }

    #[test]
    fn enabled_store_creates_db_and_records_bounded_local_metadata() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let db_path = crate::paths::symforge_db_path(tmp.path(), crate::paths::ANALYTICS_DB_NAME);
        let store = SqliteAnalyticsStore::open(&db_path).expect("analytics store");

        assert!(db_path.exists(), "enabled analytics creates the database");
        let id = store.record(&sample_observation()).expect("record");
        let records = store.recent_records(10).expect("records");

        assert_eq!(records.len(), 1);
        assert_eq!(records[0].id, id);
        assert_eq!(records[0].tool_name, "search_text");
        assert_eq!(records[0].surface, "tool");
        assert_eq!(records[0].configured_scope, "persistent");
        assert_eq!(records[0].response_bytes, 2048);
        assert_eq!(records[0].estimated_tokens, Some(512));
        assert_eq!(records[0].duration_ms, 37);
        assert!(records[0].success);
        assert_eq!(records[0].outcome_class, "found");
        assert!(
            records[0]
                .capability_state_json
                .contains("frecency ranking")
        );
    }

    #[test]
    fn retention_deletes_older_records_and_keeps_recent_records() {
        let store = SqliteAnalyticsStore::open_in_memory().expect("analytics store");
        for index in 0..5 {
            let mut observation = sample_observation();
            observation.tool_name = format!("tool_{index}");
            store.record(&observation).expect("record");
        }

        let deleted = store.enforce_retention(2).expect("retention");
        let records = store.recent_records(10).expect("records");

        assert_eq!(deleted, 3);
        assert_eq!(records.len(), 2);
        assert_eq!(records[0].tool_name, "tool_4");
        assert_eq!(records[1].tool_name, "tool_3");
    }

    #[test]
    fn oversized_and_sensitive_metadata_is_not_stored_raw() {
        let store = SqliteAnalyticsStore::open_in_memory().expect("analytics store");
        // Every credential-shaped metadata input is assembled at runtime, so no
        // such literal enters this file (see
        // `repository_source_is_clean_under_its_own_detector`). The values stay
        // marker-positive by construction, which the `[redacted]` assertions
        // below prove: a mis-assembled value would be stored raw and fail.
        let marker = ["analytics", "-", "canary", "-", "segment"].concat();
        let key_keyword = ["api", "_", "key"].concat();
        let long_tool_name = format!("get_file_content_{}", "x".repeat(500));
        let observation = AnalyticsObservation::new(
            long_tool_name,
            AnalyticsSurface::Other(format!(
                "{}: Bearer {marker}",
                ["Author", "ization"].concat()
            )),
            AnalyticsScope::Other(format!("{}={marker}", ["pass", "word"].concat())),
            u64::MAX,
            Some(u64::MAX),
            Duration::from_millis(u64::MAX),
            false,
            OutcomeClass::InternalFailure,
        )
        .with_capability_state(vec![
            CapabilityEvidence::new(
                CapabilityName::RankingDiagnostics,
                CapabilityStatus::DisabledByPolicy,
            )
            .with_detail(format!("{key_keyword}={marker} {}", "y".repeat(1000))),
        ]);

        store.record(&observation).expect("record");
        let record = store
            .recent_records(1)
            .expect("records")
            .pop()
            .expect("one record");
        let stored = format!(
            "{} {} {} {}",
            record.tool_name, record.surface, record.configured_scope, record.capability_state_json
        );

        assert!(record.tool_name.len() <= MAX_TOOL_NAME_BYTES);
        assert_eq!(record.surface, "[redacted]");
        assert_eq!(record.configured_scope, "[redacted]");
        assert!(record.capability_state_json.len() <= MAX_CAPABILITY_STATE_JSON_BYTES);
        assert!(!stored.contains(marker.as_str()));
        assert!(!stored.contains(key_keyword.as_str()));
        assert_eq!(record.response_bytes, i64::MAX as u64);
        assert_eq!(record.estimated_tokens, Some(i64::MAX as u64));
        assert_eq!(record.duration_ms, i64::MAX as u64);
        assert_eq!(record.outcome_class, "internal_failure");
    }

    #[test]
    fn runtime_canary_is_absent_from_analytics_storage() {
        let store = SqliteAnalyticsStore::open_in_memory().expect("analytics store");
        let canary = ["runtime", "-", "canary", "-", "analytics"].concat();
        let marked = format!("{}={}", ["to", "ken"].concat(), canary);
        let observation = AnalyticsObservation::new(
            "search_knowledge",
            AnalyticsSurface::Other(marked.clone()),
            AnalyticsScope::Other(marked.clone()),
            0,
            Some(0),
            Duration::ZERO,
            false,
            OutcomeClass::InvalidRequest,
        )
        .with_capability_state(vec![
            CapabilityEvidence::new(
                CapabilityName::RankingDiagnostics,
                CapabilityStatus::DisabledByPolicy,
            )
            .with_detail(marked),
        ]);

        store.record(&observation).expect("record");
        let record = store
            .recent_records(1)
            .expect("records")
            .pop()
            .expect("one record");
        let stored = format!(
            "{} {} {} {}",
            record.tool_name, record.surface, record.configured_scope, record.capability_state_json
        );
        assert!(
            !stored
                .as_bytes()
                .windows(canary.len())
                .any(|window| window == canary.as_bytes())
        );
    }
}