chasm-cli 2.0.0

Universal chat session manager - harvest, merge, and analyze AI chat history from VS Code, Cursor, and other editors
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
// Copyright (c) 2024-2026 Nervosys LLC
// SPDX-License-Identifier: AGPL-3.0-only
//! Command implementations for `chasm schema` subcommands.

use crate::schema::{Ontology, RelationshipKind, SchemaRegistry, SemanticTag};
use crate::workspace;
use anyhow::{Context, Result};
use colored::*;
use std::path::Path;

/// `chasm schema list` — List all known provider schemas
pub fn schema_list(provider: Option<&str>, json: bool) -> Result<()> {
    let registry = SchemaRegistry::new();
    let schemas = match provider {
        Some(p) => registry.schemas_for_provider(p),
        None => registry.list_schemas(),
    };

    if json {
        let json_schemas: Vec<_> = schemas
            .iter()
            .map(|s: &&crate::schema::ProviderSchema| {
                serde_json::json!({
                    "id": s.id(),
                    "provider": s.version.provider,
                    "format": s.version.format.as_str(),
                    "version": s.version.version,
                    "label": s.version.label,
                    "fields": s.field_count(),
                    "db_keys": s.db_keys.len(),
                    "extension_min": s.extension_version_min,
                    "extension_max": s.extension_version_max,
                    "host_min": s.host_version_min,
                    "introduced": s.introduced,
                    "deprecated": s.deprecated,
                    "tags": s.tags,
                })
            })
            .collect();

        println!("{}", serde_json::to_string_pretty(&json_schemas)?);
        return Ok(());
    }

    println!(
        "{} {} registered schemas\n",
        "Schema Registry:".bold(),
        schemas.len()
    );

    for schema in &schemas {
        let status = if schema.deprecated.is_some() {
            "DEPRECATED".red()
        } else {
            "ACTIVE".green()
        };

        println!(
            "  {} {} [{}]",
            schema.id().bold().cyan(),
            schema.version.label.dimmed(),
            status
        );

        // Version range
        if let (Some(min), Some(max)) =
            (&schema.extension_version_min, &schema.extension_version_max)
        {
            println!("    Extension: {}{}", min, max);
        } else if let Some(min) = &schema.extension_version_min {
            println!("    Extension: {}+", min);
        }

        if let Some(host) = &schema.host_version_min {
            println!("    Host:      VS Code {}", host);
        }

        println!(
            "    Format:    {} | {} fields | {} DB keys",
            schema.version.format.as_str(),
            schema.field_count(),
            schema.db_keys.len()
        );

        if let Some(intro) = &schema.introduced {
            print!("    Introduced: {}", intro);
            if let Some(dep) = &schema.deprecated {
                print!(" | Deprecated: {}", dep);
            }
            println!();
        }

        println!("    Tags:      {}", schema.tags.join(", ").dimmed());
        println!();
    }

    Ok(())
}

/// `chasm schema show` — Show detailed schema for a specific version
pub fn schema_show(schema_id: &str, json: bool) -> Result<()> {
    let registry = SchemaRegistry::new();

    let schema = registry.get_schema(schema_id).ok_or_else(|| {
        anyhow::anyhow!(
            "Unknown schema: '{}'. Use 'chasm schema list' to see available schemas.",
            schema_id
        )
    })?;

    if json {
        println!("{}", serde_json::to_string_pretty(schema)?);
        return Ok(());
    }

    println!("{}", format!("Schema: {}", schema.id()).bold().cyan());
    println!("{}", "=".repeat(60));
    println!("  Label:   {}", schema.version.label);
    println!("  Provider: {}", schema.version.provider);
    println!("  Format:  {}", schema.version.format);
    println!("  Version: {}", schema.version.version);

    if let (Some(min), Some(max)) = (&schema.extension_version_min, &schema.extension_version_max) {
        println!("  Extension Range: {}{}", min, max);
    } else if let Some(min) = &schema.extension_version_min {
        println!("  Extension: {}+", min);
    }

    if let Some(host) = &schema.host_version_min {
        println!("  Host Min: VS Code {}", host);
    }

    // Storage
    println!("\n{}", "Storage".bold());
    println!("  {}", schema.storage.description);
    println!("  Pattern: {}", schema.storage.path_pattern.dimmed());
    for (platform, path) in &schema.storage.platform_paths {
        println!("    {}: {}", platform, path.as_str().dimmed());
    }

    // Session fields
    println!(
        "\n{} ({} fields)",
        "Session Fields".bold(),
        schema.session_schema.fields.len()
    );
    for field in &schema.session_schema.fields {
        let req = if field.required { "*" } else { " " };
        let tag = field
            .semantic_tag
            .as_deref()
            .map(|t| format!(" [{}]", t))
            .unwrap_or_default();

        println!(
            "  {} {} : {}{}",
            req,
            field.name.bold(),
            field.data_type,
            tag.dimmed()
        );
        println!("    {}", field.description.dimmed());
    }

    // Nested objects
    for (name, fields) in &schema.session_schema.nested_objects {
        println!(
            "\n{} ({} fields)",
            format!("  {}", name).bold(),
            fields.len()
        );
        for field in fields {
            let req = if field.required { "*" } else { " " };
            println!("    {} {} : {}", req, field.name.bold(), field.data_type);
            println!("      {}", field.description.dimmed());
        }
    }

    // DB keys
    if !schema.db_keys.is_empty() {
        println!(
            "\n{} ({} keys)",
            "Database Keys".bold(),
            schema.db_keys.len()
        );
        for key in &schema.db_keys {
            let req = if key.required { "*" } else { " " };
            println!("  {} {}", req, key.key.bold().yellow());
            println!("    {}", key.description.dimmed());
            if !key.value_fields.is_empty() {
                for vf in &key.value_fields {
                    println!("{} : {}", vf.name, vf.data_type);
                }
            }
        }
    }

    // Notes
    if !schema.notes.is_empty() {
        println!("\n{}", "Notes".bold());
        for note in &schema.notes {
            println!("{}", note);
        }
    }

    // Breaking changes
    if !schema.breaking_changes.is_empty() {
        println!("\n{}", "Breaking Changes".bold().red());
        for change in &schema.breaking_changes {
            println!("  \u{26a0} {}", change.as_str().yellow());
        }
    }

    // Example
    if let Some(example) = &schema.session_schema.example {
        println!("\n{}", "Example".bold());
        println!("{}", serde_json::to_string_pretty(example)?);
    }

    Ok(())
}

/// `chasm schema detect` — Auto-detect schema for a workspace or file
pub fn schema_detect(path: Option<&str>, workspace_id: Option<&str>, json: bool) -> Result<()> {
    let registry = SchemaRegistry::new();

    let detected = if let Some(ws_id) = workspace_id {
        // Resolve by workspace hash
        let storage_path = workspace::get_workspace_storage_path()?;
        let ws_dir = storage_path.join(ws_id);
        if !ws_dir.exists() {
            anyhow::bail!("Workspace directory not found: {}", ws_dir.display());
        }
        registry.detect_schema_from_workspace(&ws_dir)?
    } else {
        // Resolve by path
        let resolved_path = resolve_detect_path(path)?;
        let p = Path::new(&resolved_path);

        if p.is_dir() {
            // Check if this is a workspace storage dir or project path
            if p.join("chatSessions").exists() {
                registry.detect_schema_from_workspace(p)?
            } else {
                // Try to find the workspace for this project path
                if let Some((_hash, ws_path, _title)) =
                    workspace::find_workspace_by_path(&resolved_path)?
                {
                    registry.detect_schema_from_workspace(&ws_path)?
                } else {
                    anyhow::bail!(
                        "No workspace found for project path: {}. Use --workspace-id instead.",
                        resolved_path
                    );
                }
            }
        } else {
            // Single file
            registry.detect_schema_from_file(p)?
        }
    };

    if json {
        println!("{}", serde_json::to_string_pretty(&detected)?);
        return Ok(());
    }

    let confidence_color = if detected.confidence >= 0.9 {
        "green"
    } else if detected.confidence >= 0.7 {
        "yellow"
    } else {
        "red"
    };

    println!("{}", "Schema Detection Result".bold());
    println!("{}", "-".repeat(40));
    println!("  Schema:     {}", detected.schema_id.bold().cyan());
    let pct_str = format!("{:.0}%", detected.confidence * 100.0);
    let colored_confidence = match confidence_color {
        "green" => pct_str.green(),
        "yellow" => pct_str.yellow(),
        _ => pct_str.red(),
    };
    println!("  Confidence: {}", colored_confidence);

    if let Some(ver) = &detected.detected_version {
        println!("  Extension:  {}", ver);
    }

    println!("\n  {}", "Evidence:".bold());
    for ev in &detected.evidence {
        println!("{}", ev);
    }

    // Show schema summary if found
    if let Some(schema) = registry.get_schema(&detected.schema_id) {
        println!("\n  {}", "Schema Details:".bold());
        println!("    Label:  {}", schema.version.label);
        println!("    Format: {}", schema.version.format);
        println!("    Fields: {}", schema.field_count());
        if !schema.db_keys.is_empty() {
            println!("    DB Keys: {}", schema.db_keys.len());
        }
    }

    Ok(())
}

/// `chasm schema export` — Export full registry + ontology as JSON
pub fn schema_export(compact: bool, output: Option<&str>) -> Result<()> {
    let registry = SchemaRegistry::new();

    let json = if compact {
        registry.to_json_compact()?
    } else {
        registry.to_json()?
    };

    if let Some(output_path) = output {
        std::fs::write(output_path, &json)?;
        println!("Schema registry exported to {}", output_path);
    } else {
        println!("{}", json);
    }

    Ok(())
}

/// `chasm schema ontology` — Show the ontology (entity types, relationships, semantic tags)
pub fn schema_ontology(json_output: bool) -> Result<()> {
    let ontology = Ontology::build();

    if json_output {
        println!("{}", serde_json::to_string_pretty(&ontology)?);
        return Ok(());
    }

    println!(
        "{}",
        format!("Ontology v{}", ontology.version).bold().cyan()
    );
    println!("{}", "=".repeat(60));

    // Entity types
    let entity_types = ontology.entity_types();
    println!("\n{} ({})", "Entity Types".bold(), entity_types.len());
    for et in &entity_types {
        println!("{}", et);
    }

    // Relationships
    println!(
        "\n{} ({})",
        "Relationships".bold(),
        ontology.relationships.len()
    );
    for rel in &ontology.relationships {
        let arrow = match rel.kind {
            RelationshipKind::Contains => "──contains──▶",
            RelationshipKind::BelongsTo => "──belongs_to──▶",
            RelationshipKind::References => "──references──▶",
            RelationshipKind::MapsTo => "──maps_to──▶",
        };
        println!("  {} {} {}", rel.from, arrow, rel.to);
    }

    // Semantic tags by entity
    println!(
        "\n{} ({})",
        "Semantic Tags".bold(),
        ontology.semantic_tags.len()
    );
    let mut tags_by_entity: std::collections::HashMap<String, Vec<&SemanticTag>> =
        std::collections::HashMap::new();
    for tag in &ontology.semantic_tags {
        tags_by_entity
            .entry(format!("{}", tag.entity))
            .or_default()
            .push(tag);
    }
    let mut entity_keys: Vec<_> = tags_by_entity.keys().cloned().collect();
    entity_keys.sort();
    for entity in &entity_keys {
        println!("\n  {}:", entity.as_str().bold());
        for tag in &tags_by_entity[entity] {
            println!(
                "    {} : {}{}",
                tag.tag.cyan(),
                tag.canonical_type,
                tag.description.dimmed()
            );
        }
    }

    // Cross-provider mappings summary
    println!(
        "\n{} ({})",
        "Cross-Provider Mappings".bold(),
        ontology.mappings.len()
    );
    // Group by source→target pair
    let mut mapping_groups: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    for m in &ontology.mappings {
        let key = format!("{}{}", m.source_schema, m.target_schema);
        *mapping_groups.entry(key).or_default() += 1;
    }
    for (pair, count) in &mapping_groups {
        println!("  {} ({} field mappings)", pair, count);
    }

    // Migration paths
    println!(
        "\n{} ({})",
        "Migration Paths".bold(),
        ontology.migration_paths.len()
    );
    for path in &ontology.migration_paths {
        let lossless = if path.lossless {
            "lossless".green()
        } else {
            "lossy".yellow()
        };
        println!("  {}{} [{}]", path.from_schema, path.to_schema, lossless);
        if !path.data_loss.is_empty() {
            for loss in &path.data_loss {
                println!("    \u{26a0} {}", loss.as_str().dimmed());
            }
        }
    }

    // Capability matrix
    println!("\n{}", "Provider Capabilities".bold());
    for (provider, caps) in &ontology.capabilities {
        println!(
            "  {}: {}",
            provider.as_str().bold(),
            caps.join(", ").dimmed()
        );
    }

    Ok(())
}

/// `chasm schema mappings` — Show cross-provider field mappings
pub fn schema_mappings(
    source: Option<&str>,
    target: Option<&str>,
    tag: Option<&str>,
    json_output: bool,
) -> Result<()> {
    let ontology = Ontology::build();

    let mappings: Vec<_> = if let (Some(s), Some(t)) = (source, target) {
        ontology.cross_provider_mappings(s, t)
    } else if let Some(tag_name) = tag {
        ontology.find_by_semantic_tag(tag_name)
    } else {
        ontology.mappings.iter().collect()
    };

    if json_output {
        println!("{}", serde_json::to_string_pretty(&mappings)?);
        return Ok(());
    }

    println!(
        "{} {} mappings\n",
        "Cross-Provider Field Mappings:".bold(),
        mappings.len()
    );

    for m in &mappings {
        let confidence = format!("{:.0}%", m.confidence * 100.0);
        let conf_color = if m.confidence >= 0.9 {
            confidence.green()
        } else if m.confidence >= 0.7 {
            confidence.yellow()
        } else {
            confidence.red()
        };

        println!(
            "  {}{}",
            format!("{}.{}", m.source_schema, m.source_field).cyan(),
            format!("{}.{}", m.target_schema, m.target_field).green(),
        );
        println!(
            "    Tag: {} | Confidence: {} | Transform: {}",
            m.semantic_tag.bold(),
            conf_color,
            match &m.transform {
                Some(t) => format!("{:?}", t),
                None => "none".into(),
            }
            .dimmed()
        );
    }

    Ok(())
}

// ============================================================================
// Helpers
// ============================================================================

fn resolve_detect_path(path: Option<&str>) -> Result<String> {
    match path {
        Some(p) => Ok(p.to_string()),
        None => {
            let cwd = std::env::current_dir().context("Failed to get current directory")?;
            Ok(cwd.to_string_lossy().to_string())
        }
    }
}