harn-vm 0.10.162

Async bytecode virtual machine for the Harn programming language
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
use std::path::{Path, PathBuf};

use sha2::{Digest, Sha256};

pub const HARN_STATE_DIR_ENV: &str = "HARN_STATE_DIR";
pub const HARN_RUN_DIR_ENV: &str = "HARN_RUN_DIR";
pub const HARN_WORKTREE_DIR_ENV: &str = "HARN_WORKTREE_DIR";
/// Overrides where the memory builtins keep their event log and vector cache.
///
/// Memory does not live under `HARN_STATE_DIR`: it resolves source-relative and
/// defaults to `.harn/memory` beside the running script. A caller that isolates
/// state therefore has to isolate memory as a second, separate act.
pub const HARN_MEMORY_ROOT_ENV: &str = "HARN_MEMORY_ROOT";
const NEXTEST_ENV: &str = "NEXTEST";
const NEXTEST_RUN_ID_ENV: &str = "NEXTEST_RUN_ID";
const NEXTEST_BINARY_ID_ENV: &str = "NEXTEST_BINARY_ID";
const NEXTEST_TEST_NAME_ENV: &str = "NEXTEST_TEST_NAME";
const NEXTEST_ATTEMPT_ID_ENV: &str = "NEXTEST_ATTEMPT_ID";

/// Directory name of the default run root, `<base>/.harn-runs`.
pub const DEFAULT_RUN_DIR_NAME: &str = ".harn-runs";

const SELF_IGNORE_CONTENTS: &str = "# Created by Harn; safe to delete.\n*\n";

/// Give a Harn-owned directory inside someone's checkout a `.gitignore` that
/// ignores everything in it, so its contents never show in `git status`.
///
/// An existing `.gitignore` is left as it is: a person who wrote one there
/// decided what that directory tracks.
pub fn ensure_self_ignored_dir(dir: &Path) -> std::io::Result<()> {
    let opened = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(dir.join(".gitignore"));
    match opened {
        Ok(mut file) => std::io::Write::write_all(&mut file, SELF_IGNORE_CONTENTS.as_bytes()),
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
        Err(error) => Err(error),
    }
}

/// Self-ignore the default run root that contains `written`, if any.
///
/// Called after a record lands under it. Only the default `.harn-runs` name is
/// Harn's to hide: an explicit `HARN_RUN_DIR` is a directory the caller chose,
/// and may be one they mean to keep. Best effort, because a record that was
/// written must not fail on its ignore file.
pub fn self_ignore_default_run_root(written: &Path) {
    let root = written
        .ancestors()
        .find(|dir| dir.file_name() == Some(std::ffi::OsStr::new(DEFAULT_RUN_DIR_NAME)));
    if let Some(root) = root {
        let _ = ensure_self_ignored_dir(root);
    }
}

#[cfg(test)]
pub(crate) fn test_env_lock() -> &'static std::sync::Mutex<()> {
    use std::sync::{Mutex, OnceLock};
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
}

fn resolve_root_value(base_dir: &Path, env_value: Option<&str>, default_relative: &str) -> PathBuf {
    match env_value {
        Some(value) if !value.trim().is_empty() => {
            let candidate = PathBuf::from(value);
            if candidate.is_absolute() {
                candidate
            } else {
                base_dir.join(candidate)
            }
        }
        _ => base_dir.join(default_relative),
    }
}

pub fn state_root(base_dir: &Path) -> PathBuf {
    if let Some(root) = crate::persistent_state::current_persistent_state_root() {
        return root;
    }
    let state_env_value = std::env::var(HARN_STATE_DIR_ENV).ok();
    state_root_value(
        base_dir,
        state_env_value.as_deref(),
        nextest_attempt_root().as_deref(),
    )
}

pub(crate) fn captured_state_root(
    base_dir: &Path,
    launcher: &crate::security::LauncherEnvironment,
) -> PathBuf {
    if let Some(root) = launcher
        .captured_value("HARN_SESSION_STORE_ROOT")
        .filter(|root| !root.trim().is_empty())
    {
        return resolve_root_value(base_dir, Some(root), ".").join(".harn");
    }
    state_root_value(base_dir, launcher.captured_value(HARN_STATE_DIR_ENV), None)
}

/// Resolve the state root for a path stored in a portable record.
pub fn state_root_reference(base_dir: &Path) -> PathBuf {
    if let Some(root) = crate::persistent_state::current_persistent_state_root() {
        return root;
    }
    let state_env_value = std::env::var(HARN_STATE_DIR_ENV).ok();
    root_reference_value(
        base_dir,
        state_env_value.as_deref(),
        ".harn",
        nextest_attempt_root().as_deref(),
        None,
    )
}

pub fn run_root(base_dir: &Path) -> PathBuf {
    let run_env_value = std::env::var(HARN_RUN_DIR_ENV).ok();
    run_root_value(
        base_dir,
        run_env_value.as_deref(),
        nextest_attempt_root().as_deref(),
    )
}

/// Resolve the run root for a path stored in a portable record.
///
/// The ordinary checkout-local default remains the relative `.harn-runs`
/// reference existing records use. An explicit override or an isolated test
/// attempt names a different physical root and therefore remains absolute.
pub fn run_root_reference(base_dir: &Path) -> PathBuf {
    let run_env_value = std::env::var(HARN_RUN_DIR_ENV).ok();
    root_reference_value(
        base_dir,
        run_env_value.as_deref(),
        DEFAULT_RUN_DIR_NAME,
        nextest_attempt_root().as_deref(),
        Some("runs"),
    )
}

fn worktree_root_value(
    base_dir: &Path,
    state_env_value: Option<&str>,
    worktree_env_value: Option<&str>,
    nextest_root: Option<&Path>,
) -> PathBuf {
    match worktree_env_value {
        Some(value) if !value.trim().is_empty() => {
            let candidate = PathBuf::from(value);
            if candidate.is_absolute() {
                candidate
            } else {
                base_dir.join(candidate)
            }
        }
        _ => state_root_value(base_dir, state_env_value, nextest_root).join("worktrees"),
    }
}

pub fn worktree_root(base_dir: &Path) -> PathBuf {
    let state_env_value = std::env::var(HARN_STATE_DIR_ENV).ok();
    let worktree_env_value = std::env::var(HARN_WORKTREE_DIR_ENV).ok();
    if worktree_env_value
        .as_deref()
        .is_none_or(|value| value.trim().is_empty())
    {
        if let Some(root) = crate::persistent_state::current_persistent_state_root() {
            return root.join("worktrees");
        }
    }
    worktree_root_value(
        base_dir,
        state_env_value.as_deref(),
        worktree_env_value.as_deref(),
        nextest_attempt_root().as_deref(),
    )
}

pub fn store_path(base_dir: &Path) -> PathBuf {
    state_root(base_dir).join("store.json")
}

pub fn checkpoint_dir(base_dir: &Path) -> PathBuf {
    state_root(base_dir).join("checkpoints")
}

pub fn metadata_dir(base_dir: &Path) -> PathBuf {
    state_root(base_dir).join("metadata")
}

pub fn event_log_dir(base_dir: &Path) -> PathBuf {
    event_log_dir_at_state_root(&state_root(base_dir))
}

pub fn event_log_sqlite_path(base_dir: &Path) -> PathBuf {
    event_log_sqlite_path_at_state_root(&state_root(base_dir))
}

/// Event-log directory under an already-resolved state root.
///
/// Callers that own their state root exactly — an orchestrator told where to
/// keep its state, an embedder running concurrent isolated VMs — use this and
/// the sibling sqlite helper instead of the `base_dir` forms, which route
/// through [`state_root`] and therefore let an absolute `HARN_STATE_DIR`
/// discard the caller's path entirely.
pub fn event_log_dir_at_state_root(state_root: &Path) -> PathBuf {
    state_root.join("events")
}

/// Sqlite event-log path under an already-resolved state root. See
/// [`event_log_dir_at_state_root`].
pub fn event_log_sqlite_path_at_state_root(state_root: &Path) -> PathBuf {
    state_root.join("events.sqlite")
}

pub fn workflow_dir(base_dir: &Path) -> PathBuf {
    state_root(base_dir).join("workflows")
}

fn state_root_value(
    base_dir: &Path,
    state_env_value: Option<&str>,
    nextest_root: Option<&Path>,
) -> PathBuf {
    attempt_scoped_root_value(base_dir, state_env_value, ".harn", nextest_root, None)
}

fn run_root_value(
    base_dir: &Path,
    run_env_value: Option<&str>,
    nextest_root: Option<&Path>,
) -> PathBuf {
    attempt_scoped_root_value(
        base_dir,
        run_env_value,
        DEFAULT_RUN_DIR_NAME,
        nextest_root,
        Some("runs"),
    )
}

fn root_reference_value(
    base_dir: &Path,
    explicit_value: Option<&str>,
    default_relative: &str,
    nextest_root: Option<&Path>,
    nextest_child: Option<&str>,
) -> PathBuf {
    if explicit_value.is_none_or(|value| value.trim().is_empty()) && nextest_root.is_none() {
        PathBuf::from(default_relative)
    } else {
        attempt_scoped_root_value(
            base_dir,
            explicit_value,
            default_relative,
            nextest_root,
            nextest_child,
        )
    }
}

fn attempt_scoped_root_value(
    base_dir: &Path,
    explicit_value: Option<&str>,
    default_relative: &str,
    nextest_root: Option<&Path>,
    nextest_child: Option<&str>,
) -> PathBuf {
    if explicit_value.is_some_and(|value| !value.trim().is_empty()) {
        return resolve_root_value(base_dir, explicit_value, default_relative);
    }
    nextest_root
        .map(|root| nextest_child.map_or_else(|| root.to_path_buf(), |child| root.join(child)))
        .unwrap_or_else(|| base_dir.join(default_relative))
}

/// Nextest runs each test attempt in its own process and identifies that
/// attempt in the environment. Keep every default runtime root inside the
/// attempt instead of letting concurrent tests persist state, runs, or
/// worktrees into the checkout. Explicit root variables still win, and child
/// processes inherit the same Nextest identity.
fn nextest_attempt_root() -> Option<PathBuf> {
    std::env::var_os(NEXTEST_ENV)?;
    let identity = [
        std::env::var(NEXTEST_RUN_ID_ENV).ok()?,
        std::env::var(NEXTEST_BINARY_ID_ENV).ok()?,
        std::env::var(NEXTEST_TEST_NAME_ENV).ok()?,
        std::env::var(NEXTEST_ATTEMPT_ID_ENV).ok()?,
    ];
    Some(nextest_attempt_root_for_identity(
        &std::env::temp_dir(),
        identity.iter().map(String::as_str),
    ))
}

fn nextest_attempt_root_for_identity<'a>(
    temp_dir: &Path,
    identity: impl IntoIterator<Item = &'a str>,
) -> PathBuf {
    let mut hasher = Sha256::new();
    for part in identity {
        hasher.update((part.len() as u64).to_le_bytes());
        hasher.update(part.as_bytes());
    }
    let digest = hasher.finalize();
    temp_dir
        .join("harn-nextest-state")
        .join(hex::encode(&digest[..16]))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn defaults_resolve_under_base_dir() {
        let base = Path::new("/tmp/harn-runtime-paths");
        assert_eq!(resolve_root_value(base, None, ".harn"), base.join(".harn"));
        assert_eq!(
            resolve_root_value(base, None, ".harn-runs"),
            base.join(".harn-runs")
        );
        assert_eq!(
            worktree_root_value(base, None, None, None),
            base.join(".harn").join("worktrees")
        );
        assert_eq!(
            resolve_root_value(base, None, ".harn").join("events"),
            base.join(".harn").join("events")
        );
        assert_eq!(
            resolve_root_value(base, None, ".harn").join("workflows"),
            base.join(".harn").join("workflows")
        );
        assert_eq!(
            resolve_root_value(base, None, ".harn").join("events.sqlite"),
            base.join(".harn").join("events.sqlite")
        );
    }

    #[test]
    fn nextest_default_roots_are_attempt_scoped_but_explicit_roots_still_win() {
        let base = Path::new("/workspace");
        let temp = Path::new("/tmp");
        let first =
            nextest_attempt_root_for_identity(temp, ["run-1", "harn-vm", "test-a", "attempt-1"]);
        let same =
            nextest_attempt_root_for_identity(temp, ["run-1", "harn-vm", "test-a", "attempt-1"]);
        let other =
            nextest_attempt_root_for_identity(temp, ["run-1", "harn-vm", "test-b", "attempt-1"]);

        assert_eq!(first, same);
        assert_ne!(first, other);
        assert_eq!(state_root_value(base, None, Some(&first)), first);
        assert_eq!(run_root_value(base, None, Some(&first)), first.join("runs"));
        assert_eq!(
            root_reference_value(base, None, ".harn-runs", Some(&first), Some("runs")),
            first.join("runs")
        );
        assert_eq!(
            root_reference_value(base, None, ".harn", Some(&first), None),
            first
        );
        assert_eq!(
            worktree_root_value(base, None, None, Some(&first)),
            first.join("worktrees")
        );
        assert_eq!(
            state_root_value(base, Some("/operator/state"), Some(&other)),
            PathBuf::from("/operator/state")
        );
        assert_eq!(
            state_root_value(base, Some("relative-state"), Some(&other)),
            base.join("relative-state")
        );
        assert_eq!(
            run_root_value(base, Some("/operator/runs"), Some(&other)),
            PathBuf::from("/operator/runs")
        );
        assert_eq!(
            run_root_value(base, Some("relative-runs"), Some(&other)),
            base.join("relative-runs")
        );
        assert_eq!(
            root_reference_value(base, None, ".harn-runs", None, Some("runs")),
            PathBuf::from(".harn-runs")
        );
        assert_eq!(
            root_reference_value(
                base,
                Some("relative-runs"),
                ".harn-runs",
                Some(&other),
                Some("runs"),
            ),
            base.join("relative-runs")
        );
        assert_eq!(
            worktree_root_value(base, Some("/operator/state"), None, Some(&other)),
            PathBuf::from("/operator/state/worktrees")
        );
        assert_eq!(
            worktree_root_value(base, None, Some("relative-worktrees"), Some(&other)),
            base.join("relative-worktrees")
        );
    }
}