routa-server 0.15.3

Routa.js HTTP Server — axum adapter on top of routa-core
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
use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    routing::{get, post},
    Json, Router,
};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::path::{Component, Path as FilePath};

use crate::api::repo_context::{normalize_local_repo_path, validate_local_git_repo_path};
use crate::error::ServerError;
use crate::state::AppState;

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/stage", post(stage_files))
        .route("/unstage", post(unstage_files))
        .route("/discard", post(discard_changes))
        .route("/commit", post(create_commit))
        .route("/commits", axum::routing::get(get_commits))
        .route("/commits/{sha}/diff", get(get_commit_diff))
        .route("/diff", get(get_file_diff))
        .route("/pull", post(pull_commits_handler))
        .route("/rebase", post(rebase_branch_handler))
        .route("/reset", post(reset_branch_handler))
        .route("/export", post(export_changes_handler))
}

pub fn read_router() -> Router<AppState> {
    Router::new()
        .route("/refs", get(get_refs))
        .route("/log", get(get_log_page))
        .route("/commit", get(get_commit_detail))
}

fn resolve_repo_path(repo_path: Option<&str>) -> Result<String, ServerError> {
    let repo_path = repo_path
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| ServerError::BadRequest("repoPath is required".to_string()))?;

    let normalized = normalize_local_repo_path(repo_path);
    validate_local_git_repo_path(&normalized)?;

    Ok(normalized.to_string_lossy().to_string())
}

fn resolve_commit_sha(sha: Option<&str>) -> Result<String, ServerError> {
    let sha = sha
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| ServerError::BadRequest("sha is required".to_string()))?;

    if sha.len() < 4 || !sha.chars().all(|character| character.is_ascii_hexdigit()) {
        return Err(ServerError::BadRequest("sha is invalid".to_string()));
    }

    Ok(sha.to_string())
}

async fn resolve_codebase_repo_path(
    state: &AppState,
    workspace_id: &str,
    codebase_id: &str,
) -> Result<String, ServerError> {
    let _workspace = state
        .workspace_store
        .get(workspace_id)
        .await
        .map_err(|error| ServerError::Internal(error.to_string()))?
        .ok_or_else(|| ServerError::NotFound("Workspace not found".to_string()))?;

    let codebase = state
        .codebase_store
        .get(codebase_id)
        .await
        .map_err(|error| ServerError::Internal(error.to_string()))?
        .ok_or_else(|| ServerError::NotFound("Codebase not found".to_string()))?;

    if !routa_core::git::is_git_repository(&codebase.repo_path) {
        return Err(ServerError::BadRequest(
            "Not a valid git repository".to_string(),
        ));
    }

    Ok(codebase.repo_path)
}

fn validate_git_file_path(path: &str) -> Result<(), String> {
    let trimmed = path.trim();
    if trimmed.is_empty() {
        return Err("File path cannot be empty".to_string());
    }

    let candidate = FilePath::new(trimmed);
    if candidate.is_absolute() {
        return Err(format!("Absolute file paths are not allowed: {trimmed}"));
    }

    if candidate.components().any(|component| {
        matches!(
            component,
            Component::ParentDir | Component::RootDir | Component::Prefix(_)
        )
    }) {
        return Err(format!(
            "File paths must stay within the repository root: {trimmed}"
        ));
    }

    Ok(())
}

fn validate_git_file_paths(files: &[String]) -> Result<(), String> {
    for file in files {
        validate_git_file_path(file)?;
    }

    Ok(())
}

fn git_command_output(repo_path: &str, args: &[&str]) -> Result<String, String> {
    let output = crate::git::git_command()
        .args(args)
        .current_dir(repo_path)
        .output()
        .map_err(|error| error.to_string())?;

    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    } else {
        Err(String::from_utf8_lossy(&output.stderr).trim().to_string())
    }
}

fn build_export_filename() -> String {
    format!("changes-{}.patch", Utc::now().format("%Y-%m-%dT%H-%M-%S"))
}

fn server_error_message(error: ServerError) -> String {
    match error {
        ServerError::Database(message)
        | ServerError::NotFound(message)
        | ServerError::BadRequest(message)
        | ServerError::Conflict(message)
        | ServerError::Internal(message)
        | ServerError::NotImplemented(message) => message,
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GitRefsQuery {
    repo_path: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GitLogPageQuery {
    repo_path: Option<String>,
    branches: Option<String>,
    search: Option<String>,
    limit: Option<usize>,
    skip: Option<usize>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GitCommitDetailQuery {
    repo_path: Option<String>,
    sha: Option<String>,
}

async fn get_refs(
    Query(query): Query<GitRefsQuery>,
) -> Result<Json<routa_core::git::GitRefsResult>, ServerError> {
    let repo_path = resolve_repo_path(query.repo_path.as_deref())?;
    let refs = tokio::task::spawn_blocking(move || routa_core::git::list_git_refs(&repo_path))
        .await
        .map_err(|error| ServerError::Internal(error.to_string()))?
        .map_err(ServerError::Internal)?;

    Ok(Json(refs))
}

async fn get_log_page(
    Query(query): Query<GitLogPageQuery>,
) -> Result<Json<routa_core::git::GitLogPage>, ServerError> {
    let repo_path = resolve_repo_path(query.repo_path.as_deref())?;
    let branches = query
        .branches
        .as_deref()
        .map(|value| {
            value
                .split(',')
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .map(str::to_string)
                .collect::<Vec<_>>()
        })
        .filter(|value| !value.is_empty());
    let search = query
        .search
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty());
    let limit = query.limit;
    let skip = query.skip;

    let page = tokio::task::spawn_blocking(move || {
        routa_core::git::get_git_log_page(
            &repo_path,
            branches.as_deref(),
            search.as_deref(),
            limit,
            skip,
        )
    })
    .await
    .map_err(|error| ServerError::Internal(error.to_string()))?
    .map_err(ServerError::Internal)?;

    Ok(Json(page))
}

async fn get_commit_detail(
    Query(query): Query<GitCommitDetailQuery>,
) -> Result<Json<routa_core::git::GitCommitDetail>, ServerError> {
    let repo_path = resolve_repo_path(query.repo_path.as_deref())?;
    let sha = resolve_commit_sha(query.sha.as_deref())?;
    let detail = tokio::task::spawn_blocking(move || {
        routa_core::git::get_git_commit_detail(&repo_path, &sha)
    })
    .await
    .map_err(|error| ServerError::Internal(error.to_string()))?
    .map_err(ServerError::Internal)?;

    Ok(Json(detail))
}

#[derive(Debug, Deserialize)]
struct StageFilesRequest {
    files: Vec<String>,
}

#[derive(Debug, Serialize)]
struct StageFilesResponse {
    success: bool,
    staged: Option<Vec<String>>,
    error: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct DiscardChangesRequest {
    files: Vec<String>,
    confirm: Option<bool>,
}

#[derive(Debug, Serialize)]
struct DiscardChangesResponse {
    success: bool,
    discarded: Option<Vec<String>>,
    error: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GetFileDiffQuery {
    path: Option<String>,
    staged: Option<bool>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct GetFileDiffResponse {
    diff: String,
    path: String,
    staged: bool,
}

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

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct GetCommitDiffResponse {
    diff: String,
    sha: String,
    path: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PullCommitsRequest {
    remote: Option<String>,
    branch: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RebaseBranchRequest {
    onto: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ResetBranchRequest {
    to: Option<String>,
    mode: Option<String>,
    confirm: Option<bool>,
}

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

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ExportChangesRequest {
    files: Option<Vec<String>>,
    format: Option<String>,
}

#[derive(Debug, Serialize)]
struct ExportChangesResponse {
    success: bool,
    patch: Option<String>,
    filename: Option<String>,
    error: Option<String>,
}

async fn stage_files(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id)): Path<(String, String)>,
    Json(req): Json<StageFilesRequest>,
) -> Result<Json<StageFilesResponse>, ServerError> {
    let repo_path = match resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await {
        Ok(repo_path) => repo_path,
        Err(error) => {
            return Ok(Json(StageFilesResponse {
                success: false,
                staged: None,
                error: Some(server_error_message(error)),
            }))
        }
    };
    let files = req.files;
    let staged_files = files.clone();

    match tokio::task::spawn_blocking(move || routa_core::git::stage_files(&repo_path, &files))
        .await
        .map_err(|error| ServerError::Internal(error.to_string()))?
    {
        Ok(()) => Ok(Json(StageFilesResponse {
            success: true,
            staged: Some(staged_files),
            error: None,
        })),
        Err(e) => Ok(Json(StageFilesResponse {
            success: false,
            staged: None,
            error: Some(e),
        })),
    }
}

async fn unstage_files(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id)): Path<(String, String)>,
    Json(req): Json<StageFilesRequest>,
) -> Result<Json<StageFilesResponse>, ServerError> {
    let repo_path = match resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await {
        Ok(repo_path) => repo_path,
        Err(error) => {
            return Ok(Json(StageFilesResponse {
                success: false,
                staged: None,
                error: Some(server_error_message(error)),
            }))
        }
    };
    let files = req.files;
    let staged_files = files.clone();

    match tokio::task::spawn_blocking(move || routa_core::git::unstage_files(&repo_path, &files))
        .await
        .map_err(|error| ServerError::Internal(error.to_string()))?
    {
        Ok(()) => Ok(Json(StageFilesResponse {
            success: true,
            staged: Some(staged_files),
            error: None,
        })),
        Err(e) => Ok(Json(StageFilesResponse {
            success: false,
            staged: None,
            error: Some(e),
        })),
    }
}

#[derive(Debug, Deserialize)]
struct CreateCommitRequest {
    message: String,
    files: Option<Vec<String>>,
}

#[derive(Debug, Serialize)]
struct CreateCommitResponse {
    success: bool,
    sha: Option<String>,
    message: Option<String>,
    error: Option<String>,
}

async fn create_commit(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id)): Path<(String, String)>,
    Json(req): Json<CreateCommitRequest>,
) -> Result<Json<CreateCommitResponse>, ServerError> {
    let repo_path = match resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await {
        Ok(repo_path) => repo_path,
        Err(error) => {
            return Ok(Json(CreateCommitResponse {
                success: false,
                sha: None,
                message: None,
                error: Some(server_error_message(error)),
            }))
        }
    };
    let message = req.message;
    let files = req.files;
    let response_message = message.clone();

    match tokio::task::spawn_blocking(move || {
        routa_core::git::create_commit(&repo_path, &message, files.as_deref())
    })
    .await
    .map_err(|error| ServerError::Internal(error.to_string()))?
    {
        Ok(sha) => Ok(Json(CreateCommitResponse {
            success: true,
            sha: Some(sha),
            message: Some(response_message),
            error: None,
        })),
        Err(e) => Ok(Json(CreateCommitResponse {
            success: false,
            sha: None,
            message: None,
            error: Some(e),
        })),
    }
}

#[derive(Debug, Deserialize)]
struct GetCommitsQuery {
    limit: Option<usize>,
    since: Option<String>,
}

#[derive(Debug, Serialize)]
struct GetCommitsResponse {
    commits: Vec<routa_core::git::CommitInfo>,
    count: usize,
}

async fn discard_changes(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id)): Path<(String, String)>,
    Json(req): Json<DiscardChangesRequest>,
) -> Result<(StatusCode, Json<DiscardChangesResponse>), ServerError> {
    if req.files.is_empty() {
        return Ok((
            StatusCode::BAD_REQUEST,
            Json(DiscardChangesResponse {
                success: false,
                discarded: None,
                error: Some("Missing or invalid 'files' array in request body".to_string()),
            }),
        ));
    }

    if req.confirm != Some(true) {
        return Ok((
            StatusCode::BAD_REQUEST,
            Json(DiscardChangesResponse {
                success: false,
                discarded: None,
                error: Some("Discard changes requires explicit confirmation".to_string()),
            }),
        ));
    }

    let repo_path = match resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await {
        Ok(repo_path) => repo_path,
        Err(error) => {
            let status = match error {
                ServerError::NotFound(_) => StatusCode::NOT_FOUND,
                ServerError::BadRequest(_) => StatusCode::BAD_REQUEST,
                _ => StatusCode::INTERNAL_SERVER_ERROR,
            };
            return Ok((
                status,
                Json(DiscardChangesResponse {
                    success: false,
                    discarded: None,
                    error: Some(server_error_message(error)),
                }),
            ));
        }
    };
    let files = req.files;
    let discarded_files = files.clone();

    let result =
        tokio::task::spawn_blocking(move || routa_core::git::discard_changes(&repo_path, &files))
            .await
            .map_err(|error| ServerError::Internal(error.to_string()))?;

    match result {
        Ok(()) => Ok((
            StatusCode::OK,
            Json(DiscardChangesResponse {
                success: true,
                discarded: Some(discarded_files),
                error: None,
            }),
        )),
        Err(error) => Ok((
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(DiscardChangesResponse {
                success: false,
                discarded: None,
                error: Some(error),
            }),
        )),
    }
}

async fn get_file_diff(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id)): Path<(String, String)>,
    Query(query): Query<GetFileDiffQuery>,
) -> Result<Json<GetFileDiffResponse>, ServerError> {
    let path = query
        .path
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| ServerError::BadRequest("Missing 'path' query parameter".to_string()))?
        .to_string();
    validate_git_file_path(&path).map_err(ServerError::BadRequest)?;
    let staged = query.staged.unwrap_or(false);
    let repo_path = resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await?;
    let response_path = path.clone();

    let diff = tokio::task::spawn_blocking(move || {
        if staged {
            git_command_output(&repo_path, &["diff", "--cached", "--", path.as_str()])
        } else {
            git_command_output(&repo_path, &["diff", "--", path.as_str()])
        }
    })
    .await
    .map_err(|error| ServerError::Internal(error.to_string()))?
    .map_err(ServerError::Internal)?;

    Ok(Json(GetFileDiffResponse {
        diff,
        path: response_path,
        staged,
    }))
}

async fn get_commit_diff(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id, sha)): Path<(String, String, String)>,
    Query(query): Query<GetCommitDiffQuery>,
) -> Result<Json<GetCommitDiffResponse>, ServerError> {
    let sha = resolve_commit_sha(Some(&sha))?;
    let path = query
        .path
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty());
    if let Some(path_value) = path.as_deref() {
        validate_git_file_path(path_value).map_err(ServerError::BadRequest)?;
    }
    let repo_path = resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await?;
    let response_sha = sha.clone();
    let response_path = path.clone();

    let diff = tokio::task::spawn_blocking(move || {
        if let Some(path_value) = path.as_deref() {
            git_command_output(&repo_path, &["show", sha.as_str(), "--", path_value])
        } else {
            git_command_output(&repo_path, &["show", sha.as_str()])
        }
    })
    .await
    .map_err(|error| ServerError::Internal(error.to_string()))?
    .map_err(ServerError::Internal)?;

    Ok(Json(GetCommitDiffResponse {
        diff,
        sha: response_sha,
        path: response_path,
    }))
}

async fn pull_commits_handler(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id)): Path<(String, String)>,
    Json(req): Json<PullCommitsRequest>,
) -> Result<(StatusCode, Json<GitOperationResponse>), ServerError> {
    let repo_path = match resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await {
        Ok(repo_path) => repo_path,
        Err(error) => {
            let status = match error {
                ServerError::NotFound(_) => StatusCode::NOT_FOUND,
                ServerError::BadRequest(_) => StatusCode::BAD_REQUEST,
                _ => StatusCode::INTERNAL_SERVER_ERROR,
            };
            return Ok((
                status,
                Json(GitOperationResponse {
                    success: false,
                    error: Some(server_error_message(error)),
                }),
            ));
        }
    };
    let remote = req.remote;
    let branch = req.branch;

    let result = tokio::task::spawn_blocking(move || {
        routa_core::git::pull_commits(&repo_path, remote.as_deref(), branch.as_deref())
    })
    .await
    .map_err(|error| ServerError::Internal(error.to_string()))?;

    match result {
        Ok(()) => Ok((
            StatusCode::OK,
            Json(GitOperationResponse {
                success: true,
                error: None,
            }),
        )),
        Err(error) => Ok((
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(GitOperationResponse {
                success: false,
                error: Some(error),
            }),
        )),
    }
}

async fn rebase_branch_handler(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id)): Path<(String, String)>,
    Json(req): Json<RebaseBranchRequest>,
) -> Result<(StatusCode, Json<GitOperationResponse>), ServerError> {
    let onto = req
        .onto
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| ServerError::BadRequest("Target branch 'onto' is required".to_string()))?
        .to_string();
    let repo_path = resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await?;

    let result =
        tokio::task::spawn_blocking(move || routa_core::git::rebase_branch(&repo_path, &onto))
            .await
            .map_err(|error| ServerError::Internal(error.to_string()))?;

    match result {
        Ok(()) => Ok((
            StatusCode::OK,
            Json(GitOperationResponse {
                success: true,
                error: None,
            }),
        )),
        Err(error) => Ok((
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(GitOperationResponse {
                success: false,
                error: Some(error),
            }),
        )),
    }
}

async fn reset_branch_handler(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id)): Path<(String, String)>,
    Json(req): Json<ResetBranchRequest>,
) -> Result<(StatusCode, Json<GitOperationResponse>), ServerError> {
    let to = req
        .to
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| {
            ServerError::BadRequest("Target commit/branch 'to' is required".to_string())
        })?
        .to_string();
    let mode = req
        .mode
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| ServerError::BadRequest("Mode must be 'soft' or 'hard'".to_string()))?
        .to_string();
    if mode != "soft" && mode != "hard" {
        return Ok((
            StatusCode::BAD_REQUEST,
            Json(GitOperationResponse {
                success: false,
                error: Some("Mode must be 'soft' or 'hard'".to_string()),
            }),
        ));
    }
    if mode == "hard" && req.confirm != Some(true) {
        return Ok((
            StatusCode::BAD_REQUEST,
            Json(GitOperationResponse {
                success: false,
                error: Some("Hard reset requires explicit confirmation".to_string()),
            }),
        ));
    }
    let repo_path = resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await?;
    let confirm = req.confirm.unwrap_or(false);

    let result = tokio::task::spawn_blocking(move || {
        routa_core::git::reset_branch(&repo_path, &to, &mode, confirm)
    })
    .await
    .map_err(|error| ServerError::Internal(error.to_string()))?;

    match result {
        Ok(()) => Ok((
            StatusCode::OK,
            Json(GitOperationResponse {
                success: true,
                error: None,
            }),
        )),
        Err(error) => Ok((
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(GitOperationResponse {
                success: false,
                error: Some(error),
            }),
        )),
    }
}

async fn export_changes_handler(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id)): Path<(String, String)>,
    Json(req): Json<ExportChangesRequest>,
) -> Result<(StatusCode, Json<ExportChangesResponse>), ServerError> {
    let repo_path = match resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await {
        Ok(repo_path) => repo_path,
        Err(error) => {
            let status = match error {
                ServerError::NotFound(_) => StatusCode::NOT_FOUND,
                ServerError::BadRequest(_) => StatusCode::BAD_REQUEST,
                _ => StatusCode::INTERNAL_SERVER_ERROR,
            };
            return Ok((
                status,
                Json(ExportChangesResponse {
                    success: false,
                    patch: None,
                    filename: None,
                    error: Some(server_error_message(error)),
                }),
            ));
        }
    };
    let files = req.files.unwrap_or_default();
    validate_git_file_paths(&files).map_err(ServerError::BadRequest)?;
    let format = req.format.unwrap_or_else(|| "patch".to_string());
    if format != "patch" && format != "diff" {
        return Ok((
            StatusCode::BAD_REQUEST,
            Json(ExportChangesResponse {
                success: false,
                patch: None,
                filename: None,
                error: Some("format must be 'patch' or 'diff'".to_string()),
            }),
        ));
    }

    let result = tokio::task::spawn_blocking(move || {
        if format == "patch" {
            git_command_output(
                &repo_path,
                &["diff", "--cached", "--no-color", "--no-ext-diff"],
            )
        } else if files.is_empty() {
            git_command_output(&repo_path, &["diff", "--no-color", "--no-ext-diff"])
        } else {
            let mut args = vec!["diff", "--no-color", "--no-ext-diff", "--"];
            args.extend(files.iter().map(|value| value.as_str()));
            git_command_output(&repo_path, &args)
        }
    })
    .await
    .map_err(|error| ServerError::Internal(error.to_string()))?;

    match result {
        Ok(patch) => {
            if patch.trim().is_empty() {
                Ok((
                    StatusCode::BAD_REQUEST,
                    Json(ExportChangesResponse {
                        success: false,
                        patch: None,
                        filename: None,
                        error: Some("No changes to export".to_string()),
                    }),
                ))
            } else {
                Ok((
                    StatusCode::OK,
                    Json(ExportChangesResponse {
                        success: true,
                        patch: Some(patch),
                        filename: Some(build_export_filename()),
                        error: None,
                    }),
                ))
            }
        }
        Err(error) => Ok((
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ExportChangesResponse {
                success: false,
                patch: None,
                filename: None,
                error: Some(error),
            }),
        )),
    }
}

async fn get_commits(
    State(state): State<AppState>,
    Path((workspace_id, codebase_id)): Path<(String, String)>,
    Query(query): Query<GetCommitsQuery>,
) -> Result<Json<GetCommitsResponse>, ServerError> {
    let repo_path = resolve_codebase_repo_path(&state, &workspace_id, &codebase_id).await?;
    let limit = query.limit;
    let since = query.since;

    let commits = tokio::task::spawn_blocking(move || {
        routa_core::git::get_commit_list(&repo_path, limit, since.as_deref())
    })
    .await
    .map_err(|error| ServerError::Internal(error.to_string()))?
    .map_err(ServerError::Internal)?;

    let count = commits.len();

    Ok(Json(GetCommitsResponse { commits, count }))
}