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
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
// generated by hxc 1.0.0-acgt-compiler from src/brief.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:3
pub(crate) struct Brief {
    exclusions: Vec<Vec<String>>,
}
// hlx:4
fn words(text: &str) -> Vec<&str> {
    // hlx:5
    text.split(|c: char| !c.is_alphanumeric() && !matches!(c, '/' | '-' | '\''))
        .filter(|word| !word.is_empty())
        .collect()
    // hlx:6
}
// hlx:7
fn article(word: &str) -> bool {
    // hlx:8
    matches!(
        word,
        "a" | "an" | "the" | "my" | "our" | "your" | "her" | "his" | "their"
    )
    // hlx:9
}
// hlx:10
fn directive_prefix(prefix: &[&str]) -> bool {
    // hlx:11
    let prefix = prefix.strip_suffix(&["please"]).unwrap_or(prefix);
    // hlx:12
    prefix.last().is_none_or(|last| {
        matches!(
            *last,
            "and"
                | "but"
                | "actually"
                | "instead"
                | "then"
                | "also"
                | "just"
                | "still"
                | "want"
                | "wants"
                | "prefer"
                | "prefers"
                | "requested"
                | "require"
                | "requires"
        )
    }) || prefix.ends_with(&["can", "you"])
        || prefix.ends_with(&["could", "you"])
        || prefix.ends_with(&["would", "you"])
    // hlx:13
}
// hlx:14
fn negation_prefix(prefix: &[&str]) -> bool {
    // hlx:15
    [
        &["do", "not"][..],
        &["don't"],
        &["never"],
        &["no", "need", "to"],
    ]
    .iter()
    .any(|ending| prefix.strip_suffix(*ending).is_some_and(directive_prefix))
    // hlx:16
}
// hlx:17
fn object(words: &[&str]) -> Vec<String> {
    // hlx:18
    let words = words.strip_prefix(&["as"]).unwrap_or(words);
    // hlx:19
    let end = words
        .iter()
        .enumerate()
        .position(|(i, word)| {
            matches!(
                *word,
                "but"
                    | "today"
                    | "this"
                    | "for"
                    | "please"
                    | "instead"
                    | "rather"
                    | "from"
                    | "on"
                    | "to"
            ) || (*word == "and"
                && words.get(i + 1).is_some_and(|next| {
                    output_verb(next)
                        || grouping(next)
                        || matches!(
                            *next,
                            "please"
                                | "also"
                                | "then"
                                | "check"
                                | "verify"
                                | "confirm"
                                | "no"
                                | "do"
                        )
                }))
        })
        .unwrap_or(words.len());
    // hlx:20
    let mut noun: Vec<String> = words[..end]
        .iter()
        .copied()
        .skip_while(|word| article(word))
        .map(str::to_owned)
        .collect();
    // hlx:21
    if noun.len() > 1
        && matches!(
            noun.last().map(String::as_str),
            Some("shorthand" | "format" | "template")
        )
    {
        // hlx:22
        noun.pop();
        // hlx:23
    }
    // hlx:24
    noun
    // hlx:25
}
// hlx:26
fn grouping(word: &str) -> bool {
    // hlx:27
    matches!(
        word,
        "group"
            | "sort"
            | "organize"
            | "organise"
            | "order"
            | "arrange"
            | "categorize"
            | "categorise"
            | "classify"
            | "split"
    )
    // hlx:28
}
// hlx:29
fn current_action(words: &[&str]) -> bool {
    // hlx:30
    words.iter().enumerate().any(|(i, w)| {
        (output_verb(w) || grouping(w))
            && (directive_prefix(&words[..i])
                || words[..i]
                    .strip_suffix(&["do"])
                    .is_some_and(directive_prefix))
    })
    // hlx:31
}
// hlx:32
fn changed_object<'a>(tokens: &'a [&'a str], i: usize) -> Option<&'a [&'a str]> {
    // hlx:33
    let prefix = &tokens[..i];
    // hlx:34
    let rest = &tokens[i + 1..];
    // hlx:35
    match tokens[i] {
        // hlx:36
        "no" if directive_prefix(prefix) => {
            Some(rest.strip_prefix(&["need", "for"]).unwrap_or(rest))
        }
        // hlx:37
        "skip" | "omit" | "avoid" | "exclude" | "drop" | "remove" if directive_prefix(prefix) => {
            Some(rest)
        }
        // hlx:38
        "without" if directive_prefix(prefix) || current_action(prefix) => Some(rest),
        // hlx:39
        "leave" | "keep" if directive_prefix(prefix) => {
            // hlx:40
            if let Some(after) = rest
                .strip_prefix(&["out"])
                .or_else(|| rest.strip_prefix(&["off"]))
            {
                return Some(after);
            }
            // hlx:41
            rest.iter()
                .position(|w| matches!(*w, "out" | "off"))
                .map(|end| &rest[..end])
            // hlx:42
        }
        // hlx:43
        "rather" | "instead" if directive_prefix(prefix) || current_action(prefix) => {
            // hlx:44
            let join = if tokens[i] == "rather" { "than" } else { "of" };
            // hlx:45
            rest.strip_prefix(&[join]).map(|after| {
                if after.first().is_some_and(|w| output_verb(w)) {
                    &after[1..]
                } else {
                    after
                }
            })
            // hlx:46
        }
        // hlx:47
        verb if output_verb(verb) && negation_prefix(prefix) => Some(rest),
        // hlx:48
        _ => None,
        // hlx:49
    }
    // hlx:50
}
// hlx:52
fn directive_text(text: &str) -> std::borrow::Cow<'_, str> {
    // hlx:53
    let spans = super::brief_action::quoted_spans(text);
    // hlx:54
    if spans.is_empty() {
        // hlx:55
        return std::borrow::Cow::Borrowed(text);
        // hlx:56
    }
    // hlx:57
    let mut out = String::new();
    // hlx:58
    let mut copied = 0;
    // hlx:59
    for span in spans {
        // hlx:60
        let prefix = &text[copied..span.start];
        // hlx:61
        out.push_str(prefix);
        // hlx:62
        let clause = prefix
            .rsplit(['.', ',', ';', '!', '?', '\n'])
            .next()
            .unwrap_or("")
            .to_lowercase();
        // hlx:63
        let preceding = words(&clause);
        // hlx:64
        let operand = preceding
            .iter()
            .rev()
            .copied()
            .find(|w| !article(w))
            .is_some_and(|w| {
                matches!(
                    w,
                    "no" | "omit"
                        | "skip"
                        | "exclude"
                        | "avoid"
                        | "without"
                        | "leave"
                        | "keep"
                        | "off"
                        | "out"
                        | "remove"
                        | "drop"
                        | "than"
                        | "of"
                ) || output_verb(w)
            });
        // hlx:65
        let mut quoted = text[span.clone()].chars();
        // hlx:66
        quoted.next();
        // hlx:67
        quoted.next_back();
        // hlx:68
        let literal = quoted.as_str();
        // hlx:69
        let lowered = literal.to_lowercase();
        // hlx:70
        let is_label = !literal.contains(['.', ';', '!', '?', '\n'])
            && !words(&lowered).iter().any(|w| {
                matches!(
                    *w,
                    "no" | "not"
                        | "without"
                        | "instead"
                        | "rather"
                        | "omit"
                        | "skip"
                        | "leave"
                        | "keep"
                        | "avoid"
                        | "exclude"
                        | "remove"
                        | "drop"
                )
            });
        // hlx:71
        if operand && is_label {
            // hlx:72
            out.push_str(literal);
            // hlx:73
        } else {
            // hlx:74
            out.push('.');
            // hlx:75
        }
        // hlx:76
        copied = span.end;
        // hlx:77
    }
    // hlx:78
    out.push_str(&text[copied..]);
    // hlx:79
    std::borrow::Cow::Owned(out)
    // hlx:80
}
// hlx:81
impl Brief {
    // hlx:82
    pub(crate) fn parse(text: &str) -> Self {
        // hlx:83
        let lower = directive_text(text).to_lowercase().replace('’', "'");
        // hlx:84
        let mut exclusions: Vec<Vec<String>> = Vec::new();
        // hlx:85
        for clause in lower.split(['.', ',', ';', '!', '?', '\n']) {
            // hlx:86
            let tokens = words(clause);
            // hlx:87
            // A subsequent affirmative instruction can reverse an earlier exclusion in this request.
            // hlx:88
            if !exclusions.is_empty() && current_action(&tokens) {
                // hlx:89
                exclusions.retain(|noun| !prescribes(clause, noun));
                // hlx:90
            }
            // hlx:91
            for i in 0..tokens.len() {
                // hlx:92
                if let Some(rejected) = changed_object(&tokens, i) {
                    // hlx:93
                    let noun = object(rejected);
                    // hlx:94
                    if !noun.is_empty() && !exclusions.contains(&noun) {
                        // hlx:95
                        exclusions.push(noun);
                        // hlx:96
                    }
                    // hlx:97
                }
                // hlx:98
            }
            // hlx:99
        }
        // hlx:100
        Self { exclusions }
        // hlx:101
    }
    // hlx:102
    pub(crate) fn excludes(&self, trigger: &str, method: &str) -> bool {
        // hlx:103
        if self.exclusions.is_empty() {
            // hlx:104
            return false;
            // hlx:105
        }
        // hlx:106
        let trigger = trigger.to_lowercase();
        // hlx:107
        let cues = words(&trigger);
        // hlx:108
        let method = method.to_lowercase();
        // hlx:109
        self.exclusions.iter().any(|noun| {
            // hlx:110
            if matches!(
                noun[0].as_str(),
                "usual" | "default" | "standard" | "regular"
            ) && noun.len() > 1
            {
                // hlx:111
                return cues.windows(noun.len()).any(|part| part == noun.as_slice());
                // hlx:112
            }
            // hlx:113
            method
                .split(['.', ',', ';', '!', '?', '\n'])
                .any(|clause| prescribes(clause, noun))
            // hlx:114
        })
        // hlx:115
    }
    // hlx:116
}
// hlx:117
fn output_verb(word: &str) -> bool {
    // hlx:118
    matches!(
        word,
        "make"
            | "create"
            | "prepare"
            | "present"
            | "publish"
            | "format"
            | "display"
            | "list"
            | "give"
            | "add"
            | "include"
            | "insert"
            | "put"
            | "show"
            | "attach"
            | "deliver"
            | "emit"
            | "export"
            | "generate"
            | "output"
            | "print"
            | "provide"
            | "render"
            | "return"
            | "send"
            | "use"
            | "write"
    )
    // hlx:119
}
// hlx:120
fn prescribes(clause: &str, noun: &[String]) -> bool {
    // hlx:121
    let tokens = words(clause);
    // hlx:122
    // An example, conditional or negative instruction does not prescribe that output.
    // hlx:123
    if tokens.iter().any(|word| {
        matches!(
            *word,
            "if" | "unless"
                | "whether"
                | "without"
                | "skip"
                | "avoid"
                | "omit"
                | "never"
                | "not"
                | "don't"
                | "no"
        )
    }) {
        // hlx:124
        return false;
        // hlx:125
    }
    // hlx:126
    // An excluded grouping criterion only conflicts with a method that organizes by that same criterion.
    // hlx:127
    if noun.first().is_some_and(|word| word == "by") {
        // hlx:128
        return noun.len() > 1
            && tokens.iter().any(|w| grouping(w))
            && tokens.windows(noun.len()).any(|part| part == noun);
        // hlx:129
    }
    // hlx:130
    // A slash-separated name can refer to the literal field labels in a template.
    // hlx:131
    if noun.len() == 1 && noun[0].contains('/') && clause.contains(':') {
        // hlx:132
        let labels: Vec<&str> = clause
            .split(|c: char| !c.is_alphanumeric() && c != ':')
            .filter_map(|s| s.strip_suffix(':'))
            .filter(|s| !s.is_empty())
            .collect();
        // hlx:133
        if labels.len() >= 2 && labels.join("/") == noun[0] {
            // hlx:134
            return true;
            // hlx:135
        }
        // hlx:136
    }
    // hlx:137
    // Match the named object in an output role, not an incidental reference to the same word.
    // hlx:138
    for (i, phrase) in tokens.windows(noun.len()).enumerate() {
        // hlx:139
        if phrase != noun {
            // hlx:140
            continue;
            // hlx:141
        }
        // hlx:142
        let before = tokens[..i]
            .iter()
            .copied()
            .rev()
            .find(|word| !article(word));
        // hlx:143
        // In "export the PDF to PNG", PDF is the input and PNG is the output.
        // hlx:144
        let following = tokens.get(i + noun.len());
        // hlx:145
        if matches!(following, Some(&"to" | &"into" | &"as"))
            && matches!(before, Some("export" | "render" | "use"))
        {
            // hlx:146
            continue;
            // hlx:147
        }
        // hlx:148
        if before.is_some_and(|word| matches!(word, "as" | "into") || output_verb(word)) {
            // hlx:149
            return true;
            // hlx:150
        }
        // hlx:151
    }
    // hlx:152
    false
    // hlx:153
}
// hlx:154
#[cfg(test)]
// hlx:155
mod tests {
    // hlx:156
    use super::Brief;
    // hlx:157
    #[test]
    // hlx:158
    fn explicit_output_overrides_are_specific_to_the_method() {
        // hlx:159
        let render = "Render the invoice as a PDF attachment.";
        // hlx:160
        for q in [
            "Do not render a PDF.",
            "Don't attach the PDF.",
            "Write the report without a PDF.",
            "Please export as HTML instead of PDF.",
        ] {
            // hlx:161
            let brief = Brief::parse(q);
            // hlx:162
            assert!(brief.excludes("invoice delivery", render), "{q}");
            // hlx:163
            assert!(
                !brief.excludes(
                    "invoice delivery",
                    "Read the PDF and verify the invoice totals."
                ),
                "{q}"
            );
            // hlx:164
        }
        // hlx:165
        for q in [
            "There is no PDF. Please send it again.",
            "The help text says \"no PDF\".",
            "No screenshots.",
            "No PDF annotations.",
            "The invoice arrived without a PDF. Please send it again.",
        ] {
            // hlx:166
            assert!(!Brief::parse(q).excludes("invoice delivery", render), "{q}");
            // hlx:167
        }
        // hlx:168
        let brief = Brief::parse("No PDF.");
        // hlx:169
        assert!(!brief.excludes("invoice", "Do not send a PDF."));
        // hlx:170
        assert!(!brief.excludes("invoice", "Export the PDF to PNG."));
        // hlx:171
    }
    // hlx:172
    #[test]
    // hlx:173
    fn a_cancelled_convention_is_not_a_global_opt_out() {
        // hlx:174
        let cue = "When Tess asks for her usual client update";
        // hlx:175
        assert!(Brief::parse("Skip my usual client update today.")
            .excludes(cue, "Use a one-line template."));
        // hlx:176
        assert!(!Brief::parse("Skip my usual client update today.")
            .excludes("Verify invoice totals", "Check the signed order."));
        // hlx:177
        assert!(!Brief::parse("Don't skip my usual client update today.")
            .excludes(cue, "Use a one-line template."));
        // hlx:178
    }
    // hlx:179
    #[test]
    // hlx:180
    fn phrasal_exclusions_and_current_reversals() {
        // hlx:181
        let add = "Include a seating chart in the handout.";
        // hlx:182
        for q in [
            "Leave the seating chart off today.",
            "Please leave out the seating chart.",
            "Keep the ‘seating chart’ off the page.",
            "Do not include the seating chart.",
        ] {
            // hlx:183
            assert!(Brief::parse(q).excludes("prepare handout", add), "{q}");
            // hlx:184
        }
        // hlx:185
        for q in [
            "Do not leave the seating chart off.",
            "The old guide says ‘leave the seating chart off.’",
            "Leave the seating chart on.",
            "No seating chart. Actually include the seating chart.",
        ] {
            // hlx:186
            assert!(!Brief::parse(q).excludes("prepare handout", add), "{q}");
            // hlx:187
        }
        // hlx:188
        let detail = Brief::parse("Keep the materials and labor breakdown off the estimate.");
        // hlx:189
        assert!(detail.excludes("write estimate", "Show a materials and labor breakdown."));
        // hlx:190
        assert!(!detail.excludes("write estimate", "Show a materials and shipping breakdown."));
        // hlx:191
        let alternate = Brief::parse("Organize the milestones as notes rather than as a grid.");
        // hlx:192
        assert!(alternate.excludes("plan", "Arrange milestones as a grid."));
        // hlx:193
        assert!(!alternate.excludes("plan", "Arrange milestones as notes."));
        // hlx:194
        let sorting = Brief::parse("Sort by region rather than by surname.");
        // hlx:195
        assert!(sorting.excludes("prepare register", "Group entries by surname."));
        // hlx:196
        assert!(!sorting.excludes("prepare register", "Group entries by region."));
        // hlx:197
        assert!(!sorting.excludes(
            "prepare register",
            "Check entries by surname against the original."
        ));
        // hlx:198
        assert!(
            !Brief::parse("We sorted by region rather than by surname last time.")
                .excludes("prepare register", "Group entries by surname.")
        );
        // hlx:199
    }
    // hlx:200
}