code-kb-core 1.1.3

Core library for code-kb AST fact querying, slicing, and progressive disclosure
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
use code_kb_core::{
    Workspace, find_julie_extract_binary, open_read_only, replace_symbol_body, safe_tempdir,
    scan_workspace, slicer,
};
use std::fs;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

#[test]
fn test_replace_symbol_body_atomic() {
    let _extract_bin =
        find_julie_extract_binary().expect("julie-extract binary must be present for tests");

    let temp_dir = safe_tempdir();
    let root = temp_dir.path().to_path_buf();

    // Create a sample rust file
    let src_dir = root.join("src");
    fs::create_dir_all(&src_dir).unwrap();
    let file_path = src_dir.join("calc.rs");

    let initial_code = r#"pub fn add_numbers(a: i32, b: i32) -> i32 {
    a + b
}
"#;
    fs::write(&file_path, initial_code).unwrap();

    let ws = Workspace::new(root.clone());
    let db_path = root.join("test.db");

    scan_workspace(&ws, &db_path, true).expect("Scan failed");
    let conn = open_read_only(&db_path).unwrap();

    let new_body = r#"{
    let sum = a + b;
    sum * 2
}"#;

    let res = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "add_numbers",
        "src/calc.rs",
        new_body,
        None,
    )
    .expect("replace_symbol_body failed");

    assert_eq!(res.symbol_name, "add_numbers");
    assert_eq!(res.file_path, "src/calc.rs");

    // Verify on disk
    let disk_content = fs::read_to_string(&file_path).unwrap();
    assert!(disk_content.contains("let sum = a + b;"));
    assert!(disk_content.contains("sum * 2"));

    // Verify in db
    let updated_symbol =
        code_kb_core::get_symbol_by_name(&conn, "add_numbers", Some("src/calc.rs"))
            .unwrap()
            .unwrap();

    let body = slicer::slice_symbol_body(&file_path, &updated_symbol).unwrap();
    assert_eq!(body.trim(), new_body.trim());
}

#[test]
fn test_replace_symbol_body_shrunk_file_does_not_panic() {
    let _extract_bin =
        find_julie_extract_binary().expect("julie-extract binary must be present for tests");

    let temp_dir = safe_tempdir();
    let root = temp_dir.path().to_path_buf();

    let src_dir = root.join("src");
    fs::create_dir_all(&src_dir).unwrap();
    let file_path = src_dir.join("calc.rs");

    let initial_code = r#"pub fn long_function_name(a: i32, b: i32) -> i32 {
    let mut x = a * 2;
    let mut y = b * 3;
    x + y
}
"#;
    fs::write(&file_path, initial_code).unwrap();

    let ws = Workspace::new(root.clone());
    let db_path = root.join("test.db");

    scan_workspace(&ws, &db_path, true).expect("Scan failed");
    let conn = open_read_only(&db_path).unwrap();

    // Now shrink the file to just 5 bytes without updating the database
    fs::write(&file_path, "short").unwrap();

    // Calling replace_symbol_body must NOT panic! It must return a clean Err
    let res = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "long_function_name",
        "src/calc.rs",
        "{\n    42\n}",
        None,
    );

    assert!(
        res.is_err(),
        "Replacing in shrunk file must return an Err, not panic"
    );
}

#[test]
fn test_replace_symbol_body_rejects_syntax_error() {
    let _extract_bin =
        find_julie_extract_binary().expect("julie-extract binary must be present for tests");

    let temp_dir = safe_tempdir();
    let root = temp_dir.path().to_path_buf();

    let src_dir = root.join("src");
    fs::create_dir_all(&src_dir).unwrap();
    let file_path = src_dir.join("calc.rs");

    let initial_code = r#"pub fn my_calc(a: i32) -> i32 {
    a * 2
}
"#;
    fs::write(&file_path, initial_code).unwrap();

    let ws = Workspace::new(root.clone());
    let db_path = root.join("test.db");

    scan_workspace(&ws, &db_path, true).expect("Scan failed");
    let conn = open_read_only(&db_path).unwrap();

    // Attempt replacing body with invalid Rust syntax (e.g. missing operand, syntax error)
    let invalid_body = "{\n    let x = ;\n}";
    let res = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "my_calc",
        "src/calc.rs",
        invalid_body,
        None,
    );

    assert!(
        res.is_err(),
        "Replacement with invalid syntax must be rejected"
    );

    // File on disk must remain uncorrupted and unchanged!
    let disk_content = fs::read_to_string(&file_path).unwrap();
    assert_eq!(
        disk_content, initial_code,
        "Disk content must not be modified when syntax error occurs"
    );
}

#[test]
fn test_replace_symbol_body_rejects_stale_indexed_hash_when_disk_differs() {
    let _extract_bin =
        find_julie_extract_binary().expect("julie-extract binary must be present for tests");

    let temp_dir = safe_tempdir();
    let root = temp_dir.path().to_path_buf();

    let src_dir = root.join("src");
    fs::create_dir_all(&src_dir).unwrap();
    let file_path = src_dir.join("calc.rs");

    let initial_code = "pub fn my_calc(a: i32) -> i32 {\n    a * 2\n}\n";
    fs::write(&file_path, initial_code).unwrap();

    let ws = Workspace::new(root.clone());
    let db_path = root.join("test.db");

    scan_workspace(&ws, &db_path, true).expect("Scan failed");
    let conn = open_read_only(&db_path).unwrap();

    let sym = code_kb_core::get_symbol_by_name_exact(&conn, "my_calc", "src/calc.rs")
        .unwrap()
        .unwrap();
    let indexed_hash = sym
        .body_hash
        .clone()
        .expect("Indexed symbol should have body_hash");

    // Manually edit the file on disk so the body is different from indexed state,
    // and keep file length same or different
    let offline_code = "pub fn my_calc(a: i32) -> i32 {\n    a * 9\n}\n";
    fs::write(&file_path, offline_code).unwrap();

    // Calling replace_symbol_body with expected_hash matching the OLD indexed hash
    // MUST fail with HashMismatch because the disk content is no longer that hash!
    let res = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "my_calc",
        "src/calc.rs",
        "{\n    a * 10\n}",
        Some(&indexed_hash),
    );

    assert!(
        matches!(res, Err(code_kb_core::EditError::HashMismatch(..))),
        "Must reject edit when expected hash does not match current disk body, got: {:?}",
        res
    );
}

#[cfg(unix)]
#[test]
fn test_replace_symbol_body_preserves_file_permissions() {
    let _extract_bin =
        find_julie_extract_binary().expect("julie-extract binary must be present for tests");

    let temp_dir = safe_tempdir();
    let root = temp_dir.path().to_path_buf();

    let src_dir = root.join("src");
    fs::create_dir_all(&src_dir).unwrap();
    let file_path = src_dir.join("script.rs");

    let initial_code = "pub fn run_script() -> i32 {\n    1\n}\n";
    fs::write(&file_path, initial_code).unwrap();

    // Set 0755 executable permissions
    fs::set_permissions(&file_path, fs::Permissions::from_mode(0o755)).unwrap();

    let ws = Workspace::new(root.clone());
    let db_path = root.join("test.db");

    scan_workspace(&ws, &db_path, true).expect("Scan failed");
    let conn = open_read_only(&db_path).unwrap();

    let res = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "run_script",
        "src/script.rs",
        "{\n    42\n}",
        None,
    );
    assert!(res.is_ok(), "replace_symbol_body should succeed: {:?}", res);

    // Verify permissions were preserved (not clobbered to 0600 by tempfile)
    let perms = fs::metadata(&file_path).unwrap().permissions();
    assert_eq!(
        perms.mode() & 0o777,
        0o755,
        "Permissions must remain 0755 after edit, got: {:o}",
        perms.mode() & 0o777
    );
}

#[cfg(unix)]
#[test]
fn test_replace_symbol_body_preserves_symlinks() {
    let _extract_bin =
        find_julie_extract_binary().expect("julie-extract binary must be present for tests");

    let temp_dir = safe_tempdir();
    let root = temp_dir.path().to_path_buf();

    let src_dir = root.join("src");
    fs::create_dir_all(&src_dir).unwrap();
    let real_file = src_dir.join("real.rs");
    let link_file = src_dir.join("link.rs");

    let initial_code = "pub fn linked_fn() -> i32 {\n    10\n}\n";
    fs::write(&real_file, initial_code).unwrap();
    std::os::unix::fs::symlink(&real_file, &link_file).unwrap();

    let ws = Workspace::new(root.clone());
    let db_path = root.join("test.db");

    scan_workspace(&ws, &db_path, true).expect("Scan failed");
    let conn = open_read_only(&db_path).unwrap();

    // Edit through the symlink path
    let res = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "linked_fn",
        "src/link.rs",
        "{\n    99\n}",
        None,
    );
    assert!(res.is_ok(), "replace_symbol_body should succeed: {:?}", res);

    // Verify link.rs is STILL a symlink
    let sym_meta = fs::symlink_metadata(&link_file).unwrap();
    assert!(
        sym_meta.is_symlink(),
        "Symlink must NOT be replaced by a regular file"
    );

    // Verify real file received the edit
    let real_content = fs::read_to_string(&real_file).unwrap();
    assert!(
        real_content.contains("99"),
        "Real file must contain edited content"
    );
}

#[test]
fn test_replace_symbol_body_normalizes_crlf() {
    let _extract_bin =
        find_julie_extract_binary().expect("julie-extract binary must be present for tests");

    let temp_dir = safe_tempdir();
    let root = temp_dir.path().to_path_buf();

    let src_dir = root.join("src");
    fs::create_dir_all(&src_dir).unwrap();
    let file_path = src_dir.join("crlf.rs");

    // File with CRLF line endings
    let initial_code = "pub fn crlf_fn() -> i32 {\r\n    1\r\n}\r\n";
    fs::write(&file_path, initial_code).unwrap();

    let ws = Workspace::new(root.clone());
    let db_path = root.join("test.db");

    scan_workspace(&ws, &db_path, true).expect("Scan failed");
    let conn = open_read_only(&db_path).unwrap();

    // Pass replacement body with LF only
    let new_body = "{\n    let a = 10;\n    a * 2\n}";
    let res = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "crlf_fn",
        "src/crlf.rs",
        new_body,
        None,
    );
    assert!(res.is_ok(), "replace_symbol_body should succeed: {:?}", res);

    // Verify disk content preserves CRLF consistently throughout
    let disk_bytes = fs::read(&file_path).unwrap();
    let disk_str = String::from_utf8(disk_bytes.clone()).unwrap();
    assert!(
        disk_str.contains("\r\n"),
        "File must maintain CRLF line endings"
    );

    // Check there are no bare LF (\n without \r before it)
    let mut prev_char = ' ';
    for ch in disk_str.chars() {
        if ch == '\n' {
            assert_eq!(
                prev_char, '\r',
                "Every newline in CRLF file must be preceded by carriage return (CRLF)"
            );
        }
        prev_char = ch;
    }
}

#[test]
fn test_replace_symbol_body_chained_edits_with_expected_hash() {
    let _extract_bin =
        find_julie_extract_binary().expect("julie-extract binary must be present for tests");

    let temp_dir = safe_tempdir();
    let root = temp_dir.path().to_path_buf();

    let src_dir = root.join("src");
    fs::create_dir_all(&src_dir).unwrap();
    let file_path = src_dir.join("calc.rs");

    let initial_code = "pub fn add_numbers(a: i32, b: i32) -> i32 {\n    a + b\n}\n";
    fs::write(&file_path, initial_code).unwrap();

    let ws = Workspace::new(root.clone());
    let db_path = root.join("test.db");

    scan_workspace(&ws, &db_path, true).expect("Scan failed");
    let conn = open_read_only(&db_path).unwrap();

    // 1. First edit: no expected hash passed
    let res1 = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "add_numbers",
        "src/calc.rs",
        "{\n    let sum = a + b;\n    sum * 2\n}",
        None,
    )
    .expect("first edit should succeed");

    assert!(!res1.new_body_hash.is_empty());

    // 2. Second edit: passing valid expected_hash matching res1.new_body_hash
    let res2 = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "add_numbers",
        "src/calc.rs",
        "{\n    let sum = a + b;\n    sum * 3\n}",
        Some(&res1.new_body_hash),
    )
    .expect("second edit with correct expected_hash should succeed");

    assert_ne!(res1.new_body_hash, res2.new_body_hash);

    // 3. Third edit: passing stale expected_hash (res1.new_body_hash) must fail
    let res3 = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "add_numbers",
        "src/calc.rs",
        "{\n    let sum = a + b;\n    sum * 4\n}",
        Some(&res1.new_body_hash),
    );

    assert!(res3.is_err(), "Edit with stale expected_hash must fail");
    let err_msg = res3.unwrap_err().to_string();
    assert!(err_msg.contains("Optimistic lock failed") || err_msg.contains("expected body hash"));
}

#[test]
fn test_replace_symbol_body_rejects_syntax_error_in_a_language_without_a_bundled_grammar() {
    let _extract_bin =
        find_julie_extract_binary().expect("julie-extract binary must be present for tests");

    let temp_dir = safe_tempdir();
    let root = temp_dir.path().to_path_buf();
    fs::create_dir_all(root.join("lib")).unwrap();
    let file_path = root.join("lib/calc.rb");
    let initial_code = "def my_calc(a)\n  a * 2\nend\n";
    fs::write(&file_path, initial_code).unwrap();

    let ws = Workspace::new(root.clone());
    let db_path = root.join("test.db");
    scan_workspace(&ws, &db_path, true).expect("Scan failed");
    let conn = open_read_only(&db_path).unwrap();

    let res = replace_symbol_body(
        &ws,
        &db_path,
        &conn,
        "my_calc",
        "lib/calc.rb",
        "def my_calc(a)\n  a * (2\nend\n",
        None,
    );

    let message = res.expect_err("broken Ruby must be rejected").to_string();
    assert!(message.contains("syntax"), "{message}");
    assert!(message.contains("at line "), "{message}");
    assert_eq!(fs::read_to_string(&file_path).unwrap(), initial_code);
}

#[test]
fn validate_syntax_skips_paths_the_extractor_has_no_grammar_for() {
    assert_eq!(
        code_kb_core::validate_syntax("notes.unknown", "anything (\n"),
        Ok(false)
    );
    assert_eq!(
        code_kb_core::validate_syntax("src/lib.rs", "pub fn f() {}\n"),
        Ok(true)
    );
}