instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
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
// generated by hxc 1.0.0-acgt-compiler from tests/case_learning.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:4
#[allow(dead_code)]
// hlx:5
#[path = "../src/check/json.rs"]
// hlx:6
mod json;
// hlx:7
use json::J;
// hlx:8
use std::collections::BTreeMap;
// hlx:9
use std::fs;
// hlx:10
use std::io::Write;
// hlx:11
use std::path::{Path, PathBuf};
// hlx:12
use std::process::{Command, Stdio};
// hlx:13
use std::time::{SystemTime, UNIX_EPOCH};
// hlx:15
const QUERY: &str = "Verify an artifact handoff when a recipient sees an old file or the wrong revision after delivery";
// hlx:16
const REBUILD: &str = "Locate or rebuild the expected producer artifact before publishing.";
// hlx:17
const PUBLISH: &str = "Publish the verified producer artifact to the intended destination.";
// hlx:18
const TRACE: &str = "Trace the recipient's selected version or read path.";
// hlx:19
const REPORT: &str = "Report the verified recipient read and its revision.";
// hlx:20
const REQUESTED: &[u8] = b"reviewed artifact\x00revision-42\xff";
// hlx:21
const STALE: &[u8] = b"reviewed artifact\x00revision-41\xff";
// hlx:23
struct Sandbox(PathBuf);
// hlx:24
impl Sandbox {
    // hlx:25
    fn new(label: &str) -> Self {
        // hlx:26
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        // hlx:27
        let path = std::env::temp_dir().join(format!(
            "instinct-case-{label}-{}-{nonce}",
            std::process::id()
        ));
        // hlx:28
        fs::create_dir(&path).unwrap();
        // hlx:29
        let sandbox = Self(path);
        // hlx:30
        let result = sandbox.run(
            &[
                "bank",
                "--from",
                "builtin:verify-handoff",
                "--project",
                "handoff",
            ],
            None,
        );
        // hlx:31
        assert!(result.starts_with("banked "), "{result}");
        // hlx:32
        sandbox
        // hlx:33
    }
    // hlx:35
    fn run(&self, args: &[&str], input: Option<&str>) -> String {
        // hlx:36
        let out = self.output(args, input);
        // hlx:37
        assert!(
            out.status.success(),
            "{args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        // hlx:38
        String::from_utf8(out.stdout).unwrap()
        // hlx:39
    }
    // hlx:41
    fn output(&self, args: &[&str], input: Option<&str>) -> std::process::Output {
        // hlx:42
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_instinct"));
        // hlx:43
        for (key, _) in std::env::vars_os() {
            // hlx:44
            if key.to_string_lossy().starts_with("INSTINCT_") {
                // hlx:45
                cmd.env_remove(key);
                // hlx:46
            }
            // hlx:47
        }
        // hlx:48
        cmd.args(args)
            .current_dir(&self.0)
            .env("INSTINCT_STORE", self.0.join("bank.hxdb"))
            // hlx:49
            .env("INSTINCT_TEAM", "0")
            .env("INSTINCT_STARTER", "0")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        // hlx:50
        cmd.stdin(if input.is_some() {
            Stdio::piped()
        } else {
            Stdio::null()
        });
        // hlx:51
        let mut child = cmd.spawn().unwrap();
        // hlx:52
        if let Some(text) = input {
            // hlx:53
            child.stdin.take().unwrap().write_all(text.as_bytes()).ok();
            // hlx:54
        }
        // hlx:55
        child.wait_with_output().unwrap()
        // hlx:56
    }
    // hlx:57
}
// hlx:59
impl Drop for Sandbox {
    // hlx:60
    fn drop(&mut self) {
        // hlx:61
        let _ = fs::remove_dir_all(&self.0);
        // hlx:62
    }
    // hlx:63
}
// hlx:65
fn field<'a>(object: &'a J, name: &str) -> &'a J {
    // hlx:66
    let J::Obj(fields) = object else {
        panic!("expected object, got {object:?}")
    };
    // hlx:67
    &fields
        .iter()
        .find(|(k, _)| k == name)
        .unwrap_or_else(|| panic!("missing {name} in {object:?}"))
        .1
    // hlx:68
}
// hlx:70
fn string<'a>(object: &'a J, name: &str) -> &'a str {
    // hlx:71
    match field(object, name) {
        J::Str(s) => s,
        other => panic!("expected text at {name}, got {other:?}"),
    }
    // hlx:72
}
// hlx:74
fn experiences(packet: &J) -> &[J] {
    // hlx:75
    match field(packet, "experiences") {
        J::Arr(rows) => rows,
        other => panic!("expected experiences array, got {other:?}"),
    }
    // hlx:76
}
// hlx:78
fn only_lesson(packet: &J) -> &J {
    // hlx:79
    let [lesson] = experiences(packet) else {
        panic!("expected exactly one lesson: {packet:?}")
    };
    // hlx:80
    lesson
    // hlx:81
}
// hlx:85
fn recipient_read(dir: &Path) -> Vec<u8> {
    // hlx:86
    let selection = fs::read_to_string(dir.join("selected-version")).unwrap();
    // hlx:87
    fs::read(dir.join(selection)).unwrap()
    // hlx:88
}
// hlx:90
fn observe(dir: &Path, key: &str) -> bool {
    // hlx:91
    let bytes = match key {
        // hlx:92
        "producer_matches" => fs::read(dir.join("producer.bin")).unwrap(),
        // hlx:93
        "destination_matches" => fs::read(dir.join("destination.bin")).unwrap(),
        // hlx:94
        "recipient_matches" => recipient_read(dir),
        // hlx:95
        key => panic!("unexpected handoff question {key}"),
        // hlx:96
    };
    // hlx:97
    bytes == REQUESTED
    // hlx:98
}
// hlx:100
fn next_action(sandbox: &Sandbox, dir: &Path) -> String {
    // hlx:101
    let mut facts = BTreeMap::<String, bool>::new();
    // hlx:102
    for _ in 0..=3 {
        // hlx:103
        let mut args = vec!["decide", "--q", QUERY, "--project", "handoff"];
        // hlx:104
        let encoded = format!(
            "{{{}}}",
            facts
                .iter()
                .map(|(k, v)| format!("\"{k}\":{v}"))
                .collect::<Vec<_>>()
                .join(",")
        );
        // hlx:105
        if !facts.is_empty() {
            // hlx:106
            args.extend(["--facts", encoded.as_str()]);
            // hlx:107
        }
        // hlx:108
        let out = sandbox.run(&args, None);
        // hlx:109
        let packet = json::parse(out.as_bytes()).unwrap();
        // hlx:110
        let [lesson] = experiences(&packet) else {
            panic!("expected one scoped lesson: {out}")
        };
        // hlx:111
        let advice = field(lesson, "case_advice");
        // hlx:112
        match string(advice, "status") {
            // hlx:113
            "ask" => {
                // hlx:114
                let key = string(advice, "key");
                // hlx:115
                assert!(!facts.contains_key(key), "repeated check {key}: {out}");
                // hlx:116
                facts.insert(key.into(), observe(dir, key));
                // hlx:117
            }
            // hlx:118
            "candidate_action" => {
                // hlx:119
                let action = string(advice, "candidate_action");
                // hlx:120
                if action == REPORT {
                    assert_eq!(
                        facts.get("recipient_matches"),
                        Some(&true),
                        "reported delivery without a fresh recipient read: {out}"
                    );
                }
                // hlx:121
                return action.into();
                // hlx:122
            }
            // hlx:123
            status => panic!("handoff decision returned {status}: {out}"),
            // hlx:124
        }
        // hlx:125
    }
    // hlx:126
    panic!("all three checks answered without an action")
    // hlx:127
}
// hlx:129
fn fixture_succeeds(sandbox: &Sandbox, mask: u8) {
    // hlx:130
    let dir = sandbox.0.join(format!("handoff-{mask}"));
    // hlx:131
    fs::create_dir(&dir).unwrap();
    // hlx:132
    let (producer, destination, recipient) = (mask & 4 != 0, mask & 2 != 0, mask & 1 != 0);
    // hlx:133
    for (name, matches) in [
        ("producer.bin", producer),
        ("destination.bin", destination),
        ("cached.bin", recipient),
    ] {
        // hlx:134
        fs::write(dir.join(name), if matches { REQUESTED } else { STALE }).unwrap();
        // hlx:135
    }
    // hlx:136
    fs::write(dir.join("selected-version"), "cached.bin").unwrap();
    // hlx:138
    let mut expected = Vec::new();
    // hlx:139
    if !recipient {
        // hlx:140
        if !destination {
            // hlx:141
            if !producer {
                // hlx:142
                expected.push(REBUILD);
                // hlx:143
            }
            // hlx:144
            expected.push(PUBLISH);
            // hlx:145
        }
        // hlx:146
        expected.push(TRACE);
        // hlx:147
    }
    // hlx:148
    expected.push(REPORT);
    // hlx:149
    for recommendation in expected {
        // hlx:151
        let action = next_action(sandbox, &dir);
        // hlx:152
        assert_eq!(
            action, recommendation,
            "wrong next action for initial fixture {mask:03b}"
        );
        // hlx:153
        match action.as_str() {
            // hlx:154
            REBUILD => fs::write(dir.join("producer.bin"), REQUESTED).unwrap(),
            // hlx:155
            PUBLISH => {
                fs::copy(dir.join("producer.bin"), dir.join("destination.bin")).unwrap();
            }
            // hlx:156
            TRACE => fs::write(dir.join("selected-version"), "destination.bin").unwrap(),
            // hlx:157
            REPORT => assert_eq!(
                recipient_read(&dir),
                REQUESTED,
                "stale bytes reported complete in fixture {mask:03b}"
            ),
            // hlx:158
            other => panic!("unknown handoff action {other}"),
            // hlx:159
        }
        // hlx:160
    }
    // hlx:161
    assert_eq!(
        recipient_read(&dir),
        REQUESTED,
        "recipient mismatch in fixture {mask:03b}"
    );
    // hlx:162
}
// hlx:164
#[test]
// hlx:165
fn shipped_handoff_recovers_the_requested_bytes_in_all_eight_initial_states() {
    // hlx:166
    let sandbox = Sandbox::new("eight");
    // hlx:167
    for mask in 0..8 {
        // hlx:168
        fixture_succeeds(&sandbox, mask);
        // hlx:169
    }
    // hlx:170
}
// hlx:172
#[test]
// hlx:173
fn ordinary_recall_and_prompt_give_the_first_check_only_in_the_right_project() {
    // hlx:174
    let sandbox = Sandbox::new("scope");
    // hlx:175
    let out = sandbox.run(&["decide", "--project", "handoff", "--q", QUERY], None);
    // hlx:176
    let packet = json::parse(out.as_bytes()).unwrap();
    // hlx:177
    let [lesson] = experiences(&packet) else {
        panic!("expected one scoped lesson: {out}")
    };
    // hlx:178
    let advice = field(lesson, "case_advice");
    // hlx:179
    assert_eq!(string(advice, "status"), "ask");
    // hlx:180
    let question = string(advice, "question");
    // hlx:181
    let key = string(advice, "key");
    // hlx:182
    assert_eq!(key, "recipient_matches");
    // hlx:183
    let prompt = format!("{{\"prompt\":\"{QUERY}\",\"session_id\":\"case-learning-scope\"}}");
    // hlx:184
    for project in ["unrelated", "handoff"] {
        // hlx:185
        let recall = sandbox.run(&["recall", "--project", project, "--q", QUERY], None);
        // hlx:186
        let hook = sandbox.run(
            &["prompt", "--format", "text", "--project", project],
            Some(&prompt),
        );
        // hlx:187
        for text in [recall, hook] {
            // hlx:188
            if project == "handoff" {
                // hlx:189
                assert!(
                    text.contains(question) && text.contains(key),
                    "missing initial check: {text}"
                );
                // hlx:190
            } else {
                // hlx:191
                assert!(
                    text.trim().is_empty(),
                    "unexpected cross-project advice: {text}"
                );
                // hlx:192
            }
            // hlx:193
        }
        // hlx:194
    }
    // hlx:195
    let guide = sandbox.run(
        &["guide", "start", "--project", "handoff", "--q", QUERY],
        None,
    );
    // hlx:196
    assert!(
        guide.contains(question) && guide.contains(key),
        "guide missed the initial check: {guide}"
    );
    // hlx:197
    let outside = sandbox.run(
        &["guide", "start", "--project", "unrelated", "--q", QUERY],
        None,
    );
    // hlx:198
    assert!(
        !outside.contains(question),
        "guide leaked the initial check: {outside}"
    );
    // hlx:199
    let unrelated = sandbox.run(&["decide", "--project", "unrelated", "--q", QUERY], None);
    // hlx:200
    assert!(experiences(&json::parse(unrelated.as_bytes()).unwrap()).is_empty());
    // hlx:201
}
// hlx:203
#[test]
// hlx:204
fn lexical_miss_uses_two_observed_facts_only_for_a_unique_scoped_casebook() {
    // hlx:205
    let sandbox = Sandbox::new("fact-match");
    // hlx:206
    let nonsense = "zorpel xyltrium kwezzit";
    // hlx:207
    let facts = r#"{"recipient_matches":false,"destination_matches":false}"#;
    // hlx:208
    let resolve = |project: &str, observed: &str| {
        // hlx:209
        let out = sandbox.run(
            &[
                "decide",
                "--q",
                nonsense,
                "--project",
                project,
                "--facts",
                observed,
            ],
            None,
        );
        // hlx:210
        json::parse(out.as_bytes()).unwrap()
        // hlx:211
    };
    // hlx:212
    assert!(experiences(&resolve("handoff", "{}")).is_empty());
    // hlx:213
    assert!(experiences(&resolve("handoff", r#"{"recipient_matches":false}"#)).is_empty());
    // hlx:214
    assert!(experiences(&resolve("other-project", facts)).is_empty());
    // hlx:215
    let matched = resolve("handoff", facts);
    // hlx:216
    let lesson = only_lesson(&matched);
    // hlx:217
    assert_eq!(
        string(field(lesson, "case_advice"), "key"),
        "producer_matches"
    );
    // hlx:218
    let alternate = include_str!("../skills/instinct/references/verify-handoff.json").replacen(
        "Verify delivery at the recipient",
        "Verify a second delivery method",
        1,
    );
    // hlx:219
    let result = sandbox.run(
        &["bank", "--from", "-", "--project", "handoff"],
        Some(&alternate),
    );
    // hlx:220
    assert!(
        result.starts_with("banked ") && !result.contains(string(lesson, "id")),
        "{result}"
    );
    // hlx:221
    assert!(
        experiences(&resolve("handoff", facts)).is_empty(),
        "ambiguous evidence selected a casebook"
    );
    // hlx:222
    let empty_store = sandbox.0.join("empty.hxdb");
    // hlx:223
    for cmd in ["decide", "recall"] {
        // hlx:224
        let bad = sandbox.output(
            &[
                cmd,
                "--q",
                nonsense,
                "--project",
                "handoff",
                "--store",
                empty_store.to_str().unwrap(),
                "--facts",
                r#"{"a":"true"}"#,
            ],
            None,
        );
        // hlx:225
        assert!(
            !bad.status.success() && String::from_utf8_lossy(&bad.stderr).contains("Boolean"),
            "{cmd}: {bad:?}"
        );
        // hlx:226
    }
    // hlx:227
}
// hlx:229
fn mcp_call(seq: usize, tool: &str, args: &str) -> String {
    // hlx:230
    format!(
        r#"{{"jsonrpc":"2.0","id":{seq},"method":"tools/call","params":{{"name":"{tool}","arguments":{args}}}}}"#
    )
    // hlx:231
}
// hlx:233
fn tool_text(line: &str, seq: usize) -> String {
    // hlx:234
    let reply = json::parse(line.as_bytes()).unwrap();
    // hlx:235
    assert_eq!(field(&reply, "id"), &J::Num(seq.to_string()));
    // hlx:236
    let result = field(&reply, "result");
    // hlx:237
    assert_eq!(field(result, "isError"), &J::Bool(false), "{line}");
    // hlx:238
    let J::Arr(parts) = field(result, "content") else {
        panic!("invalid tool content: {line}")
    };
    // hlx:239
    string(&parts[0], "text").into()
    // hlx:240
}
// hlx:242
#[test]
// hlx:243
fn observed_mcp_miss_updates_live_recall_and_retries_once_per_outcome() {
    // hlx:244
    let sandbox = Sandbox::new("case-feedback");
    // hlx:245
    let dir = &sandbox.0;
    // hlx:246
    fs::write(dir.join("producer.bin"), REQUESTED).unwrap();
    // hlx:247
    fs::write(dir.join("destination.bin"), STALE).unwrap();
    // hlx:248
    fs::write(dir.join("cached.bin"), STALE).unwrap();
    // hlx:249
    fs::write(dir.join("archive.bin"), REQUESTED).unwrap();
    // hlx:250
    fs::write(dir.join("selected-version"), "cached.bin").unwrap();
    // hlx:251
    let facts = format!(
        r#"{{"producer_matches":{},"destination_matches":{},"recipient_matches":{}}}"#,
        observe(dir, "producer_matches"),
        observe(dir, "destination_matches"),
        observe(dir, "recipient_matches")
    );
    // hlx:252
    let decide = || {
        json::parse(
            sandbox
                .run(
                    &[
                        "decide",
                        "--q",
                        QUERY,
                        "--project",
                        "handoff",
                        "--facts",
                        &facts,
                    ],
                    None,
                )
                .as_bytes(),
        )
        .unwrap()
    };
    // hlx:253
    let before = decide();
    // hlx:254
    let lesson = only_lesson(&before);
    // hlx:255
    let id = string(lesson, "id");
    // hlx:256
    assert_eq!(
        string(field(lesson, "case_advice"), "candidate_action"),
        PUBLISH
    );
    // hlx:259
    fs::copy(dir.join("producer.bin"), dir.join("destination.bin")).unwrap();
    // hlx:260
    assert_eq!(recipient_read(dir), STALE);
    // hlx:261
    assert_eq!(fs::read(dir.join("archive.bin")).unwrap(), REQUESTED);
    // hlx:262
    fs::copy(dir.join("archive.bin"), dir.join("cached.bin")).unwrap();
    // hlx:263
    assert_eq!(recipient_read(dir), REQUESTED);
    // hlx:264
    let actual = "Restore the confirmed archived revision into the recipient cache.";
    // hlx:265
    let outcome = "observed-local-archive";
    // hlx:266
    let feedback = format!(
        r#"{{"id":"{id}","project":"handoff","paid_off":false,"outcome_id":"{outcome}","note":"Recipient stayed stale after publish; restoring its cache returned the requested bytes.","case":{{"facts":{facts},"action":"{actual}"}}}}"#
    );
    // hlx:267
    let recall = format!(r#"{{"project":"handoff","q":"{QUERY}","facts":{facts}}}"#);
    // hlx:269
    let requests = [
        mcp_call(1, "instinct_recall", &recall),
        mcp_call(2, "instinct_feedback", &feedback),
        mcp_call(3, "instinct_recall", &recall),
        mcp_call(4, "instinct_feedback", &feedback),
        mcp_call(5, "instinct_recall", &recall),
    ]
    .join("\n")
        + "\n";
    // hlx:270
    let output = sandbox.run(&["mcp"], Some(&requests));
    // hlx:271
    let replies: Vec<_> = output
        .lines()
        .enumerate()
        .map(|(i, line)| tool_text(line, i + 1))
        .collect();
    // hlx:272
    let [prior, saved, after, retry, again] = replies.as_slice() else {
        panic!("unexpected MCP replies: {output}")
    };
    // hlx:273
    assert!(prior.contains(PUBLISH), "{prior}");
    // hlx:274
    assert!(saved.contains("miss and observation recorded"), "{saved}");
    // hlx:275
    assert!(retry.contains("already recorded"), "{retry}");
    // hlx:276
    let cli_recall = sandbox.run(
        &[
            "recall",
            "--project",
            "handoff",
            "--q",
            QUERY,
            "--facts",
            &facts,
        ],
        None,
    );
    // hlx:277
    for response in [after, again, &cli_recall] {
        // hlx:278
        assert!(
            response.contains("different actions for identical facts")
                && response.contains(outcome),
            "{response}"
        );
        // hlx:279
    }
    // hlx:280
    let packet = decide();
    // hlx:281
    let lesson = only_lesson(&packet);
    // hlx:282
    assert_eq!(field(lesson, "misses"), &J::Num("1".into()));
    // hlx:283
    assert_eq!(field(lesson, "hits"), &J::Num("0".into()));
    // hlx:284
    let advice = field(lesson, "case_advice");
    // hlx:285
    assert_eq!(string(advice, "status"), "conflict");
    // hlx:286
    assert_eq!(field(advice, "distinct_cases"), &J::Num("2".into()));
    // hlx:287
    assert_eq!(
        field(advice, "conflicting_refs"),
        &J::Arr(vec![
            J::Str("file-handoff-5".into()),
            J::Str(outcome.into())
        ])
    );
    // hlx:288
    assert_eq!(
        field(advice, "actions"),
        &J::Arr(vec![J::Str(PUBLISH.into()), J::Str(actual.into())])
    );
    // hlx:289
}