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
// generated by hxc 1.0.0-acgt-compiler from src/check/feedback.hlx -- do not edit by hand

#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
    let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
    if !ok {
        eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
    }
    ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    c
}

// hlx:2
use super::super::{
    append, eligibility, journal, json_out, load_plain, now_secs, parse_json, scope_identity,
    Discovery, Json,
};
// hlx:3
use super::{digest, json, observe};
// hlx:4
use std::path::PathBuf;
// hlx:5
use std::io::Read;
// hlx:6
fn text<'a>(v: &'a Json, key: &str) -> &'a str {
    v.get(key).and_then(Json::as_str).unwrap_or("")
}
// hlx:7
fn s(v: impl Into<String>) -> Json {
    Json::Str(v.into())
}
// hlx:8
fn object(v: Vec<(&str, Json)>) -> Json {
    Json::Obj(v.into_iter().map(|(k, v)| (k.into(), v)).collect())
}
// hlx:9
fn hash(v: &Json) -> String {
    digest::hex(&digest::sha256(json_out(v).as_bytes()))
}
// hlx:10
fn scope(d: &Discovery) -> Json {
    let names = ["project", "persona", "harness", "version", "machine"];
    object(
        names
            .into_iter()
            .zip(scope_identity(&d.meta))
            .filter(|(_, v)| !v.is_empty())
            .map(|(k, v)| (k, s(v)))
            .collect(),
    )
}
// hlx:11
pub(crate) fn fingerprint(d: &Discovery) -> String {
    // hlx:12
    hash(&object(vec![
        ("domain", s("instinct.lesson-check-binding/v1")),
        ("id", s(&d.id)),
        ("title", s(&d.title)),
        ("when", s(&d.when)),
        ("found", s(&d.found)),
        ("how", s(&d.how)),
        ("evidence", s(&d.evidence)),
        ("reconsider", s(&d.reconsider)),
        ("tags", s(&d.tags)),
        ("scope", scope(d)),
        ("source", s(&d.meta.source)),
        ("valid_until", s(d.meta.valid_until.to_string())),
    ]))
    // hlx:13
}
// hlx:14
fn sidecar(path: &PathBuf) -> PathBuf {
    let mut p = path.as_os_str().to_owned();
    p.push(".capabilities.hxdb");
    PathBuf::from(p)
}
// hlx:15
fn bank_binding(path: &PathBuf) -> Result<String, String> {
    // hlx:16
    let canonical =
        std::fs::canonicalize(path).map_err(|_| "cannot resolve bank binding; nothing recorded")?;
    // hlx:17
    let mut bytes = b"instinct.bank-location/v1\0".to_vec();
    // hlx:18
    bytes.extend_from_slice(canonical.as_os_str().as_encoded_bytes());
    // hlx:19
    Ok(digest::hex(&digest::sha256(&bytes)))
    // hlx:20
}
// hlx:21
fn binding_refusal(path: &PathBuf, id: &str) -> String {
    // hlx:22
    let quote = |v: &str| format!("'{}'", v.replace('\'', "'\\''"));
    // hlx:23
    format!("bank binding differs or is missing; nothing recorded. Reattach with an explicitly approved policy on stdin: instinct check attach --lesson {} --store {} --input -", quote(id), quote(&path.to_string_lossy()))
    // hlx:24
}
// hlx:25
fn strict(bytes: &[u8]) -> Result<Json, String> {
    json::parse(bytes)?;
    parse_json(std::str::from_utf8(bytes).map_err(|_| "invalid UTF-8")?)
}
// hlx:26
fn canonical(v: &Json) -> Json {
    match v {
        Json::Obj(o) => {
            let mut o: Vec<_> = o.iter().map(|(k, v)| (k.clone(), canonical(v))).collect();
            o.sort_by(|a, b| a.0.cmp(&b.0));
            Json::Obj(o)
        }
        Json::Arr(a) => Json::Arr(a.iter().map(canonical).collect()),
        other => other.clone(),
    }
}
// hlx:27
fn canonical_policy(mut p: Json) -> Json {
    if let Json::Obj(o) = &mut p {
        for (k, v) in o.iter_mut() {
            if matches!(k.as_str(), "allowed" | "required") {
                if let Json::Arr(a) = v {
                    a.sort_by(|x, y| x.as_str().cmp(&y.as_str()));
                }
            }
        }
    }
    canonical(&p)
}
// hlx:28
fn lesson(path: &PathBuf, id: &str) -> Result<Discovery, String> {
    load_plain(path)?
        .into_iter()
        .find(|d| d.id == id)
        .ok_or_else(|| "unknown active lesson".into())
}
// hlx:29
fn valid_policy(raw: &[u8], d: &Discovery) -> Result<Json, String> {
    // hlx:30
    let p = strict(raw)?;
    // hlx:31
    // Force the adapter's assumption gate OFF: validates policy without filesystem observation.
    // hlx:32
    let mut validation = p.clone();
    if let Json::Obj(o) = &mut validation {
        o.retain(|(k, _)| k != "assumptions");
        o.push((
            "assumptions".into(),
            object(vec![("trusted_quiescent_staging", Json::Bool(false))]),
        ));
    }
    // hlx:33
    let root = if cfg!(windows) { "C:\\" } else { "/" };
    // hlx:34
    let (out, error) = observe::observe(root, json_out(&validation).as_bytes());
    if error {
        return Err(format!(
            "invalid attached policy: {}",
            text(&parse_json(&out)?, "reason")
        ));
    }
    // hlx:35
    let expected = canonical(&scope(d));
    let actual = canonical(p.get("scope").unwrap_or(&Json::Obj(vec![])));
    // hlx:36
    if actual != expected {
        return Err("attached policy scope must exactly match lesson scope".into());
    }
    // hlx:37
    // Validate the original assumptions shape as well, without granting traversal.
    // hlx:38
    if let Some(a) = p.get("assumptions") {
        match a {
            Json::Obj(o)
                if o.len() <= 1
                    && o.iter().all(|(k, v)| {
                        k == "trusted_quiescent_staging" && matches!(v, Json::Bool(_))
                    }) => {}
            _ => return Err("invalid policy assumptions".into()),
        }
    }
    // hlx:39
    Ok(canonical_policy(p))
    // hlx:40
}
// hlx:41
fn attachment(path: &PathBuf, id: &str) -> Result<Option<Json>, String> {
    // hlx:42
    let p = sidecar(path);
    if !p.exists() {
        return Ok(None);
    }
    // hlx:43
    let mut found = None;
    for line in journal::read(&p)?.lines().filter(|l| !l.trim().is_empty()) {
        let v = strict(line.as_bytes())?;
        if !matches!(
            text(&v, "schema"),
            "instinct.check-attachment/v1" | "instinct.check-revocation/v1"
        ) {
            return Err("unsupported attachment record".into());
        }
        if text(&v, "schema") == "instinct.check-revocation/v1" {
            validate_revocation(&v)?;
        }
        if text(&v, "lesson_id") == id {
            found = Some(v)
        }
    }
    Ok(found)
    // hlx:44
}
// hlx:45
fn validate_revocation(v: &Json) -> Result<(), String> {
    // hlx:46
    let Json::Obj(fields) = v else {
        return Err("invalid revocation record".into());
    };
    // hlx:47
    let keys = ["schema", "bank_binding", "lesson_id", "revision"];
    // hlx:48
    let binding = text(v, "bank_binding");
    let revision = v.get("revision").and_then(Json::as_f64).unwrap_or(0.0);
    // hlx:49
    if fields.len() != keys.len()
        || fields.iter().any(|(k, _)| !keys.contains(&k.as_str()))
        || text(v, "lesson_id").is_empty()
        || binding.len() != 64
        || !binding
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
        || !revision.is_finite()
        || revision < 1.0
        || revision.fract() != 0.0
        || revision > 2147483647.0
    {
        return Err("invalid revocation record".into());
    }
    // hlx:50
    Ok(())
    // hlx:51
}
// hlx:52
fn next_revision(previous: Option<&Json>) -> Result<u64, String> {
    // hlx:53
    let Some(previous) = previous else {
        return Ok(1);
    };
    // hlx:54
    let n = previous
        .get("revision")
        .and_then(Json::as_f64)
        .ok_or("attachment revision missing")?;
    // hlx:55
    if !n.is_finite() || n < 1.0 || n.fract() != 0.0 || n >= 2147483647.0 {
        return Err("attachment revision invalid or exhausted".into());
    }
    // hlx:56
    Ok(n as u64 + 1)
    // hlx:57
}
// hlx:58
pub fn detach_cli(args: &[String]) -> Result<String, String> {
    // hlx:59
    let mut opts = std::collections::BTreeMap::new();
    let mut i = 0;
    // hlx:60
    while i < args.len() {
        let k = args[i].as_str();
        if !matches!(k, "--lesson" | "--store") || opts.contains_key(k) {
            return Err("usage: check detach --lesson ID --store BANK".into());
        }
        i += 1;
        let v = args.get(i).ok_or("missing detach option value")?;
        if v.trim().is_empty() {
            return Err("empty detach option".into());
        }
        opts.insert(k, v.as_str());
        i += 1;
    }
    // hlx:61
    let id = *opts.get("--lesson").ok_or("detach requires --lesson")?;
    let path = PathBuf::from(
        opts.get("--store")
            .ok_or("detach requires explicit --store")?,
    );
    // hlx:62
    let _bank = journal::identity_lock(&path)?;
    let _ = lesson(&path, id)?;
    // hlx:63
    let Some(previous) = attachment(&path, id)? else {
        return Ok(format!("no check attached to {id}"));
    };
    // hlx:64
    let binding = bank_binding(&path)?;
    if text(&previous, "bank_binding") != binding {
        return Err(binding_refusal(&path, id));
    }
    // hlx:65
    if text(&previous, "schema") == "instinct.check-revocation/v1" {
        return Ok(format!("check already detached from {id}"));
    }
    // hlx:66
    let revision = next_revision(Some(&previous))?;
    // hlx:67
    let event = object(vec![
        ("schema", s("instinct.check-revocation/v1")),
        ("bank_binding", s(binding)),
        ("lesson_id", s(id)),
        ("revision", Json::Num(revision as f64)),
    ]);
    // hlx:68
    let p = sidecar(&path);
    let _side = journal::identity_lock(&p)?;
    append(&p, &json_out(&event))?;
    Ok(format!("check detached from {id}"))
    // hlx:69
}
// hlx:70
pub fn attach_cli(args: &[String]) -> Result<String, String> {
    // hlx:71
    let mut opts = std::collections::BTreeMap::new();
    let mut i = 0;
    // hlx:72
    while i < args.len() {
        let k = args[i].as_str();
        if !matches!(k, "--lesson" | "--store" | "--input") || opts.contains_key(k) {
            return Err("usage: check attach --lesson ID --store BANK --input FILE|-".into());
        }
        i += 1;
        let v = args.get(i).ok_or("missing attach option value")?;
        if v.is_empty() {
            return Err("empty attach option".into());
        }
        opts.insert(k, v.as_str());
        i += 1;
    }
    // hlx:73
    let id = *opts.get("--lesson").ok_or("attach requires --lesson")?;
    let path = PathBuf::from(
        opts.get("--store")
            .ok_or("attach requires explicit --store")?,
    );
    let input = *opts.get("--input").ok_or("attach requires --input")?;
    // hlx:74
    let mut raw = Vec::new();
    if input == "-" {
        std::io::stdin()
            .lock()
            .take((json::MAX_BYTES + 1) as u64)
            .read_to_end(&mut raw)
            .map_err(|_| "cannot read attachment input")?;
    } else {
        std::fs::File::open(input)
            .map_err(|_| "cannot open attachment input")?
            .take((json::MAX_BYTES + 1) as u64)
            .read_to_end(&mut raw)
            .map_err(|_| "cannot read attachment input")?;
    }
    // hlx:75
    let _bank = journal::identity_lock(&path)?;
    let d = lesson(&path, id)?;
    let policy = valid_policy(&raw, &d)?;
    // hlx:76
    let fp = fingerprint(&d);
    let ph = hash(&policy);
    let binding = bank_binding(&path)?;
    let previous = attachment(&path, id)?;
    // hlx:77
    if previous.as_ref().is_some_and(|a| {
        text(a, "schema") == "instinct.check-attachment/v1"
            && text(a, "bank_binding") == binding
            && text(a, "lesson_fingerprint") == fp
            && text(a, "policy_sha256") == ph
    }) {
        return Ok(format!("check already attached to {id}"));
    }
    // hlx:78
    let revision = next_revision(previous.as_ref())?;
    // hlx:79
    let event = object(vec![
        ("schema", s("instinct.check-attachment/v1")),
        ("bank_binding", s(binding)),
        ("lesson_id", s(id)),
        ("lesson_fingerprint", s(fp)),
        ("policy_sha256", s(ph)),
        ("revision", Json::Num(revision as f64)),
        ("policy", policy),
    ]);
    // hlx:80
    let p = sidecar(&path);
    let _side = journal::identity_lock(&p)?;
    append(&p, &json_out(&event))?;
    Ok(format!("check attached to {id}"))
    // hlx:81
}
// hlx:82
#[cfg(test)]
// hlx:83
mod lifecycle_tests {
    // hlx:84
    use super::*;
    // hlx:85
    #[test]
    // hlx:86
    fn revocation_shape_rejects_malformed_and_unknown_fields() {
        // hlx:87
        let good = object(vec![
            ("schema", s("instinct.check-revocation/v1")),
            ("bank_binding", s("a".repeat(64))),
            ("lesson_id", s("in-test")),
            ("revision", Json::Num(2.0)),
        ]);
        // hlx:88
        assert!(validate_revocation(&good).is_ok());
        // hlx:89
        for (key, bad) in [
            ("revision", Json::Num(0.0)),
            ("revision", Json::Num(1.5)),
            ("revision", Json::Num(2147483648.0)),
            ("bank_binding", s("wrong")),
            ("lesson_id", s("")),
        ] {
            let mut v = good.clone();
            if let Json::Obj(fields) = &mut v {
                *fields.iter_mut().find(|(k, _)| k == key).unwrap() = (key.into(), bad);
            }
            assert!(validate_revocation(&v).is_err());
        }
        // hlx:90
        let mut extra = good.clone();
        if let Json::Obj(fields) = &mut extra {
            fields.push(("ignored".into(), Json::Bool(true)));
        }
        assert!(validate_revocation(&extra).is_err());
        // hlx:91
    }
    // hlx:92
    #[test]
    // hlx:93
    fn revision_limits_never_wrap_or_round() {
        assert_eq!(next_revision(None).unwrap(), 1);
        for n in [0.0, -1.0, 1.5, 2147483647.0, f64::INFINITY] {
            assert!(next_revision(Some(&object(vec![("revision", Json::Num(n))]))).is_err());
        }
        assert_eq!(
            next_revision(Some(&object(vec![("revision", Json::Num(2147483646.0))]))).unwrap(),
            2147483647
        );
    }
    // hlx:94
}
// hlx:95
fn verification_digest(v: &Json) -> String {
    if let Json::Obj(o) = v {
        hash(&canonical(&Json::Obj(
            o.iter()
                .filter(|(k, _)| k != "receipt_sha256")
                .cloned()
                .collect(),
        )))
    } else {
        String::new()
    }
}
// hlx:96
pub(crate) fn metadata(v: &Json, id: &str, key: &str) -> Option<String> {
    // hlx:97
    let Json::Obj(o) = v else { return None };
    // hlx:98
    let keys = [
        "schema",
        "adapter",
        "lesson_id",
        "lesson_fingerprint",
        "policy_sha256",
        "check_revision",
        "scope",
        "observation_key",
        "observation_sha256",
        "root_sha256",
        "authorization",
        "evidence_origin",
        "trusted_quiescent_staging",
        "receipt_sha256",
    ];
    // hlx:99
    if o.len() != keys.len() || o.iter().any(|(k, _)| !keys.contains(&k.as_str())) {
        return None;
    }
    // hlx:100
    if text(v, "schema") != "instinct.check-verification/v1"
        || text(v, "adapter") != "artifact-inventory/v1"
        || text(v, "lesson_id") != id
        || key.is_empty()
        || text(v, "observation_key") != key
        || text(v, "authorization") != "not_evaluated"
        || text(v, "evidence_origin") != "adapter_observed"
        || v.get("trusted_quiescent_staging") != Some(&Json::Bool(true))
    {
        return None;
    }
    // hlx:101
    for k in [
        "lesson_fingerprint",
        "policy_sha256",
        "observation_sha256",
        "root_sha256",
        "receipt_sha256",
    ] {
        let h = text(v, k);
        if h.len() != 64
            || !h
                .bytes()
                .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
        {
            return None;
        }
    }
    // hlx:102
    let r = v.get("check_revision")?.as_f64()?;
    if !r.is_finite() || r < 1.0 || r.fract() != 0.0 || r > 2147483647.0 {
        return None;
    }
    // hlx:103
    if !matches!(v.get("scope"), Some(Json::Obj(_)))
        || text(v, "receipt_sha256") != verification_digest(v)
    {
        return None;
    }
    // hlx:104
    Some(text(v, "lesson_fingerprint").to_owned())
    // hlx:105
}
// hlx:106
pub(crate) fn hit(
    path: &PathBuf,
    id: &str,
    note: &str,
    key: &str,
    root: &str,
    trusted: bool,
) -> Result<String, String> {
    // hlx:107
    if cfg!(not(unix)) {
        return Err(
            "check-verified hits are not supported on this platform; nothing recorded".into(),
        );
    }
    // hlx:108
    if !trusted || root.is_empty() || key.trim().is_empty() {
        return Err(
            "checked hit requires root, trusted-staging and nonempty outcome-id; nothing recorded"
                .into(),
        );
    }
    // hlx:109
    let key = key.trim();
    let _lock = journal::identity_lock(path)?;
    let d = lesson(path, id)?;
    // hlx:110
    eligibility::scope_check(&d.meta, &eligibility::env_scope(), now_secs())
        .map_err(|r| format!("check scope refused: {r}"))?;
    // hlx:111
    let a = attachment(path, id)?.ok_or("lesson has no attached check; nothing recorded")?;
    // hlx:112
    if text(&a, "bank_binding") != bank_binding(path)? {
        return Err(binding_refusal(path, id));
    }
    // hlx:113
    if text(&a, "schema") == "instinct.check-revocation/v1" {
        return Err("check attachment was revoked; explicitly reattach before verification; nothing recorded".into());
    }
    // hlx:114
    let fp = fingerprint(&d);
    if text(&a, "lesson_fingerprint") != fp {
        return Err("lesson changed since check attachment; reattach before verification".into());
    }
    // hlx:115
    if let Some(prior) = d.outcomes.get(key) {
        if *prior != Some(true) {
            return Err("outcome already has a conflicting verdict; nothing recorded".into());
        }
        return Ok(format!("outcome already recorded for {id}"));
    }
    // hlx:116
    let policy = a.get("policy").ok_or("attachment policy missing")?;
    if hash(policy) != text(&a, "policy_sha256") {
        return Err("attachment fingerprint mismatch".into());
    }
    // hlx:117
    let mut p = policy.clone();
    if let Json::Obj(o) = &mut p {
        o.retain(|(k, _)| k != "assumptions");
        o.push((
            "assumptions".into(),
            object(vec![("trusted_quiescent_staging", Json::Bool(true))]),
        ));
    }
    // hlx:118
    let (out, error) = observe::observe(root, json_out(&p).as_bytes());
    if error {
        return Err(format!(
            "check error; nothing recorded: {}",
            text(&parse_json(&out)?, "reason")
        ));
    }
    // hlx:119
    let obs = parse_json(&out)?;
    let Some(Json::Arr(checks)) = obs.get("checks") else {
        return Err("check produced no predicates; nothing recorded".into());
    };
    // hlx:120
    if text(&obs, "validity") != "observed_snapshot"
        || checks.is_empty()
        || checks
            .iter()
            .any(|c| c.get("result").map(|r| text(r, "verdict")) != Some("pass"))
    {
        return Err("observed check did not pass; nothing recorded".into());
    }
    // hlx:121
    let mut proof = object(vec![
        ("schema", s("instinct.check-verification/v1")),
        ("adapter", s("artifact-inventory/v1")),
        ("lesson_id", s(id)),
        ("lesson_fingerprint", s(fp)),
        ("policy_sha256", s(text(&a, "policy_sha256"))),
        (
            "check_revision",
            a.get("revision")
                .cloned()
                .ok_or("attachment revision missing")?,
        ),
        ("scope", scope(&d)),
        ("observation_key", s(key)),
        ("observation_sha256", s(hash(&canonical(&obs)))),
        (
            "root_sha256",
            s(digest::hex(&digest::sha256(root.as_bytes()))),
        ),
        ("authorization", s("not_evaluated")),
        ("evidence_origin", s("adapter_observed")),
        ("trusted_quiescent_staging", Json::Bool(true)),
    ]);
    // hlx:122
    let proof_hash = verification_digest(&proof);
    if let Json::Obj(o) = &mut proof {
        o.push(("receipt_sha256".into(), s(proof_hash)));
    }
    // hlx:123
    let event = object(vec![
        ("kind", s("hit")),
        ("id", s(id)),
        ("ts", Json::Num(now_secs() as f64)),
        ("note", s(note)),
        ("outcome_id", s(key)),
        ("check_verification", proof),
    ]);
    // hlx:124
    append(path, &json_out(&event))?;
    Ok(format!("check-verified hit recorded for {id}"))
    // hlx:125
}
// hlx:126
pub(crate) fn provenance(event: &Json, d: &Discovery) -> (u8, String) {
    match event.get("check_verification") {
        None => (0, String::new()),
        Some(v) => match metadata(v, &d.id, text(event, "outcome_id")) {
            Some(fp) => (1, fp),
            None => (3, String::new()),
        },
    }
}
// hlx:127
pub(crate) fn annotate_eval(
    path: &PathBuf,
    mut output: String,
    json_mode: bool,
    since: Option<u64>,
) -> Result<String, String> {
    // hlx:128
    let raw = journal::read(path)?;
    let marker = raw
        .lines()
        .filter_map(|l| parse_json(l).ok())
        .any(|v| v.get("check_verification").is_some());
    if !marker {
        return Ok(output);
    }
    // hlx:129
    let mut total = 0u64;
    let mut verified = 0u64;
    let mut downgraded = 0u64;
    let mut invalid = 0u64;
    // hlx:130
    for line in raw.lines().filter(|l| !l.trim().is_empty()) {
        let v = parse_json(line)?;
        if let Some(meta) = v.get("check_verification") {
            let ts = v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64;
            if since.is_none_or(|f| ts >= f)
                && metadata(meta, text(&v, "id"), text(&v, "outcome_id")).is_none()
            {
                invalid += 1;
            }
        }
    }
    // hlx:131
    super::super::fold_bank_verified(path, |_, ts, hit, state| {
        if hit && since.is_none_or(|f| ts >= f) {
            total += 1;
            if state == 1 {
                verified += 1;
            } else if state == 2 {
                downgraded += 1;
            }
        }
    })?;
    // hlx:132
    let summary = object(vec![
        ("schema", s("instinct.verified-feedback-summary/v1")),
        ("claimed_hits", Json::Num((total - verified) as f64)),
        ("check_verified_hits", Json::Num(verified as f64)),
        ("downgraded_hits", Json::Num(downgraded as f64)),
        ("invalid_records", Json::Num(invalid as f64)),
    ]);
    // hlx:133
    if json_mode {
        let mut v = parse_json(&output)?;
        if let Json::Obj(o) = &mut v {
            o.push(("verification".into(), summary));
        }
        output = json_out(&v);
    } else {
        output.push_str(&format!("\n\nVerification: {verified} check-verified hits, {} claimed hits; {downgraded} downgraded, {invalid} invalid records.\nA check verifies its predicate under stated assumptions, not causation or authorization.",total-verified));
    }
    Ok(output)
    // hlx:134
}