harn-hostlib 0.8.25

Opt-in code-intelligence and deterministic-tool host builtins for the Harn VM
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
//! Integration tests asserting that every module's registration surface
//! compiles, that unimplemented methods route through `HostlibError` rather
//! than panicking, and that every registered builtin has a matching schema.
//!
//! These tests are the contract implementation work must keep green:
//! when a module moves beyond scaffolding, the only change here should be
//! that a routed `Unimplemented` becomes a real return value — never a
//! removed builtin.

use harn_hostlib::{
    ast::AstCapability, code_index::CodeIndexCapability, fs::FsCapability,
    fs_snapshot::FsSnapshotCapability, fs_watch::FsWatchCapability, scanner::ScannerCapability,
    schemas, secret_store::SecretStoreCapability, tools::ToolsCapability, BuiltinRegistry,
    HostlibCapability, HostlibError, HostlibRegistry,
};

fn collect_into_registry<C: HostlibCapability>(cap: C) -> BuiltinRegistry {
    let mut registry = BuiltinRegistry::new();
    cap.register_builtins(&mut registry);
    registry
}

#[test]
fn ast_capability_registers_documented_methods() {
    let registry = collect_into_registry(AstCapability);
    let names: Vec<_> = registry.iter().map(|b| b.name).collect();
    assert_eq!(
        names,
        vec![
            "hostlib_ast_parse_file",
            "hostlib_ast_symbols",
            "hostlib_ast_outline",
            "hostlib_ast_parse_errors",
            "hostlib_ast_undefined_names",
            "hostlib_ast_function_body",
            "hostlib_ast_function_bodies",
            "hostlib_ast_extract_imports",
            "hostlib_ast_symbol_extract",
            "hostlib_ast_symbol_delete",
            "hostlib_ast_symbol_replace",
            "hostlib_ast_bracket_balance",
        ]
    );
    // Each AST builtin must reject empty input with a structured
    // `MissingParameter`. The required field differs per method:
    // file-based builtins want `path`; analysis builtins (#773) accept
    // either `content` or `path`; the source-mutation builtins (#774/#775)
    // take `source`; function_body takes `function_name`; function_bodies
    // takes `names`.
    let expected_missing: &[(&str, &str)] = &[
        ("hostlib_ast_parse_file", "path"),
        ("hostlib_ast_symbols", "path"),
        ("hostlib_ast_outline", "path"),
        ("hostlib_ast_parse_errors", "content_or_path"),
        ("hostlib_ast_undefined_names", "content_or_path"),
        ("hostlib_ast_function_body", "function_name"),
        ("hostlib_ast_function_bodies", "names"),
        ("hostlib_ast_extract_imports", "source"),
        ("hostlib_ast_symbol_extract", "source"),
        ("hostlib_ast_symbol_delete", "source"),
        ("hostlib_ast_symbol_replace", "source"),
        ("hostlib_ast_bracket_balance", "source"),
    ];
    for (name, expected_param) in expected_missing {
        let entry = registry.find(name).expect("registered");
        let err = (entry.handler)(&[]).expect_err("must reject empty args");
        match err {
            HostlibError::MissingParameter { builtin, param } => {
                assert_eq!(builtin, *name);
                assert_eq!(param, *expected_param);
            }
            other => panic!("expected MissingParameter for {name}, got {other:?}"),
        }
    }
}

#[test]
fn code_index_capability_registers_documented_methods() {
    let registry = collect_into_registry(CodeIndexCapability::new());
    let names: Vec<_> = registry.iter().map(|b| b.name).collect();
    assert_eq!(
        names,
        vec![
            // Workspace queries (the original 5).
            "hostlib_code_index_query",
            "hostlib_code_index_rebuild",
            "hostlib_code_index_stats",
            "hostlib_code_index_imports_for",
            "hostlib_code_index_importers_of",
            // File table accessors (#776).
            "hostlib_code_index_path_to_id",
            "hostlib_code_index_id_to_path",
            "hostlib_code_index_file_ids",
            "hostlib_code_index_file_meta",
            "hostlib_code_index_file_hash",
            // Cached reads (#776).
            "hostlib_code_index_read_range",
            "hostlib_code_index_reindex_file",
            "hostlib_code_index_trigram_query",
            "hostlib_code_index_extract_trigrams",
            "hostlib_code_index_word_get",
            "hostlib_code_index_deps_get",
            "hostlib_code_index_outline_get",
            // Change log (#776).
            "hostlib_code_index_current_seq",
            "hostlib_code_index_changes_since",
            "hostlib_code_index_version_record",
            // Agent registry + locks (#776).
            "hostlib_code_index_agent_register",
            "hostlib_code_index_agent_heartbeat",
            "hostlib_code_index_agent_unregister",
            "hostlib_code_index_lock_try",
            "hostlib_code_index_lock_release",
            "hostlib_code_index_status",
            "hostlib_code_index_current_agent_id",
        ]
    );
    // Without a populated workspace, code-index read methods return empty
    // payloads rather than panicking. Assert that contract here so any
    // regression to `unimplemented!()` fails loudly.
    let stats = registry
        .find("hostlib_code_index_stats")
        .expect("registered");
    let value = (stats.handler)(&[]).expect("stats works on an empty index");
    match value {
        harn_vm::VmValue::Dict(_) => {}
        other => panic!("expected dict response from stats, got {other:?}"),
    }
}

#[test]
fn scanner_capability_registers_documented_methods() {
    let registry = collect_into_registry(ScannerCapability);
    let names: Vec<_> = registry.iter().map(|b| b.name).collect();
    assert_eq!(
        names,
        vec![
            "hostlib_scanner_scan_project",
            "hostlib_scanner_scan_incremental"
        ]
    );
    // Implemented scanner methods should refuse an empty payload with
    // `MissingParameter` rather than routing through `Unimplemented`.
    // The full scanner contract is exercised end-to-end in
    // `tests/scanner_e2e.rs`.
    for name in &[
        "hostlib_scanner_scan_project",
        "hostlib_scanner_scan_incremental",
    ] {
        let entry = registry.find(name).expect("registered");
        let err = (entry.handler)(&[]).expect_err("must reject empty args");
        assert!(
            !matches!(err, HostlibError::Unimplemented { .. }),
            "scanner method {name} should be implemented, got {err:?}"
        );
    }
}

#[test]
fn fs_capability_registers_documented_methods() {
    let registry = collect_into_registry(FsCapability);
    let names: Vec<_> = registry.iter().map(|b| b.name).collect();
    assert_eq!(
        names,
        vec![
            "hostlib_fs_set_mode",
            "hostlib_fs_staged_status",
            "hostlib_fs_commit_staged",
            "hostlib_fs_discard_staged",
        ]
    );
    let expected_missing: &[(&str, &str)] = &[
        ("hostlib_fs_set_mode", "session_id"),
        ("hostlib_fs_staged_status", "session_id"),
        ("hostlib_fs_commit_staged", "session_id"),
        ("hostlib_fs_discard_staged", "session_id"),
    ];
    for (name, expected_param) in expected_missing {
        let entry = registry.find(name).expect("registered");
        let err = (entry.handler)(&[]).expect_err("must reject empty args");
        match err {
            HostlibError::MissingParameter { builtin, param } => {
                assert_eq!(builtin, *name);
                assert_eq!(param, *expected_param);
            }
            other => panic!("expected MissingParameter for {name}, got {other:?}"),
        }
    }
}

#[test]
fn fs_snapshot_capability_registers_documented_methods() {
    let registry = collect_into_registry(FsSnapshotCapability);
    let names: Vec<_> = registry.iter().map(|b| b.name).collect();
    assert_eq!(
        names,
        vec![
            "hostlib_fs_snapshot",
            "hostlib_fs_restore",
            "hostlib_fs_list_snapshots",
            "hostlib_fs_drop_snapshot",
        ]
    );
    let expected_missing: &[(&str, &str)] = &[
        ("hostlib_fs_snapshot", "session_id"),
        ("hostlib_fs_restore", "session_id"),
        ("hostlib_fs_list_snapshots", "session_id"),
        ("hostlib_fs_drop_snapshot", "session_id"),
    ];
    for (name, expected_param) in expected_missing {
        let entry = registry.find(name).expect("registered");
        let err = (entry.handler)(&[]).expect_err("must reject empty args");
        match err {
            HostlibError::MissingParameter { builtin, param } => {
                assert_eq!(builtin, *name);
                assert_eq!(param, *expected_param);
            }
            other => panic!("expected MissingParameter for {name}, got {other:?}"),
        }
    }
}

#[test]
fn fs_watch_capability_registers_documented_methods() {
    let registry = collect_into_registry(FsWatchCapability);
    let names: Vec<_> = registry.iter().map(|b| b.name).collect();
    assert_eq!(
        names,
        vec!["hostlib_fs_watch_subscribe", "hostlib_fs_watch_unsubscribe"]
    );
    for entry in registry.iter() {
        let err = (entry.handler)(&[]).expect_err("handler must reject empty args");
        assert!(
            !matches!(err, HostlibError::Unimplemented { .. }),
            "fs_watch method {} should be implemented, got {err:?}",
            entry.name
        );
    }
}

#[test]
fn tools_capability_registers_documented_methods() {
    let registry = collect_into_registry(ToolsCapability);
    let names: Vec<_> = registry.iter().map(|b| b.name).collect();
    assert_eq!(
        names,
        vec![
            // Deterministic tools — implementations live in
            // `crates/harn-hostlib/src/tools/`. Gated by
            // `hostlib_enable("tools:deterministic")`.
            "hostlib_tools_search",
            "hostlib_tools_read_file",
            "hostlib_tools_write_file",
            "hostlib_tools_delete_file",
            "hostlib_tools_list_directory",
            "hostlib_tools_get_file_outline",
            "hostlib_tools_git",
            // Process tools. Also gated by
            // `hostlib_enable("tools:deterministic")`.
            "hostlib_tools_run_command",
            "hostlib_tools_read_command_output",
            "hostlib_tools_run_test",
            "hostlib_tools_run_build_command",
            "hostlib_tools_inspect_test_results",
            "hostlib_tools_manage_packages",
            "hostlib_tools_cancel_handle",
            // Per-session opt-in builtin.
            "hostlib_enable",
        ]
    );

    // All implemented tools must refuse to run before
    // `hostlib_enable("tools:deterministic")`. We check each entry so newly
    // wired tools cannot accidentally bypass the opt-in gate.
    harn_hostlib::tools::permissions::reset();
    let gated_methods = [
        "hostlib_tools_search",
        "hostlib_tools_read_file",
        "hostlib_tools_write_file",
        "hostlib_tools_delete_file",
        "hostlib_tools_list_directory",
        "hostlib_tools_get_file_outline",
        "hostlib_tools_git",
        "hostlib_tools_run_command",
        "hostlib_tools_read_command_output",
        "hostlib_tools_run_test",
        "hostlib_tools_run_build_command",
        "hostlib_tools_inspect_test_results",
        "hostlib_tools_manage_packages",
        "hostlib_tools_cancel_handle",
    ];
    for name in gated_methods {
        let entry = registry.find(name).expect("registered");
        let err = (entry.handler)(&[]).expect_err("disabled by default");
        match err {
            HostlibError::Backend { builtin, message } => {
                assert_eq!(builtin, name);
                assert!(
                    message.contains("hostlib_enable"),
                    "gating error must point users at hostlib_enable: {message}"
                );
            }
            other => panic!("expected Backend gate error for {name}, got {other:?}"),
        }
    }
}

#[test]
fn secret_store_capability_registers_documented_methods() {
    let registry = collect_into_registry(SecretStoreCapability);
    let names: Vec<_> = registry.iter().map(|b| b.name).collect();
    assert_eq!(
        names,
        vec![
            "hostlib_secret_store_get",
            "hostlib_secret_store_set",
            "hostlib_secret_store_delete",
            "hostlib_secret_store_list",
        ]
    );
    // Each entry must refuse an empty payload with a structured
    // `MissingParameter` rather than panicking.
    let expected_missing: &[(&str, &str)] = &[
        ("hostlib_secret_store_get", "account"),
        ("hostlib_secret_store_set", "account"),
        ("hostlib_secret_store_delete", "account"),
        ("hostlib_secret_store_list", "account"),
    ];
    for (name, expected_param) in expected_missing {
        let entry = registry.find(name).expect("registered");
        let err = (entry.handler)(&[]).expect_err("must reject empty args");
        match err {
            HostlibError::MissingParameter { builtin, param } => {
                assert_eq!(builtin, *name);
                assert_eq!(param, *expected_param);
            }
            other => panic!("expected MissingParameter for {name}, got {other:?}"),
        }
    }
}

#[test]
fn install_default_wires_every_module_into_a_vm() {
    let mut vm = harn_vm::Vm::new();
    let registry = harn_hostlib::install_default(&mut vm);

    assert_eq!(
        registry.modules(),
        &[
            "ast",
            "code_index",
            "scanner",
            "fs",
            "fs",
            "fs_watch",
            "tools",
            "secret_store"
        ]
    );
    // Builtin count: 12 ast + 27 code_index + 2 scanner + 4 fs + 4 fs_snapshot
    // + 2 fs_watch + 13 tools + 1 hostlib_enable + 4 secret_store = 69.
    assert!(registry.builtins().len() >= 69);
}

#[test]
fn every_registered_builtin_has_request_and_response_schemas() {
    let registry = HostlibRegistry::new()
        .with(AstCapability)
        .with(CodeIndexCapability::new())
        .with(ScannerCapability)
        .with(FsCapability)
        .with(FsSnapshotCapability)
        .with(FsWatchCapability)
        .with(ToolsCapability)
        .with(SecretStoreCapability);

    for entry in registry.builtins().iter() {
        assert!(
            schemas::lookup(entry.module, entry.method, schemas::SchemaKind::Request).is_some(),
            "missing request schema for {}.{}",
            entry.module,
            entry.method
        );
        assert!(
            schemas::lookup(entry.module, entry.method, schemas::SchemaKind::Response).is_some(),
            "missing response schema for {}.{}",
            entry.module,
            entry.method
        );
    }
}

#[test]
fn every_schema_parses_as_valid_json_schema_2020_12() {
    for (module, method, kind, body) in schemas::SCHEMAS {
        let value: serde_json::Value = serde_json::from_str(body).unwrap_or_else(|err| {
            panic!("schema for {module}.{method} ({kind:?}) is not valid JSON: {err}")
        });
        let dialect = value
            .get("$schema")
            .and_then(|v| v.as_str())
            .expect("every shipped schema must declare its dialect via $schema");
        assert!(
            dialect.contains("draft/2020-12"),
            "schema for {module}.{method} ({kind:?}) declares unexpected dialect: {dialect}"
        );
        // Sanity check on shape: every schema must be an object and either
        // declare a top-level `type` or be a pure `$ref`. This catches
        // accidental empty or malformed files without forcing a full
        // schema-validator dependency at scaffold stage.
        assert!(
            value.is_object(),
            "schema for {module}.{method} ({kind:?}) must be a JSON object"
        );
        let object = value.as_object().unwrap();
        assert!(
            object.contains_key("type") || object.contains_key("$ref"),
            "schema for {module}.{method} ({kind:?}) must declare `type` or `$ref`"
        );
    }
}