instinct-cli 0.3.10

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
// generated by hxc 1.0.0-acgt-compiler from tests/active_experiment.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
#[allow(dead_code)]
// hlx:3
#[path = "../src/check/json.rs"]
// hlx:4
mod json;
// hlx:5
use json::J;
// hlx:6
use std::collections::BTreeSet;
// hlx:7
use std::fs;
// hlx:8
use std::io::{ErrorKind, Write};
// hlx:9
use std::path::PathBuf;
// hlx:10
use std::process::{Command, Output, Stdio};
// hlx:11
use std::time::{SystemTime, UNIX_EPOCH};
// hlx:13
const KEYS: [&str; 5] = ["generated", "log_file", "nested", "draft", "long_stem"];
// hlx:14
const TRACKABLE: &str = "trackable";
// hlx:15
const IGNORED: &str = "ignored";
// hlx:17
fn field<'a>(object: &'a J, name: &str) -> &'a J {
    // hlx:18
    let J::Obj(fields) = object else {
        panic!("expected object: {object:?}")
    };
    // hlx:19
    &fields
        .iter()
        .find(|(k, _)| k == name)
        .unwrap_or_else(|| panic!("missing {name}: {object:?}"))
        .1
    // hlx:20
}
// hlx:21
fn text(value: &J) -> &str {
    // hlx:22
    let J::Str(s) = value else {
        panic!("expected text: {value:?}")
    };
    // hlx:23
    s
    // hlx:24
}
// hlx:25
fn facts(mask: u8) -> String {
    // hlx:26
    let fields = KEYS
        .iter()
        .enumerate()
        .map(|(i, k)| format!(r#""{k}":{}"#, mask & (1 << i) != 0))
        .collect::<Vec<_>>();
    // hlx:27
    format!("{{{}}}", fields.join(","))
    // hlx:28
}
// hlx:29
fn decode(mask_facts: &J) -> u8 {
    // hlx:30
    let J::Obj(fields) = mask_facts else {
        panic!("invalid proposed facts: {mask_facts:?}")
    };
    // hlx:31
    assert_eq!(fields.len(), KEYS.len());
    // hlx:32
    KEYS.iter()
        .enumerate()
        .fold(0, |mask, (i, k)| match field(mask_facts, k) {
            // hlx:33
            J::Bool(true) => mask | (1 << i),
            J::Bool(false) => mask,
            other => panic!("missing Boolean {k}: {other:?}"),
        })
    // hlx:34
}
// hlx:35
fn relative_path(mask: u8) -> String {
    // hlx:36
    let root = if mask & 1 != 0 {
        "generated"
    } else {
        "authored"
    };
    // hlx:37
    let ext = if mask & 2 != 0 { "log" } else { "txt" };
    // hlx:38
    let subdir = if mask & 4 != 0 { "archive/" } else { "" };
    // hlx:39
    let name = if mask & 8 != 0 { "draft" } else { "report" };
    // hlx:40
    let suffix = if mask & 16 != 0 { "-supplement" } else { "" };
    // hlx:41
    format!("{root}/{subdir}{name}{suffix}.{ext}")
    // hlx:42
}
// hlx:43
fn example(reference: &str, mask: u8, action: &str) -> String {
    // hlx:44
    format!(
        r#"{{"ref":"{reference}","facts":{},"action":"{action}"}}"#,
        facts(mask)
    )
    // hlx:45
}
// hlx:47
struct Sandbox(PathBuf);
// hlx:48
impl Sandbox {
    // hlx:49
    fn new() -> Option<Self> {
        // hlx:50
        let n = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        // hlx:51
        let dir =
            std::env::temp_dir().join(format!("instinct-active-ignore-{}-{n}", std::process::id()));
        // hlx:52
        fs::create_dir(&dir).unwrap();
        // hlx:53
        let s = Self(dir);
        // hlx:54
        match s.git().args(["init", "--quiet"]).output() {
            // hlx:55
            Err(e) if e.kind() == ErrorKind::NotFound => {
                eprintln!("Git unavailable; skipping the external Git fixture.");
                return None;
            }
            // hlx:56
            res => {
                let out = res.expect("start git");
                assert!(out.status.success(), "git init: {out:?}");
            } // hlx:57
        }
        // hlx:58
        fs::write(s.0.join(".gitignore"), "/generated/**/*.log\n").unwrap();
        // hlx:59
        for mask in 0..32 {
            // hlx:60
            let path = s.0.join(relative_path(mask));
            // hlx:61
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            // hlx:62
            fs::write(path, b"fixture revision\n").unwrap();
            // hlx:63
        }
        // hlx:64
        Some(s)
        // hlx:65
    }
    // hlx:66
    fn git(&self) -> Command {
        // hlx:67
        let mut cmd = Command::new("git");
        // hlx:68
        for (k, _) in std::env::vars_os() {
            // hlx:69
            if k.to_string_lossy().starts_with("GIT_") {
                // hlx:70
                cmd.env_remove(k);
                // hlx:71
            }
            // hlx:72
        }
        // hlx:73
        cmd.current_dir(&self.0)
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env("HOME", &self.0)
            .env("XDG_CONFIG_HOME", &self.0);
        // hlx:74
        cmd
        // hlx:75
    }
    // hlx:76
    fn label(&self, mask: u8) -> &'static str {
        // hlx:77
        let out = self
            .git()
            .args(["check-ignore", "--quiet", "--", &relative_path(mask)])
            .output()
            .unwrap();
        // hlx:78
        match out.status.code() {
            Some(0) => IGNORED,
            Some(1) => TRACKABLE,
            other => panic!("git check-ignore {mask} failed: {other:?} {out:?}"),
        }
        // hlx:79
    }
    // hlx:80
    fn store(&self) -> PathBuf {
        // hlx:81
        self.0.join("bank.hxdb")
        // hlx:82
    }
    // hlx:83
    fn cli(&self, args: &[&str], input: Option<&str>) -> Output {
        // hlx:84
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_instinct"));
        // hlx:85
        for (k, _) in std::env::vars_os() {
            // hlx:86
            if k.to_string_lossy().starts_with("INSTINCT_") {
                // hlx:87
                cmd.env_remove(k);
                // hlx:88
            }
            // hlx:89
        }
        // hlx:90
        cmd.current_dir(&self.0)
            .args(args)
            .env("INSTINCT_STORE", self.store())
            .env("INSTINCT_TEAM", "0")
            // hlx:91
            .env("INSTINCT_STARTER", "0")
            .stdin(if input.is_some() {
                Stdio::piped()
            } else {
                Stdio::null()
            })
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        // hlx:92
        let mut child = cmd.spawn().unwrap();
        // hlx:93
        if let Some(data) = input {
            // hlx:94
            child
                .stdin
                .take()
                .unwrap()
                .write_all(data.as_bytes())
                .unwrap();
            // hlx:95
        }
        // hlx:96
        child.wait_with_output().unwrap()
        // hlx:97
    }
    // hlx:98
    fn run(&self, args: &[&str], input: Option<&str>) -> String {
        // hlx:99
        let out = self.cli(args, input);
        // hlx:100
        assert!(out.status.success(), "{args:?}: {out:?}");
        // hlx:101
        String::from_utf8(out.stdout).unwrap()
        // hlx:102
    }
    // hlx:103
    fn bank(&self, rows: &[String]) -> String {
        // hlx:104
        let checks = KEYS
            .iter()
            .map(|k| format!(r#"{{"key":"{k}","question":"Check {k}?","cost":1}}"#))
            .collect::<Vec<_>>()
            .join(",");
        // hlx:105
        let payload = format!(
            r#"{{"title":"Check local ignore policy","when":"Determine whether Git ignores a project file","found":"The repository policy selects which paths Git ignores.","how":"Query git check-ignore on candidate files.","evidence":"Observed exit statuses on real local paths.","cases":{{"checks":[{checks}],"examples":[{}]}}}}"#,
            rows.join(",")
        );
        // hlx:106
        self.run(
            &["bank", "--project", "ignore-study", "--from", "-"],
            Some(&payload),
        )
        // hlx:107
    }
    // hlx:108
    fn experiment(&self, id: &str, pool: &str, observations: Option<&str>) -> J {
        // hlx:109
        let mut args = vec![
            "guide",
            "experiment",
            "--project",
            "ignore-study",
            "--id",
            id,
            "--pool",
            pool,
            "--json",
        ];
        // hlx:110
        if let Some(value) = observations {
            // hlx:111
            args.extend(["--facts", value]);
            // hlx:112
        }
        // hlx:113
        json::parse(self.run(&args, None).as_bytes()).unwrap()
        // hlx:114
    }
    // hlx:115
    fn mcp(&self, id: &str, project: &str, pool: &str, observations: &str) -> J {
        // hlx:116
        let request = format!(
            r#"{{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{{"name":"instinct_guide","arguments":{{"mode":"experiment","project":"{project}","id":"{id}","pool":{pool},"facts":{observations}}}}}}}"#
        ) + "\n";
        // hlx:117
        json::parse(self.run(&["mcp"], Some(&request)).as_bytes()).unwrap()
        // hlx:118
    }
    // hlx:119
}
// hlx:120
impl Drop for Sandbox {
    // hlx:121
    fn drop(&mut self) {
        // hlx:122
        let _ = fs::remove_dir_all(&self.0);
        // hlx:123
    }
    // hlx:124
}
// hlx:126
#[test]
// hlx:127
fn agents_learn_a_repositories_ignore_policy_and_withdraw_after_a_real_policy_change() {
    // hlx:128
    let Some(s) = Sandbox::new() else { return };
    // hlx:131
    let training: Vec<u8> = (0u8..32).filter(|m| m.count_ones() % 2 == 0).collect();
    // hlx:132
    let pool = format!(
        "[{}]",
        training
            .iter()
            .map(|&m| facts(m))
            .collect::<Vec<_>>()
            .join(",")
    );
    // hlx:133
    let initial = [0, 3];
    // hlx:134
    let starting_labels = initial.map(|m| (m, s.label(m)));
    // hlx:135
    assert_ne!(starting_labels[0].1, starting_labels[1].1);
    // hlx:136
    let rows = starting_labels.map(|(m, label)| example(&format!("git-{m}"), m, label));
    // hlx:137
    let created = s.bank(&rows);
    // hlx:138
    let id = created
        .split_whitespace()
        .nth(1)
        .expect("a banked lesson id");
    // hlx:139
    let mut purchased: BTreeSet<u8> = initial.into_iter().collect();
    // hlx:140
    let before = fs::read(s.store()).unwrap();
    // hlx:141
    let first = s.experiment(id, &pool, None);
    // hlx:142
    assert_eq!(text(field(&first, "status")), "learning");
    // hlx:143
    assert_eq!(
        s.experiment(id, &pool, None),
        first,
        "the same evidence must give a fresh agent the same proposed experiment"
    );
    // hlx:144
    for tail in [
        vec!["--pools", "[]"],
        vec!["--pool", "[]", "--pool", "[]"],
        vec!["--pool"],
    ] {
        // hlx:145
        let mut args = vec![
            "guide",
            "experiment",
            "--id",
            id,
            "--project",
            "ignore-study",
        ];
        // hlx:146
        args.extend(tail);
        // hlx:147
        assert!(
            !s.cli(&args, None).status.success(),
            "ambiguous or misspelled case limit accepted"
        );
        // hlx:148
    }
    // hlx:149
    let hidden = s.cli(
        &[
            "guide",
            "experiment",
            "--project",
            "other",
            "--id",
            id,
            "--json",
        ],
        None,
    );
    // hlx:150
    assert!(
        !hidden.status.success(),
        "wrong project received case advice: {hidden:?}"
    );
    // hlx:151
    let rejected = s.mcp(id, "other", &pool, "{}");
    // hlx:152
    assert_eq!(field(field(&rejected, "result"), "isError"), &J::Bool(true));
    // hlx:153
    assert_eq!(
        fs::read(s.store()).unwrap(),
        before,
        "planning or a rejected request wrote a lesson or hit"
    );
    // hlx:154
    let mut result = first;
    // hlx:155
    while text(field(&result, "status")) == "learning" {
        // hlx:156
        let proposed = decode(field(field(&result, "next_case"), "facts"));
        // hlx:157
        assert!(training.contains(&proposed), "proposed an infeasible input");
        // hlx:158
        assert!(purchased.insert(proposed), "repeated a paid-for Git check");
        // hlx:159
        let observed = s.label(proposed);
        // hlx:160
        s.bank(&[example(&format!("git-{proposed}"), proposed, observed)]);
        // hlx:161
        result = s.experiment(id, &pool, None);
        // hlx:162
    }
    // hlx:163
    assert_eq!(text(field(&result, "status")), "identified", "{result:?}");
    // hlx:164
    assert_eq!(field(&result, "surviving_models"), &J::Num("1".into()));
    // hlx:165
    assert!(
        purchased.len() < training.len(),
        "the learner exhausted all available training labels"
    );
    // hlx:166
    let checkpoint = fs::read(s.store()).unwrap();
    // hlx:167
    let mut outcomes = BTreeSet::new();
    // hlx:168
    let mut held_out = 0;
    // hlx:169
    for probe in (0u8..32).filter(|m| !training.contains(m)) {
        // hlx:170
        let input = facts(probe);
        // hlx:171
        let predicted = s.experiment(id, "[]", Some(&input));
        // hlx:172
        let tool = s.mcp(id, "ignore-study", "[]", &input);
        // hlx:173
        let reply = field(&tool, "result");
        // hlx:174
        assert_eq!(field(reply, "isError"), &J::Bool(false));
        // hlx:175
        let J::Arr(parts) = field(reply, "content") else {
            panic!("missing MCP result: {tool:?}")
        };
        // hlx:176
        let from_tool = json::parse(text(field(&parts[0], "text")).as_bytes()).unwrap();
        // hlx:177
        assert_eq!(
            from_tool, predicted,
            "different CLI and MCP predictions on {probe}"
        );
        // hlx:178
        let observed = s.label(probe);
        // hlx:179
        assert_eq!(
            text(field(&predicted, "prediction")),
            observed,
            "wrong held-out action for {}",
            relative_path(probe)
        );
        // hlx:180
        outcomes.insert(observed);
        // hlx:181
        held_out += 1;
        // hlx:182
    }
    // hlx:183
    assert_eq!(outcomes.len(), 2);
    // hlx:184
    assert_eq!(held_out, 16);
    // hlx:185
    assert_eq!(
        fs::read(s.store()).unwrap(),
        checkpoint,
        "asking for hypotheses must not write evidence"
    );
    // hlx:186
    eprintln!("Git fixture: {} verified teaching labels, {held_out}/{held_out} disjoint path predictions, identical CLI/MCP results.",purchased.len());
    // hlx:188
    fs::write(
        s.0.join(".gitignore"),
        "# All files eligible in this revision.\n",
    )
    .unwrap();
    // hlx:189
    let revised_label = s.label(3);
    // hlx:190
    assert_eq!(revised_label, TRACKABLE);
    // hlx:191
    s.bank(&[example("revision-2-git-3", 3, revised_label)]);
    // hlx:192
    let revised = s.experiment(id, &pool, Some(&facts(31)));
    // hlx:193
    assert_eq!(text(field(&revised, "status")), "falsified");
    // hlx:194
    assert_eq!(field(&revised, "prediction"), &J::Null);
    // hlx:195
    assert_eq!(field(&revised, "next_case"), &J::Null);
    // hlx:196
}