arks-server 1.2.0

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
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
//! Atomic JSON-backed local forge store (`<git_dir>/arks-forge/store.json`) for
//! self-hosted Issues, PR review comments, Projects Kanban cards, Wiki pages,
//! and local Actions workflow run logs.

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

pub const PROJECT_COLUMNS: &[(&str, &str)] = &[
    ("backlog", "Backlog"),
    ("in_progress", "In Progress"),
    ("review", "Review"),
    ("done", "Done"),
];

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ForgeStore {
    pub next_id: u64,
    pub issues: Vec<ForgeIssue>,
    #[serde(default)]
    pub pr_comments: Vec<PrComment>,
    #[serde(default)]
    pub next_card_id: u64,
    #[serde(default)]
    pub project_cards: Vec<ProjectCard>,
    #[serde(default)]
    pub wiki_pages: Vec<WikiPage>,
    #[serde(default)]
    pub next_run_id: u64,
    #[serde(default)]
    pub workflow_runs: Vec<WorkflowRun>,
    #[serde(default)]
    pub users: Vec<UserAccount>,
    #[serde(default)]
    pub sessions: Vec<SessionRecord>,
    #[serde(default)]
    pub next_pat_id: u64,
    #[serde(default)]
    pub pats: Vec<PatRecord>,
    #[serde(default)]
    pub device_codes: Vec<DeviceCodeRecord>,
    #[serde(default)]
    pub next_pr_number: u64,
    #[serde(default)]
    pub pull_requests: Vec<PullRequestRecord>,
    #[serde(default)]
    pub next_release_id: u64,
    #[serde(default)]
    pub releases: Vec<ReleaseRecord>,
    #[serde(default)]
    pub next_webhook_id: u64,
    #[serde(default)]
    pub webhooks: Vec<WebhookRecord>,
    #[serde(default)]
    pub webhook_deliveries: Vec<WebhookDelivery>,
    #[serde(default)]
    pub branch_rules: Vec<BranchRule>,
    #[serde(default)]
    pub pr_reviews: Vec<PrReviewVerdict>,
    #[serde(default)]
    pub visibility: String,
    #[serde(default)]
    pub org_name: Option<String>,
    #[serde(default)]
    pub collaborators: Vec<String>,
    #[serde(default)]
    pub watchers: Vec<String>,
    #[serde(default)]
    pub read_notifications: Vec<String>,
    #[serde(default)]
    pub audit_log: Vec<AuditEntry>,
    #[serde(default)]
    pub action_artifacts: Vec<ActionArtifact>,
    #[serde(default)]
    pub action_secrets: BTreeMap<String, String>,
    #[serde(default)]
    pub archived: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuditEntry {
    pub id: u64,
    pub actor: String,
    pub action: String,
    pub target: String,
    pub created_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ActionArtifact {
    pub run_id: u64,
    pub name: String,
    pub sha256: String,
    pub size_bytes: usize,
    pub created_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrReviewVerdict {
    pub id: u64,
    pub branch: String,
    pub author: String,
    /// `"approved"` | `"changes_requested"` | `"commented"`
    pub state: String,
    pub body: String,
    pub created_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ForgeIssue {
    pub id: u64,
    pub title: String,
    pub body: String,
    pub state: String,
    pub author: String,
    pub created_at: i64,
    #[serde(default)]
    pub labels: Vec<String>,
    #[serde(default)]
    pub assignee: Option<String>,
    #[serde(default)]
    pub comments: Vec<ForgeComment>,
    #[serde(default)]
    pub reactions: BTreeMap<String, Vec<String>>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ForgeComment {
    pub author: String,
    pub body: String,
    pub created_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrComment {
    pub branch: String,
    pub author: String,
    pub body: String,
    pub created_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ProjectCard {
    pub id: u64,
    pub title: String,
    pub column: String,
    #[serde(default)]
    pub issue_id: Option<u64>,
    #[serde(default)]
    pub assignee: Option<String>,
    pub created_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WikiPage {
    pub slug: String,
    pub title: String,
    pub body: String,
    pub author: String,
    pub updated_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WorkflowRun {
    pub id: u64,
    pub workflow: String,
    pub status: String,
    pub exit_code: i32,
    pub log: String,
    pub started_at: i64,
    pub finished_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UserAccount {
    pub username: String,
    pub password_hash: String,
    pub role: String,
    #[serde(default)]
    pub ssh_keys: Vec<SshKeyRecord>,
    pub created_at: i64,
    #[serde(default)]
    pub totp_secret_b32: Option<String>,
    #[serde(default)]
    pub recovery_codes: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SshKeyRecord {
    pub title: String,
    pub public_key: String,
    pub added_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionRecord {
    pub token: String,
    pub username: String,
    pub csrf_token: String,
    pub expires_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PatRecord {
    pub id: u64,
    pub username: String,
    pub name: String,
    pub token_hash: String,
    pub prefix: String,
    pub created_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeviceCodeRecord {
    pub device_code: String,
    pub user_code: String,
    #[serde(default)]
    pub approved_user: Option<String>,
    pub expires_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PullRequestRecord {
    pub number: u64,
    pub title: String,
    pub body: String,
    pub head_branch: String,
    pub base_branch: String,
    #[serde(default)]
    pub draft: bool,
    pub state: String,
    pub author: String,
    pub created_at: i64,
    #[serde(default)]
    pub inline_comments: Vec<InlineComment>,
    #[serde(default)]
    pub reviewers: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InlineComment {
    pub id: u64,
    pub path: String,
    pub line: usize,
    pub author: String,
    pub body: String,
    #[serde(default)]
    pub resolved: bool,
    pub created_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReleaseRecord {
    pub id: u64,
    pub tag: String,
    pub title: String,
    pub notes: String,
    #[serde(default)]
    pub draft: bool,
    #[serde(default)]
    pub prerelease: bool,
    pub author: String,
    pub created_at: i64,
    #[serde(default)]
    pub assets: Vec<ReleaseAsset>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReleaseAsset {
    pub name: String,
    pub size: u64,
    pub sha256: String,
    pub uploaded_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WebhookRecord {
    pub id: u64,
    pub url: String,
    pub secret: String,
    #[serde(default)]
    pub events: Vec<String>,
    #[serde(default)]
    pub active: bool,
    pub created_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WebhookDelivery {
    pub id: u64,
    pub webhook_id: u64,
    pub event: String,
    pub status: u16,
    pub created_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BranchRule {
    pub pattern: String,
    #[serde(default)]
    pub require_pr: bool,
    #[serde(default)]
    pub block_force_push: bool,
    #[serde(default)]
    pub block_delete: bool,
    #[serde(default)]
    pub required_reviews: u32,
}

fn store_path(git_dir: &Path) -> PathBuf {
    git_dir.join("arks-forge").join("store.json")
}

pub fn now_unix() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

pub fn sanitize_slug(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut prev_dash = false;
    for ch in input.trim().chars() {
        let c = ch.to_ascii_lowercase();
        if c.is_ascii_alphanumeric() {
            out.push(c);
            prev_dash = false;
        } else if (c == '-' || c == '_' || c == ' ') && !prev_dash && !out.is_empty() {
            out.push('-');
            prev_dash = true;
        }
    }
    out.trim_end_matches('-').to_string()
}

pub fn parse_labels_csv(raw: &str) -> Vec<String> {
    let mut out = Vec::new();
    for part in raw.split(',') {
        let trimmed = part.trim();
        if !trimmed.is_empty() && !out.iter().any(|existing: &String| existing == trimmed) {
            out.push(trimmed.to_string());
        }
    }
    out
}

pub fn is_valid_project_column(col: &str) -> bool {
    PROJECT_COLUMNS.iter().any(|(key, _)| *key == col)
}

fn store_mutex(git_dir: &Path) -> &'static std::sync::Mutex<()> {
    use std::collections::HashMap;
    use std::sync::{Mutex, OnceLock};
    static LOCKS: OnceLock<Mutex<HashMap<PathBuf, &'static Mutex<()>>>> = OnceLock::new();
    let map_lock = LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
    let key = store_path(git_dir);
    let mut map = map_lock.lock().unwrap_or_else(|e| e.into_inner());
    map.entry(key)
        .or_insert_with(|| Box::leak(Box::new(Mutex::new(()))))
}

/// RAII atomic read-modify-write transaction guard for [`ForgeStore`].
///
/// Holds the per-repository mutex across `load_unlocked → mutate → save_unlocked`,
/// preventing lost-update races under concurrent requests. Consuming [`commit`](Self::commit)
/// persists atomically and immediately releases the lock.
pub struct ForgeStoreTx {
    git_dir: PathBuf,
    store: ForgeStore,
    _guard: std::sync::MutexGuard<'static, ()>,
}

impl std::ops::Deref for ForgeStoreTx {
    type Target = ForgeStore;
    fn deref(&self) -> &Self::Target {
        &self.store
    }
}

impl std::ops::DerefMut for ForgeStoreTx {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.store
    }
}

impl ForgeStoreTx {
    /// Atomically persist all mutations and release the per-repository mutex.
    pub fn commit(self) -> std::io::Result<()> {
        self.store.save_unlocked(&self.git_dir)
    }
}

/// Atomically write `data` to `path` via a sibling temp file, `sync_all`, and `rename`.
/// On Windows, retries transient `PermissionDenied` rename collisions (e.g. concurrent readers
/// or antivirus/indexer handle holds) up to 5 times with 10ms backoff.
pub(super) fn atomic_write_file(path: &Path, data: &[u8]) -> std::io::Result<()> {
    use std::io::Write as _;
    use std::sync::atomic::{AtomicU64, Ordering};
    static WRITE_SEQ: AtomicU64 = AtomicU64::new(1);

    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let seq = WRITE_SEQ.fetch_add(1, Ordering::Relaxed);
    let file_name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("arks-file");
    let tmp = path.with_file_name(format!(".{file_name}.{}.{seq}.tmp", std::process::id()));
    let write_res = (|| -> std::io::Result<()> {
        let mut f = fs::File::create(&tmp)?;
        f.write_all(data)?;
        f.sync_all()?;
        Ok(())
    })();
    if let Err(e) = write_res {
        let _ = fs::remove_file(&tmp);
        return Err(e);
    }
    #[cfg(windows)]
    {
        let mut last_err = None;
        for attempt in 0..5u32 {
            match fs::rename(&tmp, path) {
                Ok(()) => return Ok(()),
                Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied && attempt < 4 => {
                    last_err = Some(e);
                    std::thread::sleep(std::time::Duration::from_millis(10));
                }
                Err(e) => {
                    let _ = fs::remove_file(&tmp);
                    return Err(e);
                }
            }
        }
        let _ = fs::remove_file(&tmp);
        Err(last_err.unwrap_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::PermissionDenied, "atomic rename failed")
        }))
    }
    #[cfg(not(windows))]
    {
        if let Err(e) = fs::rename(&tmp, path) {
            let _ = fs::remove_file(&tmp);
            return Err(e);
        }
        Ok(())
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
struct FileStamp {
    len: u64,
    mtime: Option<std::time::SystemTime>,
}

fn file_stamp(path: &Path) -> Option<FileStamp> {
    let meta = fs::metadata(path).ok()?;
    Some(FileStamp {
        len: meta.len(),
        mtime: meta.modified().ok(),
    })
}

fn store_cache()
-> &'static std::sync::RwLock<std::collections::HashMap<PathBuf, (FileStamp, ForgeStore)>> {
    use std::collections::HashMap;
    use std::sync::{OnceLock, RwLock};
    static CACHE: OnceLock<RwLock<HashMap<PathBuf, (FileStamp, ForgeStore)>>> = OnceLock::new();
    CACHE.get_or_init(|| RwLock::new(HashMap::new()))
}

impl ForgeStore {
    pub fn load(git_dir: &Path) -> Self {
        let path = store_path(git_dir);
        if let Some(stamp) = file_stamp(&path) {
            let cache = store_cache().read().unwrap_or_else(|e| e.into_inner());
            if let Some((cached_stamp, cached_store)) = cache.get(&path) {
                if *cached_stamp == stamp {
                    return cached_store.clone();
                }
            }
        }
        let lock = store_mutex(git_dir);
        let _guard = lock.lock().unwrap_or_else(|e| e.into_inner());
        Self::load_unlocked(git_dir)
    }

    /// Acquire the per-repository mutex and load the store for an atomic transaction.
    pub fn lock_mut(git_dir: &Path) -> ForgeStoreTx {
        let guard = store_mutex(git_dir)
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let store = Self::load_unlocked(git_dir);
        ForgeStoreTx {
            git_dir: git_dir.to_path_buf(),
            store,
            _guard: guard,
        }
    }

    fn load_unlocked(git_dir: &Path) -> Self {
        let path = store_path(git_dir);
        let stamp = file_stamp(&path);
        if let Some(st) = stamp {
            let cache = store_cache().read().unwrap_or_else(|e| e.into_inner());
            if let Some((cached_stamp, cached_store)) = cache.get(&path) {
                if *cached_stamp == st {
                    return cached_store.clone();
                }
            }
        }
        let Ok(raw) = fs::read_to_string(&path) else {
            return Self {
                next_id: 1,
                next_card_id: 1,
                next_run_id: 1,
                ..Self::default()
            };
        };
        let mut s: Self = serde_json::from_str(&raw).unwrap_or_default();
        if s.next_id == 0 {
            s.next_id = s.issues.iter().map(|i| i.id).max().unwrap_or(0) + 1;
        }
        if s.next_card_id == 0 {
            s.next_card_id = s.project_cards.iter().map(|c| c.id).max().unwrap_or(0) + 1;
        }
        if s.next_run_id == 0 {
            s.next_run_id = s.workflow_runs.iter().map(|r| r.id).max().unwrap_or(0) + 1;
        }
        if let Some(st) = stamp {
            let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
            cache.insert(path, (st, s.clone()));
        }
        s
    }

    fn save_unlocked(&self, git_dir: &Path) -> std::io::Result<()> {
        let path = store_path(git_dir);
        let data = serde_json::to_vec_pretty(self)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        atomic_write_file(&path, &data)?;
        let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
        if let Some(st) = file_stamp(&path) {
            cache.insert(path, (st, self.clone()));
        } else {
            cache.remove(&path);
        }
        Ok(())
    }

    /// Execute an atomic load-modify-save transaction under the per-repository mutex.
    pub fn update<R>(git_dir: &Path, f: impl FnOnce(&mut Self) -> R) -> std::io::Result<R> {
        let lock = store_mutex(git_dir);
        let _guard = lock.lock().unwrap_or_else(|e| e.into_inner());
        let mut store = Self::load_unlocked(git_dir);
        let out = f(&mut store);
        store.save_unlocked(git_dir)?;
        Ok(out)
    }

    #[cfg(test)]
    pub fn save(&self, git_dir: &Path) -> std::io::Result<()> {
        let lock = store_mutex(git_dir);
        let _guard = lock.lock().unwrap_or_else(|e| e.into_inner());
        self.save_unlocked(git_dir)
    }

    pub fn create_issue(
        &mut self,
        title: String,
        body: String,
        author: String,
        labels: Vec<String>,
        assignee: Option<String>,
    ) -> u64 {
        let id = self.next_id.max(1);
        self.next_id = id + 1;
        self.issues.push(ForgeIssue {
            id,
            title,
            body,
            state: "open".into(),
            author,
            created_at: now_unix(),
            labels,
            assignee,
            comments: Vec::new(),
            reactions: BTreeMap::new(),
        });
        id
    }

    pub fn update_issue_meta(
        &mut self,
        id: u64,
        labels: Vec<String>,
        assignee: Option<String>,
    ) -> bool {
        let Some(issue) = self.issues.iter_mut().find(|i| i.id == id) else {
            return false;
        };
        issue.labels = labels;
        issue.assignee = assignee;
        true
    }

    pub fn add_issue_comment(&mut self, id: u64, author: String, body: String) -> bool {
        let Some(issue) = self.issues.iter_mut().find(|i| i.id == id) else {
            return false;
        };
        issue.comments.push(ForgeComment {
            author,
            body,
            created_at: now_unix(),
        });
        true
    }

    pub fn toggle_issue_state(&mut self, id: u64) -> Option<&str> {
        let issue = self.issues.iter_mut().find(|i| i.id == id)?;
        issue.state = if issue.state == "open" {
            "closed".into()
        } else {
            "open".into()
        };
        Some(issue.state.as_str())
    }

    pub fn add_pr_comment(&mut self, branch: String, author: String, body: String) {
        self.pr_comments.push(PrComment {
            branch,
            author,
            body,
            created_at: now_unix(),
        });
    }

    pub fn create_card(
        &mut self,
        title: String,
        column: String,
        issue_id: Option<u64>,
        assignee: Option<String>,
    ) -> u64 {
        let id = self.next_card_id.max(1);
        self.next_card_id = id + 1;
        let col = if is_valid_project_column(&column) {
            column
        } else {
            "backlog".to_string()
        };
        self.project_cards.push(ProjectCard {
            id,
            title,
            column: col,
            issue_id,
            assignee,
            created_at: now_unix(),
        });
        id
    }

    pub fn move_card(&mut self, id: u64, column: &str) -> bool {
        if !is_valid_project_column(column) {
            return false;
        }
        let Some(card) = self.project_cards.iter_mut().find(|c| c.id == id) else {
            return false;
        };
        card.column = column.to_string();
        true
    }

    pub fn delete_card(&mut self, id: u64) -> bool {
        let before = self.project_cards.len();
        self.project_cards.retain(|c| c.id != id);
        self.project_cards.len() < before
    }

    pub fn upsert_wiki_page(
        &mut self,
        slug: String,
        title: String,
        body: String,
        author: String,
    ) -> String {
        let clean_slug = sanitize_slug(if slug.is_empty() { &title } else { &slug });
        let final_slug = if clean_slug.is_empty() {
            "home".to_string()
        } else {
            clean_slug
        };
        let now = now_unix();
        if let Some(existing) = self.wiki_pages.iter_mut().find(|p| p.slug == final_slug) {
            existing.title = title;
            existing.body = body;
            existing.author = author;
            existing.updated_at = now;
        } else {
            self.wiki_pages.push(WikiPage {
                slug: final_slug.clone(),
                title,
                body,
                author,
                updated_at: now,
            });
        }
        final_slug
    }

    pub fn delete_wiki_page(&mut self, slug: &str) -> bool {
        let before = self.wiki_pages.len();
        self.wiki_pages.retain(|p| p.slug != slug);
        self.wiki_pages.len() < before
    }

    #[allow(dead_code)]
    pub fn record_workflow_run(
        &mut self,
        workflow: String,
        status: String,
        exit_code: i32,
        log: String,
        started_at: i64,
        finished_at: i64,
    ) -> u64 {
        let id = self.next_run_id.max(1);
        self.next_run_id = id + 1;
        self.workflow_runs.push(WorkflowRun {
            id,
            workflow,
            status,
            exit_code,
            log,
            started_at,
            finished_at,
        });
        id
    }
}

/// Parse `application/x-www-form-urlencoded` body or query string into key-value map.
pub fn parse_form_urlencoded(body: &[u8]) -> BTreeMap<String, String> {
    let text = String::from_utf8_lossy(body);
    let mut map = BTreeMap::new();
    for pair in text.split('&') {
        if let Some((k, v)) = pair.split_once('=') {
            map.insert(percent_decode(k), percent_decode(v));
        }
    }
    map
}

fn percent_decode(input: &str) -> String {
    let mut bytes = Vec::with_capacity(input.len());
    let raw = input.as_bytes();
    let mut i = 0;
    while i < raw.len() {
        if raw[i] == b'+' {
            bytes.push(b' ');
            i += 1;
        } else if raw[i] == b'%' && i + 2 < raw.len() {
            if let Ok(val) = u8::from_str_radix(&input[i + 1..i + 3], 16) {
                bytes.push(val);
                i += 3;
                continue;
            }
            bytes.push(b'%');
            i += 1;
        } else {
            bytes.push(raw[i]);
            i += 1;
        }
    }
    String::from_utf8_lossy(&bytes).into_owned()
}