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
// TODO: deferred perf work. See /home/user/.claude/plans/dapper-coalescing-horizon.md.
// TODO: - L2: line-start index for `line_and_col` -- only matters on the
// TODO: violation path; revisit if a single file with many hits ever becomes
// TODO: a real workload.
// TODO: - Z1: serialize the regex-bucket combined DFA. Resharp 0.5 has no
// TODO: serialization API; would require swapping that gate to the `regex`
// TODO: crate (`regex-automata::dfa::dense::DFA::to_bytes`). Trigger: when
// TODO: startup-only time goes back over ~100ms after P1+P2 land.
// What: `mod walk;` declares a child module whose source lives in
// `walk.rs` (sibling to this file). `mod` is Rust's module
// system: it does NOT import names; it simply tells the
// compiler "this file/module exists, compile it". Names
// referenced via `crate::walk::xxx` afterward.
// Why: We split the binary into four files so each unit is
// focused: `walk.rs` for the working-tree walker that
// respects `.gitignore`.
// TS map: Closer to a tsconfig file's "include" entry than to an
// `import`. The actual `import` happens via the `use` lines
// below.
// Gotcha: `mod foo;` without a body is NOT an import; it's a
// registration. Forgetting to write `mod` for a sibling file
// silently excludes it from the build.
//
// In TS you'd write (pseudocode):
// ```ts
// // No equivalent. Closest: TypeScript automatically picks up files
// // in `include` paths; Rust requires explicit `mod` declarations.
// ```
// What: `#[cfg(feature = "fuzzing")] pub mod fuzz_api;` registers
// the curated re-export module ONLY when the `fuzzing`
// Cargo feature is on. The bin target leaves the feature
// off and never sees this module; fuzz targets (in
// `fuzz/Cargo.toml`) enable the feature and use
// `forbidden_strings::fuzz_api::*` to import internals.
// Why: Keep the production public surface unchanged while
// letting fuzz targets reach the internal helpers they
// need.
// TS map: `if (process.env.FUZZING) { export * as fuzzApi from "./fuzz_api"; }`
// in spirit; no clean 1:1 equivalent because TS has no
// compile-time feature gates.
//
// In TS you'd write (pseudocode):
// ```ts
// // No clean equivalent; conditional re-export at build time.
// ```
// What: `use std::env;` imports the std `env` module so we can
// reference `env::args` / `env::var`.
// Why: Reading argv and environment variables.
// TS map: `import { argv, env } from "node:process";`.
//
// In TS you'd write (pseudocode):
// ```ts
// import { argv, env } from "node:process";
// ```
use env;
// What: `std::fs::canonicalize` is referenced via the full path at
// three sites (rules-path skip set, walker skip lookup); no
// bare `use std::fs;` because the per-file `fs::read` slurp
// moved into `read_with_binary_check` which uses
// `std::fs::File` directly.
// Why: Background on file-reading performance choices: `fs::read`
// is empirically faster than `mmap`-based access on this
// workload (many small files; per-file VMA setup cost
// dominates the saved alloc) -- the E2 mmap experiment
// regressed wall time by 35% on Mono and 43% on the Linux
// kernel. See PERF.md "Mmap experiment (rejected)".
// Thread-local scratch buffers were also tried 2026-05-03;
// rayon's nested-parallelism work-stealing (scan_content
// uses inner par_iter via prefix-matched and combined-
// shard fan-out) re-entered the outer flat_map_iter on
// the SAME thread while the buffer was borrowed,
// triggering a `RefCell already borrowed` panic. The
// per-file alloc cost is dwarfed by the unicode-mode
// speedup; not worth the re-entrancy hazard.
// TS map: N/A (no import line; `std::fs::canonicalize` is fully
// qualified at use sites).
// What: `use std::io::Write;` imports the `Write` TRAIT (interface-
// like). Methods declared by a trait are only callable when
// the trait is in scope, even when used via macros like
// `writeln!`.
// Why: We use `writeln!(handle, ...)` to emit hits.
// TS map: No 1:1 equivalent; in TS, methods are always callable.
//
// In TS you'd write (pseudocode):
// ```ts
// // Unnecessary in TS.
// ```
use Write;
// What: `use rayon::prelude::*;` brings rayon's parallel-iterator
// extension methods into scope (`par_iter`, `flat_map_iter`,
// etc.).
// Why: The two-phase main loop uses `par_iter` for both the
// parallel-read phase and the parallel-scan phase.
// TS map: No equivalent.
//
// In TS you'd write (pseudocode):
// ```ts
// // No equivalent.
// ```
use *;
// What: `use crate::walk::list_files;` re-exports the named function
// from the sibling module under a short alias for local use.
// `crate::` is the absolute root of this crate.
// Why: We call `list_files(".")` once when `--all` mode is
// selected to enumerate every scannable file.
// TS map: `import { listFiles } from "./walk";`.
//
// In TS you'd write (pseudocode):
// ```ts
// import { listFiles } from "./walk";
// ```
use crateload_ruleset;
use cratescan_content;
use cratelist_files;
// What: `fn build_skip_set(rules_path: &str) -> HashSet<PathBuf>`
// returns the set of CANONICAL absolute paths to skip when
// walking the tree in `--all` mode. Pre-fix this logic was a
// basename check (`is_skipped_file`) that matched anywhere in
// the tree, so an unrelated `sub/forbidden-strings.local.txt`
// was silently dropped along with the actual rule file. Path-
// anchored matching pins each skip to its specific filesystem
// location.
// Why: Closes BUG 6 (basename skip applies to arbitrary explicit
// args) and BUG 11 (Windows path basename via rsplit('/')) in
// one shape change. Path-anchoring removes both failure modes:
// the basename collision cannot trigger because we compare
// full canonical paths, and the Windows backslash separator
// is handled inside `std::fs::canonicalize` / `PathBuf::eq`.
//
// Skip set composition:
// - The actual rules file (whatever the user passed via
// `--rules` or `FORBIDDEN_STRINGS_RULES`; falls back to
// the default `forbidden-strings.local.txt` in cwd).
// - Four canonical self-match paths at their expected
// locations relative to repo root. Each file contains
// literal copies of rule bodies (generated source) or
// documented example matches (rules-engine test
// fixtures); scanning them in --all mode produces noise.
// If running from a different cwd they fail to
// canonicalize and are silently dropped from the set;
// matching is still correct for the rules file alone.
//
// The caller separately decides WHEN to apply the skip:
// explicit positional args are NEVER skipped (the user asked
// for them); only walker output in --all mode is filtered.
// TS map: `function buildSkipSet(rulesPath: string): Set<string>`.
//
// In TS you'd write (pseudocode):
// ```ts
// function buildSkipSet(rulesPath: string): Set<string> {
// const set = new Set<string>();
// try { set.add(fs.realpathSync(rulesPath)); } catch {}
// for (const k of CANONICAL_SELF_MATCH_PATHS) {
// try { set.add(fs.realpathSync(k)); } catch {}
// }
// return set;
// }
// ```
// What: `fn is_walker_skipped(path: &str, skip_set: &HashSet<PathBuf>) -> bool`
// returns true when the path's canonical form matches a
// skip-set entry. Used ONLY for walker output in --all mode;
// explicit positional args bypass this check entirely.
// Why: Closes BUG 6: the previous `is_skipped_file` ran on every
// queued path regardless of source, hiding real positive
// findings on `sub/forbidden-strings.local.txt`-style explicit
// args. The path-anchored form here is consulted only when
// the caller knows the path came from the walker.
// TS map: `function isWalkerSkipped(path: string, skipSet: Set<string>): boolean`.
//
// In TS you'd write (pseudocode):
// ```ts
// function isWalkerSkipped(path: string, skipSet: Set<string>): boolean {
// try {
// const canonical = fs.realpathSync(path);
// return skipSet.has(canonical);
// } catch { return false; }
// }
// ```
// What: `BIN_PROBE_SIZE` is the byte length read up-front from every
// file before deciding whether the file is binary. 8 KiB is
// the same probe size the pre-BUG-5 `is_likely_binary`
// heuristic used; it matches `git diff`'s "binary or text"
// heuristic threshold.
// Why: The probe length tunes a tradeoff: smaller probe lets a
// binary file with a leading text header (PDF header,
// machine-O header) sneak past as text; larger probe wastes
// memory on small files. 8 KiB catches the common cases
// (PNG, JPG, ELF, WASM, zip, ZSTD frames) and is the
// established convention.
const BIN_PROBE_SIZE: usize = 8192;
// What: `read_with_binary_check(path)` reads a file under a binary
// heuristic:
// 1. Always read the first `BIN_PROBE_SIZE` bytes.
// 2. If the file is smaller than that, return what we got.
// 3. If the probe contains a NUL byte and the file is
// larger than the probe, return only the probe (the
// rest is treated as binary tail and not scanned).
// 4. Otherwise (probe is NUL-free), read and return the
// full file.
// Why: Closes the BUG-5 regression without re-introducing the
// soundness gap that BUG 5 fixed. BUG 5 removed a heuristic
// that threw away the WHOLE file when the first 8 KiB
// contained a NUL byte; that masked secrets sitting BEFORE
// the NUL. This rule keeps that signal (the first 8 KiB is
// always scanned), but caps the per-file work on large
// binary blobs (firmware images, vmlinuz, font caches, lock
// sidecars) at 8 KiB instead of full content. Acceptable
// miss: a secret living AFTER a NUL byte in a file that is
// ALSO larger than 8 KiB. Acceptable: those files are the
// "binary blob with bytes that happen to spell a secret"
// case, and the secret-leak risk is dominated by source
// files and small lock files which still scan in full.
// TS map: `function readWithBinaryCheck(path: string): Buffer`.
//
// In TS you'd write (pseudocode):
// ```ts
// function readWithBinaryCheck(path: string): Buffer {
// const fd = fs.openSync(path, "r");
// try {
// const probe = Buffer.alloc(BIN_PROBE_SIZE);
// const n = fs.readSync(fd, probe, 0, BIN_PROBE_SIZE, null);
// if (n < BIN_PROBE_SIZE) return probe.subarray(0, n);
// if (probe.indexOf(0) !== -1) return probe;
// return Buffer.concat([probe, fs.readSync.readRestOf(fd)]);
// } finally {
// fs.closeSync(fd);
// }
// }
// ```
// What: `pub fn run_cli_from_env() -> Result<i32, String>` is the
// library entry point. It reads `env::args()` and env vars,
// parses flags, loads the ruleset, runs the parallel scan,
// prints hits to stderr, and returns the exit code the OS
// should see. `Result<i32, String>` lets the binary thin
// wrapper decide how to report a catastrophic failure (the
// `Err` arm) versus a regular run (`Ok(0)` clean,
// `Ok(1)` violation, `Ok(2)` usage error already eprinted).
// Sibling shape considered: returning `ExitCode` directly --
// rejected because tests written against the lib want a
// plain `i32` they can compare, and `ExitCode` has no `Eq`.
// Why: Coordinate arg parsing, ruleset loading, parallel scan,
// and result reporting from a unit testable surface. The bin
// target's `main` is now a five-line wrapper that turns the
// returned code into an `ExitCode` and prints `Err` to
// stderr with a fixed prefix.
// TS map: No entry-point function in TS; Node scripts just run top-
// to-bottom. Mentally picture an
// `async function runCliFromEnv(): Promise<number>` that
// the bin's tiny wrapper awaits and passes to
// `process.exit`.
//
// In TS you'd write (pseudocode):
// ```ts
// async function runCliFromEnv(): Promise<number> {
// // ...
// return anyViolation ? 1 : 0;
// }
// process.exit(await runCliFromEnv());
// ```