harn-cli 0.10.53

CLI for the Harn programming language — run, test, REPL, format, and lint
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
use super::{
    collect_harn_files_sorted, evaluate_conformance_case, lint_expectation_error, logical_path,
    parse_xfail_marker, resolve_conformance_selection, ConformanceRunOptions,
};
use std::fs;
use std::path::Path;

struct TempTestDir {
    dir: tempfile::TempDir,
}

impl TempTestDir {
    fn new() -> Self {
        let dir = tempfile::Builder::new()
            .prefix("harn-cli-test-")
            .tempdir()
            .unwrap();
        Self { dir }
    }

    fn write(&self, relative: &str) {
        self.write_content(relative, "// test");
    }

    fn write_content(&self, relative: &str, content: &str) {
        let path = self.dir.path().join(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(path, content).unwrap();
    }

    fn path(&self) -> &Path {
        self.dir.path()
    }
}

#[test]
fn collect_harn_files_sorted_descends_and_sorts() {
    let temp = TempTestDir::new();
    temp.write("suite/zeta.harn");
    temp.write("suite/alpha.harn");
    temp.write("suite/nested/beta.harn");
    fs::write(temp.path().join("suite/ignore.txt"), "").unwrap();

    let files = collect_harn_files_sorted(&temp.path().join("suite"));
    let relative: Vec<String> = files
        .iter()
        .map(|path| logical_path(path.strip_prefix(temp.path()).unwrap()))
        .collect();

    assert_eq!(
        relative,
        vec![
            "suite/alpha.harn",
            "suite/nested/beta.harn",
            "suite/zeta.harn"
        ]
    );
}

#[test]
fn logical_path_uses_slashes_for_native_test_paths() {
    let path = Path::new("suite").join("nested").join("beta.harn");

    assert_eq!(logical_path(&path), "suite/nested/beta.harn");
}

#[test]
fn resolve_conformance_selection_accepts_suite_relative_file() {
    let temp = TempTestDir::new();
    temp.write("conformance/tests/sample.harn");

    let files =
        resolve_conformance_selection(&temp.path().join("conformance"), Some("tests/sample.harn"))
            .unwrap();

    assert_eq!(files.len(), 1);
    assert!(files[0].ends_with("conformance/tests/sample.harn"));
}

#[test]
fn resolve_conformance_selection_rejects_paths_outside_suite_root() {
    let temp = TempTestDir::new();
    temp.write("conformance/tests/sample.harn");
    temp.write("outside.harn");

    let error =
        resolve_conformance_selection(&temp.path().join("conformance"), Some("../outside.harn"))
            .unwrap_err();

    assert!(error.contains("must be inside"));
}

#[test]
fn parse_xfail_marker_recognizes_top_of_file_marker() {
    let src = "// @xfail: tracked in #1240\npipeline main(task) {}\n";
    assert_eq!(parse_xfail_marker(src).as_deref(), Some("tracked in #1240"));
}

#[test]
fn parse_xfail_marker_recognizes_indented_marker() {
    let src = "    // @xfail: skill matching #1240\n";
    assert_eq!(
        parse_xfail_marker(src).as_deref(),
        Some("skill matching #1240")
    );
}

#[test]
fn parse_xfail_marker_returns_none_when_absent() {
    let src = "// regular comment\npipeline main(task) {}\n";
    assert!(parse_xfail_marker(src).is_none());
}

#[test]
fn parse_xfail_marker_ignores_marker_past_first_50_lines() {
    let mut src = String::new();
    for _ in 0..60 {
        src.push_str("// filler\n");
    }
    src.push_str("// @xfail: too late\n");
    assert!(parse_xfail_marker(&src).is_none());
}

#[test]
fn parse_xfail_marker_ignores_empty_reason() {
    let src = "// @xfail:   \n";
    assert!(parse_xfail_marker(src).is_none());
}

#[test]
fn parse_xfail_marker_recognizes_one_line_doc_comment() {
    let src = "/** @xfail: tracked in #1240 */\npipeline test() {}\n";
    assert_eq!(parse_xfail_marker(src).as_deref(), Some("tracked in #1240"));
}

#[test]
fn parse_xfail_marker_recognizes_multi_line_doc_comment() {
    let src = "/**\n * @xfail: tracked in #1238\n */\nfn foo() {}\n";
    assert_eq!(parse_xfail_marker(src).as_deref(), Some("tracked in #1238"));
}

#[test]
fn parse_xfail_marker_recognizes_block_comment() {
    let src = "/* @xfail: tracked in #1239 */\nfn foo() {}\n";
    assert_eq!(parse_xfail_marker(src).as_deref(), Some("tracked in #1239"));
}

#[test]
fn lint_expectations_require_at_least_one_assertion() {
    assert_eq!(
        lint_expectation_error("", "\n  \n").as_deref(),
        Some("lint expectation file is empty")
    );
}

#[test]
fn lint_expectations_support_required_and_forbidden_patterns() {
    let actual = "HARN-LNT-066 error lint[discarded-pure-result]";
    assert_eq!(
        lint_expectation_error(actual, "HARN-LNT-066\n!HARN-RMD-003"),
        None
    );
    assert_eq!(
        lint_expectation_error(actual, "!HARN-LNT-066").as_deref(),
        Some("forbidden lint matched: HARN-LNT-066")
    );
}

fn discarded_pure_result_source() -> &'static str {
    r#"fn main(harness: Harness) {
  const items = []
  items.appending(1)
  harness.stdio.println("")
}
"#
}

fn conformance_options() -> ConformanceRunOptions<'static> {
    ConformanceRunOptions {
        verbose: false,
        timing: false,
        differential_optimizations: false,
        json: false,
        skip_xfail: false,
        shard: None,
        cli_skill_dirs: &[],
    }
}

/// Run one conformance case under the process-global harn-state lock.
///
/// `execute_conformance_source` points `HARN_STATE_DIR` at a fresh case root.
/// That variable is process-global, and the root is deleted the moment the case
/// ends — so without this lock a concurrently running persona, portal, or
/// orchestrator-harness test can resolve state into this case's directory and
/// then fail to open it. Every conformance case evaluated from a test must go
/// through here rather than calling `evaluate_conformance_case` directly.
async fn evaluate_case_serialized(
    harn_file: &Path,
    rel_path: &str,
    options: &ConformanceRunOptions<'_>,
) -> super::ConformanceCaseEvaluation {
    let _state_guard = crate::tests::common::harn_state_lock::lock_harn_state_async().await;
    evaluate_conformance_case(
        harn_file,
        &harn_file.with_extension("expected"),
        &harn_file.with_extension("error"),
        &harn_file.with_extension("lint"),
        rel_path,
        2_000,
        options,
    )
    .await
}

#[tokio::test]
async fn expected_output_and_lint_expectations_are_additive() {
    let temp = TempTestDir::new();
    temp.write_content(
        "conformance/tests/additive.harn",
        discarded_pure_result_source(),
    );
    temp.write_content("conformance/tests/additive.expected", "");
    temp.write_content(
        "conformance/tests/additive.lint",
        "HARN-LNT-066\n!HARN-RMD-003\n",
    );
    let harn_file = temp.path().join("conformance/tests/additive.harn");

    let evaluation =
        evaluate_case_serialized(&harn_file, "tests/additive.harn", &conformance_options()).await;

    assert!(evaluation.passed, "{:?}", evaluation.message);
    assert_eq!(evaluation.diagnostic_codes, ["HARN-LNT-066"]);
}

#[tokio::test]
async fn expected_error_and_lint_expectations_are_additive() {
    let temp = TempTestDir::new();
    temp.write_content(
        "conformance/tests/additive_error.harn",
        r#"fn main(harness: Harness) {
  const items = []
  items.appending(1)
  harness.stdio.println("")
  throw "boom"
}
"#,
    );
    temp.write_content("conformance/tests/additive_error.error", "boom");
    temp.write_content(
        "conformance/tests/additive_error.lint",
        "HARN-LNT-066\n!HARN-RMD-003\n",
    );
    let harn_file = temp.path().join("conformance/tests/additive_error.harn");

    let evaluation = evaluate_case_serialized(
        &harn_file,
        "tests/additive_error.harn",
        &conformance_options(),
    )
    .await;

    assert!(evaluation.passed, "{:?}", evaluation.message);
    assert_eq!(evaluation.diagnostic_codes, ["HARN-LNT-066"]);
}

#[tokio::test]
async fn conformance_case_cannot_write_into_the_runner_checkout() {
    let temp = TempTestDir::new();
    let escape_path = std::env::current_dir()
        .unwrap()
        .join(format!(".harn-conformance-escape-{}", std::process::id()));
    let _ = fs::remove_file(&escape_path);
    let quoted_path = serde_json::to_string(&escape_path.display().to_string()).unwrap();
    temp.write_content(
        "conformance/tests/write_escape.harn",
        &format!(
            "fn main(harness: Harness) {{\n  harness.fs.write_text({quoted_path}, \"escaped\")\n}}\n"
        ),
    );
    temp.write_content(
        "conformance/tests/write_escape.error",
        &format!(
            "re:HARN-CAP-201.*{}",
            regex::escape(&escape_path.display().to_string())
        ),
    );
    let harn_file = temp.path().join("conformance/tests/write_escape.harn");

    let evaluation = evaluate_case_serialized(
        &harn_file,
        "tests/write_escape.harn",
        &conformance_options(),
    )
    .await;
    let escaped = escape_path.exists();
    if escaped {
        fs::remove_file(&escape_path).unwrap();
    }

    assert!(evaluation.passed, "{:?}", evaluation.message);
    assert!(!escaped, "the denied conformance write reached disk");
}

#[tokio::test]
async fn expected_output_fails_on_unasserted_error_lint() {
    let temp = TempTestDir::new();
    temp.write_content(
        "conformance/tests/unasserted.harn",
        discarded_pure_result_source(),
    );
    temp.write_content("conformance/tests/unasserted.expected", "");
    let harn_file = temp.path().join("conformance/tests/unasserted.harn");

    let evaluation =
        evaluate_case_serialized(&harn_file, "tests/unasserted.harn", &conformance_options()).await;

    assert!(!evaluation.passed);
    assert!(evaluation
        .message
        .as_deref()
        .is_some_and(|message| message.contains("unasserted error lint")));
}

#[tokio::test]
async fn empty_lint_fixture_fails_instead_of_passing_vacuously() {
    let temp = TempTestDir::new();
    temp.write_content(
        "conformance/tests/empty_lint.harn",
        discarded_pure_result_source(),
    );
    temp.write_content("conformance/tests/empty_lint.lint", "\n");
    let harn_file = temp.path().join("conformance/tests/empty_lint.harn");

    let evaluation =
        evaluate_case_serialized(&harn_file, "tests/empty_lint.harn", &conformance_options()).await;

    assert!(!evaluation.passed);
    assert!(evaluation
        .message
        .as_deref()
        .is_some_and(|message| message.contains("lint expectation file is empty")));
}

#[tokio::test]
async fn conformance_harness_sidecar_error_fails_expected_error_fixture() {
    let temp = TempTestDir::new();
    temp.write_content(
        "conformance/tests/harness_sidecar_error.harn",
        r#"fn main(harness: Harness) {
  harness.env.get("TOKEN")
}
"#,
    );
    temp.write_content(
        "conformance/tests/harness_sidecar_error.error",
        "NullHarness denied",
    );
    temp.write_content(
        "conformance/tests/harness_sidecar_error.harness.json",
        r#"{
  "mode": "null",
  "expect_deny_events": [
    {
      "sub_handle": "env",
      "method": "wrong",
      "args": ["TOKEN"]
    }
  ]
}
"#,
    );

    let harn_file = temp
        .path()
        .join("conformance/tests/harness_sidecar_error.harn");
    let expected_file = harn_file.with_extension("expected");
    let error_file = harn_file.with_extension("error");
    let lint_file = harn_file.with_extension("lint");
    let options = ConformanceRunOptions {
        verbose: false,
        timing: false,
        differential_optimizations: false,
        json: false,
        skip_xfail: false,
        shard: None,
        cli_skill_dirs: &[],
    };

    let evaluation = {
        let _state_guard = crate::tests::common::harn_state_lock::lock_harn_state_async().await;
        evaluate_conformance_case(
            &harn_file,
            &expected_file,
            &error_file,
            &lint_file,
            "tests/harness_sidecar_error.harn",
            2_000,
            &options,
        )
        .await
    };

    assert!(!evaluation.passed);
    let message = evaluation.message.unwrap_or_default();
    assert!(
        message.contains("harness deny events differed"),
        "unexpected message: {message}"
    );
}