oomtop-core 0.2.0

oomtop core: pure data model, units, attribution, headroom, forecast, throttle, query and ranking logic (no I/O)
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
//! Privacy (SPEC §13): command-line redaction for exports, the marker-key allowlist, and marker hashing.
//!
//! - Environments are read only for allowlisted keys; values are never stored (session ids are hashed).
//! - Every export (json, ndjson, serve, MCP) must call [`redact_snapshot`].
//! - Redaction is deliberately conservative: when in doubt a value is replaced. Things redacted:
//!   `--token=…`-style flags and the argument after a bare secret flag (`--api-key sk-…`), `KEY=value`
//!   assignments (any ALL-CAPS environment-style assignment and any key naming a secret — the secret word may
//!   be the whole key, `password=…`, and the assignment may sit in a comma list, `-o username=u,password=…`),
//!   credentials in URLs (`scheme://user:pw@host`, `scheme://token@host`, also when the password contains `@`
//!   or `/`) and secret query parameters, `sshpass -p …`, `Authorization`-style
//!   headers, well-known token formats (OpenAI/Anthropic/GitHub/GitLab/Slack/AWS/HF/Google/Stripe/npm/JWT),
//!   UUIDs (session ids are often passed on the command line) and long high-entropy strings.

use crate::model::{Markers, Snapshot};
use regex::Regex;
use sha2::{Digest, Sha256};
use std::sync::OnceLock;

pub const REDACTED: &str = "<redacted>";

/// Default marker-key allowlist (config `privacy.marker_allowlist` extends/overrides it).
/// Keys only — e.g. `CLAUDE_CODE_MESSAGING_TOKEN` is deliberately absent.
pub const DEFAULT_MARKER_ALLOWLIST: &[&str] = &[
    "CLAUDECODE",
    "CLAUDE_CODE_SESSION_ID",
    "CLAUDE_CODE_ENTRYPOINT",
    "CODEX_SANDBOX",
    "CODEX_SESSION_ID",
    "CURSOR_AGENT",
    "CURSOR_TRACE_ID",
    "GEMINI_CLI",
    "GOOSE_SESSION_ID",
    "AIDER_SESSION",
    "OOMTOP_SESSION",
    "TERM_PROGRAM",
];

/// Minimum length of a standalone string considered for high-entropy redaction.
const ENTROPY_MIN_LEN: usize = 32;
/// Shannon entropy (bits per char) above which a long token-shaped string is treated as a secret.
const ENTROPY_BITS: f64 = 4.2;

/// True if `key` is in the allowlist (exact match; a trailing `*` in an entry is a prefix match).
pub fn is_allowlisted(key: &str, allowlist: &[String]) -> bool {
    allowlist.iter().any(|a| match a.strip_suffix('*') {
        Some(prefix) => key.starts_with(prefix),
        None => a == key,
    })
}

pub fn default_allowlist() -> Vec<String> {
    DEFAULT_MARKER_ALLOWLIST.iter().map(|s| s.to_string()).collect()
}

/// Stable, non-reversible hash of a marker value (hex, 16 chars).
pub fn hash_marker(value: &str) -> String {
    let mut h = Sha256::new();
    h.update(b"oomtop-marker-v1:");
    h.update(value.as_bytes());
    let d = h.finalize();
    d.iter().take(8).map(|b| format!("{b:02x}")).collect()
}

fn agent_for_key(key: &str) -> Option<&'static str> {
    if key.starts_with("CLAUDE") {
        Some("claude-code")
    } else if key.starts_with("CODEX") {
        Some("codex")
    } else if key.starts_with("CURSOR") {
        Some("cursor")
    } else if key.starts_with("GEMINI") {
        Some("gemini")
    } else if key.starts_with("GOOSE") {
        Some("goose")
    } else if key.starts_with("AIDER") {
        Some("aider")
    } else {
        None
    }
}

/// Suffix of marker keys whose value is a session id.
const SESSION_ID_SUFFIX: &str = "SESSION_ID";

/// Builds [`Markers`] from environment pairs. Non-allowlisted pairs are skipped without being copied; the
/// only values that survive are *hashes* of non-empty `*SESSION_ID` values: `session_id` is the first one,
/// and when the environment carries more than one `*SESSION_ID` key (an agent started inside another agent
/// inherits the outer one's id) each is also recorded in `keys` as `KEY=<hash>`, so a rule reads the id of
/// its own key ([`session_id_for_key`]) and never another agent's.
pub fn markers_from_env<'a>(
    pairs: impl IntoIterator<Item = (&'a str, &'a str)>,
    allowlist: &[String],
) -> Markers {
    let mut m = Markers::default();
    let mut session_keys = 0usize;
    let mut ids: Vec<(String, String)> = Vec::new();
    for (k, v) in pairs {
        if !is_allowlisted(k, allowlist) {
            continue;
        }
        // An allowlist pattern such as `FOO*` must never smuggle a `KEY=<value>` shaped key in.
        if k.contains('=') {
            continue;
        }
        if !m.keys.iter().any(|x| x == k) && k.ends_with(SESSION_ID_SUFFIX) {
            session_keys += 1;
        }
        m.keys.push(k.to_string());
        if m.agent.is_none() {
            m.agent = agent_for_key(k).map(str::to_string);
        }
        if k.ends_with(SESSION_ID_SUFFIX) && !v.trim().is_empty() {
            let h = hash_marker(v);
            if m.session_id.is_none() {
                m.session_id = Some(h.clone());
            }
            if !ids.iter().any(|(key, _)| key == k) {
                ids.push((k.to_string(), h));
            }
        }
    }
    if session_keys > 1 {
        m.keys.extend(ids.into_iter().map(|(k, h)| format!("{k}={h}")));
    }
    m.keys.sort();
    m.keys.dedup();
    m
}

/// The hashed session id that belongs to marker key `key` (a rule's `session_key = "env:KEY"`), if the
/// process carries one. With a single `*SESSION_ID` key that is `markers.session_id`; with several, the
/// `KEY=<hash>` entry of that key. A session id is never attributed to a key it did not come from.
pub fn session_id_for_key<'a>(m: &'a Markers, key: &str) -> Option<&'a str> {
    let mut qualified = false;
    for k in &m.keys {
        if let Some((name, hash)) = k.split_once('=') {
            qualified = true;
            if name == key {
                return Some(hash);
            }
        }
    }
    if qualified {
        return None;
    }
    let mut ids = m.keys.iter().filter(|k| k.ends_with(SESSION_ID_SUFFIX));
    match (ids.next(), ids.next()) {
        (Some(only), None) if only == key => m.session_id.as_deref(),
        _ => None,
    }
}

struct Patterns {
    flag_eq: Regex,
    kv_secret: Regex,
    kv_env: Regex,
    url_scheme: Regex,
    url_query: Regex,
    list_kv: Regex,
    auth_header: Regex,
    bearer: Regex,
    known_tokens: Regex,
    uuid: Regex,
    token_shape: Regex,
    hex_long: Regex,
    inline_flag: Regex,
    inline_flag_eq: Regex,
    inline_flag_arg: Regex,
    inline_sshpass: Regex,
    inline_kv: Regex,
    inline_userpass: Regex,
    inline_mysql: Regex,
}

fn patterns() -> &'static Patterns {
    static P: OnceLock<Patterns> = OnceLock::new();
    P.get_or_init(|| Patterns {
        flag_eq: Regex::new(
            r"(?is)^(--?[a-z0-9_.-]*(token|api[-_]?key|secret|password|passwd|pass|pwd|auth|credential|cookie|bearer|private[-_]?key|key)[a-z0-9_.-]*)=(.+)$",
        )
        .expect("static regex"),
        // The secret word may start the key (`password=…`, `token=…`) or follow a prefix (`db_password=…`).
        kv_secret: Regex::new(
            r"(?is)^((?:[a-z_][a-z0-9_.-]*)?(?:token|key|secret|password|passwd|pass|pwd|auth|cred|cookie)[a-z0-9_.-]*)=(.+)$",
        )
        .expect("static regex"),
        // ALL-CAPS environment-style assignment (`FOO=bar cmd`, `env HF_HOME=… …`): values may be secrets.
        kv_env: Regex::new(r"(?s)^([A-Z][A-Z0-9_]*)=(.+)$").expect("static regex"),
        // Start of a URL; any userinfo after it (user:password@ or token@) is a credential, see
        // [`redact_url_userinfo`].
        url_scheme: Regex::new(r"[a-zA-Z][a-zA-Z0-9+.-]*://").expect("static regex"),
        url_query: Regex::new(
            r"(?i)([?&;](?:[a-z0-9_.-]*(?:token|key|secret|password|passwd|auth|sig|signature|credential|session)[a-z0-9_.-]*|code)=)[^&;#\s]+",
        )
        .expect("static regex"),
        // A secret-named assignment inside a comma list (`mount -o username=u,password=…`).
        list_kv: Regex::new(
            r"(?i)(,(?:[a-z_][a-z0-9_.-]*)?(?:token|key|secret|password|passwd|pass|pwd|auth|cred|cookie)[a-z0-9_.-]*=)[^,\s]+",
        )
        .expect("static regex"),
        auth_header: Regex::new(
            r"(?i)((?:proxy-)?authorization:\s*(?:basic|bearer|token|digest)?\s*|x-api-key:\s*|api-key:\s*|cookie:\s*|x-auth-token:\s*)\S.*$",
        )
        .expect("static regex"),
        bearer: Regex::new(r"(?i)\b(bearer\s+)[A-Za-z0-9._~+/=-]+").expect("static regex"),
        known_tokens: Regex::new(concat!(
            // `\b`: a token starts a word — `task-manager-service-worker` is not an `sk-…` key.
            r"\b(sk-ant-[A-Za-z0-9_-]{10,}|sk-(?:proj-|live-|test-)?[A-Za-z0-9_-]{16,}|[sr]k_(?:live|test)_[A-Za-z0-9]{10,}",
            r"|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{20,}",
            r"|xox[abprs]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16}|ASIA[0-9A-Z]{16}|hf_[A-Za-z0-9]{20,}",
            r"|AIza[0-9A-Za-z_-]{35}|npm_[A-Za-z0-9]{36}|pypi-[A-Za-z0-9_-]{50,}|gsk_[A-Za-z0-9]{20,}|xai-[A-Za-z0-9]{20,}",
            r"|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,})"
        ))
        .expect("static regex"),
        uuid: Regex::new(r"(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$").expect("static regex"),
        token_shape: Regex::new(r"^[A-Za-z0-9_+/=-]+$").expect("static regex"),
        hex_long: Regex::new(r"(?i)^[0-9a-f]{32,}$").expect("static regex"),
        // Inside a string with whitespace (`sh -c "…"`, a rewritten process title): `--api-key=v`,
        // `--token v` (the value must not itself be a flag).
        inline_flag: Regex::new(
            r#"(?i)((?:^|\s)--?[a-z0-9_.-]*(?:token|api[-_]?key|secret|password|passphrase|passwd|auth|credential|cookie|private[-_]?key)[a-z0-9_.-]*)(=|\s+)("[^"]*"|'[^']*'|[^\s"'-][^\s]*)"#,
        )
        .expect("static regex"),
        // `--flag=value` with the same word list as `flag_eq` (`--pass=…`, `--pwd=…`, `--ssh-key=…`).
        inline_flag_eq: Regex::new(
            r#"(?i)((?:^|\s)--?[a-z0-9_.-]*(?:token|api[-_]?key|secret|password|passphrase|passwd|pass|pwd|auth|credential|cookie|bearer|private[-_]?key|key)[a-z0-9_.-]*=)("[^"]*"|'[^']*'|[^\s"']+)"#,
        )
        .expect("static regex"),
        // Any `--flag value` pair; [`is_secret_flag`] decides (so `--pass x` / `--ssh-key x` / `--pwd x` are
        // redacted like in an argv, and `--bypass x` / `--monkey x` are not).
        inline_flag_arg: Regex::new(
            r#"((?:^|\s)(--?[A-Za-z0-9_.-]+)\s+)("[^"]*"|'[^']*'|[^\s"'-][^\s]*)"#,
        )
        .expect("static regex"),
        // `sshpass -p PASSWORD ssh …` / `sshpass -pPASSWORD …` inside a shell string.
        inline_sshpass: Regex::new(r#"((?:^|[\s;&|(/"'`])sshpass\s+(?:-[a-oq-zA-Z]\S*\s+)*-p\s*)("[^"]*"|'[^']*'|[^\s"']+)"#)
            .expect("static regex"),
        // …and `NAME=value` assignments that are ALL-CAPS or name a secret (`OPENAI_API_KEY=sk-… node x`,
        // `psql "host=db password=…"`).
        inline_kv: Regex::new(
            r#"((?:^|[\s;&|(])(?:[A-Z][A-Z0-9_]*|(?i:(?:[a-z_][a-z0-9_]*)?(?:token|key|secret|password|passwd|pass|pwd|auth|cred|cookie)[a-z0-9_]*))=)("[^"]*"|'[^']*'|[^\s;&|)]+)"#,
        )
        .expect("static regex"),
        // `curl -u bob:pw`, `--user=bob:pw`, `--proxy-user 'al:pw'` inside a shell string: keep the user name.
        // A value with `://` is a URL (handled by `redact_url_userinfo`), not a user:password pair.
        inline_userpass: Regex::new(
            r#"((?:^|\s)(?:-u|-U|--user|--proxy-user)(?:=|\s+)["']?)([^\s:"'/]+):([^\s"'/][^\s"']*|/[^\s"'/][^\s"']*)"#,
        )
        .expect("static regex"),
        // `mysql -pSECRET` / `mysqldump … -pSECRET` inside a shell string (up to the end of that command).
        inline_mysql: Regex::new(
            r#"(?i)((?:^|[\s;&|(/"'`])(?:mysql|mariadb)[a-z_-]*(?:\s[^;&|\n]*?)?\s)-p([^\s"']+)"#,
        )
        .expect("static regex"),
    })
}

/// Words that name a secret anywhere at the end of a flag, compared after lowercasing and removing `-`/`_`
/// (so `--accessToken`, `--client_secret`, `--githubToken`, `--db-passphrase` all match).
const SECRET_FLAG_SUFFIXES: &[&str] = &[
    "token",
    "secret",
    "password",
    "passphrase",
    "passwd",
    "apikey",
    "credential",
    "credentials",
    "privatekey",
    "cookie",
    "auth",
    "bearer",
    "pwd",
];

/// True if a bare flag (e.g. `--token`, `--api-key`, `--password`, `--accessToken`) takes a secret as its
/// next argument.
pub fn is_secret_flag(arg: &str) -> bool {
    if !arg.starts_with('-') || arg.contains('=') {
        return false;
    }
    let a = arg.trim_start_matches('-').to_ascii_lowercase();
    if a.is_empty() {
        return false;
    }
    let squashed: String = a.chars().filter(|c| *c != '-' && *c != '_').collect();
    if SECRET_FLAG_SUFFIXES.iter().any(|k| squashed.ends_with(k)) {
        return true;
    }
    // Short words that are only secrets as a whole word (`--pass`, `--ssh-key`, not `--bypass`/`--monkey`).
    ["pass", "key"]
        .iter()
        .any(|k| a == *k || a.ends_with(&format!("-{k}")) || a.ends_with(&format!("_{k}")))
}

/// Flags whose next argument is `user:password` (curl `-u`, `--user`, `--proxy-user`, wget/httpie style).
fn is_userpass_flag(arg: &str) -> bool {
    matches!(arg, "-u" | "-U" | "--user" | "--proxy-user")
}

/// `user:password` → `user:<redacted>` (values without `:` are left alone: `-u` is often just a name).
fn redact_userpass(v: &str) -> Option<String> {
    let (user, pw) = v.split_once(':')?;
    (!pw.is_empty() && !v.contains("://")).then(|| format!("{user}:{REDACTED}"))
}

fn shannon_bits(s: &str) -> f64 {
    let mut counts = [0u32; 256];
    let bytes = s.as_bytes();
    for &b in bytes {
        counts[b as usize] += 1;
    }
    let n = bytes.len() as f64;
    counts
        .iter()
        .filter(|&&c| c > 0)
        .map(|&c| {
            let p = c as f64 / n;
            -p * p.log2()
        })
        .sum()
}

/// True if a standalone value looks like a secret or an identifier that must not leave the machine:
/// UUIDs (session ids), long hex strings, or long high-entropy token-shaped strings.
pub fn looks_like_secret(v: &str) -> bool {
    let p = patterns();
    if p.uuid.is_match(v) || p.hex_long.is_match(v) {
        return true;
    }
    if v.len() < ENTROPY_MIN_LEN || !p.token_shape.is_match(v) || v.starts_with('/') {
        return false;
    }
    let has_digit = v.bytes().any(|b| b.is_ascii_digit());
    let has_alpha = v.bytes().any(|b| b.is_ascii_alphabetic());
    has_digit && has_alpha && shannon_bits(v) >= ENTROPY_BITS
}

/// Nested `a=b=c` assignments looked into by [`redact_text`] (`--env=OPENAI_API_KEY=sk-…` is depth 1). A
/// bound, not recursion: a hostile `a=a=a=…` argument costs a few passes, never a deep stack.
const MAX_NESTED_ASSIGNMENTS: usize = 8;

/// The anchored rules for one `flag=value` / `KEY=value` string: `Some(redacted)` when the whole value goes.
fn redact_assignment(p: &Patterns, s: &str, spaced: bool) -> Option<String> {
    if let Some(c) = p.flag_eq.captures(s) {
        return Some(format!("{}={REDACTED}", &c[1]));
    }
    // A key that names a secret loses its whole value (it may contain spaces); a generic ALL-CAPS
    // assignment at the start of a shell string (`FOO=1 cmd …`) is handled word by word by the caller.
    let c = p
        .kv_secret
        .captures(s)
        .or_else(|| (!spaced).then(|| p.kv_env.captures(s)).flatten())?;
    Some(format!("{}={REDACTED}", &c[1]))
}

/// Redacts the userinfo of every URL in `s` (`scheme://user:pw@host`, `scheme://token@host`). A password
/// may contain `@` (the userinfo then ends at the last `@` of the authority) or `/` (`u:pa/ss@host`: what
/// follows the `:` is not a port, so the text up to the next `@` is still userinfo).
fn redact_url_userinfo<'a>(p: &Patterns, s: &'a str) -> std::borrow::Cow<'a, str> {
    let mut out: Option<String> = None;
    let mut copied = 0;
    for m in p.url_scheme.find_iter(s) {
        if m.start() < copied {
            continue;
        }
        let rest = &s[m.end()..];
        let url_len = rest.find(char::is_whitespace).unwrap_or(rest.len());
        let url = &rest[..url_len];
        let authority_len = url.find(['/', '?', '#']).unwrap_or(url.len());
        let mut userinfo = url[..authority_len].rfind('@');
        if userinfo.is_none() && url[authority_len..].starts_with('/') {
            // `user:pa/ss@host`: a `:` followed by something that is not a port number.
            // (`host:8080/a@b` and `[::1]:8080/a@b` are a host and a port, not credentials)
            let authority = &url[..authority_len];
            if let Some((_, after)) = authority.rsplit_once(':').filter(|_| !authority.starts_with('[')) {
                if !after.is_empty() && !after.bytes().all(|b| b.is_ascii_digit()) {
                    let tail = &url[authority_len..];
                    let stop = tail.find(['?', '#']).unwrap_or(tail.len());
                    if let Some(at) = tail[..stop].find('@') {
                        // …and the password may hold further `@`s before the host's own `/`.
                        let host = &tail[at + 1..stop];
                        let host_len = host.find('/').unwrap_or(host.len());
                        let last = host[..host_len].rfind('@').map(|k| at + 1 + k).unwrap_or(at);
                        userinfo = Some(authority_len + last);
                    }
                }
            }
        }
        let Some(at) = userinfo.filter(|&at| at > 0) else {
            continue;
        };
        let o = out.get_or_insert_with(|| String::with_capacity(s.len()));
        o.push_str(&s[copied..m.end()]);
        o.push_str(REDACTED);
        copied = m.end() + at;
    }
    match out {
        Some(mut o) => {
            o.push_str(&s[copied..]);
            o.into()
        }
        None => s.into(),
    }
}

/// Redacts secrets inside one string (flags with `=`, KEY=value, URL credentials/query tokens, auth
/// headers, bearer tokens, known token formats, UUIDs and high-entropy values).
pub fn redact_text(s: &str) -> String {
    let p = patterns();
    let spaced = s.chars().any(char::is_whitespace);
    // `--flag=value` / `key=value`: the anchored rules, a secret-looking value, or a nested assignment
    // such as `--env=OPENAI_API_KEY=sk-…` (looked into iteratively, at most `MAX_NESTED_ASSIGNMENTS` deep).
    let mut start = 0;
    for depth in 0..=MAX_NESTED_ASSIGNMENTS {
        let cur = &s[start..];
        if let Some(r) = redact_assignment(p, cur, spaced) {
            return format!("{}{r}", &s[..start]);
        }
        match cur.split_once('=') {
            Some((k, v))
                if !k.is_empty() && !v.bytes().all(|b| b == b'=') && !k.contains("://") && !spaced =>
            {
                if looks_like_secret(v) {
                    return format!("{}{k}={REDACTED}", &s[..start]);
                }
                if v.contains('=') && !v.contains("://") {
                    start += k.len() + 1;
                    continue;
                }
            }
            _ => {
                if depth == 0 && looks_like_secret(s) {
                    return REDACTED.to_string();
                }
            }
        }
        break;
    }
    let mut s = std::borrow::Cow::Borrowed(s);
    if spaced {
        // MySQL first: a password that happens to contain a secret word (`-pSECRET`, `-pmytoken`) would
        // otherwise read as a secret *flag* and take the next word (the database name) with it.
        s = p
            .inline_mysql
            .replace_all(&s, format!("${{1}}-p{REDACTED}").as_str())
            .into_owned()
            .into();
        s = p
            .inline_sshpass
            .replace_all(&s, format!("${{1}}{REDACTED}").as_str())
            .into_owned()
            .into();
        s = p
            .inline_flag_eq
            .replace_all(&s, format!("${{1}}{REDACTED}").as_str())
            .into_owned()
            .into();
        s = p
            .inline_flag
            .replace_all(&s, format!("${{1}}${{2}}{REDACTED}").as_str())
            .into_owned()
            .into();
        // `--pass x`, `--ssh-key x`, `--pwd x`: the flags `redact_cmdline` treats as taking a secret.
        s = p
            .inline_flag_arg
            .replace_all(&s, |c: &regex::Captures<'_>| {
                if is_secret_flag(&c[2]) && !c[3].contains(REDACTED) {
                    format!("{}{REDACTED}", &c[1])
                } else {
                    c[0].to_string()
                }
            })
            .into_owned()
            .into();
        s = p
            .inline_kv
            .replace_all(&s, format!("${{1}}{REDACTED}").as_str())
            .into_owned()
            .into();
        s = p
            .inline_userpass
            .replace_all(&s, format!("${{1}}${{2}}:{REDACTED}").as_str())
            .into_owned()
            .into();
    }
    let s = p
        .auth_header
        .replace_all(&s, format!("${{1}}{REDACTED}").as_str());
    let s = redact_url_userinfo(p, &s);
    let s = p.url_query.replace_all(&s, format!("${{1}}{REDACTED}").as_str());
    let s = p.list_kv.replace_all(&s, format!("${{1}}{REDACTED}").as_str());
    let s = p.bearer.replace_all(&s, format!("${{1}}{REDACTED}").as_str());
    let s = p.known_tokens.replace_all(&s, REDACTED);
    if spaced {
        // standalone UUIDs / long hex / high-entropy words inside free text
        let words: Vec<&str> = s.split(' ').collect();
        if words
            .iter()
            .any(|w| looks_like_secret(w.trim_matches(|c| c == '"' || c == '\'')))
        {
            return words
                .iter()
                .map(|w| {
                    if looks_like_secret(w.trim_matches(|c| c == '"' || c == '\'')) {
                        REDACTED
                    } else {
                        w
                    }
                })
                .collect::<Vec<_>>()
                .join(" ");
        }
    }
    s.into_owned()
}

/// Redacts an argv: each element via [`redact_text`], the value following a secret flag, `user:password`
/// after `-u`/`--user`/`--proxy-user`, and MySQL-style attached passwords (`mysql -pSECRET`).
pub fn redact_cmdline(argv: &[String]) -> Vec<String> {
    // `mysql …`, but also `sudo mysql …`, `env X=1 mariadb …` and a shell command split into words
    // (`zsh -c mysql -pSECRET db`): a `-p…` after a MySQL client word, before the next `;`/`&&`/`|`.
    let is_mysql = |a: &str| {
        let base = a
            .rsplit('/')
            .next()
            .unwrap_or(a)
            .trim_start_matches(['"', '\'', '`']);
        base.starts_with("mysql") || base.starts_with("mariadb")
    };
    let is_sshpass = |a: &str| {
        a.rsplit('/')
            .next()
            .unwrap_or(a)
            .trim_start_matches(['"', '\'', '`'])
            == "sshpass"
    };
    let mut mysql_like = false;
    // `sshpass -p PASSWORD ssh …` / `sshpass -pPASSWORD …`: the options before the wrapped command.
    let mut sshpass_like = false;
    let mut out = Vec::with_capacity(argv.len());
    let mut next_secret = false;
    let mut next_userpass = false;
    for a in argv {
        if next_secret {
            out.push(REDACTED.to_string());
            next_secret = false;
            next_userpass = false;
            continue;
        }
        if next_userpass {
            next_userpass = false;
            if let Some(r) = redact_userpass(a) {
                out.push(r);
                continue;
            }
        }
        if let Some((flag, v)) = a.split_once('=') {
            if is_userpass_flag(flag) {
                if let Some(r) = redact_userpass(v) {
                    out.push(format!("{flag}={r}"));
                    continue;
                }
            }
        }
        if mysql_like && a.len() > 2 && a.starts_with("-p") && !a.starts_with("--") {
            out.push(format!("-p{REDACTED}"));
            continue;
        }
        if sshpass_like {
            if a == "-p" {
                next_secret = true;
                out.push(a.clone());
                continue;
            }
            if a.len() > 2 && a.starts_with("-p") {
                out.push(format!("-p{REDACTED}"));
                continue;
            }
            // the first non-option word is the wrapped command
            if !a.starts_with('-') {
                sshpass_like = false;
            }
        }
        if is_sshpass(a) {
            sshpass_like = true;
        }
        if is_mysql(a) {
            mysql_like = true;
        } else if matches!(a.as_str(), ";" | "&&" | "||" | "|" | "&") || a.ends_with(';') {
            mysql_like = false;
            sshpass_like = false;
        }
        next_secret = is_secret_flag(a);
        next_userpass = !next_secret && is_userpass_flag(a);
        out.push(redact_text(a));
    }
    out
}

/// The exported form of a group id. Ids embed a slug of the group label (`app:<slug>`,
/// `other:<slug>:<pid>`); when [`redact_text`] changes the label, or a `:`-separated part of the id is
/// itself a UUID or long hex string, that part becomes `redacted-<8 hex>` (a hash of the original id, so two redacted
/// groups never collide and the same group keeps the same exported id). Ids without anything to hide are
/// returned unchanged. A frontend that receives an id back from an export consumer (an MCP action) resolves
/// it by comparing against `redact_group_id(&g.id, &g.label)`.
pub fn redact_group_id(id: &str, label: &str) -> String {
    let tag = || format!("redacted-{}", &hash_marker(id)[..8]);
    let mut out = id.to_string();
    if !label.is_empty() && redact_text(label) != label {
        let slug = crate::attribution::slug(label);
        if !slug.is_empty() && out.contains(&slug) {
            out = out.replace(&slug, &tag());
        }
    }
    // (UUIDs and long hex only: a slug such as `node-server-v2` is not a secret)
    let p = patterns();
    let secret = |part: &str| p.uuid.is_match(part) || p.hex_long.is_match(part);
    if out.split(':').any(secret) {
        out = out
            .split(':')
            .map(|part| if secret(part) { tag() } else { part.to_string() })
            .collect::<Vec<_>>()
            .join(":");
    }
    out
}

/// Clone of the snapshot safe for export: redacted command lines and paths; markers keep keys + hashed ids
/// only; model-server endpoints, model file paths, loaded-model names, job labels and every free-text label
/// derived from process data (group / sandbox labels, OOM victim names) go through [`redact_text`]; a group
/// id that embeds a redacted label is rewritten the same way everywhere it is referenced
/// ([`redact_group_id`]). User names (`Process.user`) are part of the data model (SPEC §5) and are exported
/// as they are, like the home directory in a path. This is the one export view: json, ndjson, serve and MCP
/// all build on it.
pub fn redact_snapshot(s: &Snapshot) -> Snapshot {
    let mut out = s.clone();
    for p in &mut out.processes {
        p.cmdline = redact_cmdline(&p.cmdline);
        p.exe = redact_text(&p.exe);
        p.name = redact_text(&p.name);
        if let Some(cwd) = &p.cwd {
            p.cwd = Some(redact_text(cwd));
        }
        for f in &mut p.model_files {
            *f = redact_text(f);
        }
        // Markers never carry raw values; drop anything that is not a known hash shape defensively.
        if let Some(sid) = &p.markers.session_id {
            if sid.len() != 16 || !sid.bytes().all(|b| b.is_ascii_hexdigit()) {
                p.markers.session_id = Some(hash_marker(sid));
            }
        }
    }
    // Group ids embed a slug of the label (`app:<slug>`, `other:<slug>:<pid>`): where the label is
    // redacted the id is too, consistently in every field that refers to it.
    let mut renamed: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    for g in &mut out.groups {
        let id = redact_group_id(&g.id, &g.label);
        if id != g.id {
            renamed.insert(std::mem::replace(&mut g.id, id.clone()), id);
        }
        g.label = redact_text(&g.label);
    }
    let rename = |id: &mut Option<String>| {
        if let Some(old) = id {
            let new = match renamed.get(old.as_str()) {
                Some(n) => n.clone(),
                // an id of a group that is gone (a dead session's orphans): only secret-shaped segments
                None => redact_group_id(old, ""),
            };
            if new != *old {
                *old = new;
            }
        }
    };
    for g in &mut out.groups {
        rename(&mut g.owner_group);
    }
    for sb in &mut out.sandboxes {
        sb.label = redact_text(&sb.label);
        rename(&mut sb.started_by_group);
    }
    for m in &mut out.model_servers {
        rename(&mut m.group_id);
    }
    if let Some(v) = &mut out.oom.likely_victim {
        v.name = redact_text(&v.name);
        rename(&mut v.group_id);
    }
    for k in &mut out.oom.recent_kills {
        if let Some(n) = &k.victim_name {
            k.victim_name = Some(redact_text(n));
        }
    }
    for m in &mut out.model_servers {
        if let Some(e) = &m.endpoint {
            m.endpoint = Some(redact_text(e));
        }
        for model in &mut m.models {
            if let Some(f) = &model.file {
                model.file = Some(redact_text(f));
            }
            model.name = redact_text(&model.name);
        }
        // Job labels come from a model server's API and can carry user text (a prompt, a file name).
        if let Some(p) = &mut m.progress {
            p.label = redact_text(&p.label);
        }
    }
    // Time and staleness (SPEC §5): projects are paths like the cwd; evidence and cohort sentences name
    // processes and sessions; cohort and duplicate lists refer to group ids.
    for p in &mut out.processes {
        if let Some(pr) = &p.project {
            p.project = Some(redact_text(pr));
        }
    }
    for g in &mut out.groups {
        if let Some(pr) = &g.project {
            g.project = Some(redact_text(pr));
        }
        rename(&mut g.cohort);
        for e in &mut g.staleness.evidence {
            e.sentence = redact_text(&e.sentence);
        }
    }
    let rename_all = |ids: &mut Vec<String>| {
        for id in ids.iter_mut() {
            let mut o = Some(std::mem::take(id));
            rename(&mut o);
            *id = o.unwrap_or_default();
        }
    };
    for c in &mut out.cohorts {
        let mut id = Some(std::mem::take(&mut c.id));
        rename(&mut id);
        c.id = id.unwrap_or_default();
        c.label = redact_text(&c.label);
        c.sentence = redact_text(&c.sentence);
        rename_all(&mut c.group_ids);
    }
    for d in &mut out.duplicates {
        d.label = redact_text(&d.label);
        d.project = redact_text(&d.project);
        rename_all(&mut d.group_ids);
    }
    // Ports and links: labels, unix paths and group ids (foreign addresses are never stored, SPEC §13).
    crate::net::redact(&mut out.net, &rename);
    // Containers, clusters, limits, namespace sets (SPEC §11): names and labels from engines and processes.
    crate::cluster::redact(&mut out.isolation, &rename);
    out
}

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

    fn v(a: &[&str]) -> Vec<String> {
        a.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn redacts_cmdlines() {
        let r = redact_cmdline(&v(&[
            "server",
            "--token=abc123",
            "--api-key",
            "sk-verysecretvalue123456",
            "HF_TOKEN=hf_xxx",
            "https://user:pw@example.com/x?token=zzz&a=1",
            "--port",
            "7861",
            "Authorization: Bearer abc.def",
        ]));
        assert_eq!(
            r,
            v(&[
                "server",
                "--token=<redacted>",
                "--api-key",
                "<redacted>",
                "HF_TOKEN=<redacted>",
                "https://<redacted>@example.com/x?token=<redacted>&a=1",
                "--port",
                "7861",
                "Authorization: Bearer <redacted>",
            ])
        );
        assert_eq!(redact_text("run sk-ant-api03-abcdefghijkl"), "run <redacted>");
    }

    #[test]
    fn env_assignments_and_ids() {
        assert_eq!(redact_text("OPENAI_BASE=http://x"), "OPENAI_BASE=<redacted>");
        assert_eq!(redact_text("db_password=hunter2"), "db_password=<redacted>");
        assert_eq!(redact_text("2f1c3a4b-1111-2222-3333-444455556666"), REDACTED);
        assert_eq!(
            redact_text("--session=2f1c3a4b-1111-2222-3333-444455556666"),
            "--session=<redacted>"
        );
        assert_eq!(
            redact_text("https://ghp_abcdefghijklmnopqrstuvwx@github.com/o/r"),
            "https://<redacted>@github.com/o/r"
        );
        assert_eq!(redact_text("Qx7fT2mZp9LkV4bN8wR1sY6cH3jD0aEu"), REDACTED);
        // ordinary arguments survive
        for keep in [
            "--listen-port",
            "7861",
            "org.gradle.launcher.daemon.bootstrap.GradleDaemon",
            "/Users/x/models/qwen-image-edit-2509-Q4_K_M.gguf",
            "--add-opens=java.base/java.lang=ALL-UNNAMED",
            "Qwen-Image-Edit-2509-Q4_K_M",
            "http://127.0.0.1:11434/api/ps",
        ] {
            assert_eq!(redact_text(keep), keep, "{keep}");
        }
    }

    #[test]
    fn secrets_inside_shell_strings_and_titles() {
        let cases = [
            ("OPENAI_API_KEY=sk-abc123 node x.js", "OPENAI_API_KEY=<redacted>"),
            (
                "cd /x && GITHUB_TOKEN=abc123 make deploy",
                "cd /x && GITHUB_TOKEN=<redacted> make deploy",
            ),
            (
                "curl --token abc123 --verbose https://h",
                "curl --token <redacted> --verbose https://h",
            ),
            (
                "node server.js --api-key=abc123 --port 80",
                "node server.js --api-key=<redacted> --port 80",
            ),
            ("run --auth --verbose", "run --auth --verbose"),
            (
                "FOO=bar HF_HOME=/m python app.py",
                "FOO=<redacted> HF_HOME=<redacted> python app.py",
            ),
            (
                "resume 2f1c3a4b-1111-2222-3333-444455556666 now",
                "resume <redacted> now",
            ),
        ];
        for (input, want) in cases {
            assert_eq!(redact_text(input), want, "{input}");
        }
        // nested assignment inside a non-secret flag
        assert_eq!(
            redact_text("--env=OPENAI_API_KEY=sk-abc"),
            "--env=OPENAI_API_KEY=<redacted>"
        );
        // multi-line values never escape the anchored patterns
        assert_eq!(redact_text("--token=abc\ndef"), "--token=<redacted>");
        assert_eq!(redact_text("API_KEY=abc\ndef"), "API_KEY=<redacted>");
        // ordinary free text survives
        assert_eq!(redact_text("fix the failing test"), "fix the failing test");
        assert_eq!(
            redact_text("nginx: master process /usr/sbin/nginx -g daemon off;"),
            "nginx: master process /usr/sbin/nginx -g daemon off;"
        );
    }

    #[test]
    fn export_redacts_labels() {
        let mut s = Snapshot::default();
        s.groups.push(crate::model::Group {
            label: "srv --token=abc123 x".into(),
            ..Default::default()
        });
        s.sandboxes.push(crate::model::Sandbox {
            label: "API_KEY=zzz".into(),
            ..Default::default()
        });
        s.oom.likely_victim = Some(crate::model::Victim {
            name: "tool --password hunter2".into(),
            ..Default::default()
        });
        s.processes.push(crate::model::Process {
            name: "tool API_KEY=qqq".into(),
            ..Default::default()
        });
        let json = serde_json::to_string(&redact_snapshot(&s)).unwrap();
        for leak in ["abc123", "zzz", "hunter2", "qqq"] {
            assert!(!json.contains(leak), "{leak} in {json}");
        }
    }

    #[test]
    fn markers_allowlist_only() {
        let allow = default_allowlist();
        let m = markers_from_env(
            [
                ("CLAUDECODE", "1"),
                ("CLAUDE_CODE_SESSION_ID", "sess-1"),
                ("CLAUDE_CODE_MESSAGING_TOKEN", "secret"),
                ("HOME", "/Users/x"),
            ],
            &allow,
        );
        assert_eq!(m.keys, v(&["CLAUDECODE", "CLAUDE_CODE_SESSION_ID"]));
        assert_eq!(m.agent.as_deref(), Some("claude-code"));
        assert_eq!(m.session_id, Some(hash_marker("sess-1")));
        assert_ne!(m.session_id.as_deref(), Some("sess-1"));
        assert!(is_allowlisted("AIDER_X", &["AIDER_*".to_string()]));
    }

    #[test]
    fn snapshot_export_is_redacted() {
        let mut s = Snapshot::default();
        s.processes.push(crate::model::Process {
            cmdline: v(&["srv", "--password", "hunter2", "KEY=v"]),
            ..Default::default()
        });
        s.processes[0].markers.session_id = Some("raw-session-value".into());
        let r = redact_snapshot(&s);
        assert_eq!(
            r.processes[0].cmdline,
            v(&["srv", "--password", REDACTED, "KEY=<redacted>"])
        );
        assert_eq!(
            r.processes[0].markers.session_id,
            Some(hash_marker("raw-session-value"))
        );
        let json = serde_json::to_string(&r).unwrap();
        assert!(!json.contains("hunter2") && !json.contains("raw-session-value"));
    }

    #[test]
    fn camel_case_and_passphrase_flags_take_the_next_argument() {
        for flag in [
            "--accessToken",
            "--authToken",
            "--clientSecret",
            "--githubToken",
            "--passphrase",
            "--db_passphrase",
            "--apiKey",
            "--privateKey",
            "--sessionCookie",
            "--oauth",
            "--token",
            "--ssh-key",
            "--pass",
        ] {
            assert!(is_secret_flag(flag), "{flag}");
            assert_eq!(
                redact_cmdline(&v(&["tool", flag, "QQvalue1"])),
                v(&["tool", flag, REDACTED]),
                "{flag}"
            );
        }
        for flag in ["--bypass", "--monkey", "--author", "--verbose", "--port", "-p"] {
            assert!(!is_secret_flag(flag), "{flag}");
        }
        assert_eq!(
            redact_cmdline(&v(&["x", "--accessToken=EQtok1"])),
            v(&["x", "--accessToken=<redacted>"])
        );
        assert_eq!(
            redact_cmdline(&v(&["x", "--passphrase=QQpass8"])),
            v(&["x", "--passphrase=<redacted>"])
        );
    }

    #[test]
    fn user_password_pairs_and_mysql_passwords() {
        assert_eq!(
            redact_cmdline(&v(&["curl", "-u", "bob:QQcurlpw5", "https://x"])),
            v(&["curl", "-u", "bob:<redacted>", "https://x"])
        );
        assert_eq!(
            redact_cmdline(&v(&["curl", "--user", "alice:QQcurlpw6", "--proxy-user=u:p"])),
            v(&["curl", "--user", "alice:<redacted>", "--proxy-user=u:<redacted>"])
        );
        // A bare user name after -u is not a secret.
        assert_eq!(
            redact_cmdline(&v(&["ps", "-u", "root"])),
            v(&["ps", "-u", "root"])
        );
        assert_eq!(
            redact_cmdline(&v(&["/usr/bin/mysql", "-pQQmysql7", "-h", "db"])),
            v(&["/usr/bin/mysql", "-p<redacted>", "-h", "db"])
        );
        assert_eq!(redact_cmdline(&v(&["ssh", "-p2222"])), v(&["ssh", "-p2222"]));
        // In a free-text process title too.
        let t = redact_text("node server.js --accessToken hunter2hunterBBB --passphrase correcthorseCCC");
        assert!(
            !t.contains("hunter2hunterBBB") && !t.contains("correcthorseCCC"),
            "{t}"
        );
    }

    #[test]
    fn user_password_pairs_and_mysql_passwords_inside_shell_strings() {
        let cases = [
            (
                "curl -u bob:hunter2 https://x",
                "curl -u bob:<redacted> https://x",
            ),
            (
                "curl --proxy-user al:pw -s https://x",
                "curl --proxy-user al:<redacted> -s https://x",
            ),
            (
                "curl --user='carol:QQpw 9' https://x",
                "curl --user='carol:<redacted> 9' https://x",
            ),
            ("curl -u \"dave:pw\" x", "curl -u \"dave:<redacted>\" x"),
            (
                "cd /srv && mysql -pSECRET -h db app",
                "cd /srv && mysql -p<redacted> -h db app",
            ),
            (
                "/usr/bin/mysqldump -u root -pS3cr3t app > dump.sql",
                "/usr/bin/mysqldump -u root -p<redacted> app > dump.sql",
            ),
            ("mariadb -h db -pQQ7 x", "mariadb -h db -p<redacted> x"),
        ];
        for (input, want) in cases {
            assert_eq!(redact_text(input), want, "{input}");
        }
        // Not user:password pairs / not MySQL: left alone.
        for keep in [
            "ps -u root -o pid",
            "curl -u https://h/x",
            "rsync -p src/ dst/",
            "mysql -p -h db",
            "echo done; ssh -p2222 host",
        ] {
            assert_eq!(redact_text(keep), keep, "{keep}");
        }
        // The whole argv of `zsh -c '…'`, as `oomtop json` exports it.
        let argv = v(&[
            "/bin/zsh",
            "-c",
            "curl -u bob:hunter2 --proxy-user al:pw https://x && mysql -pSECRET db",
        ]);
        let out = redact_cmdline(&argv).join(" ");
        for leak in ["hunter2", ":pw", "SECRET"] {
            assert!(!out.contains(leak), "{leak} leaked: {out}");
        }
        assert!(
            out.contains("bob:<redacted>") && out.contains("-p<redacted>"),
            "{out}"
        );
    }

    #[test]
    fn mysql_passwords_take_only_the_password() {
        // A password containing a secret word must not read as a secret flag that eats the database name.
        for (input, want) in [
            ("mysql -pSECRET db;", "mysql -p<redacted> db;"),
            ("mysql -pmytoken db; echo ok", "mysql -p<redacted> db; echo ok"),
            ("mysql -pAuth9 -h db app", "mysql -p<redacted> -h db app"),
            // quoted shell strings as a whole argument (`zsh -c 'mysql -p… db'` printed as one string)
            ("zsh -c 'mysql -pPW db;'", "zsh -c 'mysql -p<redacted> db;'"),
            (
                "sh -c \"mysqldump -pPW db\"",
                "sh -c \"mysqldump -p<redacted> db\"",
            ),
        ] {
            assert_eq!(redact_text(input), want, "{input}");
        }
        let cases: [(&[&str], &[&str]); 5] = [
            // shell words split into argv: `-p…` after a MySQL word is a password even if argv[0] is a shell
            (
                &["/bin/zsh", "-c", "mysql", "-pSECRET", "db;"],
                &["/bin/zsh", "-c", "mysql", "-p<redacted>", "db;"],
            ),
            (
                &["sudo", "/usr/bin/mariadb", "-u", "root", "-pPW", "app"],
                &["sudo", "/usr/bin/mariadb", "-u", "root", "-p<redacted>", "app"],
            ),
            (&["mysql", "-pSECRET", "db;"], &["mysql", "-p<redacted>", "db;"]),
            // …but not after the command ended: `ssh -p2222` is a port
            (
                &["sh", "-c", "mysql", "db", ";", "ssh", "-p2222", "host"],
                &["sh", "-c", "mysql", "db", ";", "ssh", "-p2222", "host"],
            ),
            (&["rsync", "-p", "src/", "dst/"], &["rsync", "-p", "src/", "dst/"]),
        ];
        for (input, want) in cases {
            assert_eq!(redact_cmdline(&v(input)), v(want), "{input:?}");
        }
    }

    #[test]
    fn model_names_and_job_labels_are_redacted_in_every_export() {
        let secret = "sk-ant-api03-verysecretvalue1234567890abcdef";
        let mut s = Snapshot::default();
        s.model_servers.push(crate::model::ModelServer {
            models: vec![crate::model::LoadedModel {
                name: format!("model --token={secret}"),
                ..Default::default()
            }],
            progress: Some(crate::model::JobProgress {
                label: format!("prompt with {secret}"),
                ..Default::default()
            }),
            ..Default::default()
        });
        let json = serde_json::to_string(&redact_snapshot(&s)).unwrap();
        assert!(!json.contains(secret), "{json}");
    }

    /// Audit finding 1: the secret word may be the whole key, and the assignment may sit in a comma list.
    #[test]
    fn keys_that_start_with_the_secret_word() {
        for (input, leak) in [
            ("password=hunter2", "hunter2"),
            ("token=abc123", "abc123"),
            ("secret=s3", "s3"),
            ("key=v4lue", "v4lue"),
            ("pass=opensesame", "opensesame"),
            ("Password=Hunter2", "Hunter2"),
            ("username=bob,password=hunter2", "hunter2"),
            ("rw,username=bob,password=hunter2,vers=3.0", "hunter2"),
            ("host=db user=app password=hunter2 dbname=x", "hunter2"),
            ("psql \"host=db password=hunter2\"", "hunter2"),
            ("curl --pass=hunter2 https://x", "hunter2"),
            ("tool --pwd=hunter2 run", "hunter2"),
            ("tool --pwd hunter2 run", "hunter2"),
            ("tool --pass hunter2 run", "hunter2"),
            ("tool --ssh-key hunter2 run", "hunter2"),
            ("sh -c 'sshpass -p hunter2 ssh host'", "hunter2"),
            ("sshpass -phunter2 ssh host", "hunter2"),
        ] {
            let out = redact_text(input);
            assert!(!out.contains(leak), "{input:?} → {out:?}");
            assert!(out.contains(REDACTED), "{input:?} → {out:?}");
        }
        assert_eq!(
            redact_text("rw,username=bob,password=hunter2,vers=3.0"),
            format!("rw,username=bob,password={REDACTED},vers=3.0")
        );
        let argv =
            |a: &[&str]| redact_cmdline(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>()).join(" ");
        assert_eq!(
            argv(&["mount", "-o", "username=bob,password=hunter2", "//nas/x", "/mnt"]),
            format!("mount -o username=bob,password={REDACTED} //nas/x /mnt")
        );
        assert_eq!(
            argv(&["tool", "--pwd", "hunter2"]),
            format!("tool --pwd {REDACTED}")
        );
        assert_eq!(
            argv(&["sshpass", "-p", "hunter2", "ssh", "-p", "2222", "host"]),
            format!("sshpass -p {REDACTED} ssh -p 2222 host")
        );
        assert_eq!(
            argv(&["sshpass", "-phunter2", "ssh", "host"]),
            format!("sshpass -p{REDACTED} ssh host")
        );
        // not secrets: words that merely contain a secret word, and ordinary flags
        for keep in [
            "tool --bypass yes",
            "tool --monkey see",
            "ssh -p 2222 host",
            "--output=result.txt",
            "mode=fast,level=3",
            "ls -la /tmp/keyboard",
        ] {
            assert_eq!(redact_text(keep), keep);
        }
    }

    /// Audit finding 3: nested assignments are followed iteratively, a bounded number of levels.
    #[test]
    fn nested_assignments_are_bounded_not_recursive() {
        assert_eq!(
            redact_text("--env=OPENAI_API_KEY=sk-abcdefghijklmnopqrstuvwx"),
            format!("--env=OPENAI_API_KEY={REDACTED}")
        );
        assert_eq!(
            redact_text("-e=a=b=password=hunter2"),
            format!("-e=a=b=password={REDACTED}")
        );
        // 200k `a=`: used to recurse once per `=` (stack overflow, and quadratic work)
        let hostile = "a=".repeat(200_000);
        let t = std::time::Instant::now();
        let out = redact_text(&hostile);
        assert_eq!(out.len(), hostile.len());
        assert!(
            t.elapsed() < std::time::Duration::from_secs(2),
            "{:?}",
            t.elapsed()
        );
        let deep = format!("{}password=hunter2", "a=".repeat(MAX_NESTED_ASSIGNMENTS + 4));
        let _ = redact_text(&deep); // no panic; beyond the bound the value is not chased
    }

    /// Audit finding 4: `sk-` starts a token only at a word boundary.
    #[test]
    fn sk_prefix_needs_a_left_boundary() {
        for keep in [
            "task-manager-service-worker",
            "/opt/app/disk-usage-analyzer-daemon-helper",
            "--name=risk-assessment-pipeline-runner",
            "desk-booking-notification-service",
        ] {
            assert_eq!(redact_text(keep), keep);
        }
        for (input, leak) in [
            ("sk-abcdefghijklmnopqrstuvwx", "abcdefghijkl"),
            ("x=sk-proj-abcdefghijklmnopqrstuvwx", "abcdefghijkl"),
            ("echo \"sk-ant-abcdefghijklmnop\"", "abcdefghijkl"),
            ("curl -H x:sk-live-abcdefghijklmnopqrstuvwx", "abcdefghijkl"),
        ] {
            let out = redact_text(input);
            assert!(!out.contains(leak), "{input:?} → {out:?}");
        }
    }

    /// Audit finding 12: a password with `@` or `/` in it is still inside the userinfo.
    #[test]
    fn url_userinfo_with_at_and_slash() {
        for (input, want) in [
            ("https://bob:p@ss@host/x", "https://<redacted>@host/x"),
            (
                "https://bob:p@ss@w0rd@host:8443/x?y=1",
                "https://<redacted>@host:8443/x?y=1",
            ),
            (
                "postgres://app:pa/ss@db:5432/prod",
                "postgres://<redacted>@db:5432/prod",
            ),
            ("postgres://app:pa/s@s@db/prod", "postgres://<redacted>@db/prod"),
            ("https://tok3n@host/x", "https://<redacted>@host/x"),
            (
                "git clone https://u:p@h/r.git dir",
                "git clone https://<redacted>@h/r.git dir",
            ),
        ] {
            assert_eq!(
                redact_text(input),
                want.replace("<redacted>", REDACTED),
                "{input}"
            );
        }
        // no credentials: an `@` in the path or query is not userinfo
        for keep in [
            "https://host/users/@bob",
            "https://host:8080/a@b",
            "http://[::1]:8080/a@b",
            "https://registry.npmjs.org/@scope/pkg",
            "https://host/x?mail=a@b.c",
            "file:///tmp/a@b",
        ] {
            assert_eq!(redact_text(keep), keep);
        }
    }

    /// Audit finding 5: with several `*SESSION_ID` keys each id stays tied to its key.
    #[test]
    fn session_ids_are_per_key() {
        let allow: Vec<String> = ["CLAUDE_CODE_SESSION_ID", "CODEX_SESSION_ID", "CLAUDECODE"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let one = markers_from_env([("CLAUDECODE", "1"), ("CLAUDE_CODE_SESSION_ID", "raw-a")], &allow);
        assert_eq!(one.keys, vec!["CLAUDECODE", "CLAUDE_CODE_SESSION_ID"]);
        assert_eq!(
            session_id_for_key(&one, "CLAUDE_CODE_SESSION_ID"),
            Some(hash_marker("raw-a").as_str())
        );
        assert_eq!(session_id_for_key(&one, "CODEX_SESSION_ID"), None);
        let two = markers_from_env(
            [("CLAUDE_CODE_SESSION_ID", "raw-a"), ("CODEX_SESSION_ID", "raw-b")],
            &allow,
        );
        assert_eq!(two.session_id, Some(hash_marker("raw-a")));
        assert_eq!(
            session_id_for_key(&two, "CLAUDE_CODE_SESSION_ID"),
            Some(hash_marker("raw-a").as_str())
        );
        assert_eq!(
            session_id_for_key(&two, "CODEX_SESSION_ID"),
            Some(hash_marker("raw-b").as_str())
        );
        // raw values never appear, also in the qualified keys
        let json = serde_json::to_string(&two).unwrap();
        assert!(!json.contains("raw-a") && !json.contains("raw-b"), "{json}");
        // an empty id of one key does not borrow the other key's
        let half = markers_from_env(
            [("CLAUDE_CODE_SESSION_ID", "raw-a"), ("CODEX_SESSION_ID", " ")],
            &allow,
        );
        assert_eq!(session_id_for_key(&half, "CODEX_SESSION_ID"), None);
        assert_eq!(
            session_id_for_key(&half, "CLAUDE_CODE_SESSION_ID"),
            Some(hash_marker("raw-a").as_str())
        );
    }

    /// Audit finding 8: a group id embeds a slug of the label; where the label is redacted, so is the id,
    /// in every field that refers to it.
    #[test]
    fn group_ids_that_embed_a_redacted_label() {
        use crate::model::{Group, Victim};
        let secret = "0123456789abcdef0123456789abcdef";
        let groups = vec![
            Group {
                id: format!("other:{secret}:42"),
                label: secret.into(),
                ..Default::default()
            },
            Group {
                id: "daemon:builtin:tsserver:43".into(),
                label: "tsserver".into(),
                owner_group: Some(format!("other:{secret}:42")),
                ..Default::default()
            },
            Group {
                id: "app:firefox".into(),
                label: "Firefox".into(),
                owner_group: Some("agent:abcdef012345".into()),
                ..Default::default()
            },
        ];
        let mut s = Snapshot {
            groups,
            ..Default::default()
        };
        s.oom.likely_victim = Some(Victim {
            group_id: Some(format!("other:{secret}:42")),
            ..Default::default()
        });
        let out = redact_snapshot(&s);
        let json = serde_json::to_string(&out).unwrap();
        assert!(!json.contains(secret), "{json}");
        let id = out.groups[0].id.clone();
        assert!(id.starts_with("other:redacted-") && id.ends_with(":42"), "{id}");
        assert_eq!(id, redact_group_id(&s.groups[0].id, &s.groups[0].label));
        assert_eq!(out.groups[1].owner_group.as_deref(), Some(id.as_str()));
        assert_eq!(
            out.oom.likely_victim.as_ref().unwrap().group_id.as_deref(),
            Some(id.as_str())
        );
        // nothing to hide → ids are untouched
        assert_eq!(out.groups[1].id, "daemon:builtin:tsserver:43");
        assert_eq!(out.groups[2].id, "app:firefox");
        assert_eq!(out.groups[2].owner_group.as_deref(), Some("agent:abcdef012345"));
        for id in [
            "agent:builtin:claude-code:412",
            "mserver:ollama:800",
            "app:google-chrome@u502",
            "self",
        ] {
            assert_eq!(redact_group_id(id, "Claude Code"), id);
        }
    }
}