githttp-fs 1.5.1

A git-backed content management database served over HTTP
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
// githttp-fs
//
// Git-based Content Management System
// Copyright: 2026, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)

//! File CRUD routes: listing, read, existence check, write, delete, move.
//!
//! See `routes/mod.rs` for the shared handler shape (validate → lock →
//! blocking git op → hook enqueue → maintenance arm) that every write
//! handler here follows.

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use chrono::Utc;
use serde::Deserialize;
use serde_json::json;

use std::collections::HashSet;

use crate::{
    error::AppError,
    git,
    hooks::HookJob,
    routes::AuthorRequest,
    seek::{SeekBody, SeekFilter, SeekOptions},
    state::AppState,
    util::run_blocking,
    validate,
};

/// Query parameters for the listing endpoint. All optional: the bare
/// endpoint returns page 1 of the full recursive tree.
#[derive(Deserialize)]
pub struct ListFilesQuery {
    /// Folder to root the listing at (e.g. `/docs`); repo root if omitted.
    pub prefix_path: Option<String>,
    /// How many directory levels to descend from the listing root; full
    /// recursion if omitted.
    pub maximum_depth: Option<u32>,
    /// When true, hidden entries (names starting with `.`, per the Unix
    /// convention) are included in the listing; excluded if omitted or false.
    pub include_hidden_files: Option<bool>,
    /// When set, narrows the listing to files *and directories* whose leaf
    /// name begins with the given prefix(es), compared case-insensitively (a
    /// matched directory brings its subtree along). Accepts either a bare
    /// string (a single prefix) or a JSON-array string of prefixes, e.g.
    /// `["intro", "readme"]` — an entry matches if its leaf name begins with
    /// *any* of them. Empty is rejected (`400`).
    pub file_name_starts_with: Option<String>,
    pub page: Option<usize>,
    pub per_page: Option<usize>,
}

// Pagination bounds shared with the commits endpoint: a generous default,
// and a hard cap so a caller cannot request unbounded response sizes.
const DEFAULT_PER_PAGE: usize = 100;
const MAX_PER_PAGE: usize = 500;

/// Query parameters for the count endpoint. All optional: the bare endpoint
/// counts the full recursive tree. The first three carry the exact
/// semantics of their `ListFilesQuery` namesakes.
#[derive(Deserialize)]
pub struct CountFilesQuery {
    /// Folder to root the count at (e.g. `/docs`); repo root if omitted.
    pub prefix_path: Option<String>,
    /// How many directory levels to descend from the count root; full
    /// recursion if omitted.
    pub maximum_depth: Option<u32>,
    /// When true, hidden entries (names starting with `.`, per the Unix
    /// convention) are included in the count; excluded if omitted or false.
    pub include_hidden_files: Option<bool>,
    /// A JSON array of file extensions as a string (query parameters are
    /// strings), e.g. `["md", "mdx"]`; when set, only files carrying one of
    /// these extensions are counted. Omitted: every file counts.
    pub restrict_file_extensions: Option<String>,
}

/// Body of the batch read endpoint: the entries to read, plus an optional
/// seek window applied to every file that does not carry its own (see
/// `seek.rs` for the field formats).
#[derive(Deserialize)]
pub struct BatchReadFilesRequest {
    pub files: Vec<BatchReadFileRequest>,
    pub seek: Option<SeekBody>,
}

/// One entry of the batch read `files` array: either a bare path string,
/// or an object holding the path plus an optional per-file seek window.
/// When the per-file `seek` is set it *replaces* the request-level `seek`
/// for that file (no field-by-field merge).
#[derive(Deserialize)]
#[serde(untagged)]
pub enum BatchReadFileRequest {
    Path(String),
    Options {
        path: String,
        seek: Option<SeekBody>,
    },
}

impl BatchReadFileRequest {
    /// The raw path and optional per-file seek, whichever spelling was used.
    fn parts(&self) -> (&str, Option<&SeekBody>) {
        match self {
            Self::Path(path) => (path, None),
            Self::Options { path, seek } => (path, seek.as_ref()),
        }
    }
}

#[derive(Deserialize)]
pub struct WriteFileRequest {
    pub author: AuthorRequest,
    pub content: String,
    pub message: Option<String>,
}

#[derive(Deserialize)]
pub struct DeleteFileRequest {
    pub author: AuthorRequest,
    pub message: Option<String>,
}

#[derive(Deserialize)]
pub struct MoveFileRequest {
    pub author: AuthorRequest,
    pub destination: String,
    pub message: Option<String>,
}

/// Decodes the `file_name_starts_with` query value into its list of prefixes.
/// A value that looks like a JSON array (its first non-whitespace character is
/// `[`) must be a valid JSON array of strings; any other value is taken
/// verbatim as a single prefix — the original bare-string spelling, kept for
/// backward compatibility. Empty arrays and empty prefixes are rejected with
/// `400`: an empty prefix would match every entry (indistinguishable from
/// omitting the parameter), an empty array none — both only caller bugs.
fn parse_file_name_prefixes(raw: &str) -> Result<Vec<String>, AppError> {
    let prefixes = if raw.trim_start().starts_with('[') {
        serde_json::from_str::<Vec<String>>(raw).map_err(|_err| AppError::InvalidOperation {
            reason:
                "file_name_starts_with must be a string or a JSON array of strings, e.g. [\"intro\", \"readme\"]"
                    .to_string(),
        })?
    } else {
        vec![raw.to_string()]
    };

    if prefixes.is_empty() {
        return Err(AppError::InvalidOperation {
            reason: "file_name_starts_with must contain at least one prefix".to_string(),
        });
    }

    if prefixes.iter().any(|prefix| prefix.is_empty()) {
        return Err(AppError::InvalidOperation {
            reason: "file_name_starts_with must not be empty".to_string(),
        });
    }

    Ok(prefixes)
}

/// GET /:collection_id/:tenant_id/files
/// Returns the repository contents as a recursive file tree.
/// Accepts an optional `prefix_path` query parameter (e.g. `?prefix_path=/docs`) to scope
/// the listing to a specific sub-directory. The path must be a folder and must
/// not escape the repository root (`..' components are rejected).
///
/// Pagination is *parent-based*: `page`/`per_page` window over the
/// root-level entries of the listing, each carrying its full subtree.
/// Combined with `maximum_depth` this lets clients bound response size on
/// arbitrarily large repositories.
pub async fn list_files(
    State(state): State<AppState>,
    Path((collection_id, tenant_id)): Path<(String, String)>,
    Query(query): Query<ListFilesQuery>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    // An empty sanitised prefix ("/" or "") means "repo root", which is the
    // same as no prefix at all — normalise it to None here so the git layer
    // only ever sees a meaningful prefix.
    let path_prefix: Option<String> = query
        .prefix_path
        .as_deref()
        .map(validate::folder_path)
        .transpose()?
        .filter(|p| !p.is_empty())
        .map(|p| p.to_string());

    // maximum_depth=0 would mean "list nothing", which is more likely a
    // caller bug than an intent — reject it explicitly.
    let maximum_depth: Option<usize> = match query.maximum_depth {
        Some(0) => {
            return Err(AppError::InvalidOperation {
                reason: "maximum_depth must be at least 1".to_string(),
            })
        }
        Some(d) => Some(d as usize),
        None => None,
    };

    let include_hidden_files = query.include_hidden_files.unwrap_or(false);

    // Accepts either a bare string (a single prefix) or a JSON-array string
    // of prefixes (query parameters are strings, so an array travels the same
    // way `seek_from_line_starts_with` does), so several prefixes can be
    // searched at once — an entry matches if its leaf name begins with *any*
    // of them.
    let file_name_starts_with: Option<Vec<String>> = query
        .file_name_starts_with
        .as_deref()
        .map(parse_file_name_prefixes)
        .transpose()?;

    let page = query.page.unwrap_or(1).max(1);
    let per_page = query
        .per_page
        .unwrap_or(DEFAULT_PER_PAGE)
        .clamp(1, MAX_PER_PAGE);

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, include_hidden_files = include_hidden_files, file_name_starts_with = ?file_name_starts_with, page = page, per_page = per_page, "handling list files request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let tenant_id_for_task = tenant_id.clone();

    let (tree, has_more) = run_blocking(move || {
        git::GitFiles::list_files(
            &repo_path,
            &tenant_id_for_task,
            path_prefix.as_deref(),
            maximum_depth,
            include_hidden_files,
            file_name_starts_with.as_deref(),
            page,
            per_page,
        )
    })
    .await?;

    tracing::debug!(tenant_id = %tenant_id, page = page, returned = tree.len(), has_more = has_more, "list files tree response ready");

    Ok(Json(json!({
        "page": page,
        "per_page": per_page,
        "has_more": has_more,
        "files": tree,
    })))
}

/// GET /:collection_id/:tenant_id/count/files
/// Returns file and directory count statistics for the repository.
///
/// `prefix_path`, `maximum_depth` and `include_hidden_files` scope the
/// count exactly like the listing endpoint (sub-directory root, depth
/// bound, hidden filter). `restrict_file_extensions` — a JSON-array string,
/// same wire spelling as the `seek_*` prefix lists — narrows the file count
/// to files carrying one of the given extensions, compared
/// case-insensitively; directories are counted regardless.
pub async fn count_files(
    State(state): State<AppState>,
    Path((collection_id, tenant_id)): Path<(String, String)>,
    Query(query): Query<CountFilesQuery>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    // An empty sanitised prefix ("/" or "") means "repo root", which is the
    // same as no prefix at all — normalise it to None here so the git layer
    // only ever sees a meaningful prefix.
    let path_prefix: Option<String> = query
        .prefix_path
        .as_deref()
        .map(validate::folder_path)
        .transpose()?
        .filter(|p| !p.is_empty())
        .map(|p| p.to_string());

    // maximum_depth=0 would mean "count nothing", which is more likely a
    // caller bug than an intent — reject it explicitly.
    let maximum_depth: Option<usize> = match query.maximum_depth {
        Some(0) => {
            return Err(AppError::InvalidOperation {
                reason: "maximum_depth must be at least 1".to_string(),
            })
        }
        Some(d) => Some(d as usize),
        None => None,
    };

    let include_hidden_files = query.include_hidden_files.unwrap_or(false);

    let restrict_file_extensions: Option<Vec<String>> = query
        .restrict_file_extensions
        .as_deref()
        .map(parse_restrict_file_extensions)
        .transpose()?;

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, include_hidden_files = include_hidden_files, restrict_file_extensions = ?restrict_file_extensions, "handling count files request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let tenant_id_for_task = tenant_id.clone();

    let counts = run_blocking(move || {
        git::GitFiles::count_files(
            &repo_path,
            &tenant_id_for_task,
            path_prefix.as_deref(),
            maximum_depth,
            include_hidden_files,
            restrict_file_extensions.as_deref(),
        )
    })
    .await?;

    tracing::debug!(tenant_id = %tenant_id, files = counts.files, directories = counts.directories, "count files response ready");

    Ok(Json(json!({
        "files": counts.files,
        "directories": counts.directories,
    })))
}

/// Decodes and validates the `restrict_file_extensions` query parameter
/// from its JSON-array-string spelling. Entries are normalised by trimming
/// leading dots (`".md"` and `"md"` name the same extension); a non-array
/// value, an empty array, or an entry left empty after trimming are all
/// caller bugs and rejected with a `400`.
fn parse_restrict_file_extensions(raw: &str) -> Result<Vec<String>, AppError> {
    let extensions: Vec<String> =
        serde_json::from_str(raw).map_err(|_err| AppError::InvalidOperation {
            reason:
                "restrict_file_extensions must be a JSON array of strings, e.g. [\"md\", \"mdx\"]"
                    .to_string(),
        })?;

    if extensions.is_empty() {
        return Err(AppError::InvalidOperation {
            reason: "restrict_file_extensions must contain at least one extension".to_string(),
        });
    }

    let normalized: Vec<String> = extensions
        .iter()
        .map(|extension| extension.trim_start_matches('.').to_string())
        .collect();

    if normalized.iter().any(|extension| extension.is_empty()) {
        return Err(AppError::InvalidOperation {
            reason: "restrict_file_extensions extensions must not be empty".to_string(),
        });
    }

    Ok(normalized)
}

/// GET /:collection_id/:tenant_id/files/*path
/// Returns the file content and path as JSON.
///
/// Optional `seek_*` query parameters (`seek_from_line_starts_with`,
/// `seek_to_line_starts_with`, `seek_lines_maximum`) narrow `content` to a
/// line window — see `seek.rs` for the exact semantics and accepted
/// formats. The seek runs inside the git read so it can scan the blob as a
/// line stream instead of decoding it whole.
pub async fn read_file(
    State(state): State<AppState>,
    Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
    Query(seek): Query<SeekOptions>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
    let file_path = validate::file_path(&file_path)?.to_string();

    let seek = seek.parse()?;

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, seek = ?seek, "handling read file request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let file_path_for_task = file_path.clone();
    let tenant_id_for_task = tenant_id.clone();

    let content = run_blocking(move || {
        git::GitFiles::read_file(&repo_path, &tenant_id_for_task, &file_path_for_task, &seek)
    })
    .await?;

    Ok(Json(json!({
        "path": file_path,
        "content": content,
    })))
}

/// POST /:collection_id/:tenant_id/batch/files/read
/// Reads several files in one request. The response array is index-aligned
/// with the request's `files` array: each slot is either the same
/// `{ path, content }` object the single read route returns, or `null`
/// when that path does not exist (or is a folder). Each entry is a bare
/// path string or a `{ path, seek? }` object; an optional request-level
/// `seek` object applies the same line window to every file, and an
/// entry-level `seek` replaces it for that file.
///
/// The whole request is rejected upfront (400) when a path is invalid,
/// paths are duplicated, or more than `limits.batch_read_maximum_files`
/// paths are asked for — a safety cap against unbounded response sizes.
/// A file that exists but cannot be represented (invalid UTF-8) fails the
/// whole batch with a 422, so `null` strictly means "not found".
pub async fn batch_read_files(
    State(state): State<AppState>,
    Path((collection_id, tenant_id)): Path<(String, String)>,
    Json(body): Json<BatchReadFilesRequest>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    if body.files.is_empty() {
        return Err(AppError::InvalidOperation {
            reason: "files must contain at least one path".to_string(),
        });
    }

    let maximum_files = state.config.limits.batch_read_maximum_files;

    if body.files.len() > maximum_files {
        return Err(AppError::InvalidOperation {
            reason: format!(
                "files must not contain more than {} paths ({} requested)",
                maximum_files,
                body.files.len()
            ),
        });
    }

    let global_seek = body.seek.unwrap_or_default().parse()?;

    // Sanitise every path with the same rules as the single read route,
    // *before* the uniqueness check so that two spellings of the same file
    // (e.g. `a.md` and `/a.md`) are caught as duplicates. Each entry's
    // effective seek is resolved here too: its own window when it carries
    // one, the request-level window otherwise.
    let mut seen_paths = HashSet::new();
    let mut file_reads: Vec<(String, SeekFilter)> = Vec::with_capacity(body.files.len());

    for (index, entry) in body.files.iter().enumerate() {
        let (raw_path, entry_seek) = entry.parts();

        let file_path = validate::file_path(raw_path)?.to_string();

        if !seen_paths.insert(file_path.clone()) {
            return Err(AppError::InvalidOperation {
                reason: format!("files must be unique: '{}' is requested twice", file_path),
            });
        }

        let seek = match entry_seek {
            None => global_seek.clone(),

            // Prefix validation errors with the entry's index so the caller
            // knows which per-file seek is malformed (the request-level one
            // reports without a prefix).
            Some(entry_seek) => entry_seek.parse().map_err(|err| match err {
                AppError::InvalidOperation { reason } => AppError::InvalidOperation {
                    reason: format!("files[{}]: {}", index, reason),
                },
                other => other,
            })?,
        };

        file_reads.push((file_path, seek));
    }

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, count = file_reads.len(), seek = ?global_seek, "handling batch read files request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let file_reads_for_task = file_reads.clone();

    let contents = run_blocking(move || {
        git::GitFiles::batch_read_files(&repo_path, &tenant_id, &file_reads_for_task)
    })
    .await?;

    let files: Vec<_> = file_reads
        .iter()
        .zip(contents)
        .map(|((path, _seek), content)| {
            content.map(|content| json!({ "path": path, "content": content }))
        })
        .collect();

    Ok(Json(json!({ "files": files })))
}

/// HEAD /:collection_id/:tenant_id/files/*path
/// Returns 200 with no body when the file exists in HEAD, 404 otherwise.
/// Cheaper than GET as the blob content is never loaded.
pub async fn file_exists(
    State(state): State<AppState>,
    Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
    let file_path = validate::file_path(&file_path)?.to_string();

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, "handling file existence request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    run_blocking(move || git::GitFiles::file_exists(&repo_path, &tenant_id, &file_path)).await?;

    Ok(StatusCode::OK)
}

/// PUT /:collection_id/:tenant_id/files/*path
/// Creates or updates a file, commits the change, and fires a hook.
///
/// PUT is idempotent by design: the caller does not need to know whether the
/// file exists. The server decides created-vs-updated from HEAD's tree and
/// reflects that in both the auto-generated commit message and the hook
/// event kind. Idempotency extends to content: re-PUTting a file with the
/// exact content HEAD already holds creates no commit and fires no hook —
/// the response carries HEAD's sha instead. This is also the endpoint that
/// lazily initialises a tenant repository on first use — there is no
/// explicit "create tenant" call.
pub async fn write_file(
    State(state): State<AppState>,
    Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
    Json(body): Json<WriteFileRequest>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
    let file_path = validate::file_path(&file_path)?.to_string();

    validate::file_extension(
        &file_path,
        state.config.limits.allowed_extensions.as_deref(),
    )?;

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, "handling write file request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let lock_key = format!("{}/{}", collection_id, tenant_id);
    let lock = state.get_repo_lock(&lock_key);
    let _lock_guard = lock.lock().await;

    let WriteFileRequest {
        author,
        content,
        message,
    } = body;

    let repo_path_for_maintenance = repo_path.clone();

    let (commit_sha, file_change) = run_blocking(move || {
        git::GitFiles::write_file(
            &repo_path,
            &file_path,
            &content,
            message.as_deref(),
            &author.name,
            &author.email,
        )
    })
    .await?;

    // A `None` change means the content already matched HEAD: no commit was
    // created, so there is nothing for downstream systems to sync and no new
    // objects for maintenance to consolidate. The returned sha is HEAD's —
    // the commit whose tree already contains exactly this content.
    let Some(file_change) = file_change else {
        tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "content unchanged, no commit created");

        return Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))));
    };

    tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "file write committed, enqueuing hook delivery");

    // Enqueued while the tenant write lock is still held, so per-tenant hook
    // order always matches commit order.
    state.hook_queue.enqueue(
        &lock_key,
        HookJob {
            tenant_id,
            commit_sha: commit_sha.clone(),
            committed_at: Utc::now(),
            file_changes: vec![file_change],
        },
    );

    state
        .maintenance
        .schedule(&lock_key, repo_path_for_maintenance, lock.clone());

    Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}

/// DELETE /:collection_id/:tenant_id/files/*path
/// Deletes a file, commits the removal, and fires a hook.
pub async fn delete_file(
    State(state): State<AppState>,
    Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
    Json(body): Json<DeleteFileRequest>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
    let file_path = validate::file_path(&file_path)?.to_string();

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, "handling delete file request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let lock_key = format!("{}/{}", collection_id, tenant_id);
    let lock = state.get_repo_lock(&lock_key);
    let _lock_guard = lock.lock().await;

    let DeleteFileRequest { author, message } = body;

    let repo_path_for_maintenance = repo_path.clone();
    let tenant_id_for_task = tenant_id.clone();

    let (commit_sha, file_change) = run_blocking(move || {
        git::GitFiles::delete_file(
            &repo_path,
            &tenant_id_for_task,
            &file_path,
            message.as_deref(),
            &author.name,
            &author.email,
        )
    })
    .await?;

    tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "file deletion committed, enqueuing hook delivery");

    // Enqueued while the tenant write lock is still held, so per-tenant hook
    // order always matches commit order.
    state.hook_queue.enqueue(
        &lock_key,
        HookJob {
            tenant_id,
            commit_sha: commit_sha.clone(),
            committed_at: Utc::now(),
            file_changes: vec![file_change],
        },
    );

    state
        .maintenance
        .schedule(&lock_key, repo_path_for_maintenance, lock.clone());

    Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}

/// POST /:collection_id/:tenant_id/files/*path/move
/// Moves/renames a file to a new path in a single atomic commit, fires a
/// single hook with both the old and new paths so the receiver can
/// correlate the rename without losing attached metadata.
///
/// Axum cannot match a fixed suffix after a wildcard segment, so this handler
/// is registered on POST `/*path` and enforces the `/move` suffix itself.
pub async fn move_file(
    State(state): State<AppState>,
    Path((collection_id, tenant_id, raw_path)): Path<(String, String, String)>,
    Json(body): Json<MoveFileRequest>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    // Enforce that the URL ends with /move — anything else on POST is not found.
    let from_path_raw = raw_path
        .strip_suffix("/move")
        .ok_or_else(|| AppError::InvalidPath {
            reason: "POST on a file path must end with /move".to_string(),
        })?;

    let from_path = validate::file_path(from_path_raw)?.to_string();
    let to_path = validate::file_path(&body.destination)?.to_string();

    // Only the destination is checked against the whitelist: files written
    // before the whitelist was configured must remain movable.
    validate::file_extension(&to_path, state.config.limits.allowed_extensions.as_deref())?;

    tracing::debug!(
        collection_id = %collection_id,
        tenant_id = %tenant_id,
        from_path = %from_path,
        to_path = %to_path,
        "handling move file request"
    );

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let lock_key = format!("{}/{}", collection_id, tenant_id);
    let lock = state.get_repo_lock(&lock_key);
    let _lock_guard = lock.lock().await;

    let MoveFileRequest {
        author,
        destination: _,
        message,
    } = body;

    let repo_path_for_maintenance = repo_path.clone();
    let tenant_id_for_task = tenant_id.clone();

    let (commit_sha, file_change) = run_blocking(move || {
        git::GitFiles::move_file(
            &repo_path,
            &tenant_id_for_task,
            &from_path,
            &to_path,
            message.as_deref(),
            &author.name,
            &author.email,
        )
    })
    .await?;

    tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "file move committed, enqueuing hook delivery");

    // Enqueued while the tenant write lock is still held, so per-tenant hook
    // order always matches commit order.
    state.hook_queue.enqueue(
        &lock_key,
        HookJob {
            tenant_id,
            commit_sha: commit_sha.clone(),
            committed_at: Utc::now(),
            file_changes: vec![file_change],
        },
    );

    state
        .maintenance
        .schedule(&lock_key, repo_path_for_maintenance, lock.clone());

    Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}