anda_kip 0.7.6

A Rust SDK of KIP (Knowledge Interaction Protocol) for building sustainable AI knowledge memory systems.
Documentation
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
//! # Comprehensive error types and handling
//!
//! This module implements the KIP Standard Error Codes as defined in KIP specification Appendix 4.
//! Error codes are divided into 4 categories:
//! - **1xxx (Syntax Errors)**: Syntax errors where the code generated by the LLM has incorrect format.
//! - **2xxx (Schema Errors)**: Schema errors violating type definitions or data constraints.
//! - **3xxx (Logic/Data Errors)**: Logic or data errors, such as referencing non-existent variables or IDs.
//! - **4xxx (System Errors)**: System-level errors, such as timeouts or insufficient permissions.

use nom_language::error::{VerboseError, VerboseErrorKind};
use std::fmt::Display;

use thiserror::Error;

/// KIP Standard Error Codes
///
/// These codes follow the KIP specification for standardized error reporting.
/// Error codes enable AI Agents to implement self-correction capabilities.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KipErrorCode {
    // 1xxx: Syntax & Parsing errors
    /// KIP_1001: InvalidSyntax - KQL/KML code cannot be parsed due to spelling or structural errors.
    InvalidSyntax,
    /// KIP_1002: InvalidIdentifier - Used illegal identifier format (e.g., starting with a number).
    InvalidIdentifier,

    // 2xxx: Schema & Type errors
    /// KIP_2001: TypeMismatch - Attempted to use a Concept Type or Proposition Predicate undefined in Schema.
    TypeMismatch,
    /// KIP_2002: ConstraintViolation - Violated data constraints (e.g., missing required field).
    ConstraintViolation,
    /// KIP_2003: InvalidValueType - JSON type of attribute value mismatches Schema definition.
    InvalidValueType,

    // 3xxx: Logic & Data errors
    /// KIP_3001: ReferenceError - Referenced an undefined variable or Handle.
    ReferenceError,
    /// KIP_3002: NotFound - Node/Link with specified ID or name does not exist.
    NotFound,
    /// KIP_3003: DuplicateExists - Violated uniqueness constraint.
    DuplicateExists,
    /// KIP_3004: ImmutableTarget - Attempted to modify/delete protected system nodes.
    ImmutableTarget,

    // 4xxx: System & Execution errors
    /// KIP_4001: ExecutionTimeout - Query too complex, execution time exceeded system limit.
    ExecutionTimeout,
    /// KIP_4002: ResourceExhausted - Result set too large or insufficient memory.
    ResourceExhausted,
    /// KIP_4003: InternalError - Unknown internal database error.
    InternalError,
}

impl KipErrorCode {
    /// Returns the string code (e.g., "KIP_1001")
    pub fn code(&self) -> &'static str {
        match self {
            // 1xxx: Syntax & Parsing
            Self::InvalidSyntax => "KIP_1001",
            Self::InvalidIdentifier => "KIP_1002",
            // 2xxx: Schema & Type
            Self::TypeMismatch => "KIP_2001",
            Self::ConstraintViolation => "KIP_2002",
            Self::InvalidValueType => "KIP_2003",
            // 3xxx: Logic & Data
            Self::ReferenceError => "KIP_3001",
            Self::NotFound => "KIP_3002",
            Self::DuplicateExists => "KIP_3003",
            Self::ImmutableTarget => "KIP_3004",
            // 4xxx: System & Execution
            Self::ExecutionTimeout => "KIP_4001",
            Self::ResourceExhausted => "KIP_4002",
            Self::InternalError => "KIP_4003",
        }
    }

    /// Returns the error name (e.g., "InvalidSyntax")
    pub fn name(&self) -> &'static str {
        match self {
            // 1xxx: Syntax & Parsing
            Self::InvalidSyntax => "InvalidSyntax",
            Self::InvalidIdentifier => "InvalidIdentifier",
            // 2xxx: Schema & Type
            Self::TypeMismatch => "TypeMismatch",
            Self::ConstraintViolation => "ConstraintViolation",
            Self::InvalidValueType => "InvalidValueType",
            // 3xxx: Logic & Data
            Self::ReferenceError => "ReferenceError",
            Self::NotFound => "NotFound",
            Self::DuplicateExists => "DuplicateExists",
            Self::ImmutableTarget => "ImmutableTarget",
            // 4xxx: System & Execution
            Self::ExecutionTimeout => "ExecutionTimeout",
            Self::ResourceExhausted => "ResourceExhausted",
            Self::InternalError => "InternalError",
        }
    }

    /// Returns a recovery hint for the AI Agent
    pub fn hint(&self) -> &'static str {
        match self {
            // 1xxx: Syntax & Parsing
            Self::InvalidSyntax => {
                "Check parenthesis matching, keyword spelling, and statement structure. Ensure JSON data format is valid."
            }
            Self::InvalidIdentifier => "Identifiers must match regex `[a-zA-Z_][a-zA-Z0-9_]*`.",
            // 2xxx: Schema & Type
            Self::TypeMismatch => {
                "Execute `DESCRIBE` to confirm type names. Remember types are case-sensitive (`Drug` vs `drug`)."
            }
            Self::ConstraintViolation => "Supply the missing required attributes.",
            Self::InvalidValueType => "Correct the JSON value type.",
            // 3xxx: Logic & Data
            Self::ReferenceError => {
                "Ensure the variable is defined and bound in the WHERE clause (for KQL) or the CONCEPT block is placed before referencing clauses (for KML)."
            }
            Self::NotFound => {
                "Target may have been deleted or never created. Try `SEARCH` or `FIND` to confirm existence first."
            }
            Self::DuplicateExists => {
                "If intent is update, check if `UPSERT` should be used instead of creation logic."
            }
            Self::ImmutableTarget => {
                "**Operation Prohibited.** Do not attempt to modify system meta-definitions or core identity nodes."
            }
            // 4xxx: System & Execution
            Self::ExecutionTimeout => {
                "Optimize query. Reduce `UNION` usage, lower `LIMIT`, or reduce regex/hops."
            }
            Self::ResourceExhausted => "Must use `LIMIT` and `CURSOR` for pagination.",
            Self::InternalError => "Contact system administrator or retry later.",
        }
    }
}

impl Display for KipErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.code())
    }
}

/// KIP Error type with standard error codes and messages
#[derive(Error, Debug, Clone)]
#[error("{code}: {message}")]
pub struct KipError {
    /// The standard KIP error code
    pub code: KipErrorCode,
    /// Detailed error message
    pub message: String,
}

impl KipError {
    /// Creates a new KipError with the given code and message
    pub fn new(code: KipErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }

    /// Returns the error code string (e.g., "KIP_1001")
    pub fn code_str(&self) -> &'static str {
        self.code.code()
    }

    /// Returns the error name (e.g., "InvalidSyntax")
    pub fn name(&self) -> &'static str {
        self.code.name()
    }

    /// Returns the recovery hint for the AI Agent
    pub fn hint(&self) -> &'static str {
        self.code.hint()
    }

    // ==================== 1xxx: Syntax & Parsing Errors ====================

    /// Creates an InvalidSyntax error (KIP_1001)
    pub fn invalid_syntax(err: impl Display) -> Self {
        Self::new(KipErrorCode::InvalidSyntax, format!("{err}"))
    }

    /// Creates an InvalidIdentifier error (KIP_1002)
    pub fn invalid_identifier(err: impl Display) -> Self {
        Self::new(KipErrorCode::InvalidIdentifier, format!("{err}"))
    }

    // ==================== 2xxx: Schema & Type Errors ====================

    /// Creates a TypeMismatch error (KIP_2001)
    pub fn type_mismatch(err: impl Display) -> Self {
        Self::new(KipErrorCode::TypeMismatch, format!("{err}"))
    }

    /// Creates a ConstraintViolation error (KIP_2002)
    pub fn constraint_violation(err: impl Display) -> Self {
        Self::new(KipErrorCode::ConstraintViolation, format!("{err}"))
    }

    /// Creates an InvalidValueType error (KIP_2003)
    pub fn invalid_value_type(err: impl Display) -> Self {
        Self::new(KipErrorCode::InvalidValueType, format!("{err}"))
    }

    // ==================== 3xxx: Logic & Data Errors ====================

    /// Creates a ReferenceError (KIP_3001)
    pub fn reference_error(err: impl Display) -> Self {
        Self::new(KipErrorCode::ReferenceError, format!("{err}"))
    }

    /// Creates a NotFound error (KIP_3002)
    pub fn not_found(err: impl Display) -> Self {
        Self::new(KipErrorCode::NotFound, format!("{err}"))
    }

    /// Creates a DuplicateExists error (KIP_3003)
    pub fn duplicate_exists(err: impl Display) -> Self {
        Self::new(KipErrorCode::DuplicateExists, format!("{err}"))
    }

    /// Creates an ImmutableTarget error (KIP_3004)
    pub fn immutable_target(err: impl Display) -> Self {
        Self::new(KipErrorCode::ImmutableTarget, format!("{err}"))
    }

    // ==================== 4xxx: System & Execution Errors ====================

    /// Creates an ExecutionTimeout error (KIP_4001)
    pub fn execution_timeout(err: impl Display) -> Self {
        Self::new(KipErrorCode::ExecutionTimeout, format!("{err}"))
    }

    /// Creates a ResourceExhausted error (KIP_4002)
    pub fn resource_exhausted(err: impl Display) -> Self {
        Self::new(KipErrorCode::ResourceExhausted, format!("{err}"))
    }

    /// Creates an InternalError (KIP_4003)
    pub fn internal_error(err: impl Display) -> Self {
        Self::new(KipErrorCode::InternalError, format!("{err}"))
    }
}

/// Formats a nom parsing error into a KipError with detailed context
pub fn format_nom_error(input: &str, err: nom::Err<VerboseError<&str>>) -> KipError {
    let message = match err {
        nom::Err::Incomplete(needed) => {
            format!("Parse incomplete, need more input: {needed:?}")
        }
        nom::Err::Error(ve) | nom::Err::Failure(ve) => format_verbose_error(input, ve),
    };
    KipError::invalid_syntax(message)
}

fn format_verbose_error(input: &str, ve: VerboseError<&str>) -> String {
    let mut msg = String::new();

    // 1. Collect all context labels (from outermost to innermost)
    let contexts: Vec<&str> = ve
        .errors
        .iter()
        .filter_map(|(_, kind)| match kind {
            VerboseErrorKind::Context(ctx) => Some(*ctx),
            _ => None,
        })
        .collect();

    // 2. Find the deepest (most specific) error entry
    let deepest = ve.errors.first();

    // 3. Check if error is at the start of input (top-level parse failure)
    let is_at_start = deepest
        .map(|(slice, _)| slice.len() == input.len())
        .unwrap_or(false);

    // 4. Build the parsing context — show only the most relevant 3 levels
    if !contexts.is_empty() && !is_at_start {
        msg.push_str("Parsing context: ");
        let display_contexts: Vec<&str> = contexts.iter().rev().copied().collect();
        let start_idx = if display_contexts.len() > 3 {
            display_contexts.len() - 3
        } else {
            0
        };
        for (i, ctx) in display_contexts[start_idx..].iter().enumerate() {
            if i > 0 {
                msg.push_str(" > ");
            }
            msg.push_str(ctx);
        }
        msg.push('\n');
    }

    // 5. Show the specific error
    if let Some((slice, kind)) = deepest {
        let error_desc = match kind {
            VerboseErrorKind::Char(c) => {
                let got = slice.chars().next();
                match got {
                    Some(g) => format!("Expected '{}', but found '{}'", c, g),
                    None => format!("Expected '{}', but reached end of input", c),
                }
            }
            VerboseErrorKind::Context(ctx) => format!("Failed to parse: {ctx}"),
            VerboseErrorKind::Nom(e) => match e {
                nom::error::ErrorKind::Tag => {
                    if is_at_start {
                        let got = take_first_chars(slice, 20);
                        format!(
                            "Unrecognized KIP command starting with: \"{}\". \
                             A KIP statement must begin with FIND, UPSERT, DELETE, DESCRIBE, or SEARCH (case-sensitive).",
                            got
                        )
                    } else {
                        let got = take_first_chars(slice, 30);
                        format!("Expected a keyword, but found: \"{}\"", got)
                    }
                }
                nom::error::ErrorKind::Char => "Unexpected character".to_string(),
                nom::error::ErrorKind::Alpha => {
                    let got = slice.chars().next();
                    match got {
                        Some(g) => {
                            format!("Expected a letter (a-z, A-Z), but found '{}'", g)
                        }
                        None => {
                            "Expected a letter (a-z, A-Z), but reached end of input".to_string()
                        }
                    }
                }
                nom::error::ErrorKind::Verify => "Validation check failed".to_string(),
                nom::error::ErrorKind::MapRes => "Value conversion/validation failed".to_string(),
                nom::error::ErrorKind::Eof => {
                    let remaining = take_first_chars(slice, 60);
                    format!(
                        "Unexpected trailing content after valid KIP statement: \"{}\"",
                        remaining
                    )
                }
                nom::error::ErrorKind::Alt => {
                    if is_at_start {
                        if slice.is_empty() {
                            "Empty input. A KIP statement must begin with FIND, UPSERT, DELETE, DESCRIBE, or SEARCH.".to_string()
                        } else {
                            let got = take_first_chars(slice, 20);
                            format!(
                                "Unrecognized KIP command starting with: \"{}\". \
                                 A KIP statement must begin with FIND, UPSERT, DELETE, DESCRIBE, or SEARCH (case-sensitive).",
                                got
                            )
                        }
                    } else {
                        let got = take_first_chars(slice, 40);
                        format!("No valid KIP syntax matched at: \"{}\"", got)
                    }
                }
                _ => format!("Parser {:?} failed", e),
            },
        };
        msg.push_str(&error_desc);
        msg.push('\n');

        // 6. Show precise location (line:column) and context window
        let offset = input.len() - slice.len();
        let (line, col) = compute_line_col(input, offset);
        msg.push_str(&format!("Location: line {}, column {}\n", line, col));

        // 7. Show a context window around the error
        if !input.is_empty() {
            msg.push_str(&format_error_context_window(input, offset));
        }
    }

    // 8. Add recovery suggestions based on context
    if let Some(suggestion) = generate_recovery_suggestion(&contexts, deepest, is_at_start) {
        msg.push_str("\nSuggestion: ");
        msg.push_str(&suggestion);
        msg.push('\n');
    }

    msg
}

/// Compute 1-based line and column from byte offset
fn compute_line_col(input: &str, offset: usize) -> (usize, usize) {
    let prefix = &input[..offset];
    let line = prefix.chars().filter(|c| *c == '\n').count() + 1;
    let last_newline = prefix.rfind('\n').map(|p| p + 1).unwrap_or(0);
    let col = input[last_newline..offset].chars().count() + 1;
    (line, col)
}

/// Format a context window showing the error location with a pointer
fn format_error_context_window(input: &str, offset: usize) -> String {
    let mut result = String::new();
    let lines: Vec<&str> = input.lines().collect();

    let prefix = &input[..offset];
    let error_line_idx = prefix.chars().filter(|c| *c == '\n').count(); // 0-based
    let last_newline = prefix.rfind('\n').map(|p| p + 1).unwrap_or(0);
    let error_col = input[last_newline..offset].chars().count(); // 0-based for pointer

    // Show up to 2 lines before and 1 line after
    let start = error_line_idx.saturating_sub(2);
    let end = (error_line_idx + 2).min(lines.len());

    result.push_str("Context:\n");
    for (i, line_content) in lines.iter().enumerate().take(end).skip(start) {
        let line_num = i + 1;
        let trimmed = take_first_chars(line_content, 120);
        if i == error_line_idx {
            result.push_str(&format!("  --> | {}\n", trimmed));
            // Add pointer
            let pointer_offset = error_col;
            result.push_str(&format!("      | {}^\n", " ".repeat(pointer_offset)));
        } else {
            result.push_str(&format!("  {:>3} | {}\n", line_num, trimmed));
        }
    }

    result
}

/// Generate a recovery suggestion based on the parsing context and error
fn generate_recovery_suggestion(
    contexts: &[&str],
    deepest: Option<&(&str, VerboseErrorKind)>,
    is_at_start: bool,
) -> Option<String> {
    // If error is at the start of input, always give top-level guidance
    if is_at_start {
        return Some(
            "A KIP statement must start with one of: \
             FIND (for queries), UPSERT/DELETE (for modifications), \
             or DESCRIBE/SEARCH (for schema exploration). \
             All keywords are case-sensitive and must be UPPERCASE."
                .to_string(),
        );
    }

    let innermost = contexts.first().copied().unwrap_or("");

    // JSON-specific suggestions
    if innermost.contains("JSON string") {
        return Some(
            "Check for unterminated strings: ensure every '\"' has a matching closing '\"'. \
             Inside JSON strings, special characters must be escaped: \
             use \\\" for quotes, \\\\ for backslashes, \\n for newlines."
                .to_string(),
        );
    }

    if innermost.contains("JSON object") || innermost.contains("key-value") {
        if let Some((_, VerboseErrorKind::Char(c))) = deepest {
            if *c == '}' {
                return Some(
                    "Unclosed JSON object. Ensure every '{' has a matching '}'. \
                     Check for missing commas between key-value pairs, \
                     or unterminated string values inside the object."
                        .to_string(),
                );
            }
            if *c == ':' {
                return Some(
                    "Expected ':' after key in object. Format: { key: value } or { \"key\": value }. \
                     Keys can be unquoted identifiers (letters, digits, underscores) or quoted strings."
                        .to_string(),
                );
            }
        }
        return Some(
            "Check JSON object syntax: { key: value, key2: value2 }. \
             Keys can be identifiers or quoted strings. \
             Values can be strings, numbers, booleans, null, arrays, or nested objects. \
             Trailing commas are allowed."
                .to_string(),
        );
    }

    if innermost.contains("JSON array") {
        return Some(
            "Check JSON array syntax: [value1, value2, ...]. \
             Ensure every '[' has a matching ']'. \
             Trailing commas are allowed."
                .to_string(),
        );
    }

    // KIP structure-specific suggestions
    if innermost.contains("FIND") {
        return Some(
            "FIND clause syntax: FIND(?variable) or FIND(?var1, ?var2, COUNT(?var3)). \
             Variables start with '?' followed by an identifier. \
             Aggregation functions: COUNT, SUM, AVG, MIN, MAX."
                .to_string(),
        );
    }

    if innermost.contains("WHERE") {
        return Some(
            "WHERE clause syntax: WHERE { <clauses> }. \
             Each clause is either: a concept match (?var {type: \"T\", name: \"N\"}), \
             a proposition match (?s, \"predicate\", ?o), \
             FILTER(...), OPTIONAL {...}, NOT {...}, or UNION {...}."
                .to_string(),
        );
    }

    if innermost.contains("CONCEPT") && innermost.contains("?local_handle") {
        return Some(
            "CONCEPT block syntax: CONCEPT [?handle] { {type: \"T\", name: \"N\"} [SET ATTRIBUTES {...}] [SET PROPOSITIONS {...}] }. \
             The concept matcher {type: \"...\", name: \"...\"} or {id: \"...\"} or {type: \"...\"} or {name: \"...\"} is required. \
             Handle is optional: CONCEPT { ... } is also valid."
                .to_string(),
        );
    }

    if innermost.contains("PROPOSITION") && innermost.contains("?local_handle") {
        return Some(
            "PROPOSITION block syntax: PROPOSITION [?handle] { (subject, \"predicate\", object) [SET ATTRIBUTES {...}] }. \
             Subject/object can be: ?variable, {type: \"T\", name: \"N\"}, {id: \"...\"}, or {type: \"...\"}, or {name: \"...\"}."
                .to_string(),
        );
    }

    if innermost.contains("SET ATTRIBUTES") {
        return Some(
            "SET ATTRIBUTES syntax: SET ATTRIBUTES { key: value, key2: value2 }. \
             Keys are identifiers or quoted strings. Values are JSON values."
                .to_string(),
        );
    }

    if innermost.contains("SET PROPOSITIONS") {
        return Some(
            "SET PROPOSITIONS syntax: SET PROPOSITIONS { (\"predicate\", target) [WITH METADATA {...}] ... }. \
             Target can be: ?variable, {type: \"T\", name: \"N\"}, {id: \"...\"}, or {type: \"...\"}, or {name: \"...\"}."
                .to_string(),
        );
    }

    if innermost.contains("WITH METADATA") {
        return Some(
            "WITH METADATA syntax: WITH METADATA { key: value, ... }. \
             Common metadata keys: source, author, confidence (0.0-1.0), status."
                .to_string(),
        );
    }

    if innermost.contains("UPSERT") {
        return Some(
            "UPSERT block syntax: UPSERT { CONCEPT ... | PROPOSITION ... } [WITH METADATA {...}]. \
             Must contain at least one CONCEPT or PROPOSITION block."
                .to_string(),
        );
    }

    if innermost.contains("DELETE") {
        return Some(
            "DELETE syntax variants: \
             DELETE ATTRIBUTES {\"attr1\", \"attr2\"} FROM ?var WHERE {...}, \
             DELETE METADATA {\"key1\"} FROM ?var WHERE {...}, \
             DELETE PROPOSITIONS ?var WHERE {...}, \
             DELETE CONCEPT ?var DETACH WHERE {...}."
                .to_string(),
        );
    }

    if innermost.contains("FILTER") {
        return Some(
            "FILTER syntax: FILTER(expression). \
             Comparisons: ?var == value, ?var != value, ?var < value, ?var > value, ?var <= value, ?var >= value. \
             Functions: CONTAINS(?var, \"text\"), STARTS_WITH(?var, \"prefix\"), ENDS_WITH(?var, \"suffix\"), REGEX(?var, \"pattern\"). \
             Logical: expr && expr, expr || expr, !(expr)."
                .to_string(),
        );
    }

    if innermost.contains("DESCRIBE") || innermost.contains("SEARCH") {
        return Some(
            "META commands: DESCRIBE PRIMER | DESCRIBE DOMAINS | \
             DESCRIBE CONCEPT TYPES [LIMIT N] | DESCRIBE CONCEPT TYPE \"TypeName\" | \
             DESCRIBE PROPOSITION TYPES [LIMIT N] | DESCRIBE PROPOSITION TYPE \"pred\" | \
             SEARCH CONCEPT \"term\" [WITH TYPE \"T\"] [LIMIT N] | \
             SEARCH PROPOSITION \"term\" [WITH TYPE \"T\"] [LIMIT N]."
                .to_string(),
        );
    }

    if innermost.contains("concept matcher") || innermost.contains("proposition matcher") {
        return Some(
            "Concept matcher formats: {type: \"TypeName\", name: \"Name\"} or {id: \"ID\"} or {type: \"Name\"} or {name: \"Name\"}. \
             Proposition matcher formats: (?subject, \"predicate\", ?object) or (id: \"proposition_id\")."
                .to_string(),
        );
    }

    if innermost.contains("dot notation") {
        return Some(
            "Dot path syntax: ?variable or ?variable.field or ?variable.field.subfield. \
             Variable names must start with '?' followed by a letter or underscore, \
             and can contain letters, digits, and underscores. \
             Path segments follow the same identifier rules."
                .to_string(),
        );
    }

    // Generic fallback based on error type
    if let Some((slice, kind)) = deepest {
        if slice.is_empty() {
            return Some(
                "Unexpected end of input. Check for unclosed brackets { }, parentheses ( ), \
                 or unterminated strings \"...\". The KIP statement may be incomplete."
                    .to_string(),
            );
        }
        // Trailing content error
        if matches!(kind, VerboseErrorKind::Nom(nom::error::ErrorKind::Eof)) {
            return Some(
                "There is unexpected content after a valid KIP statement. \
                 Each parse_kip() call should contain exactly one complete statement. \
                 Remove the extra text or split into separate statements."
                    .to_string(),
            );
        }
    }

    // Top-level suggestion
    if contexts.is_empty() {
        return Some(
            "A KIP statement must start with one of: \
             FIND (for queries), UPSERT/DELETE (for modifications), \
             or DESCRIBE/SEARCH (for schema exploration). \
             Keywords are case-sensitive and must be UPPERCASE."
                .to_string(),
        );
    }

    None
}

/// Take the first n characters of a string (avoids mid-byte truncation)
fn take_first_chars(s: &str, n: usize) -> String {
    s.chars().take(n).collect()
}