ironbridge-cli 2.0.1

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
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
// Copyright (c) 2024-2026 Nervosys LLC
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-IronBridge-Commercial
//! Sync Handler for real-time data synchronization
//!
//! This module provides HTTP/SSE-based synchronization between
//! ironbridge-rust (backend), ironbridge-web, and ironbridge-app clients.
//!
//! Uses Server-Sent Events (SSE) for real-time push updates instead of
//! WebSockets for better compatibility with various deployment scenarios.

use actix_web::{web, HttpResponse};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, RwLock};
use tokio::sync::broadcast;

// =============================================================================
// Sync Message Types
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SyncEntityType {
    Workspace,
    Session,
    Message,
    Agent,
    Swarm,
    Provider,
    Settings,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SyncOperation {
    Create,
    Update,
    Delete,
    Sync,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncEvent {
    pub id: String,
    #[serde(rename = "type")]
    pub entity_type: SyncEntityType,
    pub operation: SyncOperation,
    pub entity_id: String,
    pub data: Option<serde_json::Value>,
    pub timestamp: i64,
    pub client_id: String,
    pub version: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncSnapshot {
    pub workspaces: Vec<serde_json::Value>,
    pub sessions: Vec<serde_json::Value>,
    pub agents: Vec<serde_json::Value>,
    pub swarms: Vec<serde_json::Value>,
    pub providers: Vec<serde_json::Value>,
    pub timestamp: i64,
    pub version: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncDelta {
    pub created: Vec<SyncEvent>,
    pub updated: Vec<SyncEvent>,
    pub deleted: Vec<SyncEvent>,
    pub timestamp: i64,
    pub from_version: u64,
    pub to_version: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ServerMessage {
    Welcome { version: u64 },
    SyncEvent { event: SyncEvent },
    Ack { version: u64 },
}

// =============================================================================
// Sync State
// =============================================================================

/// Global sync state shared across all connections
pub struct SyncState {
    /// Current version counter
    pub version: u64,
    /// Event history for delta sync
    pub events: Vec<SyncEvent>,
    /// Maximum events to keep in history
    pub max_history: usize,
    /// Broadcast channel for events
    pub broadcast_tx: broadcast::Sender<ServerMessage>,
}

impl SyncState {
    pub fn new() -> Self {
        let (broadcast_tx, _) = broadcast::channel(1000);
        Self {
            version: 0,
            events: Vec::new(),
            max_history: 10000,
            broadcast_tx,
        }
    }

    /// Increment version and return new version
    pub fn next_version(&mut self) -> u64 {
        self.version += 1;
        self.version
    }

    /// Add event to history and broadcast
    pub fn add_event(&mut self, mut event: SyncEvent) -> u64 {
        let version = self.next_version();
        event.version = version;
        event.timestamp = chrono::Utc::now().timestamp_millis();

        self.events.push(event.clone());

        // Trim history if needed
        if self.events.len() > self.max_history {
            let trim_count = self.events.len() - self.max_history;
            self.events.drain(0..trim_count);
        }

        // Broadcast to all clients
        let _ = self.broadcast_tx.send(ServerMessage::SyncEvent { event });

        version
    }

    /// Get events since a version
    pub fn get_delta(&self, from_version: u64) -> SyncDelta {
        let events: Vec<_> = self
            .events
            .iter()
            .filter(|e| e.version > from_version)
            .cloned()
            .collect();

        let mut created = Vec::new();
        let mut updated = Vec::new();
        let mut deleted = Vec::new();

        for event in events {
            match event.operation {
                SyncOperation::Create => created.push(event),
                SyncOperation::Update | SyncOperation::Sync => updated.push(event),
                SyncOperation::Delete => deleted.push(event),
            }
        }

        SyncDelta {
            created,
            updated,
            deleted,
            timestamp: chrono::Utc::now().timestamp_millis(),
            from_version,
            to_version: self.version,
        }
    }

    /// Get broadcast receiver
    pub fn subscribe(&self) -> broadcast::Receiver<ServerMessage> {
        self.broadcast_tx.subscribe()
    }
}

impl Default for SyncState {
    fn default() -> Self {
        Self::new()
    }
}

pub type SharedSyncState = Arc<RwLock<SyncState>>;

/// Create shared sync state
pub fn create_sync_state() -> SharedSyncState {
    Arc::new(RwLock::new(SyncState::new()))
}

// =============================================================================
// HTTP/REST Sync Endpoints
// =============================================================================

/// Query parameters for delta request
#[derive(Debug, Deserialize)]
pub struct DeltaQuery {
    pub from: Option<u64>,
}

/// Get current sync version
pub async fn get_sync_version(sync_state: web::Data<SharedSyncState>) -> HttpResponse {
    let state = sync_state.read().unwrap();
    HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "data": {
            "version": state.version,
            "eventCount": state.events.len(),
        }
    }))
}

/// Get sync delta since a version
pub async fn get_sync_delta(
    sync_state: web::Data<SharedSyncState>,
    query: web::Query<DeltaQuery>,
) -> HttpResponse {
    let from_version = query.from.unwrap_or(0);

    let state = sync_state.read().unwrap();
    let delta = state.get_delta(from_version);

    HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "data": delta,
    }))
}

/// Post a sync event
pub async fn post_sync_event(
    sync_state: web::Data<SharedSyncState>,
    body: web::Json<SyncEvent>,
) -> HttpResponse {
    let mut state = sync_state.write().unwrap();
    let version = state.add_event(body.into_inner());

    HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "data": {
            "version": version,
        }
    }))
}

/// Batch sync events request
#[derive(Debug, Deserialize)]
pub struct BatchSyncRequest {
    pub events: Vec<SyncEvent>,
}

/// Post multiple sync events
pub async fn post_sync_batch(
    sync_state: web::Data<SharedSyncState>,
    body: web::Json<BatchSyncRequest>,
) -> HttpResponse {
    let mut state = sync_state.write().unwrap();
    let mut last_version = 0;

    for event in body.into_inner().events {
        last_version = state.add_event(event);
    }

    HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "data": {
            "version": last_version,
        }
    }))
}

/// Get full snapshot
/// A snapshot that cannot be built is an error, not an empty snapshot.
///
/// Naming the part that failed matters here: a client that gets "swarms" back
/// knows its sessions and workspaces are fine and that this is a server-side
/// fault, which an empty list told it nothing about.
fn snapshot_failed(part: &str, e: &rusqlite::Error) -> HttpResponse {
    HttpResponse::InternalServerError().json(serde_json::json!({
        "success": false,
        "data": null,
        "error": format!("Could not read {part} for the snapshot: {e}"),
    }))
}

pub async fn get_sync_snapshot(
    sync_state: web::Data<SharedSyncState>,
    app_state: web::Data<crate::api::state::AppState>,
) -> HttpResponse {
    let db = app_state.db.lock().unwrap();
    let sync = sync_state.read().unwrap();

    // Get workspaces from database
    let workspaces = db
        .list_workspaces()
        .unwrap_or_default()
        .into_iter()
        .map(|w| serde_json::to_value(w).unwrap_or_default())
        .collect();

    // Get sessions (3 args: workspace_id, provider, limit)
    let sessions = db
        .list_sessions(None, None, 1000)
        .unwrap_or_default()
        .into_iter()
        .map(|s| serde_json::to_value(s).unwrap_or_default())
        .collect();

    // A failed query is reported, not flattened into an empty list.
    //
    // These two used to end in `unwrap_or_default()`, and that is what hid the
    // schema conflict below for as long as it existed: `query_swarms_from_db`
    // selected columns the `swarms` table does not have, so the query errored
    // on every call and the snapshot answered 200 with `"swarms": []`. No
    // client could tell "no swarms" from "this server cannot read its swarms".
    let agents: Vec<serde_json::Value> = match query_agents_from_db(&db.conn) {
        Ok(agents) => agents,
        Err(e) => return snapshot_failed("agents", &e),
    };

    let swarms: Vec<serde_json::Value> = match query_swarms_from_db(&db.conn) {
        Ok(swarms) => swarms,
        Err(e) => return snapshot_failed("swarms", &e),
    };

    // Providers are hardcoded, return empty for snapshot
    // (clients should call /api/providers for the full list)
    let providers: Vec<serde_json::Value> = Vec::new();

    let snapshot = SyncSnapshot {
        workspaces,
        sessions,
        agents,
        swarms,
        providers,
        timestamp: chrono::Utc::now().timestamp_millis(),
        version: sync.version,
    };

    HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "data": snapshot,
    }))
}

/// Query agents directly from database
fn query_agents_from_db(
    conn: &rusqlite::Connection,
) -> Result<Vec<serde_json::Value>, rusqlite::Error> {
    // Ensure table exists
    conn.execute(
        "CREATE TABLE IF NOT EXISTS agents (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            description TEXT,
            instruction TEXT NOT NULL,
            role TEXT,
            model TEXT,
            provider TEXT,
            temperature REAL DEFAULT 0.7,
            max_tokens INTEGER,
            tools TEXT,
            sub_agents TEXT,
            is_active INTEGER DEFAULT 1,
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL,
            metadata TEXT
        )",
        [],
    )?;

    let mut stmt = conn.prepare(
        "SELECT id, name, description, instruction, role, model, provider,
                temperature, max_tokens, tools, sub_agents, is_active,
                created_at, updated_at, metadata
         FROM agents ORDER BY updated_at DESC",
    )?;

    let agents: Vec<serde_json::Value> = stmt
        .query_map([], |row| {
            let tools_str: String = row.get::<_, Option<String>>(9)?.unwrap_or_default();
            let tools: Vec<String> = serde_json::from_str(&tools_str).unwrap_or_default();
            let sub_agents_str: String = row.get::<_, Option<String>>(10)?.unwrap_or_default();
            let sub_agents: Vec<String> = serde_json::from_str(&sub_agents_str).unwrap_or_default();
            Ok(serde_json::json!({
                "id": row.get::<_, String>(0)?,
                "name": row.get::<_, String>(1)?,
                "description": row.get::<_, Option<String>>(2)?,
                "instruction": row.get::<_, String>(3)?,
                "role": row.get::<_, Option<String>>(4)?,
                "model": row.get::<_, Option<String>>(5)?,
                "provider": row.get::<_, Option<String>>(6)?,
                "temperature": row.get::<_, f64>(7)?,
                "maxTokens": row.get::<_, Option<i32>>(8)?,
                "tools": tools,
                "subAgents": sub_agents,
                "isActive": row.get::<_, i32>(11)? == 1,
                "createdAt": row.get::<_, i64>(12)?,
                "updatedAt": row.get::<_, i64>(13)?,
                "metadata": row.get::<_, Option<String>>(14)?,
            }))
        })?
        .collect::<Result<Vec<_>, _>>()?;

    Ok(agents)
}

/// The swarms in the database, in the shape `GET /api/swarms` returns.
///
/// # There is only one `swarms` table
///
/// This function used to declare a second one -- `orchestrator`, `is_active`
/// and `metadata`, where the real table has `orchestration`, `max_iterations`
/// and `status` -- and then select those columns. `CREATE TABLE IF NOT EXISTS`
/// made the conflict silent: the table already existed with the other schema,
/// so the statement did nothing and the SELECT failed on every call. Paired
/// with an `unwrap_or_default()` at the call site, the sync snapshot reported
/// an empty swarm list to every client while `GET /api/swarms` returned the
/// same swarms perfectly well.
///
/// The table belongs to `handlers_simple`, so its initializer is the one that
/// runs here. Two modules each declaring one table is how the two schemas
/// drifted apart without anything noticing.
fn query_swarms_from_db(
    conn: &rusqlite::Connection,
) -> Result<Vec<serde_json::Value>, rusqlite::Error> {
    super::handlers_simple::init_swarms_table(conn)?;

    let mut stmt = conn.prepare(
        "SELECT id, name, description, orchestration, agents, max_iterations,
                status, created_at, updated_at
         FROM swarms ORDER BY updated_at DESC",
    )?;

    let swarms: Vec<serde_json::Value> = stmt
        .query_map([], |row| {
            // Objects of `{agentId, role}`, not bare id strings: the old
            // mapping deserialized them as `Vec<String>`, which would have
            // silently emptied every swarm's membership even once the columns
            // were right.
            let agents_str: String = row.get::<_, String>(4)?;
            let agents: Vec<serde_json::Value> =
                serde_json::from_str(&agents_str).unwrap_or_default();
            Ok(serde_json::json!({
                "id": row.get::<_, String>(0)?,
                "name": row.get::<_, String>(1)?,
                "description": row.get::<_, Option<String>>(2)?,
                "orchestration": row.get::<_, String>(3)?,
                "agents": agents,
                "maxIterations": row.get::<_, Option<i32>>(5)?,
                "status": row.get::<_, String>(6)?,
                "createdAt": row.get::<_, i64>(7)?,
                "updatedAt": row.get::<_, i64>(8)?,
            }))
        })?
        .collect::<Result<Vec<_>, _>>()?;

    Ok(swarms)
}

/// Subscribe to sync events via Server-Sent Events (SSE)
pub async fn sync_sse(sync_state: web::Data<SharedSyncState>) -> HttpResponse {
    let state = sync_state.read().unwrap();
    let mut rx = state.subscribe();
    let current_version = state.version;
    drop(state);

    let stream = async_stream::stream! {
        // Send initial welcome with version
        let welcome = ServerMessage::Welcome { version: current_version };
        if let Ok(json) = serde_json::to_string(&welcome) {
            yield Ok::<_, std::io::Error>(web::Bytes::from(format!("data: {}\n\n", json)));
        }

        // Stream events
        loop {
            match rx.recv().await {
                Ok(msg) => {
                    if let Ok(json) = serde_json::to_string(&msg) {
                        yield Ok(web::Bytes::from(format!("data: {}\n\n", json)));
                    }
                }
                Err(broadcast::error::RecvError::Lagged(_)) => {
                    // Client missed some messages, they should request a delta
                    continue;
                }
                Err(broadcast::error::RecvError::Closed) => {
                    break;
                }
            }
        }
    };

    HttpResponse::Ok()
        .content_type("text/event-stream")
        .insert_header(("Cache-Control", "no-cache"))
        .insert_header(("Connection", "keep-alive"))
        .streaming(stream)
}

// =============================================================================
// Route Configuration
// =============================================================================

/// Configure sync routes
pub fn configure_sync_routes(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::scope("/sync")
            .route("/version", web::get().to(get_sync_version))
            .route("/delta", web::get().to(get_sync_delta))
            .route("/event", web::post().to(post_sync_event))
            .route("/batch", web::post().to(post_sync_batch))
            .route("/snapshot", web::get().to(get_sync_snapshot))
            .route("/subscribe", web::get().to(sync_sse)),
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ChatDatabase;
    use actix_web::{test, App};

    /// A swarm written through `/api/swarms` must appear in the sync snapshot.
    ///
    /// It did not, for as long as `sync` declared its own `swarms` table.
    /// `CREATE TABLE IF NOT EXISTS` is a no-op against an existing table, so
    /// the second schema never took effect and every SELECT of its columns
    /// failed -- silently, because the call site called `unwrap_or_default()`.
    /// The snapshot answered 200 with an empty list while `GET /api/swarms`
    /// returned the swarm.
    ///
    /// This test fails against that code: it writes through one module and
    /// reads through the other, which is the only way the conflict shows.
    #[tokio::test]
    async fn a_swarm_written_by_the_api_appears_in_the_snapshot() {
        let dir = tempfile::tempdir().expect("tempdir");
        let db_path = dir.path().join("sync-swarms.db");
        crate::commands::create_harvest_database(&db_path).expect("schema");

        let db = ChatDatabase::open(&db_path).expect("open");
        let state = web::Data::new(crate::api::state::AppState::new(db, db_path));
        let sync_state = web::Data::new(crate::api::create_sync_state());

        let app = test::init_service(
            App::new()
                .app_data(state.clone())
                .app_data(sync_state.clone())
                .configure(crate::api::configure_routes)
                .configure(crate::api::configure_sync_routes),
        )
        .await;

        let created = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/swarms")
                .set_json(serde_json::json!({
                    "name": "probe swarm",
                    "description": "d",
                    "orchestration": "sequential",
                    "agents": [{ "agent_id": "a1", "role": "coordinator" }],
                    "max_iterations": 5
                }))
                .to_request(),
        )
        .await;
        assert_eq!(created.status(), 200);

        let snapshot = test::call_service(
            &app,
            test::TestRequest::get().uri("/sync/snapshot").to_request(),
        )
        .await;
        assert_eq!(snapshot.status(), 200);
        let body: serde_json::Value = test::read_body_json(snapshot).await;

        let swarms = body["data"]["swarms"].as_array().expect("swarms array");
        assert_eq!(
            swarms.len(),
            1,
            "the snapshot dropped the swarm: {}",
            serde_json::to_string(&body).unwrap_or_default()
        );
        assert_eq!(swarms[0]["name"], "probe swarm");
        assert_eq!(swarms[0]["orchestration"], "sequential");
        assert_eq!(swarms[0]["status"], "idle");
        assert_eq!(swarms[0]["maxIterations"], 5);

        // Membership survives as objects. Deserializing these as `Vec<String>`
        // would empty every swarm without erroring.
        let agents = swarms[0]["agents"].as_array().expect("agents array");
        assert_eq!(agents.len(), 1);
        assert_eq!(agents[0]["agent_id"], "a1");
        assert_eq!(agents[0]["role"], "coordinator");
    }

    /// The snapshot and `GET /api/swarms` must not disagree about a swarm.
    #[tokio::test]
    async fn the_snapshot_and_the_swarms_endpoint_agree() {
        let dir = tempfile::tempdir().expect("tempdir");
        let db_path = dir.path().join("sync-agree.db");
        crate::commands::create_harvest_database(&db_path).expect("schema");

        let db = ChatDatabase::open(&db_path).expect("open");
        let state = web::Data::new(crate::api::state::AppState::new(db, db_path));
        let sync_state = web::Data::new(crate::api::create_sync_state());

        let app = test::init_service(
            App::new()
                .app_data(state.clone())
                .app_data(sync_state.clone())
                .configure(crate::api::configure_routes)
                .configure(crate::api::configure_sync_routes),
        )
        .await;

        for name in ["one", "two"] {
            test::call_service(
                &app,
                test::TestRequest::post()
                    .uri("/api/swarms")
                    .set_json(serde_json::json!({
                        "name": name,
                        "orchestration": "parallel",
                        "agents": []
                    }))
                    .to_request(),
            )
            .await;
        }

        let listed = test::call_service(
            &app,
            test::TestRequest::get().uri("/api/swarms").to_request(),
        )
        .await;
        let listed: serde_json::Value = test::read_body_json(listed).await;

        let snapshot = test::call_service(
            &app,
            test::TestRequest::get().uri("/sync/snapshot").to_request(),
        )
        .await;
        let snapshot: serde_json::Value = test::read_body_json(snapshot).await;

        assert_eq!(listed["data"], snapshot["data"]["swarms"]);
    }
}