instinct-cli 0.3.8

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
// generated by hxc 1.0.0-acgt-compiler from src/brief_action.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 std::{borrow::Cow, ops::Range};
// hlx:4
fn escaped(text: &str, at: usize) -> bool {
    // hlx:5
    text.as_bytes()[..at]
        .iter()
        .rev()
        .take_while(|&&byte| byte == b'\\')
        .count()
        % 2
        == 1
    // hlx:6
}
// hlx:8
pub(crate) fn quoted_spans(text: &str) -> Vec<Range<usize>> {
    // hlx:9
    let mut spans = Vec::new();
    // hlx:10
    let mut open = None;
    // hlx:11
    for (at, ch) in text.char_indices() {
        // hlx:12
        if let Some((from, end)) = open {
            // hlx:13
            if ch == end && !escaped(text, at) {
                // hlx:14
                let after = at + ch.len_utf8();
                // hlx:15
                if matches!(ch, '\'' | '’') && text[after..].starts_with(char::is_alphanumeric) {
                    // hlx:16
                    continue;
                    // hlx:17
                }
                // hlx:18
                spans.push(from..after);
                // hlx:19
                open = None;
                // hlx:20
            }
        // hlx:21
        } else {
            // hlx:22
            let end = match ch {
                '"' | '\'' | '`' => ch,
                '“' => '”',
                '‘' => '’',
                _ => continue,
            };
            // hlx:23
            if !text[..at].ends_with(char::is_alphanumeric) && !escaped(text, at) {
                // hlx:24
                open = Some((at, end));
                // hlx:25
            }
            // hlx:26
        }
        // hlx:27
    }
    // hlx:28
    spans
    // hlx:29
}
// hlx:31
fn words(text: &str) -> impl Iterator<Item = &str> {
    // hlx:32
    text.split(|c: char| !c.is_alphanumeric() && c != '\'')
        .filter(|w| !w.is_empty())
    // hlx:33
}
// hlx:38
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
// hlx:39
enum Role {
    Transform,
    Language,
    Meaning,
    Count,
    Check,
    Find,
    Create,
    Change,
}
// hlx:40
impl Role {
    // hlx:41
    fn acts_on_words_or_quantity(self) -> bool {
        // hlx:42
        matches!(
            self,
            Self::Transform | Self::Language | Self::Meaning | Self::Count
        )
        // hlx:43
    }
    // hlx:44
}
// hlx:45
fn operator(w: &str) -> Option<Role> {
    // hlx:46
    match w {
        // hlx:47
        "translate" | "alphabetize" | "alphabetise" | "reorder" | "transcribe" | "uppercase"
        | "lowercase" | "capitalize" | "capitalise" | "paraphrase" | "proofread" | "rephrase"
        | "rewrite" => Some(Role::Transform),
        // hlx:48
        "define" => Some(Role::Meaning),
        "count" | "calculate" | "enumerate" => Some(Role::Count),
        // hlx:49
        "verify" | "confirm" | "check" | "validate" | "crosscheck" | "compare" | "inspect"
        | "diagnose" | "audit" | "debug" => Some(Role::Check),
        // hlx:50
        "locate" | "search" | "find" | "grep" | "scan" | "filter" | "look" | "retrieve" => {
            Some(Role::Find)
        }
        // hlx:51
        "write" | "prepare" | "draft" | "produce" | "compose" | "generate" | "make" | "create"
        | "build" | "print" | "publish" | "deliver" | "send" => Some(Role::Create),
        // hlx:52
        "change" | "add" | "repair" | "fix" | "remove" | "arrange" | "organize" | "sort"
        | "update" => Some(Role::Change),
        // hlx:53
        _ => None,
        // hlx:54
    }
    // hlx:55
}
// hlx:57
fn unit(w: &str) -> bool {
    // hlx:58
    matches!(
        w,
        "word"
            | "words"
            | "letter"
            | "letters"
            | "character"
            | "characters"
            | "lines"
            | "syllables"
    )
    // hlx:59
}
// hlx:60
fn syntax_word(w: &str) -> bool {
    // hlx:61
    matches!(
        w,
        "verb"
            | "noun"
            | "adjective"
            | "adverb"
            | "pronoun"
            | "subject"
            | "tense"
            | "syllable"
            | "grammar"
            | "punctuation"
    )
    // hlx:62
}
// hlx:63
fn filler(w: &str) -> bool {
    // hlx:64
    matches!(
        w,
        "please"
            | "can"
            | "could"
            | "would"
            | "you"
            | "kindly"
            | "just"
            | "then"
            | "also"
            | "separately"
            | "still"
            | "when"
            | "to"
            | "i"
            | "we"
            | "need"
            | "want"
            | "should"
    )
    // hlx:65
}
// hlx:66
fn clause_role(terms: &[&str]) -> Option<Role> {
    // hlx:67
    let start = terms.iter().position(|w| !filler(w)).unwrap_or(terms.len());
    // hlx:68
    let terms = &terms[start..];
    // hlx:69
    let first = *terms.first()?;
    // hlx:70
    let asks = matches!(
        first,
        "is" | "are"
            | "does"
            | "do"
            | "how"
            | "what"
            | "which"
            | "in"
            | "within"
            | "from"
            | "identify"
            | "tell"
            | "find"
            | "spot"
            | "give"
            | "explain"
    );
    // hlx:71
    let has = |w: &str| terms.contains(&w);
    // hlx:72
    if terms.windows(2).any(|p| p == ["how", "many"])
        || (first == "count" && terms.iter().skip(1).take(4).any(|w| unit(w)))
    {
        // hlx:73
        return Some(Role::Count);
        // hlx:74
    }
    // hlx:75
    if first == "define"
        || has("definition")
            && !matches!(
                operator(first),
                Some(Role::Check | Role::Find | Role::Change)
            )
        || (asks && has("difference") && has("between"))
        || (matches!(first, "what" | "explain")
            && has("mean")
            && terms.iter().any(|w| {
                matches!(
                    *w,
                    "term" | "word" | "phrase" | "expression" | "acronym" | "abbreviation"
                )
            }))
    {
        // hlx:76
        return Some(Role::Meaning);
        // hlx:77
    }
    // hlx:78
    let refers_to_words = terms.iter().any(|w| {
        matches!(
            *w,
            "wording" | "phrase" | "sentence" | "phrasing" | "spelling" | "typo"
        )
    });
    // hlx:79
    let tone = terms.iter().any(|w| {
        matches!(
            *w,
            "formal"
                | "informal"
                | "natural"
                | "polite"
                | "rude"
                | "harsh"
                | "abrupt"
                | "clear"
                | "awkward"
                | "friendly"
                | "grammatical"
        )
    });
    // hlx:80
    if (refers_to_words
        && (matches!(
            first,
            "soften" | "reword" | "correct" | "spot" | "proofread" | "rephrase"
        ) || asks && (tone || has("typo") || has("wording"))))
        || (asks
            && terms.iter().any(|w| syntax_word(w))
            && (has("which") || has("what") || has("or")))
        || (asks && (has("sound") || has("read")) && tone)
    {
        // hlx:81
        return Some(Role::Language);
        // hlx:82
    }
    // hlx:83
    operator(first)
    // hlx:84
}
// hlx:86
fn is_source(prefix: &str, suffix: &str) -> bool {
    // hlx:87
    let before = prefix
        .rsplit(['.', '!', '?', ';', ',', '\n'])
        .next()
        .unwrap_or("");
    // hlx:88
    // The immediate grammatical complement suffices; bound repeated right-context lookahead.
    // hlx:89
    let mut after = String::new();
    // hlx:90
    for word in suffix.split_whitespace().take(16) {
        // hlx:91
        if let Some(end) = word.find(['.', '!', '?', ';']) {
            // hlx:92
            after.push_str(&word[..end]);
            // hlx:93
            break;
            // hlx:94
        }
        // hlx:95
        after.push_str(word);
        // hlx:96
        after.push(' ');
        // hlx:97
    }
    // hlx:98
    let lower = before.to_lowercase();
    // hlx:99
    let terms: Vec<_> = words(&lower).collect();
    // hlx:100
    // A subsequent command can change the role of its own quoted operand.
    // hlx:101
    let cut = terms
        .windows(2)
        .rposition(|p| matches!(p[0], "then" | "also" | "and" | "but") && operator(p[1]).is_some())
        .map_or(0, |i| i + 1);
    // hlx:102
    let after = after.to_lowercase();
    // hlx:103
    let mut surrounding = terms[cut..].to_vec();
    // hlx:104
    surrounding.extend(words(&after));
    // hlx:105
    match clause_role(&surrounding) {
        // hlx:106
        Some(Role::Count) => surrounding.iter().any(|w| unit(w)),
        // hlx:107
        Some(role) => role.acts_on_words_or_quantity(),
        // hlx:108
        None => false,
        // hlx:109
    }
    // hlx:110
}
// hlx:111
pub(crate) fn action_text(text: &str) -> Cow<'_, str> {
    // hlx:112
    if !text.contains(['"', '\'', '`', '“', '‘']) {
        // hlx:113
        return Cow::Borrowed(text);
        // hlx:114
    }
    // hlx:115
    let mut copied = 0;
    // hlx:116
    let mut last_source = false;
    // hlx:117
    let mut out = String::new();
    // hlx:118
    for range in quoted_spans(text) {
        // hlx:119
        let between = &text[copied..range.start];
        // hlx:120
        out.push_str(between);
        // hlx:121
        let continuation = last_source
            && !between.contains(['.', '!', '?', ';', '\n'])
            && words(between).all(|w| matches!(w, "and" | "or"));
        // hlx:122
        last_source = continuation || is_source(between, &text[range.end..]);
        // hlx:123
        if last_source {
            // hlx:124
            out.push(' ');
            // hlx:125
        } else {
            // hlx:126
            out.push_str(&text[range.clone()]);
            // hlx:127
        }
        // hlx:128
        copied = range.end;
        // hlx:129
    }
    // hlx:130
    if copied == 0 || out == text[..copied] {
        // hlx:131
        return Cow::Borrowed(text);
        // hlx:132
    }
    // hlx:133
    out.push_str(&text[copied..]);
    // hlx:134
    Cow::Owned(out)
    // hlx:135
}
// hlx:137
fn split_roles(text: &str) -> Vec<(Role, String)> {
    // hlx:138
    let mut found = Vec::new();
    // hlx:139
    for sentence in text.split(['.', '!', '?', ';', '\n']) {
        // hlx:140
        let lower = sentence.to_lowercase();
        // hlx:141
        let terms: Vec<_> = words(&lower).collect();
        // hlx:142
        let mut starts = vec![0];
        // hlx:143
        for (i, pair) in terms.windows(2).enumerate() {
            // hlx:144
            if matches!(pair[0], "and" | "then" | "also" | "but" | "separately")
                && operator(pair[1]).is_some()
            {
                // hlx:145
                starts.push(i + 1);
                // hlx:146
            }
            // hlx:147
        }
        // hlx:148
        // A leading purpose phrase may precede the imperative after a comma.
        // hlx:149
        starts.push(terms.len());
        // hlx:150
        for range in starts.windows(2) {
            // hlx:151
            let part = &terms[range[0]..range[1]];
            // hlx:152
            let role = clause_role(part).or_else(|| {
                if starts.len() == 2 {
                    let tail = lower.rsplit_once(',')?.1;
                    clause_role(&words(tail).collect::<Vec<_>>())
                } else {
                    None
                }
            });
            // hlx:153
            if let Some(role) = role {
                // hlx:154
                found.push((role, part.join(" ")));
                // hlx:155
            }
            // hlx:156
        }
        // hlx:157
    }
    // hlx:158
    found
    // hlx:159
}
// hlx:161
pub(crate) struct TaskRoles(Vec<(Role, std::collections::HashSet<String>)>);
// hlx:162
impl TaskRoles {
    // hlx:163
    pub(crate) fn parse(text: &str) -> Self {
        // hlx:164
        // Most ordinary tasks need only the existing ranker. Avoid allocating clause/method profiles on that path.
        // hlx:165
        if !words(text).any(|w| {
            let folded;
            let term = if w.bytes().any(|b| b.is_ascii_uppercase()) {
                folded = w.to_ascii_lowercase();
                &folded
            } else {
                w
            };
            operator(term).is_some_and(Role::acts_on_words_or_quantity)
                || matches!(
                    term,
                    "how"
                        | "meaning"
                        | "mean"
                        | "difference"
                        | "definition"
                        | "wording"
                        | "phrasing"
                        | "phrase"
                        | "sentence"
                        | "spot"
                        | "sound"
                        | "read"
                        | "typo"
                        | "soften"
                )
                || syntax_word(term)
        }) {
            // hlx:166
            return Self(Vec::new());
            // hlx:167
        }
        // hlx:168
        let parts = split_roles(text);
        // hlx:169
        if !parts
            .iter()
            .any(|(role, _)| role.acts_on_words_or_quantity())
        {
            // hlx:170
            return Self(Vec::new());
            // hlx:171
        }
        // hlx:172
        Self(
            parts
                .into_iter()
                .map(|(r, s)| (r, super::anchors(&s)))
                .collect(),
        )
        // hlx:173
    }
    // hlx:174
    pub(crate) fn allows(&self, cue: &str, method: &str, tags: &str) -> bool {
        // hlx:175
        if self.0.is_empty() {
            // hlx:176
            return true;
            // hlx:177
        }
        // hlx:178
        let mut method_roles = split_roles(cue);
        // hlx:179
        method_roles.extend(split_roles(method));
        // hlx:180
        let cue_words = super::anchors(&format!("{} {} {}", cue, method, tags));
        // hlx:181
        for (role, args) in &self.0 {
            // hlx:182
            let agreement = method_roles.iter().any(|(r, _)| {
                r == role
                    || matches!(
                        (r, role),
                        (Role::Transform, Role::Language) | (Role::Language, Role::Transform)
                    )
            });
            // hlx:183
            if agreement && args.intersection(&cue_words).take(2).count() >= 2 {
                // hlx:184
                return true;
                // hlx:185
            }
            // hlx:186
            // Implicit or unclassified methods can still apply to the explicit operational task.
            // hlx:187
            if !role.acts_on_words_or_quantity()
                && method_roles.is_empty()
                && args.intersection(&cue_words).take(2).count() >= 2
            {
                // hlx:188
                return true;
                // hlx:189
            }
            // hlx:190
        }
        // hlx:191
        false
        // hlx:192
    }
    // hlx:193
}
// hlx:195
#[cfg(test)]
// hlx:196
mod tests {
    // hlx:197
    use super::*;
    // hlx:198
    #[test]
    // hlx:199
    fn quoted_data_and_commands_take_different_roles() {
        // hlx:200
        assert!(
            !action_text("Please translate ‘deliver the annual report’ into Spanish.")
                .contains("annual report")
        );
        // hlx:201
        assert!(!action_text("Count the words in \"send the invoices\".").contains("invoices"));
        // hlx:202
        assert!(action_text("Debug the message \"missing route file\".").contains("route file"));
        // hlx:203
        assert!(
            action_text("Proofread 'this message'. Then diagnose 'expired lease'.")
                .contains("expired lease")
        );
        // hlx:204
        assert!(action_text("Translate 'unfinished phrase").contains("unfinished phrase"));
        // hlx:205
        assert!(!action_text("Does ‘install the generator’ sound abrupt?").contains("generator"));
        // hlx:206
        assert!(!action_text("In `clean the kettle`, what noun is the object?").contains("kettle"));
        // hlx:207
        assert!(
            action_text("Does 'service unavailable' indicate a broken endpoint?")
                .contains("service unavailable")
        );
        // hlx:208
        assert!(action_text("Does `route lookup` read from the cache?").contains("route lookup"));
        // hlx:209
        assert!(action_text("Count records matching 'connection refused'.")
            .contains("connection refused"));
        // hlx:210
        assert!(
            action_text("What does 'connection refused' mean when starting the service?")
                .contains("connection refused")
        );
        // hlx:211
        assert!(!action_text("Translate 'blue' and 'yellow'.").contains("yellow"));
        // hlx:212
    }
    // hlx:213
    #[test]
    // hlx:214
    fn quoted_subject_and_separate_search_can_need_different_methods() {
        // hlx:215
        let q = action_text(
            "Translate ‘solar power’. Then search all archived logs for the solar power.",
        );
        // hlx:216
        assert!(q.contains("search all archived logs for the solar power"));
        // hlx:217
        let roles = TaskRoles::parse(&q);
        // hlx:218
        assert!(roles.allows(
            "Search archived logs for solar power",
            "Find its original source",
            ""
        ));
        // hlx:219
        assert!(!roles.allows("Create a solar power supply", "Install the equipment", ""));
        // hlx:220
        let q = action_text("Count the words and letters in ‘check cooling pressure’.");
        // hlx:221
        assert!(!q.contains("cooling pressure"));
        // hlx:222
        assert!(TaskRoles::parse(&q).allows(
            "Count words and letters",
            "Count alphabetic characters separately",
            ""
        ));
        // hlx:223
        assert!(!TaskRoles::parse(&q).allows("Check cooling pressure", "Read the gauge", ""));
        // hlx:224
    }
    // hlx:225
    #[test]
    // hlx:226
    fn apostrophes_and_escapes_do_not_split_balanced_spans() {
        // hlx:227
        let s = r#"Don't strip \"unquoted\" or 'this isn't a command', “nor this” and ‘unfinished"#;
        // hlx:228
        assert_eq!(
            quoted_spans(s)
                .into_iter()
                .map(|r| &s[r])
                .collect::<Vec<_>>(),
            ["'this isn't a command'", "“nor this”"]
        );
        // hlx:229
    }
    // hlx:230
}