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
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
// Copyright (c) 2024-2026 Nervosys LLC
// SPDX-License-Identifier: AGPL-3.0-only
//! SWE (Software Engineering) Mode Handlers
//!
//! Provides API endpoints for the SWE mode with persistent project memory,
//! user-defined rules, and context injection for AI assistants.

#![allow(dead_code, unused_variables)]

use actix_web::{web, HttpResponse, Responder};
use rusqlite::{params, OptionalExtension};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::process::Command;

use super::state::AppState;

// =============================================================================
// Response Types
// =============================================================================

#[derive(Debug, Serialize)]
struct ApiResponse<T> {
    success: bool,
    data: Option<T>,
    error: Option<String>,
}

impl<T: Serialize> ApiResponse<T> {
    fn success(data: T) -> HttpResponse {
        HttpResponse::Ok().json(Self {
            success: true,
            data: Some(data),
            error: None,
        })
    }

    fn error(message: &str) -> HttpResponse {
        HttpResponse::InternalServerError().json(ApiResponse::<()> {
            success: false,
            data: None,
            error: Some(message.to_string()),
        })
    }

    fn not_found(message: &str) -> HttpResponse {
        HttpResponse::NotFound().json(ApiResponse::<()> {
            success: false,
            data: None,
            error: Some(message.to_string()),
        })
    }

    fn bad_request(message: &str) -> HttpResponse {
        HttpResponse::BadRequest().json(ApiResponse::<()> {
            success: false,
            data: None,
            error: Some(message.to_string()),
        })
    }
}

// =============================================================================
// Data Models
// =============================================================================

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SweProject {
    pub id: String,
    pub name: String,
    pub path: String,
    pub description: Option<String>,
    pub git_remote: Option<String>,
    pub git_branch: Option<String>,
    pub language: Option<String>,
    pub framework: Option<String>,
    pub last_opened: i64,
    pub created_at: i64,
    pub updated_at: i64,
    pub memory_count: i64,
    pub rule_count: i64,
    pub session_count: i64,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SweMemory {
    pub id: String,
    pub project_id: String,
    pub key: String,
    pub value: String,
    pub category: String,
    pub importance: String,
    pub source: Option<String>,
    pub source_message_id: Option<String>,
    pub expires_at: Option<i64>,
    pub access_count: i64,
    pub last_accessed: Option<i64>,
    pub created_at: i64,
    pub updated_at: i64,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SweRule {
    pub id: String,
    pub project_id: String,
    pub rule: String,
    pub description: Option<String>,
    pub category: String,
    pub priority: i32,
    pub enabled: bool,
    pub scope: Option<String>,      // JSON string
    pub conditions: Option<String>, // JSON string
    pub created_at: i64,
    pub updated_at: i64,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SweSession {
    pub id: String,
    pub project_id: String,
    pub title: String,
    pub model: Option<String>,
    pub provider: String,
    pub message_count: i64,
    pub token_count: Option<i64>,
    pub working_directory: Option<String>,
    pub git_branch: Option<String>,
    pub created_at: i64,
    pub updated_at: i64,
    pub archived: bool,
}

// =============================================================================
// Request Types
// =============================================================================

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateProjectRequest {
    pub path: String,
    pub name: Option<String>,
    pub description: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateMemoryRequest {
    pub key: String,
    pub value: String,
    pub category: Option<String>,
    pub importance: Option<String>,
    pub expires_at: Option<i64>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateMemoryRequest {
    pub value: Option<String>,
    pub category: Option<String>,
    pub importance: Option<String>,
    pub expires_at: Option<i64>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateRuleRequest {
    pub rule: String,
    pub description: Option<String>,
    pub category: Option<String>,
    pub priority: Option<i32>,
    pub scope: Option<serde_json::Value>,
    pub conditions: Option<serde_json::Value>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateRuleRequest {
    pub rule: Option<String>,
    pub description: Option<String>,
    pub category: Option<String>,
    pub priority: Option<i32>,
    pub enabled: Option<bool>,
    pub scope: Option<serde_json::Value>,
    pub conditions: Option<serde_json::Value>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecuteToolRequest {
    pub tool: String,
    pub input: serde_json::Value,
}

#[derive(Debug, Deserialize)]
pub struct ProjectQuery {
    pub limit: Option<usize>,
}

#[derive(Debug, Deserialize)]
pub struct MemoryQuery {
    pub category: Option<String>,
    pub importance: Option<String>,
    pub search: Option<String>,
    pub limit: Option<usize>,
}

#[derive(Debug, Deserialize)]
pub struct RuleQuery {
    pub category: Option<String>,
    pub enabled: Option<bool>,
}

// =============================================================================
// Database Initialization
// =============================================================================

pub fn init_swe_tables(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
    // Projects table
    conn.execute(
        "CREATE TABLE IF NOT EXISTS swe_projects (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            path TEXT NOT NULL UNIQUE,
            description TEXT,
            git_remote TEXT,
            git_branch TEXT,
            language TEXT,
            framework TEXT,
            last_opened INTEGER NOT NULL,
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL,
            metadata TEXT
        )",
        [],
    )?;

    // Memory table (key-value store per project)
    conn.execute(
        "CREATE TABLE IF NOT EXISTS swe_memory (
            id TEXT PRIMARY KEY,
            project_id TEXT NOT NULL,
            key TEXT NOT NULL,
            value TEXT NOT NULL,
            category TEXT NOT NULL DEFAULT 'context',
            importance TEXT NOT NULL DEFAULT 'medium',
            source TEXT,
            source_message_id TEXT,
            expires_at INTEGER,
            access_count INTEGER NOT NULL DEFAULT 0,
            last_accessed INTEGER,
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL,
            metadata TEXT,
            FOREIGN KEY (project_id) REFERENCES swe_projects(id) ON DELETE CASCADE,
            UNIQUE(project_id, key)
        )",
        [],
    )?;

    // Rules table
    conn.execute(
        "CREATE TABLE IF NOT EXISTS swe_rules (
            id TEXT PRIMARY KEY,
            project_id TEXT NOT NULL,
            rule TEXT NOT NULL,
            description TEXT,
            category TEXT NOT NULL DEFAULT 'custom',
            priority INTEGER NOT NULL DEFAULT 50,
            enabled INTEGER NOT NULL DEFAULT 1,
            scope TEXT,
            conditions TEXT,
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL,
            metadata TEXT,
            FOREIGN KEY (project_id) REFERENCES swe_projects(id) ON DELETE CASCADE
        )",
        [],
    )?;

    // Sessions table
    conn.execute(
        "CREATE TABLE IF NOT EXISTS swe_sessions (
            id TEXT PRIMARY KEY,
            project_id TEXT NOT NULL,
            title TEXT NOT NULL,
            model TEXT,
            provider TEXT NOT NULL,
            message_count INTEGER NOT NULL DEFAULT 0,
            token_count INTEGER,
            working_directory TEXT,
            git_branch TEXT,
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL,
            archived INTEGER NOT NULL DEFAULT 0,
            metadata TEXT,
            FOREIGN KEY (project_id) REFERENCES swe_projects(id) ON DELETE CASCADE
        )",
        [],
    )?;

    // Messages table
    conn.execute(
        "CREATE TABLE IF NOT EXISTS swe_messages (
            id TEXT PRIMARY KEY,
            session_id TEXT NOT NULL,
            role TEXT NOT NULL,
            content TEXT NOT NULL,
            model TEXT,
            token_count INTEGER,
            tool_calls TEXT,
            tool_results TEXT,
            context_snapshot TEXT,
            created_at INTEGER NOT NULL,
            metadata TEXT,
            FOREIGN KEY (session_id) REFERENCES swe_sessions(id) ON DELETE CASCADE
        )",
        [],
    )?;

    // Create indexes
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_swe_memory_project ON swe_memory(project_id)",
        [],
    )?;
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_swe_memory_category ON swe_memory(category)",
        [],
    )?;
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_swe_rules_project ON swe_rules(project_id)",
        [],
    )?;
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_swe_sessions_project ON swe_sessions(project_id)",
        [],
    )?;
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_swe_messages_session ON swe_messages(session_id)",
        [],
    )?;

    Ok(())
}

// =============================================================================
// Project Endpoints
// =============================================================================

/// List all SWE projects
pub async fn list_projects(
    state: web::Data<AppState>,
    query: web::Query<ProjectQuery>,
) -> impl Responder {
    let db = state.db.lock().unwrap();

    // Initialize tables if needed
    if let Err(e) = init_swe_tables(&db.conn) {
        return ApiResponse::<()>::error(&format!("Failed to init tables: {}", e));
    }

    let limit = query.limit.unwrap_or(50);

    let mut stmt = match db.conn.prepare(
        "SELECT p.id, p.name, p.path, p.description, p.git_remote, p.git_branch,
                p.language, p.framework, p.last_opened, p.created_at, p.updated_at,
                (SELECT COUNT(*) FROM swe_memory WHERE project_id = p.id) as memory_count,
                (SELECT COUNT(*) FROM swe_rules WHERE project_id = p.id) as rule_count,
                (SELECT COUNT(*) FROM swe_sessions WHERE project_id = p.id) as session_count
         FROM swe_projects p
         ORDER BY p.last_opened DESC
         LIMIT ?",
    ) {
        Ok(stmt) => stmt,
        Err(e) => return ApiResponse::<()>::error(&format!("Query error: {}", e)),
    };

    let projects: Vec<SweProject> = stmt
        .query_map([limit], |row| {
            Ok(SweProject {
                id: row.get(0)?,
                name: row.get(1)?,
                path: row.get(2)?,
                description: row.get(3)?,
                git_remote: row.get(4)?,
                git_branch: row.get(5)?,
                language: row.get(6)?,
                framework: row.get(7)?,
                last_opened: row.get(8)?,
                created_at: row.get(9)?,
                updated_at: row.get(10)?,
                memory_count: row.get(11)?,
                rule_count: row.get(12)?,
                session_count: row.get(13)?,
            })
        })
        .unwrap()
        .filter_map(|r| r.ok())
        .collect();

    ApiResponse::success(projects)
}

/// Get a single project by ID
pub async fn get_project(state: web::Data<AppState>, path: web::Path<String>) -> impl Responder {
    let project_id = path.into_inner();
    let db = state.db.lock().unwrap();

    let project: Option<SweProject> = db
        .conn
        .query_row(
            "SELECT p.id, p.name, p.path, p.description, p.git_remote, p.git_branch,
                    p.language, p.framework, p.last_opened, p.created_at, p.updated_at,
                    (SELECT COUNT(*) FROM swe_memory WHERE project_id = p.id) as memory_count,
                    (SELECT COUNT(*) FROM swe_rules WHERE project_id = p.id) as rule_count,
                    (SELECT COUNT(*) FROM swe_sessions WHERE project_id = p.id) as session_count
             FROM swe_projects p WHERE p.id = ?",
            [&project_id],
            |row| {
                Ok(SweProject {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    path: row.get(2)?,
                    description: row.get(3)?,
                    git_remote: row.get(4)?,
                    git_branch: row.get(5)?,
                    language: row.get(6)?,
                    framework: row.get(7)?,
                    last_opened: row.get(8)?,
                    created_at: row.get(9)?,
                    updated_at: row.get(10)?,
                    memory_count: row.get(11)?,
                    rule_count: row.get(12)?,
                    session_count: row.get(13)?,
                })
            },
        )
        .optional()
        .unwrap_or(None);

    match project {
        Some(p) => ApiResponse::success(p),
        None => ApiResponse::<()>::not_found("Project not found"),
    }
}

/// Create a new SWE project
pub async fn create_project(
    state: web::Data<AppState>,
    body: web::Json<CreateProjectRequest>,
) -> impl Responder {
    let db = state.db.lock().unwrap();

    // Initialize tables if needed
    if let Err(e) = init_swe_tables(&db.conn) {
        return ApiResponse::<()>::error(&format!("Failed to init tables: {}", e));
    }

    let path = PathBuf::from(&body.path);
    if !path.exists() {
        return ApiResponse::<()>::bad_request("Project path does not exist");
    }

    let id = uuid::Uuid::new_v4().to_string();
    let name = body.name.clone().unwrap_or_else(|| {
        path.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("Untitled")
            .to_string()
    });
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;

    // Try to detect git info
    let git_branch = get_git_branch(&body.path);
    let git_remote = get_git_remote(&body.path);

    // Try to detect language/framework from common files
    let (language, framework) = detect_project_type(&path);

    match db.conn.execute(
        "INSERT INTO swe_projects (id, name, path, description, git_remote, git_branch, 
                                   language, framework, last_opened, created_at, updated_at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?9)",
        params![
            &id,
            &name,
            &body.path,
            &body.description,
            &git_remote,
            &git_branch,
            &language,
            &framework,
            now,
        ],
    ) {
        Ok(_) => {
            let project = SweProject {
                id,
                name,
                path: body.path.clone(),
                description: body.description.clone(),
                git_remote,
                git_branch,
                language,
                framework,
                last_opened: now,
                created_at: now,
                updated_at: now,
                memory_count: 0,
                rule_count: 0,
                session_count: 0,
            };
            ApiResponse::success(project)
        }
        Err(e) => {
            if e.to_string().contains("UNIQUE constraint failed") {
                ApiResponse::<()>::bad_request("Project with this path already exists")
            } else {
                ApiResponse::<()>::error(&format!("Failed to create project: {}", e))
            }
        }
    }
}

/// Delete a project
pub async fn delete_project(state: web::Data<AppState>, path: web::Path<String>) -> impl Responder {
    let project_id = path.into_inner();
    let db = state.db.lock().unwrap();

    match db
        .conn
        .execute("DELETE FROM swe_projects WHERE id = ?", [&project_id])
    {
        Ok(rows) if rows > 0 => ApiResponse::success(serde_json::json!({"deleted": true})),
        Ok(_) => ApiResponse::<()>::not_found("Project not found"),
        Err(e) => ApiResponse::<()>::error(&format!("Failed to delete project: {}", e)),
    }
}

/// Open a project (update last_opened timestamp)
pub async fn open_project(state: web::Data<AppState>, path: web::Path<String>) -> impl Responder {
    let project_id = path.into_inner();
    let db = state.db.lock().unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;

    match db.conn.execute(
        "UPDATE swe_projects SET last_opened = ?, updated_at = ? WHERE id = ?",
        params![now, now, &project_id],
    ) {
        Ok(rows) if rows > 0 => ApiResponse::success(serde_json::json!({"opened": true})),
        Ok(_) => ApiResponse::<()>::not_found("Project not found"),
        Err(e) => ApiResponse::<()>::error(&format!("Failed to update project: {}", e)),
    }
}

// =============================================================================
// Memory Endpoints
// =============================================================================

/// List memory entries for a project
pub async fn list_memory(
    state: web::Data<AppState>,
    path: web::Path<String>,
    query: web::Query<MemoryQuery>,
) -> impl Responder {
    let project_id = path.into_inner();
    let db = state.db.lock().unwrap();

    let limit = query.limit.unwrap_or(100);
    let mut sql = String::from(
        "SELECT id, project_id, key, value, category, importance, source, source_message_id,
                expires_at, access_count, last_accessed, created_at, updated_at
         FROM swe_memory WHERE project_id = ?",
    );

    let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(project_id.clone())];

    if let Some(ref category) = query.category {
        sql.push_str(" AND category = ?");
        params_vec.push(Box::new(category.clone()));
    }

    if let Some(ref importance) = query.importance {
        sql.push_str(" AND importance = ?");
        params_vec.push(Box::new(importance.clone()));
    }

    if let Some(ref search) = query.search {
        sql.push_str(" AND (key LIKE ? OR value LIKE ?)");
        let pattern = format!("%{}%", search);
        params_vec.push(Box::new(pattern.clone()));
        params_vec.push(Box::new(pattern));
    }

    sql.push_str(" ORDER BY importance DESC, updated_at DESC LIMIT ?");
    params_vec.push(Box::new(limit as i64));

    let params: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();

    let mut stmt = match db.conn.prepare(&sql) {
        Ok(s) => s,
        Err(e) => return ApiResponse::<()>::error(&format!("Query error: {}", e)),
    };

    let memories: Vec<SweMemory> = stmt
        .query_map(params.as_slice(), |row| {
            Ok(SweMemory {
                id: row.get(0)?,
                project_id: row.get(1)?,
                key: row.get(2)?,
                value: row.get(3)?,
                category: row.get(4)?,
                importance: row.get(5)?,
                source: row.get(6)?,
                source_message_id: row.get(7)?,
                expires_at: row.get(8)?,
                access_count: row.get(9)?,
                last_accessed: row.get(10)?,
                created_at: row.get(11)?,
                updated_at: row.get(12)?,
            })
        })
        .unwrap_or_else(|_| panic!())
        .filter_map(|r| r.ok())
        .collect();

    ApiResponse::success(memories)
}

/// Get a single memory entry
pub async fn get_memory(
    state: web::Data<AppState>,
    path: web::Path<(String, String)>,
) -> impl Responder {
    let (project_id, memory_id) = path.into_inner();
    let db = state.db.lock().unwrap();

    // Update access count and last_accessed
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;

    let _ = db.conn.execute(
        "UPDATE swe_memory SET access_count = access_count + 1, last_accessed = ? 
         WHERE id = ? AND project_id = ?",
        params![now, &memory_id, &project_id],
    );

    let memory: Option<SweMemory> = db
        .conn
        .query_row(
            "SELECT id, project_id, key, value, category, importance, source, source_message_id,
                    expires_at, access_count, last_accessed, created_at, updated_at
             FROM swe_memory WHERE id = ? AND project_id = ?",
            params![&memory_id, &project_id],
            |row| {
                Ok(SweMemory {
                    id: row.get(0)?,
                    project_id: row.get(1)?,
                    key: row.get(2)?,
                    value: row.get(3)?,
                    category: row.get(4)?,
                    importance: row.get(5)?,
                    source: row.get(6)?,
                    source_message_id: row.get(7)?,
                    expires_at: row.get(8)?,
                    access_count: row.get(9)?,
                    last_accessed: row.get(10)?,
                    created_at: row.get(11)?,
                    updated_at: row.get(12)?,
                })
            },
        )
        .optional()
        .unwrap_or(None);

    match memory {
        Some(m) => ApiResponse::success(m),
        None => ApiResponse::<()>::not_found("Memory entry not found"),
    }
}

/// Create a memory entry
pub async fn create_memory(
    state: web::Data<AppState>,
    path: web::Path<String>,
    body: web::Json<CreateMemoryRequest>,
) -> impl Responder {
    let project_id = path.into_inner();
    let db = state.db.lock().unwrap();

    let id = uuid::Uuid::new_v4().to_string();
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;

    let category = body
        .category
        .clone()
        .unwrap_or_else(|| "context".to_string());
    let importance = body
        .importance
        .clone()
        .unwrap_or_else(|| "medium".to_string());

    match db.conn.execute(
        "INSERT INTO swe_memory (id, project_id, key, value, category, importance, source, 
                                 expires_at, access_count, created_at, updated_at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'user', ?7, 0, ?8, ?8)",
        params![
            &id,
            &project_id,
            &body.key,
            &body.value,
            &category,
            &importance,
            body.expires_at,
            now,
        ],
    ) {
        Ok(_) => {
            let memory = SweMemory {
                id,
                project_id,
                key: body.key.clone(),
                value: body.value.clone(),
                category,
                importance,
                source: Some("user".to_string()),
                source_message_id: None,
                expires_at: body.expires_at,
                access_count: 0,
                last_accessed: None,
                created_at: now,
                updated_at: now,
            };
            ApiResponse::success(memory)
        }
        Err(e) => {
            if e.to_string().contains("UNIQUE constraint failed") {
                ApiResponse::<()>::bad_request("Memory with this key already exists")
            } else {
                ApiResponse::<()>::error(&format!("Failed to create memory: {}", e))
            }
        }
    }
}

/// Update a memory entry
pub async fn update_memory(
    state: web::Data<AppState>,
    path: web::Path<(String, String)>,
    body: web::Json<UpdateMemoryRequest>,
) -> impl Responder {
    let (project_id, memory_id) = path.into_inner();
    let db = state.db.lock().unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;

    // Build dynamic update
    let mut updates = vec!["updated_at = ?".to_string()];
    let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(now)];

    if let Some(ref value) = body.value {
        updates.push("value = ?".to_string());
        params_vec.push(Box::new(value.clone()));
    }
    if let Some(ref category) = body.category {
        updates.push("category = ?".to_string());
        params_vec.push(Box::new(category.clone()));
    }
    if let Some(ref importance) = body.importance {
        updates.push("importance = ?".to_string());
        params_vec.push(Box::new(importance.clone()));
    }
    if body.expires_at.is_some() {
        updates.push("expires_at = ?".to_string());
        params_vec.push(Box::new(body.expires_at));
    }

    params_vec.push(Box::new(memory_id.clone()));
    params_vec.push(Box::new(project_id.clone()));

    let sql = format!(
        "UPDATE swe_memory SET {} WHERE id = ? AND project_id = ?",
        updates.join(", ")
    );

    let params: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();

    match db.conn.execute(&sql, params.as_slice()) {
        Ok(rows) if rows > 0 => ApiResponse::success(serde_json::json!({"updated": true})),
        Ok(_) => ApiResponse::<()>::not_found("Memory entry not found"),
        Err(e) => ApiResponse::<()>::error(&format!("Failed to update memory: {}", e)),
    }
}

/// Delete a memory entry
pub async fn delete_memory(
    state: web::Data<AppState>,
    path: web::Path<(String, String)>,
) -> impl Responder {
    let (project_id, memory_id) = path.into_inner();
    let db = state.db.lock().unwrap();

    match db.conn.execute(
        "DELETE FROM swe_memory WHERE id = ? AND project_id = ?",
        params![&memory_id, &project_id],
    ) {
        Ok(rows) if rows > 0 => ApiResponse::success(serde_json::json!({"deleted": true})),
        Ok(_) => ApiResponse::<()>::not_found("Memory entry not found"),
        Err(e) => ApiResponse::<()>::error(&format!("Failed to delete memory: {}", e)),
    }
}

// =============================================================================
// Rules Endpoints
// =============================================================================

/// List rules for a project
pub async fn list_rules(
    state: web::Data<AppState>,
    path: web::Path<String>,
    query: web::Query<RuleQuery>,
) -> impl Responder {
    let project_id = path.into_inner();
    let db = state.db.lock().unwrap();

    let mut sql = String::from(
        "SELECT id, project_id, rule, description, category, priority, enabled, scope, conditions,
                created_at, updated_at
         FROM swe_rules WHERE project_id = ?",
    );

    let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(project_id.clone())];

    if let Some(ref category) = query.category {
        sql.push_str(" AND category = ?");
        params_vec.push(Box::new(category.clone()));
    }

    if let Some(enabled) = query.enabled {
        sql.push_str(" AND enabled = ?");
        params_vec.push(Box::new(enabled as i32));
    }

    sql.push_str(" ORDER BY priority ASC, created_at ASC");

    let params: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();

    let mut stmt = match db.conn.prepare(&sql) {
        Ok(s) => s,
        Err(e) => return ApiResponse::<()>::error(&format!("Query error: {}", e)),
    };

    let rules: Vec<SweRule> = stmt
        .query_map(params.as_slice(), |row| {
            Ok(SweRule {
                id: row.get(0)?,
                project_id: row.get(1)?,
                rule: row.get(2)?,
                description: row.get(3)?,
                category: row.get(4)?,
                priority: row.get(5)?,
                enabled: row.get::<_, i32>(6)? != 0,
                scope: row.get(7)?,
                conditions: row.get(8)?,
                created_at: row.get(9)?,
                updated_at: row.get(10)?,
            })
        })
        .unwrap()
        .filter_map(|r| r.ok())
        .collect();

    ApiResponse::success(rules)
}

/// Create a rule
pub async fn create_rule(
    state: web::Data<AppState>,
    path: web::Path<String>,
    body: web::Json<CreateRuleRequest>,
) -> impl Responder {
    let project_id = path.into_inner();
    let db = state.db.lock().unwrap();

    let id = uuid::Uuid::new_v4().to_string();
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;

    let category = body
        .category
        .clone()
        .unwrap_or_else(|| "custom".to_string());
    let priority = body.priority.unwrap_or(50);
    let scope = body.scope.as_ref().map(|s| s.to_string());
    let conditions = body.conditions.as_ref().map(|c| c.to_string());

    match db.conn.execute(
        "INSERT INTO swe_rules (id, project_id, rule, description, category, priority, enabled,
                                scope, conditions, created_at, updated_at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1, ?7, ?8, ?9, ?9)",
        params![
            &id,
            &project_id,
            &body.rule,
            &body.description,
            &category,
            priority,
            &scope,
            &conditions,
            now,
        ],
    ) {
        Ok(_) => {
            let rule = SweRule {
                id,
                project_id,
                rule: body.rule.clone(),
                description: body.description.clone(),
                category,
                priority,
                enabled: true,
                scope,
                conditions,
                created_at: now,
                updated_at: now,
            };
            ApiResponse::success(rule)
        }
        Err(e) => ApiResponse::<()>::error(&format!("Failed to create rule: {}", e)),
    }
}

/// Update a rule
pub async fn update_rule(
    state: web::Data<AppState>,
    path: web::Path<(String, String)>,
    body: web::Json<UpdateRuleRequest>,
) -> impl Responder {
    let (project_id, rule_id) = path.into_inner();
    let db = state.db.lock().unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;

    let mut updates = vec!["updated_at = ?".to_string()];
    let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(now)];

    if let Some(ref rule) = body.rule {
        updates.push("rule = ?".to_string());
        params_vec.push(Box::new(rule.clone()));
    }
    if let Some(ref description) = body.description {
        updates.push("description = ?".to_string());
        params_vec.push(Box::new(description.clone()));
    }
    if let Some(ref category) = body.category {
        updates.push("category = ?".to_string());
        params_vec.push(Box::new(category.clone()));
    }
    if let Some(priority) = body.priority {
        updates.push("priority = ?".to_string());
        params_vec.push(Box::new(priority));
    }
    if let Some(enabled) = body.enabled {
        updates.push("enabled = ?".to_string());
        params_vec.push(Box::new(enabled as i32));
    }
    if let Some(ref scope) = body.scope {
        updates.push("scope = ?".to_string());
        params_vec.push(Box::new(scope.to_string()));
    }
    if let Some(ref conditions) = body.conditions {
        updates.push("conditions = ?".to_string());
        params_vec.push(Box::new(conditions.to_string()));
    }

    params_vec.push(Box::new(rule_id.clone()));
    params_vec.push(Box::new(project_id.clone()));

    let sql = format!(
        "UPDATE swe_rules SET {} WHERE id = ? AND project_id = ?",
        updates.join(", ")
    );

    let params: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();

    match db.conn.execute(&sql, params.as_slice()) {
        Ok(rows) if rows > 0 => ApiResponse::success(serde_json::json!({"updated": true})),
        Ok(_) => ApiResponse::<()>::not_found("Rule not found"),
        Err(e) => ApiResponse::<()>::error(&format!("Failed to update rule: {}", e)),
    }
}

/// Delete a rule
pub async fn delete_rule(
    state: web::Data<AppState>,
    path: web::Path<(String, String)>,
) -> impl Responder {
    let (project_id, rule_id) = path.into_inner();
    let db = state.db.lock().unwrap();

    match db.conn.execute(
        "DELETE FROM swe_rules WHERE id = ? AND project_id = ?",
        params![&rule_id, &project_id],
    ) {
        Ok(rows) if rows > 0 => ApiResponse::success(serde_json::json!({"deleted": true})),
        Ok(_) => ApiResponse::<()>::not_found("Rule not found"),
        Err(e) => ApiResponse::<()>::error(&format!("Failed to delete rule: {}", e)),
    }
}

// =============================================================================
// Context Injection Endpoint
// =============================================================================

/// Get the context to inject into model prompts
/// This returns all enabled rules and relevant memory for the project
pub async fn get_context(state: web::Data<AppState>, path: web::Path<String>) -> impl Responder {
    let project_id = path.into_inner();
    let db = state.db.lock().unwrap();

    // Get all enabled rules, ordered by priority
    let mut rules_stmt = match db.conn.prepare(
        "SELECT rule, category, priority FROM swe_rules 
         WHERE project_id = ? AND enabled = 1 
         ORDER BY priority ASC",
    ) {
        Ok(s) => s,
        Err(e) => return ApiResponse::<()>::error(&format!("Query error: {}", e)),
    };

    let rules: Vec<serde_json::Value> = rules_stmt
        .query_map([&project_id], |row| {
            Ok(serde_json::json!({
                "rule": row.get::<_, String>(0)?,
                "category": row.get::<_, String>(1)?,
                "priority": row.get::<_, i32>(2)?,
            }))
        })
        .unwrap()
        .filter_map(|r| r.ok())
        .collect();

    // Get important memory entries (critical and high importance, not expired)
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;

    let mut memory_stmt = match db.conn.prepare(
        "SELECT key, value, category, importance FROM swe_memory 
         WHERE project_id = ? AND importance IN ('critical', 'high')
         AND (expires_at IS NULL OR expires_at > ?)
         ORDER BY 
            CASE importance WHEN 'critical' THEN 0 WHEN 'high' THEN 1 ELSE 2 END,
            updated_at DESC
         LIMIT 50",
    ) {
        Ok(s) => s,
        Err(e) => return ApiResponse::<()>::error(&format!("Query error: {}", e)),
    };

    let memory: Vec<serde_json::Value> = memory_stmt
        .query_map(params![&project_id, now], |row| {
            Ok(serde_json::json!({
                "key": row.get::<_, String>(0)?,
                "value": row.get::<_, String>(1)?,
                "category": row.get::<_, String>(2)?,
                "importance": row.get::<_, String>(3)?,
            }))
        })
        .unwrap()
        .filter_map(|r| r.ok())
        .collect();

    // Get project info
    let project_info: Option<(String, String, Option<String>, Option<String>)> = db
        .conn
        .query_row(
            "SELECT name, path, language, framework FROM swe_projects WHERE id = ?",
            [&project_id],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
        )
        .optional()
        .unwrap_or(None);

    // Build system prompt addition
    let mut system_parts = vec![];

    if let Some((name, path, language, framework)) = project_info {
        system_parts.push(format!(
            "You are working on the project '{}' located at '{}'.",
            name, path
        ));
        if let Some(lang) = language {
            system_parts.push(format!("Primary language: {}", lang));
        }
        if let Some(fw) = framework {
            system_parts.push(format!("Framework: {}", fw));
        }
    }

    if !rules.is_empty() {
        system_parts.push("\n## Project Rules (MUST FOLLOW):".to_string());
        for rule in &rules {
            let rule_text = rule["rule"].as_str().unwrap_or("");
            let category = rule["category"].as_str().unwrap_or("custom");
            system_parts.push(format!("- [{}] {}", category.to_uppercase(), rule_text));
        }
    }

    if !memory.is_empty() {
        system_parts.push("\n## Project Context (Important Information):".to_string());
        for mem in &memory {
            let key = mem["key"].as_str().unwrap_or("");
            let value = mem["value"].as_str().unwrap_or("");
            let importance = mem["importance"].as_str().unwrap_or("medium");
            system_parts.push(format!(
                "- **{}** [{}]: {}",
                key,
                importance.to_uppercase(),
                value
            ));
        }
    }

    ApiResponse::success(serde_json::json!({
        "systemPromptAddition": system_parts.join("\n"),
        "rules": rules,
        "memory": memory,
        "ruleCount": rules.len(),
        "memoryCount": memory.len(),
    }))
}

// =============================================================================
// Tool Execution Endpoints
// =============================================================================

/// Execute a tool (file operations, terminal commands, etc.)
pub async fn execute_tool(
    state: web::Data<AppState>,
    path: web::Path<String>,
    body: web::Json<ExecuteToolRequest>,
) -> impl Responder {
    let project_id = path.into_inner();
    let db = state.db.lock().unwrap();

    // Get project path
    let project_path: Option<String> = db
        .conn
        .query_row(
            "SELECT path FROM swe_projects WHERE id = ?",
            [&project_id],
            |row| row.get(0),
        )
        .optional()
        .unwrap_or(None);

    let project_path = match project_path {
        Some(p) => p,
        None => return ApiResponse::<()>::not_found("Project not found"),
    };

    let base_path = PathBuf::from(&project_path);

    match body.tool.as_str() {
        "read_file" => {
            let file_path = body.input["path"].as_str().unwrap_or("");
            let full_path = resolve_path(&base_path, file_path);

            match std::fs::read_to_string(&full_path) {
                Ok(content) => ApiResponse::success(serde_json::json!({
                    "success": true,
                    "content": content,
                    "path": full_path.to_string_lossy(),
                })),
                Err(e) => ApiResponse::success(serde_json::json!({
                    "success": false,
                    "error": e.to_string(),
                })),
            }
        }
        "write_file" => {
            let file_path = body.input["path"].as_str().unwrap_or("");
            let content = body.input["content"].as_str().unwrap_or("");
            let full_path = resolve_path(&base_path, file_path);

            // Create parent directories if needed
            if let Some(parent) = full_path.parent() {
                let _ = std::fs::create_dir_all(parent);
            }

            match std::fs::write(&full_path, content) {
                Ok(_) => ApiResponse::success(serde_json::json!({
                    "success": true,
                    "path": full_path.to_string_lossy(),
                })),
                Err(e) => ApiResponse::success(serde_json::json!({
                    "success": false,
                    "error": e.to_string(),
                })),
            }
        }
        "list_directory" => {
            let dir_path = body.input["path"].as_str().unwrap_or(".");
            let full_path = resolve_path(&base_path, dir_path);

            match std::fs::read_dir(&full_path) {
                Ok(entries) => {
                    let files: Vec<serde_json::Value> = entries
                        .filter_map(|e| e.ok())
                        .map(|entry| {
                            let name = entry.file_name().to_string_lossy().to_string();
                            let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
                            let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
                            serde_json::json!({
                                "name": name,
                                "type": if is_dir { "directory" } else { "file" },
                                "size": size,
                            })
                        })
                        .collect();
                    ApiResponse::success(serde_json::json!({
                        "success": true,
                        "files": files,
                        "path": full_path.to_string_lossy(),
                    }))
                }
                Err(e) => ApiResponse::success(serde_json::json!({
                    "success": false,
                    "error": e.to_string(),
                })),
            }
        }
        "run_command" => {
            let command = body.input["command"].as_str().unwrap_or("");
            let working_dir = body.input["workingDirectory"]
                .as_str()
                .map(|d| resolve_path(&base_path, d))
                .unwrap_or_else(|| base_path.clone());

            // Execute command
            #[cfg(target_os = "windows")]
            let output = Command::new("cmd")
                .args(["/C", command])
                .current_dir(&working_dir)
                .output();

            #[cfg(not(target_os = "windows"))]
            let output = Command::new("sh")
                .args(["-c", command])
                .current_dir(&working_dir)
                .output();

            match output {
                Ok(out) => ApiResponse::success(serde_json::json!({
                    "success": out.status.success(),
                    "exitCode": out.status.code().unwrap_or(-1),
                    "stdout": String::from_utf8_lossy(&out.stdout),
                    "stderr": String::from_utf8_lossy(&out.stderr),
                    "command": command,
                    "workingDirectory": working_dir.to_string_lossy(),
                })),
                Err(e) => ApiResponse::success(serde_json::json!({
                    "success": false,
                    "error": e.to_string(),
                })),
            }
        }
        "search_files" => {
            let pattern = body.input["pattern"].as_str().unwrap_or("*");
            let search_dir = body.input["directory"]
                .as_str()
                .map(|d| resolve_path(&base_path, d))
                .unwrap_or_else(|| base_path.clone());

            let mut results = vec![];
            if let Ok(entries) =
                glob::glob(&format!("{}/{}", search_dir.to_string_lossy(), pattern))
            {
                for entry in entries
                    .filter_map(|e: Result<std::path::PathBuf, glob::GlobError>| e.ok())
                    .take(100)
                {
                    results.push(serde_json::json!({
                        "path": entry.to_string_lossy(),
                        "relativePath": entry.strip_prefix(&base_path)
                            .map(|p: &std::path::Path| p.to_string_lossy().to_string())
                            .unwrap_or_else(|_| entry.to_string_lossy().to_string()),
                    }));
                }
            }

            ApiResponse::success(serde_json::json!({
                "success": true,
                "results": results,
                "count": results.len(),
            }))
        }
        "git_status" => {
            let output = Command::new("git")
                .args(["status", "--porcelain", "-b"])
                .current_dir(&base_path)
                .output();

            match output {
                Ok(out) => {
                    let status = String::from_utf8_lossy(&out.stdout).to_string();
                    ApiResponse::success(serde_json::json!({
                        "success": out.status.success(),
                        "status": status,
                    }))
                }
                Err(e) => ApiResponse::success(serde_json::json!({
                    "success": false,
                    "error": e.to_string(),
                })),
            }
        }
        "git_diff" => {
            let staged = body.input["staged"].as_bool().unwrap_or(false);
            let mut args = vec!["diff"];
            if staged {
                args.push("--staged");
            }

            let output = Command::new("git")
                .args(&args)
                .current_dir(&base_path)
                .output();

            match output {
                Ok(out) => {
                    let diff = String::from_utf8_lossy(&out.stdout).to_string();
                    ApiResponse::success(serde_json::json!({
                        "success": out.status.success(),
                        "diff": diff,
                    }))
                }
                Err(e) => ApiResponse::success(serde_json::json!({
                    "success": false,
                    "error": e.to_string(),
                })),
            }
        }
        _ => ApiResponse::<()>::bad_request(&format!("Unknown tool: {}", body.tool)),
    }
}

// =============================================================================
// Helper Functions
// =============================================================================

fn get_git_branch(path: &str) -> Option<String> {
    Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(path)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}

fn get_git_remote(path: &str) -> Option<String> {
    Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(path)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}

fn detect_project_type(path: &std::path::Path) -> (Option<String>, Option<String>) {
    let mut language = None;
    let mut framework = None;

    // Check for common project files
    if path.join("Cargo.toml").exists() {
        language = Some("rust".to_string());
    } else if path.join("package.json").exists() {
        language = Some("typescript".to_string());

        // Check for specific frameworks
        if path.join("next.config.js").exists() || path.join("next.config.mjs").exists() {
            framework = Some("next.js".to_string());
        } else if path.join("vite.config.ts").exists() || path.join("vite.config.js").exists() {
            framework = Some("vite".to_string());
        } else if path.join("angular.json").exists() {
            framework = Some("angular".to_string());
        }
    } else if path.join("requirements.txt").exists() || path.join("pyproject.toml").exists() {
        language = Some("python".to_string());

        if path.join("manage.py").exists() {
            framework = Some("django".to_string());
        }
    } else if path.join("go.mod").exists() {
        language = Some("go".to_string());
    } else if path.join("pom.xml").exists() || path.join("build.gradle").exists() {
        language = Some("java".to_string());
    } else if path.join("*.csproj").exists() || path.join("*.sln").exists() {
        language = Some("csharp".to_string());
    }

    (language, framework)
}

fn resolve_path(base: &std::path::Path, relative: &str) -> PathBuf {
    let path = PathBuf::from(relative);
    if path.is_absolute() {
        path
    } else {
        base.join(relative)
    }
}