instinct-cli 0.3.6

Local memory for AI coding agents: an MCP server and CLI that gives Claude Code, Codex, Cursor and any MCP client the one lesson that fits. Lessons that keep failing go quiet.
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
# Instinct scoped checks: observe. Authored as raw Rust lines (TAA); hxc export-rust writes src/check/observe.rs. Read-only artifact inventory adapter.
TAA # // `instinct check observe`: first M2 adapter, artifact-inventory/v1. Spec: docs/check-observation-wire.md.
TAA # // Reads directory NAMES and KINDS only: no file contents, no writes, no network, no process, no bank, no logging.
TAA # // Granted root = the explicit --root argument for this one invocation. Nothing in the policy JSON grants access.
TAA # // Assumption, not proof: the caller asserts `trusted_quiescent_staging`. Portable std paths are not a hostile-race
TAA # // security boundary; the two-pass compare only catches VISIBLE mutation between passes. A hostile concurrent writer
TAA # // is outside what this adapter can contain. Symlinks in the root path (every ancestor and the root itself) are rejected, under the same assumption.
TAA # // Subset and required checks are delegated to the pure kernel (`kernel::evaluate`); there is no second evaluator here.
TAA # // Not implemented in this increment: grant/root fingerprints, metadata or content digests, receipts, MCP.
TAA # use super::json::{self, J};
TAA # use super::kernel::{self, Mode};
TAA # use std::collections::BTreeSet;
TAA # use std::path::{Component, Path, PathBuf};
TAA # const OBSERVE_USAGE: &str = "usage: instinct check observe --root /absolute/staging/root --input FILE|-\n\
TAA #   Read-only inventory of names and kinds under the granted root, checked against the caller policy\n\
TAA #   (schema instinct.artifact-policy/v1). No bank is opened; exit 0 for observed/incomplete, exit 2 for an error result.\n\
TAA #   Spec: docs/check-observation-wire.md.";
TAA # const POLICY_SCHEMA: &str = "instinct.artifact-policy/v1";
TAA # const CEIL_ENTRIES: u64 = 10000;
TAA # const CEIL_DEPTH: u64 = 64;
TAA # const CEIL_BYTES: u64 = 1 << 20;
TAA # const META_ALLOWANCE: u64 = 64;
TAA # #[derive(Clone, Copy)]
TAA # struct Limits {
TAA #     entries: u64,
TAA #     depth: u64,
TAA #     bytes: u64,
TAA # }
TAA # struct Policy {
TAA #     trusted: bool,
TAA #     allowed: Vec<String>,
TAA #     required: Vec<String>,
TAA #     scope: Vec<(String, String)>,
TAA #     limits: Limits,
TAA # }
TAA # #[derive(Clone, PartialEq, Eq, Debug)]
TAA # struct Meta {
TAA #     len: u64,
TAA #     stamp: [i64; 6],
TAA #     mode: u32,
TAA # }
TAA # #[derive(Clone, PartialEq, Eq, Debug)]
TAA # struct Ent {
TAA #     path: String,
TAA #     dir: bool,
TAA #     meta: Meta,
TAA # }
TAA # #[derive(PartialEq, Eq, Debug)]
TAA # struct Snap {
TAA #     root_before: Meta,
TAA #     root_after: Meta,
TAA #     ents: Vec<Ent>,
TAA # }
TAA # struct Stop {
TAA #     reason: String,
TAA #     witness: Option<String>,
TAA # }
TAA # fn stop(reason: &str, witness: Option<&str>) -> Stop {
TAA #     Stop { reason: reason.to_string(), witness: witness.map(|w| w.to_string()) }
TAA # }
TAA # fn jstr(s: &str) -> String {
TAA #     let mut o = String::with_capacity(s.len() + 2);
TAA #     o.push('"');
TAA #     for c in s.chars() {
TAA #         match c {
TAA #             '"' => o.push_str("\\\""),
TAA #             '\\' => o.push_str("\\\\"),
TAA #             '\n' => o.push_str("\\n"),
TAA #             '\r' => o.push_str("\\r"),
TAA #             '\t' => o.push_str("\\t"),
TAA #             c if (c as u32) < 0x20 || c as u32 == 0x7f => o.push_str(&format!("\\u{:04x}", c as u32)),
TAA #             c => o.push(c),
TAA #         }
TAA #     }
TAA #     o.push('"');
TAA #     o
TAA # }
TAA # fn jlist(items: &[String]) -> String {
TAA #     let parts: Vec<String> = items.iter().map(|s| jstr(s)).collect();
TAA #     format!("[{}]", parts.join(","))
TAA # }
TAA # fn jscope(scope: &[(String, String)]) -> String {
TAA #     let parts: Vec<String> = scope.iter().map(|(k, v)| format!("{}:{}", jstr(k), jstr(v))).collect();
TAA #     format!("{{{}}}", parts.join(","))
TAA # }
TAA # fn valid_rel(p: &str) -> Result<(), &'static str> {
TAA #     if p.is_empty() {
TAA #         return Err("empty path");
TAA #     }
TAA #     if p.contains('\0') {
TAA #         return Err("NUL in path");
TAA #     }
TAA #     if p.starts_with('/') {
TAA #         return Err("absolute path");
TAA #     }
TAA #     if p.starts_with("\\\\") {
TAA #         return Err("UNC path");
TAA #     }
TAA #     let b = p.as_bytes();
TAA #     if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' {
TAA #         return Err("drive path");
TAA #     }
TAA #     if p.ends_with('/') {
TAA #         return Err("trailing slash");
TAA #     }
TAA #     for c in p.split('/') {
TAA #         if c.is_empty() {
TAA #             return Err("empty component");
TAA #         }
TAA #         if c == "." || c == ".." {
TAA #             return Err("dot component");
TAA #         }
TAA #     }
TAA #     Ok(())
TAA # }
TAA # fn obj<'a>(v: &'a J, what: &str) -> Result<&'a [(String, J)], String> {
TAA #     match v {
TAA #         J::Obj(o) => Ok(o),
TAA #         _ => Err(format!("malformed_policy: {what} must be an object")),
TAA #     }
TAA # }
TAA # fn only_keys(o: &[(String, J)], allowed: &[&str], what: &str) -> Result<(), String> {
TAA #     for (k, _) in o {
TAA #         if !allowed.contains(&k.as_str()) {
TAA #             return Err(format!("malformed_policy: unknown field in {what}"));
TAA #         }
TAA #     }
TAA #     Ok(())
TAA # }
TAA # fn get<'a>(o: &'a [(String, J)], k: &str) -> Option<&'a J> {
TAA #     o.iter().find(|(n, _)| n == k).map(|(_, v)| v)
TAA # }
TAA # fn path_list(v: &J, name: &str) -> Result<Vec<String>, String> {
TAA #     let items = match v {
TAA #         J::Arr(a) => a,
TAA #         _ => return Err(format!("malformed_policy: {name} must be an array of strings")),
TAA #     };
TAA #     if items.len() as u64 > CEIL_ENTRIES {
TAA #         return Err(format!("limit_exceeded: {name} has more than 10000 entries"));
TAA #     }
TAA #     let mut seen: BTreeSet<&str> = BTreeSet::new();
TAA #     let mut out = Vec::new();
TAA #     for (i, it) in items.iter().enumerate() {
TAA #         let s = match it {
TAA #             J::Str(s) => s,
TAA #             _ => return Err(format!("malformed_policy: {name}[{i}] must be a string")),
TAA #         };
TAA #         if let Err(why) = valid_rel(s) {
TAA #             return Err(format!("invalid_path: {name}[{i}]: {why}"));
TAA #         }
TAA #         if !seen.insert(s.as_str()) {
TAA #             return Err(format!("malformed_policy: {name}[{i}] is a duplicate"));
TAA #         }
TAA #         out.push(s.clone());
TAA #     }
TAA #     Ok(out)
TAA # }
TAA # fn limit(o: &[(String, J)], key: &str, default: u64, ceil: u64) -> Result<u64, String> {
TAA #     let v = match get(o, key) {
TAA #         None => return Ok(default),
TAA #         Some(J::Num(n)) => n,
TAA #         Some(_) => return Err(format!("invalid_limit: {key} must be an integer")),
TAA #     };
TAA #     let canon = !v.is_empty() && v.len() <= 10 && v.bytes().all(|c| c.is_ascii_digit()) && (v == "0" || !v.starts_with('0'));
TAA #     if !canon {
TAA #         return Err(format!("invalid_limit: {key} must be a canonical non-negative integer"));
TAA #     }
TAA #     let n: u64 = v.parse().map_err(|_| format!("invalid_limit: {key} is not a number"))?;
TAA #     if n > ceil {
TAA #         return Err(format!("invalid_limit: {key} exceeds the ceiling {ceil}"));
TAA #     }
TAA #     Ok(n)
TAA # }
TAA # fn parse_policy(bytes: &[u8]) -> Result<Policy, String> {
TAA #     let tree = json::parse(bytes)?;
TAA #     let top = obj(&tree, "the policy")?;
TAA #     only_keys(top, &["schema", "assumptions", "allowed", "required", "scope", "limits"], "policy")?;
TAA #     match get(top, "schema") {
TAA #         Some(J::Str(s)) if s == POLICY_SCHEMA => {}
TAA #         _ => return Err(format!("malformed_policy: schema must be {POLICY_SCHEMA}")),
TAA #     }
TAA #     let trusted = match get(top, "assumptions") {
TAA #         None => false,
TAA #         Some(a) => {
TAA #             let ao = obj(a, "assumptions")?;
TAA #             only_keys(ao, &["trusted_quiescent_staging"], "assumptions")?;
TAA #             match get(ao, "trusted_quiescent_staging") {
TAA #                 None => false,
TAA #                 Some(J::Bool(b)) => *b,
TAA #                 Some(_) => return Err("malformed_policy: trusted_quiescent_staging must be a boolean".to_string()),
TAA #             }
TAA #         }
TAA #     };
TAA #     let allowed = match get(top, "allowed") {
TAA #         Some(v) => path_list(v, "allowed")?,
TAA #         None => return Err("malformed_policy: allowed is required".to_string()),
TAA #     };
TAA #     let required = match get(top, "required") {
TAA #         Some(v) => path_list(v, "required")?,
TAA #         None => Vec::new(),
TAA #     };
TAA #     let allow_set: BTreeSet<&str> = allowed.iter().map(String::as_str).collect();
TAA #     if required.iter().any(|r| !allow_set.contains(r.as_str())) {
TAA #         return Err("contradictory_policy: every required path must also be allowed".to_string());
TAA #     }
TAA #     let mut scope: Vec<(String, String)> = Vec::new();
TAA #     if let Some(s) = get(top, "scope") {
TAA #         for (k, v) in obj(s, "scope")? {
TAA #             match v {
TAA #                 J::Str(v) => scope.push((k.clone(), v.clone())),
TAA #                 _ => return Err("malformed_policy: scope values must be strings".to_string()),
TAA #             }
TAA #         }
TAA #     }
TAA #     let mut limits = Limits { entries: CEIL_ENTRIES, depth: CEIL_DEPTH, bytes: CEIL_BYTES };
TAA #     if let Some(l) = get(top, "limits") {
TAA #         let lo = obj(l, "limits")?;
TAA #         only_keys(lo, &["max_entries", "max_depth", "max_inventory_bytes"], "limits")?;
TAA #         limits.entries = limit(lo, "max_entries", CEIL_ENTRIES, CEIL_ENTRIES)?;
TAA #         limits.depth = limit(lo, "max_depth", CEIL_DEPTH, CEIL_DEPTH)?;
TAA #         limits.bytes = limit(lo, "max_inventory_bytes", CEIL_BYTES, CEIL_BYTES)?;
TAA #     }
TAA #     Ok(Policy { trusted, allowed, required, scope, limits })
TAA # }
TAA # fn check_text(id: &str, left: &str, right: &str, facts: &str, conds: bool, scope: &str) -> String {
TAA #     let conditions = if conds { "{\"complete-inventory\":true,\"explicit-policy\":true}" } else { "{}" };
TAA #     format!(
TAA #         "{{\"check\":{{\"schema\":\"instinct.check/v1\",\"id\":{},\"revision\":1,\"inputs\":{{{}:\"set<string>\",{}:\"set<string>\"}},\"claim\":{{\"op\":\"subset\",\"left\":{{\"fact\":{}}},\"right\":{{\"fact\":{}}}}},\"required_conditions\":[\"complete-inventory\",\"explicit-policy\"],\"scope\":{}}},\"facts\":{},\"conditions\":{},\"scope\":{}}}",
TAA #         jstr(id),
TAA #         jstr(left),
TAA #         jstr(right),
TAA #         jstr(left),
TAA #         jstr(right),
TAA #         scope,
TAA #         facts,
TAA #         conditions,
TAA #         scope
TAA #     )
TAA # }
TAA # const ID_ALLOWED: &str = "artifact-actual-subset-allowed";
TAA # const ID_REQUIRED: &str = "artifact-required-subset-actual";
TAA # fn policy_facts(p: &Policy, which: u8) -> String {
TAA #     if which == 0 {
TAA #         format!("{{\"allowed\":{}}}", jlist(&p.allowed))
TAA #     } else {
TAA #         format!("{{\"required\":{}}}", jlist(&p.required))
TAA #     }
TAA # }
TAA # fn preflight(p: &Policy) -> Result<(), String> {
TAA #     let scope = jscope(&p.scope);
TAA #     let a = check_text(ID_ALLOWED, "actual", "allowed", &policy_facts(p, 0), false, &scope);
TAA #     let (out, err) = kernel::evaluate(Mode::Validate, a.as_bytes());
TAA #     if err {
TAA #         return Err(out);
TAA #     }
TAA #     if !p.required.is_empty() {
TAA #         let r = check_text(ID_REQUIRED, "required", "actual", &policy_facts(p, 1), false, &scope);
TAA #         let (out, err) = kernel::evaluate(Mode::Validate, r.as_bytes());
TAA #         if err {
TAA #             return Err(out);
TAA #         }
TAA #     }
TAA #     Ok(())
TAA # }
TAA # fn validate_root(root: &str) -> Result<PathBuf, String> {
TAA #     if root.is_empty() || root.contains('\0') {
TAA #         return Err("usage: --root must be a nonempty path".to_string());
TAA #     }
TAA #     let p = Path::new(root);
TAA #     if !p.is_absolute() {
TAA #         return Err("usage: --root must be an absolute path".to_string());
TAA #     }
TAA #     // Lexical check on the RAW string: Path::components() silently drops `.`, repeated and trailing separators, and the
TAA #     // OS resolves a trailing slash through a final symlink, so none of that may reach symlink_metadata.
TAA #     let sep = |c: char| c == '/' || (cfg!(windows) && c == '\\');
TAA #     // A filesystem root has no parent (including Windows drive/verbatim/UNC roots).
TAA #     // Still reject doubled trailing separators that components() would normalize away.
TAA #     let filesystem_root = p.parent().is_none()
TAA #         && !root.strip_suffix(sep).is_some_and(|prefix| prefix.ends_with(sep));
TAA #     if root.len() > 1 && root.ends_with(sep) && !filesystem_root {
TAA #         return Err("usage: --root must not end with a separator".to_string());
TAA #     }
TAA #     if root.split(sep).skip(1).any(|c| c.is_empty() && root.len() > 1) && !cfg!(windows) {
TAA #         return Err("usage: --root must not contain empty components".to_string());
TAA #     }
TAA #     if root.split(sep).any(|c| c == "." || c == "..") {
TAA #         return Err("usage: --root must not contain . or .. components".to_string());
TAA #     }
TAA #     if p.components().any(|c| matches!(c, Component::CurDir | Component::ParentDir)) {
TAA #         return Err("usage: --root must not contain . or .. components".to_string());
TAA #     }
TAA #     Ok(p.to_path_buf())
TAA # }
TAA # // Only macOS's fixed OS aliases are resolved, and only above the named root.
TAA # // Arbitrary user-created ancestor symlinks remain rejected by root_meta.
TAA # #[cfg(any(target_os = "macos", all(test, unix)))]
TAA # fn system_alias_candidate(root: &Path) -> Option<(&'static str, &'static str, PathBuf)> {
TAA #     for (alias, target) in [("/var", "/private/var"), ("/tmp", "/private/tmp"), ("/etc", "/private/etc")] {
TAA #         if let Ok(rest) = root.strip_prefix(alias) {
TAA #             if !rest.as_os_str().is_empty() { return Some((alias, target, Path::new(target).join(rest))); }
TAA #         }
TAA #     }
TAA #     None
TAA # }
TAA # fn platform_root(root: PathBuf) -> Result<PathBuf, String> {
TAA #     #[cfg(target_os = "macos")]
TAA #     if let Some((alias, target, resolved)) = system_alias_candidate(&root) {
TAA #         let meta = std::fs::symlink_metadata(alias).map_err(|_| "root_invalid: cannot inspect system ancestor")?;
TAA #         if meta.file_type().is_symlink() {
TAA #             let link = std::fs::read_link(alias).map_err(|_| "root_invalid: cannot inspect system alias")?;
TAA #             let actual = if link.is_absolute() { link } else { Path::new("/").join(link) };
TAA #             if actual != Path::new(target) { return Err("root_invalid: unexpected system alias target".into()); }
TAA #             return Ok(resolved);
TAA #         }
TAA #     }
TAA #     Ok(root)
TAA # }
TAA # #[cfg(unix)]
TAA # fn meta_of(m: &std::fs::Metadata) -> Meta {
TAA #     use std::os::unix::fs::MetadataExt;
TAA #     Meta {
TAA #         len: m.len(),
TAA #         stamp: [m.mtime(), m.mtime_nsec(), m.ctime(), m.ctime_nsec(), m.dev() as i64, m.ino() as i64],
TAA #         mode: m.mode(),
TAA #     }
TAA # }
TAA # #[cfg(not(unix))]
TAA # fn meta_of(m: &std::fs::Metadata) -> Meta {
TAA #     Meta { len: m.len(), stamp: [0; 6], mode: 0 }
TAA # }
TAA # fn io_reason(what: &str, e: &std::io::Error) -> String {
TAA #     format!("{what}: {:?}", e.kind())
TAA # }
TAA # fn root_meta(root: &Path) -> Result<Meta, Stop> {
TAA #     let comps: Vec<Component> = root.components().collect();
TAA #     let mut cur = PathBuf::new();
TAA #     for (i, c) in comps.iter().enumerate() {
TAA #         cur.push(c.as_os_str());
TAA #         if i + 1 == comps.len() || matches!(c, Component::RootDir | Component::Prefix(_)) {
TAA #             continue;
TAA #         }
TAA #         let am = std::fs::symlink_metadata(&cur).map_err(|e| stop(&io_reason("root_unreadable", &e), None))?;
TAA #         if am.file_type().is_symlink() {
TAA #             return Err(stop("symlink_rejected: root_ancestor", None));
TAA #         }
TAA #     }
TAA #     let m = std::fs::symlink_metadata(root).map_err(|e| stop(&io_reason("root_unreadable", &e), None))?;
TAA #     if m.file_type().is_symlink() {
TAA #         return Err(stop("symlink_rejected: root", None));
TAA #     }
TAA #     if !m.is_dir() {
TAA #         return Err(stop("root_not_directory", None));
TAA #     }
TAA #     Ok(meta_of(&m))
TAA # }
TAA # /// One bounded traversal. Charges entry, depth and byte budgets before storing each entry.
TAA # fn walk(root: &Path, lim: Limits, seen: &mut usize) -> Result<Snap, Stop> {
TAA #     let root_before = root_meta(root)?;
TAA #     let mut ents: Vec<Ent> = Vec::new();
TAA #     let mut bytes: u64 = 0;
TAA #     let mut pending: Vec<(String, u64)> = vec![(String::new(), 0)];
TAA #     while let Some((rel, depth)) = pending.pop() {
TAA #         let abs = if rel.is_empty() { root.to_path_buf() } else { root.join(&rel) };
TAA #         let shown = if rel.is_empty() { "." } else { rel.as_str() };
TAA #         let rd = std::fs::read_dir(&abs).map_err(|e| stop(&io_reason("read_dir_failed", &e), Some(shown)))?;
TAA #         let mut names: Vec<String> = Vec::new();
TAA #         for item in rd {
TAA #             let item = item.map_err(|e| stop(&io_reason("read_dir_failed", &e), Some(shown)))?;
TAA #             let name = match item.file_name().into_string() {
TAA #                 Ok(n) => n,
TAA #                 Err(_) => return Err(stop("non_utf8_name", Some(shown))),
TAA #             };
TAA #             let child = if rel.is_empty() { name.clone() } else { format!("{rel}/{name}") };
TAA #             if ents.len() as u64 + names.len() as u64 + 1 > lim.entries {
TAA #                 return Err(stop("budget_exceeded: max_entries", Some(&child)));
TAA #             }
TAA #             if depth + 1 > lim.depth {
TAA #                 return Err(stop("budget_exceeded: max_depth", Some(&child)));
TAA #             }
TAA #             bytes += child.len() as u64 + META_ALLOWANCE;
TAA #             if bytes > lim.bytes {
TAA #                 return Err(stop("budget_exceeded: max_inventory_bytes", Some(&child)));
TAA #             }
TAA #             names.push(name);
TAA #             *seen += 1;
TAA #         }
TAA #         names.sort();
TAA #         for name in names {
TAA #             let child = if rel.is_empty() { name.clone() } else { format!("{rel}/{name}") };
TAA #             let m = std::fs::symlink_metadata(abs.join(&name)).map_err(|e| stop(&io_reason("entry_unreadable", &e), Some(&child)))?;
TAA #             let ft = m.file_type();
TAA #             if ft.is_symlink() {
TAA #                 return Err(stop("symlink_rejected", Some(&child)));
TAA #             }
TAA #             let dir = ft.is_dir();
TAA #             if !dir && !ft.is_file() {
TAA #                 return Err(stop("unsupported_entry_kind", Some(&child)));
TAA #             }
TAA #             if dir {
TAA #                 pending.push((child.clone(), depth + 1));
TAA #             }
TAA #             ents.push(Ent { path: child, dir, meta: meta_of(&m) });
TAA #         }
TAA #     }
TAA #     ents.sort_by(|a, b| a.path.cmp(&b.path));
TAA #     let root_after = root_meta(root)?;
TAA #     Ok(Snap { root_before, root_after, ents })
TAA # }
TAA # fn first_difference(a: &Snap, b: &Snap) -> String {
TAA #     for (x, y) in a.ents.iter().zip(b.ents.iter()) {
TAA #         if x != y {
TAA #             return x.path.clone();
TAA #         }
TAA #     }
TAA #     if a.ents.len() > b.ents.len() {
TAA #         return a.ents[b.ents.len()].path.clone();
TAA #     }
TAA #     if b.ents.len() > a.ents.len() {
TAA #         return b.ents[a.ents.len()].path.clone();
TAA #     }
TAA #     ".".to_string()
TAA # }
TAA # fn limits_json(l: Limits) -> String {
TAA #     format!(
TAA #         "{{\"max_entries\":{},\"max_depth\":{},\"max_inventory_bytes\":{},\"metadata_allowance_bytes\":{}}}",
TAA #         l.entries, l.depth, l.bytes, META_ALLOWANCE
TAA #     )
TAA # }
TAA # fn incomplete(p: &Policy, reason: &str, witness: Option<&str>, visited: usize) -> String {
TAA #     let w = match witness {
TAA #         Some(w) => format!(",\"witness\":{}", jstr(w)),
TAA #         None => String::new(),
TAA #     };
TAA #     format!(
TAA #         "{{\"schema\":\"instinct.artifact-observation/v1\",\"adapter\":\"artifact-inventory/v1\",\"validity\":\"incomplete\",\"evidence_origin\":\"adapter_observed\",\"authorization\":\"not_evaluated\",\"reason\":{}{},\"assumptions\":{{\"trusted_quiescent_staging\":{}}},\"scope\":{},\"inventory\":[],\"checks\":[],\"limits\":{},\"visited_entries\":{}}}",
TAA #         jstr(reason),
TAA #         w,
TAA #         p.trusted,
TAA #         jscope(&p.scope),
TAA #         limits_json(p.limits),
TAA #         visited
TAA #     )
TAA # }
TAA # fn observed(p: &Policy, snap: &Snap) -> Result<String, String> {
TAA #     let actual: Vec<String> = snap.ents.iter().map(|e| e.path.clone()).collect();
TAA #     let scope = jscope(&p.scope);
TAA #     let mut checks: Vec<String> = Vec::new();
TAA #     let a = check_text(ID_ALLOWED, "actual", "allowed", &format!("{{\"actual\":{},\"allowed\":{}}}", jlist(&actual), jlist(&p.allowed)), true, &scope);
TAA #     let (out, err) = kernel::evaluate(Mode::Run, a.as_bytes());
TAA #     if err {
TAA #         return Err(out);
TAA #     }
TAA #     checks.push(format!("{{\"name\":\"actual_subset_allowed\",\"provenance\":{{\"actual\":\"adapter_observed\",\"allowed\":\"caller_policy\"}},\"result\":{out}}}"));
TAA #     if !p.required.is_empty() {
TAA #         let r = check_text(ID_REQUIRED, "required", "actual", &format!("{{\"required\":{},\"actual\":{}}}", jlist(&p.required), jlist(&actual)), true, &scope);
TAA #         let (out, err) = kernel::evaluate(Mode::Run, r.as_bytes());
TAA #         if err {
TAA #             return Err(out);
TAA #         }
TAA #         checks.push(format!("{{\"name\":\"required_subset_actual\",\"provenance\":{{\"required\":\"caller_policy\",\"actual\":\"adapter_observed\"}},\"result\":{out}}}"));
TAA #     }
TAA #     let inv: Vec<String> = snap
TAA #         .ents
TAA #         .iter()
TAA #         .map(|e| format!("{{\"path\":{},\"kind\":\"{}\"}}", jstr(&e.path), if e.dir { "directory" } else { "file" }))
TAA #         .collect();
TAA #     Ok(format!(
TAA #         "{{\"schema\":\"instinct.artifact-observation/v1\",\"adapter\":\"artifact-inventory/v1\",\"validity\":\"observed_snapshot\",\"evidence_origin\":\"adapter_observed\",\"authorization\":\"not_evaluated\",\"reason\":\"inventory_observed_under_caller_assumption\",\"assumptions\":{{\"trusted_quiescent_staging\":true}},\"scope\":{},\"inventory\":[{}],\"checks\":[{}],\"limits\":{},\"visited_entries\":{}}}",
TAA #         scope,
TAA #         inv.join(","),
TAA #         checks.join(","),
TAA #         limits_json(p.limits),
TAA #         snap.ents.len()
TAA #     ))
TAA # }
TAA # /// Core entry. `between` runs after pass one and before pass two: an internal test seam only, never wired to the CLI.
TAA # fn observe_inner(root: &str, policy: &[u8], between: &mut dyn FnMut()) -> (String, bool) {
TAA #     let root = match validate_root(root) {
TAA #         Ok(r) => r,
TAA #         Err(e) => return (kernel::error_json(&e), true),
TAA #     };
TAA #     let p = match parse_policy(policy) {
TAA #         Ok(p) => p,
TAA #         Err(e) => return (kernel::error_json(&e), true),
TAA #     };
TAA #     if let Err(e) = preflight(&p) {
TAA #         return (e, true);
TAA #     }
TAA #     if !p.trusted {
TAA #         return (incomplete(&p, "assumption_not_asserted: trusted_quiescent_staging", None, 0), false);
TAA #     }
TAA #     if cfg!(not(unix)) {
TAA #         return (incomplete(&p, "unsupported_platform: inventory observation is implemented for Unix only", None, 0), false);
TAA #     }
TAA #     let root = match platform_root(root) { Ok(root) => root, Err(e) => return (kernel::error_json(&e), true) };
TAA #     let mut seen1 = 0usize;
TAA #     let first = match walk(&root, p.limits, &mut seen1) {
TAA #         Ok(s) => s,
TAA #         Err(s) => {
TAA #             if s.reason.starts_with("root_unreadable") || s.reason == "root_not_directory" || s.reason.starts_with("symlink_rejected: root") {
TAA #                 return (kernel::error_json(&format!("root_invalid: {}", s.reason)), true);
TAA #             }
TAA #             return (incomplete(&p, &s.reason, s.witness.as_deref(), seen1), false);
TAA #         }
TAA #     };
TAA #     between();
TAA #     let second = match walk(&root, p.limits, &mut 0usize) {
TAA #         Ok(s) => s,
TAA #         Err(s) => return (incomplete(&p, &format!("changed_during_observation: {}", s.reason), s.witness.as_deref(), first.ents.len()), false),
TAA #     };
TAA #     if first != second {
TAA #         let w = first_difference(&first, &second);
TAA #         return (incomplete(&p, "changed_during_observation: inventory or metadata differs between passes", Some(&w), first.ents.len()), false);
TAA #     }
TAA #     let out = match observed(&p, &first) {
TAA #         Ok(o) => o,
TAA #         Err(e) => return (e, true),
TAA #     };
TAA #     (out, false)
TAA # }
TAA # /// Every result path (errors, incomplete, abstain, observed) goes through this one output bound. No silent truncation.
TAA # fn observe_with(root: &str, policy: &[u8], between: &mut dyn FnMut()) -> (String, bool) {
TAA #     let (out, is_error) = observe_inner(root, policy, between);
TAA #     if out.len() > kernel::MAX_OUTPUT_BYTES {
TAA #         return (kernel::error_json("limit_exceeded: observation result exceeds 65536 bytes"), true);
TAA #     }
TAA #     (out, is_error)
TAA # }
TAA # pub fn observe(root: &str, policy: &[u8]) -> (String, bool) {
TAA #     observe_with(root, policy, &mut || {})
TAA # }
TAA # fn usage_error(why: &str) -> i32 {
TAA #     println!("{}", kernel::error_json(&format!("usage: {why}")));
TAA #     2
TAA # }
TAA # /// `instinct check observe ...` (args after `observe`). Returns the process exit code.
TAA # pub fn cli(args: &[String]) -> i32 {
TAA #     if args.len() == 1 && (args[0] == "--help" || args[0] == "-h") {
TAA #         println!("{OBSERVE_USAGE}");
TAA #         return 0;
TAA #     }
TAA #     let mut root: Option<String> = None;
TAA #     let mut input: Option<String> = None;
TAA #     let mut i = 0;
TAA #     while i < args.len() {
TAA #         let a = &args[i];
TAA #         let (slot, name, value) = if a == "--root" || a == "--input" {
TAA #             i += 1;
TAA #             match args.get(i) {
TAA #                 Some(v) if v == "-" || !v.starts_with("--") => (if a == "--root" { &mut root } else { &mut input }, a.as_str(), v.clone()),
TAA #                 _ => return usage_error(&format!("{a} needs a value")),
TAA #             }
TAA #         } else if let Some(v) = a.strip_prefix("--root=") {
TAA #             (&mut root, "--root", v.to_string())
TAA #         } else if let Some(v) = a.strip_prefix("--input=") {
TAA #             (&mut input, "--input", v.to_string())
TAA #         } else if a.starts_with('-') && a != "-" {
TAA #             return usage_error("unknown option (observe accepts only --root and --input)");
TAA #         } else {
TAA #             return usage_error("unexpected positional argument");
TAA #         };
TAA #         if slot.is_some() {
TAA #             return usage_error(&format!("{name} given more than once"));
TAA #         }
TAA #         *slot = Some(value);
TAA #         i += 1;
TAA #     }
TAA #     let root = match root {
TAA #         Some(r) if !r.is_empty() => r,
TAA #         _ => return usage_error("--root ABSOLUTE_DIR is required"),
TAA #     };
TAA #     let input = match input {
TAA #         Some(p) if !p.is_empty() => p,
TAA #         _ => return usage_error("--input FILE|- is required"),
TAA #     };
TAA #     let bytes = match super::read_input(&input) {
TAA #         Ok(b) => b,
TAA #         Err(e) => {
TAA #             println!("{}", kernel::error_json(&e));
TAA #             return 2;
TAA #         }
TAA #     };
TAA #     let (out, is_error) = observe(&root, &bytes);
TAA #     println!("{out}");
TAA #     if is_error {
TAA #         2
TAA #     } else {
TAA #         0
TAA #     }
TAA # }
TAA # #[cfg(all(test, unix))]
TAA # mod tests {
TAA #     use super::*;
TAA #     use std::sync::atomic::{AtomicUsize, Ordering};
TAA #     static N: AtomicUsize = AtomicUsize::new(0);
TAA #     fn tmp() -> PathBuf {
TAA #         let d = std::env::temp_dir().join(format!("instinct-observe-{}-{}", std::process::id(), N.fetch_add(1, Ordering::SeqCst)));
TAA #         std::fs::create_dir_all(&d).unwrap();
TAA #         d
TAA #     }
TAA #     fn put(root: &Path, rel: &str) {
TAA #         let p = root.join(rel);
TAA #         std::fs::create_dir_all(p.parent().unwrap()).unwrap();
TAA #         std::fs::write(p, b"x").unwrap();
TAA #     }
TAA #     fn run(root: &Path, policy: &str) -> (String, bool) {
TAA #         observe(root.to_str().unwrap(), policy.as_bytes())
TAA #     }
TAA #     fn pol(allowed: &str, required: &str, extra: &str) -> String {
TAA #         format!("{{\"schema\":\"instinct.artifact-policy/v1\",\"assumptions\":{{\"trusted_quiescent_staging\":true}},\"allowed\":{allowed},\"required\":{required}{extra}}}")
TAA #     }
TAA #     #[test]
TAA #     fn fixed_system_alias_mapping_is_component_bounded() {
TAA #         assert_eq!(system_alias_candidate(Path::new("/var/folders/x")).unwrap().2, PathBuf::from("/private/var/folders/x"));
TAA #         assert!(system_alias_candidate(Path::new("/var")).is_none());
TAA #         assert!(system_alias_candidate(Path::new("/var-other/x")).is_none());
TAA #         assert!(system_alias_candidate(Path::new("/home/user/link/x")).is_none());
TAA #     }
TAA #     #[cfg(target_os = "macos")]
TAA #     #[test]
TAA #     fn macos_system_temp_alias_works_but_user_links_do_not() {
TAA #         let r = tmp(); put(&r, "a");
TAA #         let canonical = std::fs::canonicalize(&r).unwrap();
TAA #         let alias = canonical.to_string_lossy().replacen("/private/var/", "/var/", 1).replacen("/private/tmp/", "/tmp/", 1);
TAA #         let (out, error) = observe(&alias, pol("[\"a\"]", "[]", "").as_bytes());
TAA #         assert!(!error && out.contains("observed_snapshot"), "{out}");
TAA #         std::os::unix::fs::symlink(&r, r.join("link")).unwrap();
TAA #         let (out, error) = observe(r.join("link").to_str().unwrap(), pol("[\"a\"]", "[]", "").as_bytes());
TAA #         assert!(error && out.contains("symlink_rejected"), "{out}");
TAA #     }
TAA #     #[test]
TAA #     fn clean_tree_passes_with_names_and_kinds() {
TAA #         let r = tmp();
TAA #         put(&r, "docs/README");
TAA #         put(&r, "release.bin");
TAA #         put(&r, "my file \u{e9}.txt");
TAA #         let (o, e) = run(&r, &pol("[\"docs\",\"docs/README\",\"release.bin\",\"my file \u{e9}.txt\"]", "[\"release.bin\"]", ""));
TAA #         assert!(!e, "{o}");
TAA #         assert!(o.contains("\"validity\":\"observed_snapshot\""), "{o}");
TAA #         assert!(o.contains("{\"path\":\"docs\",\"kind\":\"directory\"}"), "{o}");
TAA #         assert!(o.contains("{\"path\":\"my file \u{e9}.txt\",\"kind\":\"file\"}"), "{o}");
TAA #         assert_eq!(o.matches("\"verdict\":\"pass\"").count(), 2, "{o}");
TAA #         assert!(o.contains("\"assumptions\":{\"trusted_quiescent_staging\":true}"));
TAA #         assert!(!o.contains(r.to_str().unwrap()), "absolute root must not be echoed");
TAA #     }
TAA #     #[test]
TAA #     fn empty_root_is_complete_empty_inventory() {
TAA #         let r = tmp();
TAA #         let (o, e) = run(&r, &pol("[]", "[]", ""));
TAA #         assert!(!e && o.contains("\"inventory\":[]") && o.contains("observed_snapshot") && o.contains("\"verdict\":\"pass\""), "{o}");
TAA #     }
TAA #     #[test]
TAA #     fn hidden_extra_file_fails_membership_with_witness() {
TAA #         let r = tmp();
TAA #         put(&r, "release.bin");
TAA #         put(&r, ".env");
TAA #         let (o, e) = run(&r, &pol("[\"release.bin\"]", "[]", ""));
TAA #         assert!(!e && o.contains("\"verdict\":\"fail\"") && o.contains("\"witness\":\".env\""), "{o}");
TAA #     }
TAA #     #[test]
TAA #     fn missing_required_fails_separate_check() {
TAA #         let r = tmp();
TAA #         put(&r, "a");
TAA #         let (o, e) = run(&r, &pol("[\"a\",\"b\"]", "[\"b\"]", ""));
TAA #         assert!(!e, "{o}");
TAA #         assert!(o.contains("\"name\":\"required_subset_actual\"") && o.contains("\"witness\":\"b\""), "{o}");
TAA #     }
TAA #     #[test]
TAA #     fn missing_or_false_assumption_abstains_before_traversal() {
TAA #         let bad = "/nonexistent-instinct-observe-root";
TAA #         for p in [
TAA #             "{\"schema\":\"instinct.artifact-policy/v1\",\"allowed\":[]}",
TAA #             "{\"schema\":\"instinct.artifact-policy/v1\",\"assumptions\":{\"trusted_quiescent_staging\":false},\"allowed\":[]}",
TAA #         ] {
TAA #             let (o, e) = observe(bad, p.as_bytes());
TAA #             assert!(!e && o.contains("\"validity\":\"incomplete\"") && o.contains("assumption_not_asserted"), "{o}");
TAA #             assert!(o.contains("\"inventory\":[]") && o.contains("\"checks\":[]"), "{o}");
TAA #         }
TAA #     }
TAA #     #[test]
TAA #     fn policy_errors_are_rejected_before_observation() {
TAA #         let r = tmp();
TAA #         let cases = [
TAA #             pol("[\"../x\"]", "[]", ""),
TAA #             pol("[\"/abs\"]", "[]", ""),
TAA #             pol("[\"a//b\"]", "[]", ""),
TAA #             pol("[\"a/\"]", "[]", ""),
TAA #             pol("[\"a/./b\"]", "[]", ""),
TAA #             pol("[\"C:\\\\x\"]", "[]", ""),
TAA #             pol("[\"\\\\\\\\srv\\\\share\"]", "[]", ""),
TAA #             pol("[\"a\",\"a\"]", "[]", ""),
TAA #             pol("[\"a\"]", "[\"b\"]", ""),
TAA #             pol("[\"a\"]", "[]", ",\"scope\":{\"bogus\":\"x\"}"),
TAA #             pol("[\"a\"]", "[]", ",\"scope\":{\"project\":\"\"}"),
TAA #             pol("[\"a\"]", "[]", ",\"limits\":{\"max_entries\":10001}"),
TAA #             pol("[\"a\"]", "[]", ",\"limits\":{\"max_depth\":1.5}"),
TAA #             pol("[\"a\"]", "[]", ",\"limits\":{\"max_depth\":-1}"),
TAA #             pol("[\"a\"]", "[]", ",\"extra\":1"),
TAA #             "{\"schema\":\"instinct.artifact-policy/v1\",\"allowed\":[],\"allowed\":[]}".to_string(),
TAA #             "{\"schema\":\"wrong\",\"allowed\":[]}".to_string(),
TAA #         ];
TAA #         for c in cases {
TAA #             let (o, e) = run(&r, &c);
TAA #             assert!(e && o.contains("instinct.check-error/v1"), "accepted {c}: {o}");
TAA #         }
TAA #         assert!(std::fs::read_dir(&r).unwrap().next().is_none(), "root untouched");
TAA #     }
TAA #     #[test]
TAA #     fn relative_or_missing_root_is_an_error() {
TAA #         let p = pol("[]", "[]", "");
TAA #         assert!(observe("relative/dir", p.as_bytes()).1);
TAA #         assert!(observe("/nonexistent-instinct-observe-root", p.as_bytes()).1);
TAA #         let r = tmp();
TAA #         put(&r, "f");
TAA #         assert!(observe(r.join("f").to_str().unwrap(), p.as_bytes()).1);
TAA #     }
TAA #     #[cfg(unix)]
TAA #     #[test]
TAA #     fn symlink_abstains_without_target_disclosure() {
TAA #         let r = tmp();
TAA #         let outside = tmp();
TAA #         put(&outside, "secret-target-name");
TAA #         std::os::unix::fs::symlink(&outside, r.join("link")).unwrap();
TAA #         let (o, e) = run(&r, &pol("[\"link\"]", "[]", ""));
TAA #         assert!(!e && o.contains("\"validity\":\"incomplete\"") && o.contains("symlink_rejected") && o.contains("\"witness\":\"link\""), "{o}");
TAA #         assert!(!o.contains("secret-target-name") && !o.contains(outside.to_str().unwrap()), "{o}");
TAA #         assert!(o.contains("\"inventory\":[]") && o.contains("\"checks\":[]"));
TAA #         let rl = tmp();
TAA #         std::os::unix::fs::symlink(&r, rl.join("rootlink")).unwrap();
TAA #         let (o, e) = run(&rl.join("rootlink"), &pol("[]", "[]", ""));
TAA #         assert!(e && o.contains("root_invalid"), "{o}");
TAA #     }
TAA #     #[cfg(unix)]
TAA #     #[test]
TAA #     fn symlinked_root_ancestor_is_rejected_before_enumeration() {
TAA #         let real = tmp();
TAA #         put(&real, "stage/release.bin");
TAA #         let base = tmp();
TAA #         std::os::unix::fs::symlink(&real, base.join("alias")).unwrap();
TAA #         let p = pol("[\"release.bin\"]", "[]", "");
TAA #         let (o, e) = run(&base.join("alias").join("stage"), &p);
TAA #         assert!(e && o.contains("root_invalid") && o.contains("root_ancestor"), "{o}");
TAA #         assert!(!o.contains("release.bin") && !o.contains(real.to_str().unwrap()), "{o}");
TAA #         let (o, e) = run(&real.join("stage"), &p);
TAA #         assert!(!e && o.contains("observed_snapshot"), "{o}");
TAA #         let np = "{\"schema\":\"instinct.artifact-policy/v1\",\"allowed\":[]}";
TAA #         let (o, e) = observe(base.join("alias").join("stage").to_str().unwrap(), np.as_bytes());
TAA #         assert!(!e && o.contains("assumption_not_asserted") && o.contains("\"inventory\":[]"), "{o}");
TAA #     }
TAA #     #[test]
TAA #     fn oversized_result_on_every_path_is_a_bounded_error() {
TAA #         let big = "p".repeat(90000);
TAA #         let np = format!("{{\"schema\":\"instinct.artifact-policy/v1\",\"allowed\":[],\"scope\":{{\"project\":\"{big}\"}}}}");
TAA #         let (o, e) = observe("/nonexistent-instinct-observe-root", np.as_bytes());
TAA #         assert!(e && o.len() < 1000 && o.contains("limit_exceeded") && !o.contains("pppp"), "{}", o.len());
TAA #         let r = tmp();
TAA #         let tp = format!("{{\"schema\":\"instinct.artifact-policy/v1\",\"assumptions\":{{\"trusted_quiescent_staging\":true}},\"allowed\":[],\"scope\":{{\"project\":\"{big}\"}}}}");
TAA #         let (o, e) = run(&r, &tp);
TAA #         assert!(e && o.contains("limit_exceeded") && o.len() < 1000, "{}", o.len());
TAA #     }
TAA #     #[cfg(unix)]
TAA #     #[test]
TAA #     fn root_spelling_variants_cannot_bypass_the_symlink_rule() {
TAA #         let real = tmp();
TAA #         put(&real, "f");
TAA #         let base = tmp();
TAA #         std::os::unix::fs::symlink(&real, base.join("rl")).unwrap();
TAA #         let p = pol("[\"f\"]", "[]", "");
TAA #         let rl = base.join("rl").to_str().unwrap().to_string();
TAA #         let rs = real.to_str().unwrap().to_string();
TAA #         for bad in [rl.clone(), format!("{rl}/"), format!("{rl}//"), format!("{rl}/."), format!("{rl}/./"), format!("{}/./{}", base.to_str().unwrap(), "rl"), format!("{rs}/"), format!("{rs}//"), format!("{rs}/."), format!("{rs}/../{}", real.file_name().unwrap().to_str().unwrap()), format!("/./{}", &rs[1..]), rs.replacen('/', "//", 1)] {
TAA #             let (o, e) = observe(&bad, p.as_bytes());
TAA #             assert!(e && o.contains("instinct.check-error/v1") && !o.contains("observed_snapshot"), "accepted {bad}: {o}");
TAA #         }
TAA #         let (o, e) = observe(&rs, p.as_bytes());
TAA #         assert!(!e && o.contains("observed_snapshot"), "{o}");
TAA #     }
TAA #     #[cfg(unix)]
TAA #     #[test]
TAA #     fn non_utf8_name_abstains() {
TAA #         use std::os::unix::ffi::OsStrExt;
TAA #         let r = tmp();
TAA #         if let Err(e) = std::fs::write(r.join(std::ffi::OsStr::from_bytes(b"bad\xff")), b"x") {
TAA #             if cfg!(target_os = "macos") && e.raw_os_error() == Some(92) {
TAA #                 eprintln!("SKIP non-UTF-8 fixture: this macOS filesystem rejects the name (EILSEQ); observation not exercised");
TAA #                 std::fs::remove_dir(&r).unwrap();
TAA #                 return;
TAA #             }
TAA #             panic!("cannot create raw-name fixture: {e}");
TAA #         }
TAA #         let (o, e) = run(&r, &pol("[]", "[]", ""));
TAA #         assert!(!e && o.contains("non_utf8_name") && o.contains("\"validity\":\"incomplete\""), "{o}");
TAA #     }
TAA #     #[cfg(unix)]
TAA #     #[test]
TAA #     fn socket_is_unsupported_entry() {
TAA #         let r = tmp();
TAA #         let _l = std::os::unix::net::UnixListener::bind(r.join("sock")).unwrap();
TAA #         let (o, e) = run(&r, &pol("[\"sock\"]", "[]", ""));
TAA #         assert!(!e && o.contains("unsupported_entry_kind"), "{o}");
TAA #     }
TAA #     #[cfg(unix)]
TAA #     #[test]
TAA #     fn unreadable_directory_abstains() {
TAA #         use std::os::unix::fs::PermissionsExt;
TAA #         let r = tmp();
TAA #         put(&r, "d/inner");
TAA #         let d = r.join("d");
TAA #         std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o000)).unwrap();
TAA #         if std::fs::read_dir(&d).is_ok() {
TAA #             std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o755)).unwrap();
TAA #             return; // running with privileges that bypass permissions; cannot exercise
TAA #         }
TAA #         let (o, e) = run(&r, &pol("[\"d\",\"d/inner\"]", "[]", ""));
TAA #         std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o755)).unwrap();
TAA #         assert!(!e && o.contains("read_dir_failed") && o.contains("\"validity\":\"incomplete\"") && o.contains("\"checks\":[]"), "{o}");
TAA #     }
TAA #     #[test]
TAA #     fn mutation_between_passes_abstains() {
TAA #         let r = tmp();
TAA #         put(&r, "a");
TAA #         let p = pol("[\"a\",\"late\"]", "[]", "");
TAA #         let rc = r.clone();
TAA #         let (o, e) = observe_with(r.to_str().unwrap(), p.as_bytes(), &mut || put(&rc, "late"));
TAA #         assert!(!e && o.contains("changed_during_observation") && o.contains("\"witness\":\"late\"") && o.contains("\"inventory\":[]"), "{o}");
TAA #         let rc = r.clone();
TAA #         let (o, _) = observe_with(r.to_str().unwrap(), p.as_bytes(), &mut || {
TAA #             std::fs::write(rc.join("a"), b"longer content").unwrap();
TAA #         });
TAA #         assert!(o.contains("changed_during_observation") && o.contains("\"witness\":\"a\""), "{o}");
TAA #     }
TAA #     #[test]
TAA #     fn budgets_terminate_without_partial_pass() {
TAA #         let r = tmp();
TAA #         for n in 0..5 {
TAA #             put(&r, &format!("f{n}"));
TAA #         }
TAA #         let all = "[\"f0\",\"f1\",\"f2\",\"f3\",\"f4\"]";
TAA #         let (o, e) = run(&r, &pol(all, "[]", ",\"limits\":{\"max_entries\":3}"));
TAA #         assert!(!e && o.contains("budget_exceeded: max_entries") && !o.contains("\"verdict\"") && o.contains("\"inventory\":[]"), "{o}");
TAA #         let (o, _) = run(&r, &pol(all, "[]", ",\"limits\":{\"max_inventory_bytes\":100}"));
TAA #         assert!(o.contains("budget_exceeded: max_inventory_bytes"), "{o}");
TAA #         let d = tmp();
TAA #         put(&d, "a/b/c");
TAA #         let (o, _) = run(&d, &pol("[\"a\",\"a/b\",\"a/b/c\"]", "[]", ",\"limits\":{\"max_depth\":2}"));
TAA #         assert!(o.contains("budget_exceeded: max_depth") && o.contains("\"witness\":\"a/b/c\""), "{o}");
TAA #         let (o, _) = run(&d, &pol("[\"a\",\"a/b\",\"a/b/c\"]", "[]", ",\"limits\":{\"max_depth\":3}"));
TAA #         assert!(o.contains("observed_snapshot"), "{o}");
TAA #     }
TAA #     #[test]
TAA #     fn scope_mismatch_is_delegated_to_kernel_abstain() {
TAA #         let r = tmp();
TAA #         put(&r, "a");
TAA #         let (o, e) = run(&r, &pol("[\"a\"]", "[]", ",\"scope\":{\"project\":\"release-lab\"}"));
TAA #         assert!(!e && o.contains("\"scope\":{\"project\":\"release-lab\"}") && o.contains("\"verdict\":\"pass\""), "{o}");
TAA #     }
TAA #     #[test]
TAA #     fn cli_arg_errors() {
TAA #         let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
TAA #         assert_eq!(cli(&s(&["--help"])), 0);
TAA #         assert_eq!(cli(&s(&[])), 2);
TAA #         assert_eq!(cli(&s(&["--root", "/x"])), 2);
TAA #         assert_eq!(cli(&s(&["--input", "-"])), 2);
TAA #         assert_eq!(cli(&s(&["--root", "/x", "--root", "/y", "--input", "-"])), 2);
TAA #         assert_eq!(cli(&s(&["--root", "/x", "--input", "-", "extra"])), 2);
TAA #         assert_eq!(cli(&s(&["--root", "/x", "--input", "-", "--bogus"])), 2);
TAA #     }
TAA # }