arks-server 1.3.11

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
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
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
//! 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::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

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

/// Current `ForgeStore` on-disk schema version (SO-MIG-1).
pub const CURRENT_SCHEMA_VERSION: u32 = 1;

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ForgeStore {
    #[serde(default)]
    pub schema_version: u32,
    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,
    #[serde(default)]
    pub next_deploy_key_id: u64,
    #[serde(default)]
    pub deploy_keys: Vec<DeployKeyRecord>,
    #[serde(default)]
    pub oauth_clients: Vec<OAuthClientRecord>,
    #[serde(default)]
    pub oauth_codes: Vec<OAuthCodeRecord>,
    #[serde(default)]
    pub oauth_tokens: Vec<OAuthTokenRecord>,
    #[serde(default)]
    pub repo_members: BTreeMap<String, String>,
    #[serde(default)]
    pub teams: Vec<TeamRecord>,
    /// Set when an existing `store.json` fails read or JSON parse (SEC-05 fail-closed).
    #[serde(skip)]
    pub corrupt: 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>,
    #[serde(default)]
    pub external_ids: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OAuthClientRecord {
    pub client_id: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub redirect_uris: Vec<String>,
    #[serde(default = "default_true")]
    pub public: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OAuthCodeRecord {
    pub code_hash: String,
    pub client_id: String,
    pub username: String,
    pub redirect_uri: String,
    pub scope: String,
    #[serde(default)]
    pub code_challenge: String,
    #[serde(default)]
    pub nonce: Option<String>,
    pub expires_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OAuthTokenRecord {
    pub access_hash: String,
    pub refresh_hash: String,
    pub family_id: String,
    pub client_id: String,
    pub username: String,
    pub scope: String,
    pub expires_at: i64,
    #[serde(default)]
    pub refresh_used: bool,
    #[serde(default)]
    pub revoked: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TeamRecord {
    pub name: String,
    #[serde(default)]
    pub members: Vec<String>,
    pub permission: String,
}

fn default_device_interval() -> u64 {
    5
}

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

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeployKeyRecord {
    pub id: u64,
    pub title: String,
    pub public_key: String,
    #[serde(default)]
    pub fingerprint: String,
    #[serde(default = "default_true")]
    pub read_only: bool,
    pub added_at: i64,
}

fn default_true() -> bool {
    true
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionRecord {
    pub token: String,
    pub username: String,
    pub csrf_token: String,
    pub expires_at: i64,
    #[serde(default)]
    pub last_seen_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,
    /// Scopes granted to this token (e.g. `repo:read`, `repo:write`, `admin`, `webhooks`).
    /// An empty list represents a legacy pre-E3 token with default read/write/webhooks access.
    #[serde(default)]
    pub scopes: Vec<String>,
    /// Optional Unix timestamp after which this PAT is rejected.
    #[serde(default)]
    pub expires_at: Option<i64>,
    /// Last Unix timestamp when this PAT was accepted.
    #[serde(default)]
    pub last_used_at: Option<i64>,
}

impl PatRecord {
    pub fn is_expired(&self, now: i64) -> bool {
        self.expires_at.is_some_and(|exp| exp <= now)
    }

    pub fn has_scope(&self, required: &str) -> bool {
        if self.scopes.is_empty() {
            // Backward compatibility for legacy pre-E3 tokens: read/write/webhooks allowed,
            // explicit `admin` scope only when user role is admin (checked by caller).
            return required != "admin";
        }
        if self.scopes.iter().any(|s| s == "admin" || s == required) {
            return true;
        }
        if required == "repo:read" && self.scopes.iter().any(|s| s == "repo:write") {
            return true;
        }
        false
    }
}

#[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,
    #[serde(default)]
    pub denied: bool,
    #[serde(default)]
    pub last_polled_at: i64,
    #[serde(default = "default_device_interval")]
    pub interval: u64,
}

#[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)
}

#[derive(Default)]
struct StoreSlot {
    locked: std::sync::Mutex<bool>,
    cvar: std::sync::Condvar,
}

struct OwnedStoreSlotGuard {
    slot: Arc<StoreSlot>,
}

impl OwnedStoreSlotGuard {
    fn lock(slot: Arc<StoreSlot>) -> Self {
        let mut locked = slot.locked.lock().unwrap_or_else(|e| e.into_inner());
        while *locked {
            locked = slot.cvar.wait(locked).unwrap_or_else(|e| e.into_inner());
        }
        *locked = true;
        drop(locked);
        Self { slot }
    }
}

impl Drop for OwnedStoreSlotGuard {
    fn drop(&mut self) {
        let mut locked = self.slot.locked.lock().unwrap_or_else(|e| e.into_inner());
        *locked = false;
        self.slot.cvar.notify_one();
    }
}

fn acquire_in_process_store_lock(git_dir: &Path) -> OwnedStoreSlotGuard {
    use std::collections::HashMap;
    use std::sync::{Mutex, OnceLock, Weak};
    static LOCKS: OnceLock<Mutex<HashMap<PathBuf, Weak<StoreSlot>>>> = OnceLock::new();
    let map_lock = LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
    let key = store_path(git_dir);
    let slot = {
        let mut map = map_lock.lock().unwrap_or_else(|e| e.into_inner());
        match map.get(&key).and_then(Weak::upgrade) {
            Some(existing) => existing,
            None => {
                if map.len() > 64 {
                    map.retain(|_, w| w.strong_count() > 0);
                }
                let fresh = Arc::new(StoreSlot::default());
                map.insert(key, Arc::downgrade(&fresh));
                fresh
            }
        }
    };
    OwnedStoreSlotGuard::lock(slot)
}

const STORE_LOCK_STALE_SECS: u64 = 30;
const STORE_LOCK_TIMEOUT_SECS: u64 = 15;

struct StoreFileLock {
    lock_path: PathBuf,
}

impl Drop for StoreFileLock {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.lock_path);
    }
}

/// Parse `pid=<u32>` written inside an arks cross-process lockfile (`store.json.lock`
/// or `arks-ref-gate.lock`). Returns `None` if unreadable, empty (mid-creation), or malformed.
pub(crate) fn parse_lockfile_pid(path: &Path) -> Option<u32> {
    let text = fs::read_to_string(path).ok()?;
    let pid_str = text.trim().strip_prefix("pid=")?;
    let pid = pid_str.trim().parse::<u32>().ok()?;
    if pid == 0 { None } else { Some(pid) }
}

/// Strict cross-process PID liveness probe without `unsafe` or subprocesses.
/// Returns `Some(true)` if definitely alive, `Some(false)` if definitely dead (Linux `/proc`),
/// or `None` when liveness cannot be reliably determined on this platform.
pub(crate) fn is_other_pid_alive_strict(pid: u32) -> Option<bool> {
    if pid == std::process::id() {
        return Some(true);
    }
    #[cfg(target_os = "linux")]
    {
        if Path::new("/proc/self").exists() {
            return Some(Path::new(&format!("/proc/{pid}")).exists());
        }
        None
    }
    #[cfg(not(target_os = "linux"))]
    {
        None
    }
}

fn is_store_lock_stale(lock_path: &Path, stale_after: std::time::Duration) -> bool {
    if let Some(pid) = parse_lockfile_pid(lock_path) {
        if is_other_pid_alive_strict(pid) == Some(false) {
            return true;
        }
    }
    match fs::metadata(lock_path).and_then(|m| m.modified()) {
        Ok(mtime) => mtime
            .elapsed()
            .map(|age| age >= stale_after)
            .unwrap_or(false),
        Err(_) => false,
    }
}

fn acquire_store_file_lock_with(
    lock_path: &Path,
    stale_after: std::time::Duration,
    timeout: std::time::Duration,
) -> std::io::Result<StoreFileLock> {
    use std::io::Write as _;
    if let Some(parent) = lock_path.parent() {
        fs::create_dir_all(parent)?;
    }
    let deadline = std::time::Instant::now() + timeout;
    let mut backoff_ms = 2u64;
    loop {
        match fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(lock_path)
        {
            Ok(mut f) => {
                let payload = format!("pid={}\n", std::process::id());
                let _ = f.write_all(payload.as_bytes());
                drop(f);
                return Ok(StoreFileLock {
                    lock_path: lock_path.to_path_buf(),
                });
            }
            Err(e)
                if e.kind() == std::io::ErrorKind::AlreadyExists
                    || (cfg!(windows) && e.kind() == std::io::ErrorKind::PermissionDenied) =>
            {
                if e.kind() == std::io::ErrorKind::AlreadyExists
                    && is_store_lock_stale(lock_path, stale_after)
                {
                    let _ = fs::remove_file(lock_path);
                    continue;
                }
                if std::time::Instant::now() >= deadline {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::WouldBlock,
                        format!(
                            "timed out waiting for forge store lock {}",
                            lock_path.display()
                        ),
                    ));
                }
                std::thread::sleep(std::time::Duration::from_millis(backoff_ms));
                backoff_ms = (backoff_ms * 2).min(20);
            }
            Err(e) => return Err(e),
        }
    }
}

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

/// RAII atomic read-modify-write transaction guard for [`ForgeStore`].
///
/// Holds both the per-repository in-process mutex and sibling cross-process
/// `store.json.lock` across `load → mutate → save`, preventing lost-update races
/// across threads and processes. Consuming [`commit`](Self::commit) persists
/// atomically (refusing to overwrite a corrupted store) and releases the locks.
pub struct ForgeStoreTx {
    git_dir: PathBuf,
    store: ForgeStore,
    lock_err: Option<String>,
    // Field order matters: remove lockfile BEFORE releasing in-process guard.
    _file_lock: Option<StoreFileLock>,
    _in_proc: OwnedStoreSlotGuard,
}

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 locks.
    pub fn commit(self) -> std::io::Result<()> {
        if let Some(ref err) = self.lock_err {
            return Err(std::io::Error::new(
                std::io::ErrorKind::WouldBlock,
                err.clone(),
            ));
        }
        self.store.save_owned_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(crate) 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(())
    }
}

/// Parse `<pid>` from a ForgeStore sibling temp filename `.store.json.<pid>.<seq>.tmp`.
fn parse_store_temp_pid(file_name: &str) -> Option<u32> {
    let rest = file_name.strip_prefix(".store.json.")?;
    let stem = rest.strip_suffix(".tmp")?;
    let (pid_str, seq_str) = stem.split_once('.')?;
    let pid = pid_str.parse::<u32>().ok()?;
    let _seq = seq_str.parse::<u64>().ok()?;
    if pid == 0 { None } else { Some(pid) }
}

/// Best-effort liveness probe for another process ID without `unsafe` or subprocesses.
/// Returns `true` when the PID appears alive or liveness cannot be safely disproved.
fn is_other_pid_alive(pid: u32, path: &Path) -> bool {
    if pid == std::process::id() {
        return true;
    }
    #[cfg(target_os = "linux")]
    {
        let _ = path;
        if Path::new("/proc/self").exists() {
            return Path::new(&format!("/proc/{pid}")).exists();
        }
        true
    }
    #[cfg(not(target_os = "linux"))]
    {
        // On non-Linux hosts without `/proc`, treat only sufficiently old temp files (>60s)
        // from another PID as definitely stale so concurrent processes cannot be disturbed.
        match fs::metadata(path).and_then(|m| m.modified()) {
            Ok(mtime) => mtime
                .elapsed()
                .map(|age| age < std::time::Duration::from_secs(60))
                .unwrap_or(true),
            Err(_) => true,
        }
    }
}

/// Sweep dead-PID `.store.json.<pid>.<seq>.tmp` temp files and dead-PID `store.json.lock`
/// lockfiles in `forge_dir` using a caller-supplied liveness predicate (returns removed count).
pub(crate) fn sweep_stale_temps_in_dir_with<F>(forge_dir: &Path, mut is_alive: F) -> usize
where
    F: FnMut(u32, &Path) -> bool,
{
    let Ok(entries) = fs::read_dir(forge_dir) else {
        return 0;
    };
    let mut removed = 0usize;
    for entry in entries.flatten() {
        let path = entry.path();
        let Some(name) = entry.file_name().to_str().map(str::to_string) else {
            continue;
        };
        let pid = if name == "store.json.lock" {
            parse_lockfile_pid(&path)
        } else {
            parse_store_temp_pid(&name)
        };
        let Some(pid) = pid else {
            continue;
        };
        if !is_alive(pid, &path) && fs::remove_file(&path).is_ok() {
            removed += 1;
        }
    }
    removed
}

fn sweep_stale_ref_gate_lock<F>(repo_dir: &Path, mut is_alive: F) -> usize
where
    F: FnMut(u32, &Path) -> bool,
{
    let lock_path = repo_dir.join("arks-ref-gate.lock");
    if let Some(pid) = parse_lockfile_pid(&lock_path) {
        if !is_alive(pid, &lock_path) && fs::remove_file(&lock_path).is_ok() {
            return 1;
        }
    }
    0
}

/// Sweep stale dead-PID `.store.json.*.tmp`, `store.json.lock`, and `arks-ref-gate.lock`
/// files for a single repository (or multi-repo root).
pub(crate) fn sweep_stale_temps(git_dir: &Path, multi_repo_root: bool) -> usize {
    let mut removed =
        sweep_stale_temps_in_dir_with(&git_dir.join("arks-forge"), is_other_pid_alive);
    removed += sweep_stale_ref_gate_lock(git_dir, is_other_pid_alive);
    if multi_repo_root {
        if let Ok(entries) = fs::read_dir(git_dir) {
            for entry in entries.flatten() {
                let p = entry.path();
                if p.is_dir() {
                    removed +=
                        sweep_stale_temps_in_dir_with(&p.join("arks-forge"), is_other_pid_alive);
                    removed += sweep_stale_ref_gate_lock(&p, is_other_pid_alive);
                }
            }
        }
    }
    removed
}

fn sweep_stale_temps_once(git_dir: &Path) {
    use std::collections::HashSet;
    use std::sync::{Mutex, OnceLock};
    static SWEPT: OnceLock<Mutex<HashSet<PathBuf>>> = OnceLock::new();
    let set = SWEPT.get_or_init(|| Mutex::new(HashSet::new()));
    let forge_dir = git_dir.join("arks-forge");
    let first_time = {
        let mut g = set.lock().unwrap_or_else(|e| e.into_inner());
        g.insert(forge_dir.clone())
    };
    if first_time {
        let _ = sweep_stale_temps_in_dir_with(&forge_dir, is_other_pid_alive);
    }
}

#[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(),
    })
}

type StoreCacheMap = std::collections::HashMap<PathBuf, (FileStamp, Arc<ForgeStore>)>;

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

impl ForgeStore {
    /// Returns `true` when repository visibility is explicitly `"private"`.
    pub fn is_private(&self) -> bool {
        self.visibility == "private"
    }

    /// Load a shared read-only snapshot of the forge store without deep-cloning
    /// on cache hits and without blocking on write locks. Prefer this over [`load`](Self::load)
    /// for all read handlers.
    pub fn load_shared(git_dir: &Path) -> Arc<Self> {
        sweep_stale_temps_once(git_dir);
        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 Arc::clone(cached_store);
                }
            }
        }
        Self::load_shared_unlocked(git_dir)
    }

    #[cfg(test)]
    pub fn load(git_dir: &Path) -> Self {
        (*Self::load_shared(git_dir)).clone()
    }

    /// Acquire the per-repository in-process mutex and sibling `store.json.lock`
    /// and load the store for an atomic transaction.
    pub fn lock_mut(git_dir: &Path) -> ForgeStoreTx {
        sweep_stale_temps_once(git_dir);
        let in_proc = acquire_in_process_store_lock(git_dir);
        let (file_lock, lock_err) = match acquire_store_file_lock_with(
            &store_lock_path(git_dir),
            std::time::Duration::from_secs(STORE_LOCK_STALE_SECS),
            std::time::Duration::from_secs(STORE_LOCK_TIMEOUT_SECS),
        ) {
            Ok(fl) => (Some(fl), None),
            Err(e) => (None, Some(e.to_string())),
        };
        let store = (*Self::load_shared_unlocked(git_dir)).clone();
        ForgeStoreTx {
            git_dir: git_dir.to_path_buf(),
            store,
            lock_err,
            _file_lock: file_lock,
            _in_proc: in_proc,
        }
    }

    fn load_shared_unlocked(git_dir: &Path) -> Arc<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 Arc::clone(cached_store);
                }
            }
        }
        let raw = match fs::read_to_string(&path) {
            Ok(content) => content,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Arc::new(Self {
                    schema_version: CURRENT_SCHEMA_VERSION,
                    next_id: 1,
                    next_card_id: 1,
                    next_run_id: 1,
                    ..Self::default()
                });
            }
            Err(_) => {
                let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
                cache.remove(&path);
                return Arc::new(Self {
                    corrupt: true,
                    ..Self::default()
                });
            }
        };
        let mut s: Self = match serde_json::from_str(&raw) {
            Ok(parsed) => parsed,
            Err(_) => {
                let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
                cache.remove(&path);
                return Arc::new(Self {
                    corrupt: true,
                    ..Self::default()
                });
            }
        };
        if s.schema_version > CURRENT_SCHEMA_VERSION {
            eprintln!(
                "arks serve: store {} has schema_version {} > supported {} (fail-closed)",
                path.display(),
                s.schema_version,
                CURRENT_SCHEMA_VERSION
            );
            let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
            cache.remove(&path);
            return Arc::new(Self {
                schema_version: s.schema_version,
                corrupt: true,
                ..Self::default()
            });
        }
        if s.schema_version < CURRENT_SCHEMA_VERSION {
            let from = s.schema_version;
            let bak = path.with_extension(format!("json.pre-migrate-v{from}.bak"));
            if !bak.exists() {
                let _ = atomic_write_file(&bak, raw.as_bytes());
            }
            while s.schema_version < CURRENT_SCHEMA_VERSION {
                match s.schema_version {
                    0 => {
                        // v0 -> v1: normalize sequence counters and stamp schema_version = 1.
                        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;
                        }
                        s.schema_version = 1;
                    }
                    _ => break,
                }
            }
        }
        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;
        }
        let arc = Arc::new(s);
        if let Some(st) = stamp {
            let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
            cache.insert(path, (st, Arc::clone(&arc)));
        }
        arc
    }

    fn save_owned_unlocked(mut self, git_dir: &Path) -> std::io::Result<()> {
        if self.corrupt {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "refusing to overwrite corrupted forge store.json (fail-closed)",
            ));
        }
        if self.schema_version > CURRENT_SCHEMA_VERSION {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "refusing to overwrite future store schema_version {} (supported {})",
                    self.schema_version, CURRENT_SCHEMA_VERSION
                ),
            ));
        }
        self.schema_version = CURRENT_SCHEMA_VERSION;
        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, Arc::new(self)));
        } else {
            cache.remove(&path);
        }
        Ok(())
    }

    /// Execute an atomic load-modify-save transaction under the per-repository locks.
    pub fn update<R>(git_dir: &Path, f: impl FnOnce(&mut Self) -> R) -> std::io::Result<R> {
        let mut tx = Self::lock_mut(git_dir);
        if tx.corrupt {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "refusing to mutate corrupted forge store.json (fail-closed)",
            ));
        }
        let out = f(&mut tx);
        tx.commit()?;
        Ok(out)
    }

    #[cfg(test)]
    pub fn save(&self, git_dir: &Path) -> std::io::Result<()> {
        let _in_proc = acquire_in_process_store_lock(git_dir);
        let _file_lock = acquire_store_file_lock_with(
            &store_lock_path(git_dir),
            std::time::Duration::from_secs(STORE_LOCK_STALE_SECS),
            std::time::Duration::from_secs(STORE_LOCK_TIMEOUT_SECS),
        )?;
        self.clone().save_owned_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()
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn corrupt_store_json_fails_closed_and_refuses_overwrite() {
        let dir = TempDir::new().unwrap();
        let path = store_path(dir.path());
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        let corrupt_payload = b"{not valid json!!!";
        fs::write(&path, corrupt_payload).unwrap();

        let loaded = ForgeStore::load_shared(dir.path());
        assert!(loaded.corrupt, "corrupt JSON must mark ForgeStore::corrupt");

        let tx = ForgeStore::lock_mut(dir.path());
        assert!(tx.corrupt);
        let commit_err = tx.commit().unwrap_err();
        assert_eq!(commit_err.kind(), std::io::ErrorKind::InvalidData);

        let update_err = ForgeStore::update(dir.path(), |s| {
            s.create_issue("nope".into(), "".into(), "alice".into(), vec![], None);
        })
        .unwrap_err();
        assert_eq!(update_err.kind(), std::io::ErrorKind::InvalidData);

        // Original corrupted bytes must remain untouched for operator inspection/recovery.
        assert_eq!(fs::read(&path).unwrap(), corrupt_payload);
    }

    #[test]
    fn store_tx_holds_and_releases_sibling_lockfile_and_reclaims_stale() {
        let dir = TempDir::new().unwrap();
        let lock_path = store_lock_path(dir.path());
        {
            let mut tx = ForgeStore::lock_mut(dir.path());
            assert!(
                lock_path.is_file(),
                "store.json.lock must exist while ForgeStoreTx is held"
            );
            tx.create_issue("locked".into(), "".into(), "alice".into(), vec![], None);
            tx.commit().unwrap();
        }
        assert!(
            !lock_path.exists(),
            "store.json.lock must be removed after ForgeStoreTx commit"
        );

        // Pre-seed a stale lockfile and verify immediate reclaim with short stale window.
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();
        fs::write(&lock_path, b"pid=999999\n").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(15));
        let fl = acquire_store_file_lock_with(
            &lock_path,
            std::time::Duration::from_millis(5),
            std::time::Duration::from_secs(2),
        )
        .expect("stale lockfile must be reclaimed");
        assert!(lock_path.is_file());
        drop(fl);
        assert!(!lock_path.exists());
    }

    #[test]
    fn store_tx_startup_gc_sweeps_dead_pid_lockfile_and_preserves_live_pid() {
        let dir = TempDir::new().unwrap();
        let forge_dir = dir.path().join("arks-forge");
        fs::create_dir_all(&forge_dir).unwrap();
        let lock_path = forge_dir.join("store.json.lock");

        // Live PID lockfile must NOT be swept.
        fs::write(&lock_path, format!("pid={}\n", 424_242)).unwrap();
        assert_eq!(
            sweep_stale_temps_in_dir_with(&forge_dir, |pid, _| pid == 424_242),
            0
        );
        assert!(lock_path.is_file());

        // Dead PID lockfile MUST be swept immediately by startup GC.
        fs::write(&lock_path, b"pid=999999999\n").unwrap();
        assert_eq!(
            sweep_stale_temps_in_dir_with(&forge_dir, |pid, _| pid == 424_242),
            1
        );
        assert!(!lock_path.exists());

        // On Linux (/proc), acquire_store_file_lock_with must reclaim dead PID even under a long stale window.
        #[cfg(target_os = "linux")]
        {
            fs::write(&lock_path, b"pid=999999999\n").unwrap();
            let fl = acquire_store_file_lock_with(
                &lock_path,
                std::time::Duration::from_secs(300),
                std::time::Duration::from_secs(2),
            )
            .expect("dead-PID store.json.lock must be reclaimed immediately");
            drop(fl);
            assert!(!lock_path.exists());
        }
    }

    #[test]
    fn schema_version_migrates_v0_and_fails_closed_on_future_version() {
        let dir = tempfile::TempDir::new().unwrap();
        let forge_dir = dir.path().join("arks-forge");
        fs::create_dir_all(&forge_dir).unwrap();
        let path = forge_dir.join("store.json");

        // Legacy v0 store without schema_version field.
        fs::write(&path, r#"{"next_id":0,"issues":[]}"#).unwrap();
        let loaded = ForgeStore::load_shared(dir.path());
        assert!(!loaded.corrupt);
        assert_eq!(loaded.schema_version, CURRENT_SCHEMA_VERSION);
        assert_eq!(loaded.next_id, 1);
        let bak = forge_dir.join("store.json.pre-migrate-v0.bak");
        assert!(bak.is_file(), "pre-migration backup must be written");

        // Saving stamps schema_version = CURRENT_SCHEMA_VERSION.
        ForgeStore::update(dir.path(), |s| {
            s.create_issue(
                "Migrated".into(),
                "ok".into(),
                "alice".into(),
                Vec::new(),
                None,
            );
        })
        .unwrap();
        let saved_raw = fs::read_to_string(&path).unwrap();
        assert!(saved_raw.contains(&format!("\"schema_version\": {CURRENT_SCHEMA_VERSION}")));

        // Future schema_version must fail closed and refuse mutations without touching disk.
        let future_json = format!(
            r#"{{"schema_version":{},"next_id":1,"issues":[]}}"#,
            CURRENT_SCHEMA_VERSION + 99
        );
        let dir2 = tempfile::TempDir::new().unwrap();
        let forge_dir2 = dir2.path().join("arks-forge");
        fs::create_dir_all(&forge_dir2).unwrap();
        let path2 = forge_dir2.join("store.json");
        fs::write(&path2, &future_json).unwrap();

        let future_loaded = ForgeStore::load_shared(dir2.path());
        assert!(
            future_loaded.corrupt,
            "future schema_version must fail closed"
        );
        let err = ForgeStore::update(dir2.path(), |s| {
            s.create_issue(
                "Should fail".into(),
                "".into(),
                "bob".into(),
                Vec::new(),
                None,
            );
        })
        .unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
        assert_eq!(
            fs::read_to_string(&path2).unwrap(),
            future_json,
            "fail-closed must not overwrite future store.json"
        );
    }
}