netsky-core 0.1.2

netsky core: agent model, prompt loader, spawner, config
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
//! Filesystem paths used across the netsky runtime.

use std::path::{Path, PathBuf};

use chrono::Utc;

use crate::Result;
use crate::consts::{
    AGENT0_CRASHLOOP_MARKER, AGENT0_HANG_MARKER, AGENT0_HANG_PAGED_MARKER, AGENT0_INBOX_SUBDIR,
    AGENT0_PANE_HASH_FILE, AGENT0_QUIET_UNTIL_PREFIX, AGENT0_RESTART_ATTEMPTS_FILE,
    AGENTINFINITY_READY_MARKER, AGENTINIT_ESCALATION_MARKER, AGENTINIT_FAILURES_FILE,
    CRASH_HANDOFF_FILENAME_PREFIX, CRASH_HANDOFF_FILENAME_SUFFIX, CRASH_HANDOFFS_SUBDIR,
    ENV_NETSKY_DIR, HANDOFF_ARCHIVE_SUBDIR, LAUNCHD_LABEL, LAUNCHD_PLIST_SUBDIR, LOOP_RESUME_FILE,
    NETSKY_DIR_DEFAULT_SUBDIR, PROMPTS_SUBDIR, RESTART_ARCHIVE_SUBDIR,
    RESTART_DETACHED_LOG_FILENAME, RESTART_STATUS_SUBDIR, STATE_DIR, TICKER_MISSING_COUNT_FILE,
};

pub fn home() -> PathBuf {
    dirs::home_dir().expect("netsky requires a home directory")
}

/// Resolve the canonical netsky source-checkout root. Resolution order:
///
/// 1. `$NETSKY_DIR` if set and a valid netsky checkout (sentinel files
///    present per [`is_valid_netsky_dir`]).
/// 2. `$HOME/netsky` if it exists and is a valid checkout.
/// 3. Walk up from the current working directory looking for a valid
///    checkout (lets clones work from `workspaces/<task>/repo`).
///
/// Returns `None` if no candidate was valid. Callers that need a hard
/// path use [`require_netsky_cwd`] which produces a usage-shaped error.
pub fn resolve_netsky_dir() -> Option<PathBuf> {
    if let Ok(env) = std::env::var(ENV_NETSKY_DIR) {
        let p = PathBuf::from(env);
        if is_valid_netsky_dir(&p) {
            return Some(p);
        }
    }
    let home_default = home().join(NETSKY_DIR_DEFAULT_SUBDIR);
    if is_valid_netsky_dir(&home_default) {
        return Some(home_default);
    }
    let cwd = std::env::current_dir().ok()?;
    walk_up_to_netsky_dir(&cwd)
}

/// Walk from `start` toward the filesystem root looking for a directory
/// satisfying [`is_valid_netsky_dir`]. Returns the first match. Used as
/// the dev escape hatch when the user is in `workspaces/<task>/repo`
/// (a valid netsky checkout deeper in the tree) and `$NETSKY_DIR` is
/// unset.
pub fn walk_up_to_netsky_dir(start: &Path) -> Option<PathBuf> {
    for ancestor in start.ancestors() {
        if is_valid_netsky_dir(ancestor) {
            return Some(ancestor.to_path_buf());
        }
    }
    None
}

/// A "valid netsky checkout" requires both sentinel files. Picking two
/// (`prompts/base.md` AND `src/crates/netsky-cli/Cargo.toml`) defends
/// against half-populated or moved trees: a workspace clone always has
/// both; an empty `~/netsky/` placeholder has neither; a rust crate
/// elsewhere on disk has the Cargo.toml but not the prompts file.
pub fn is_valid_netsky_dir(p: &Path) -> bool {
    p.join("prompts/base.md").is_file() && p.join("src/crates/netsky-cli/Cargo.toml").is_file()
}

/// Hard-exit guard for side-effecting top-level commands. Returns Ok if
/// the current working directory matches the resolved netsky dir;
/// otherwise prints a one-line stderr message naming the expected dir
/// and exits the process with code 2.
///
/// Skipping the gate on read-only commands (doctor, attach, --help) is
/// deliberate: those should work from anywhere so the operator can
/// diagnose a misconfigured machine without first fighting the cwd.
pub fn require_netsky_cwd(command_name: &str) -> std::io::Result<()> {
    let resolved = match resolve_netsky_dir() {
        Some(p) => p,
        None => {
            eprintln!(
                "netsky: refusing to run `{command_name}`: no valid netsky checkout found.\n\
                 expected `prompts/base.md` and `src/crates/netsky-cli/Cargo.toml` under \
                 $NETSKY_DIR, $HOME/netsky, or any ancestor of cwd. set NETSKY_DIR or run \
                 from inside a netsky source tree."
            );
            std::process::exit(2);
        }
    };
    let cwd = std::env::current_dir()?;
    let cwd_canon = std::fs::canonicalize(&cwd).unwrap_or(cwd);
    let resolved_canon = std::fs::canonicalize(&resolved).unwrap_or(resolved.clone());
    if cwd_canon != resolved_canon {
        eprintln!(
            "netsky: refusing to run `{command_name}` from {}; expected cwd is {} \
             ($NETSKY_DIR or $HOME/netsky). cd there and retry, or set NETSKY_DIR if you \
             have moved the checkout.",
            cwd_canon.display(),
            resolved_canon.display(),
        );
        std::process::exit(2);
    }
    Ok(())
}

pub fn state_dir() -> PathBuf {
    home().join(STATE_DIR)
}

pub fn prompts_dir() -> PathBuf {
    home().join(PROMPTS_SUBDIR)
}

/// Directory holding crash-handoff drafts written by the watchdog on
/// crash-recovery. Lives under the durable state dir so the macOS /tmp
/// reaper does not eat pending handoffs after ~3 days.
pub fn crash_handoffs_dir() -> PathBuf {
    home().join(CRASH_HANDOFFS_SUBDIR)
}

/// Canonical crash-handoff path for a given pid under [`crash_handoffs_dir`].
pub fn crash_handoff_file_for(pid: u32) -> PathBuf {
    crash_handoffs_dir().join(format!(
        "{CRASH_HANDOFF_FILENAME_PREFIX}{pid}{CRASH_HANDOFF_FILENAME_SUFFIX}"
    ))
}

/// Path to the on-disk system-prompt file for `agent_name`. The spawner
/// atomically writes the rendered prompt here and sets `NETSKY_PROMPT_FILE`
/// to this path so the tmux-spawned shell can `cat` it at exec time.
pub fn prompt_file_for(agent_name: &str) -> PathBuf {
    prompts_dir().join(format!("{agent_name}.md"))
}

/// Refuse to traverse any symlink under `root` on the path to `target`.
///
/// Missing components are allowed so callers can still `create_dir_all`
/// the destination afterward. This keeps channel writes and drains from
/// following a tampered inbox tree out of the netsky state directory.
pub fn assert_no_symlink_under(root: &Path, target: &Path) -> Result<()> {
    let rel = match target.strip_prefix(root) {
        Ok(r) => r,
        Err(_) => crate::bail!(
            "internal: target {} is not under channel root {}",
            target.display(),
            root.display()
        ),
    };
    if let Ok(meta) = std::fs::symlink_metadata(root)
        && meta.file_type().is_symlink()
    {
        crate::bail!("refusing to operate on symlinked root {}", root.display());
    }
    let mut cur = root.to_path_buf();
    for comp in rel.components() {
        cur.push(comp);
        match std::fs::symlink_metadata(&cur) {
            Ok(meta) if meta.file_type().is_symlink() => {
                crate::bail!("refusing to traverse symlink at {}", cur.display());
            }
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(e) => return Err(e.into()),
        }
    }
    Ok(())
}

pub fn agentinfinity_ready_marker() -> PathBuf {
    home().join(AGENTINFINITY_READY_MARKER)
}

pub fn agentinit_escalation_marker() -> PathBuf {
    home().join(AGENTINIT_ESCALATION_MARKER)
}

pub fn agentinit_failures_file() -> PathBuf {
    home().join(AGENTINIT_FAILURES_FILE)
}

pub fn agent0_pane_hash_file() -> PathBuf {
    home().join(AGENT0_PANE_HASH_FILE)
}

pub fn agent0_hang_marker() -> PathBuf {
    home().join(AGENT0_HANG_MARKER)
}

pub fn agent0_hang_paged_marker() -> PathBuf {
    home().join(AGENT0_HANG_PAGED_MARKER)
}

/// P0-1 crashloop sliding-window attempts file. Newline-delimited unix
/// ts; pruned by the watchdog on every append.
pub fn agent0_restart_attempts_file() -> PathBuf {
    home().join(AGENT0_RESTART_ATTEMPTS_FILE)
}

/// P0-1 crashloop marker. Presence = the watchdog has fired escalation
/// for a sustained restart-failure pattern; cleared on the first
/// healthy tick after recovery.
pub fn agent0_crashloop_marker() -> PathBuf {
    home().join(AGENT0_CRASHLOOP_MARKER)
}

/// P0-2 restart-status directory. The detached `netsky restart` child
/// writes `<ts>-<pid>.json` files here at known phase transitions.
pub fn restart_status_dir() -> PathBuf {
    home().join(RESTART_STATUS_SUBDIR)
}

/// P1-4 restart-archive directory. Forensic home for the detached
/// restart log + archived stale-processing files. Out of the /tmp
/// reaper window; swept on age by the watchdog tick preflight.
pub fn restart_archive_dir() -> PathBuf {
    home().join(RESTART_ARCHIVE_SUBDIR)
}

/// Canonical path for the detached restart subprocess stdout+stderr log.
pub fn restart_detached_log_path() -> PathBuf {
    restart_archive_dir().join(RESTART_DETACHED_LOG_FILENAME)
}

pub fn ticker_missing_count_file() -> PathBuf {
    home().join(TICKER_MISSING_COUNT_FILE)
}

pub fn watchdog_event_log_for(day: &str) -> PathBuf {
    state_dir().join(format!("netsky-io-watchdog.{day}.log"))
}

pub fn watchdog_event_log_path() -> PathBuf {
    watchdog_event_log_for(&Utc::now().format("%Y-%m-%d").to_string())
}

/// Path for a quiet sentinel that expires at `epoch` (unix seconds). The
/// filename embeds the epoch so multiple arms can co-exist transiently
/// and the watchdog picks the max. `netsky quiet <seconds>` writes one.
pub fn agent0_quiet_sentinel_for(epoch: u64) -> PathBuf {
    state_dir().join(format!("{AGENT0_QUIET_UNTIL_PREFIX}{epoch}"))
}

/// Filename prefix used by the watchdog to glob for quiet sentinels.
pub fn agent0_quiet_sentinel_prefix() -> &'static str {
    AGENT0_QUIET_UNTIL_PREFIX
}

pub fn loop_resume_file() -> PathBuf {
    home().join(LOOP_RESUME_FILE)
}

pub fn handoff_archive_dir() -> PathBuf {
    home().join(HANDOFF_ARCHIVE_SUBDIR)
}

pub fn agent0_inbox_dir() -> PathBuf {
    home().join(AGENT0_INBOX_SUBDIR)
}

pub fn launchd_plist_path() -> PathBuf {
    home()
        .join(LAUNCHD_PLIST_SUBDIR)
        .join(format!("{LAUNCHD_LABEL}.plist"))
}

/// Ensure the state directory exists. Idempotent.
pub fn ensure_state_dir() -> std::io::Result<()> {
    std::fs::create_dir_all(state_dir())
}

/// Resolve the netsky source-checkout root, falling back to the
/// current working directory with a stderr warning. Used by spawn
/// pathways (`cmd::agent::run`, `cmd::up::run`) so a clone always
/// lands its tmux session on the netsky root, regardless of which
/// random subdir agent0 happened to be in when it called `netsky
/// agent N`.
///
/// Closes the spawn-cwd-pin gap from `briefs/clone-cwd-pin.md`
/// (agent5): the `prompts/clone.md` stanza promises clones a netsky
/// cwd, but `current_dir()` would silently inherit `workspaces/foo/`
/// when agent0 wandered there. Now the resolver is consulted first.
///
/// The fallback is intentional defense-in-depth: if no checkout
/// resolves at all, today's behavior is preserved (spawn from
/// whatever cwd) plus a one-line warning so the operator can see the
/// degraded path. Same risk envelope as before, with a better steady
/// state on top.
pub fn netsky_root_or_cwd() -> std::io::Result<PathBuf> {
    if let Some(p) = resolve_netsky_dir() {
        return Ok(p);
    }
    let cwd = std::env::current_dir()?;
    eprintln!(
        "netsky: WARNING: no NETSKY_DIR resolved; spawn cwd falls back to {} \
         (clone may inherit a non-netsky checkout). set NETSKY_DIR or run from \
         inside the source tree to silence.",
        cwd.display()
    );
    Ok(cwd)
}

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

    fn make_valid_checkout(root: &Path) {
        fs::create_dir_all(root.join("prompts")).unwrap();
        fs::write(root.join("prompts/base.md"), "# base").unwrap();
        fs::create_dir_all(root.join("src/crates/netsky-cli")).unwrap();
        fs::write(
            root.join("src/crates/netsky-cli/Cargo.toml"),
            "[package]\nname = \"netsky\"\n",
        )
        .unwrap();
    }

    #[test]
    fn is_valid_netsky_dir_requires_both_sentinels() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(!is_valid_netsky_dir(tmp.path()), "empty dir should fail");

        // Just one sentinel = still invalid.
        fs::create_dir_all(tmp.path().join("prompts")).unwrap();
        fs::write(tmp.path().join("prompts/base.md"), "x").unwrap();
        assert!(
            !is_valid_netsky_dir(tmp.path()),
            "only base.md present should fail"
        );

        // Both sentinels = valid.
        fs::create_dir_all(tmp.path().join("src/crates/netsky-cli")).unwrap();
        fs::write(tmp.path().join("src/crates/netsky-cli/Cargo.toml"), "x").unwrap();
        assert!(
            is_valid_netsky_dir(tmp.path()),
            "both sentinels should pass"
        );
    }

    #[test]
    fn walk_up_finds_valid_ancestor() {
        let tmp = tempfile::tempdir().unwrap();
        make_valid_checkout(tmp.path());
        let nested = tmp.path().join("workspaces/iroh-v0/repo");
        fs::create_dir_all(&nested).unwrap();
        let found = walk_up_to_netsky_dir(&nested).expect("should find ancestor");
        assert_eq!(
            fs::canonicalize(&found).unwrap(),
            fs::canonicalize(tmp.path()).unwrap()
        );
    }

    #[test]
    fn walk_up_returns_none_when_no_ancestor_valid() {
        let tmp = tempfile::tempdir().unwrap();
        let nested = tmp.path().join("a/b/c");
        fs::create_dir_all(&nested).unwrap();
        assert!(walk_up_to_netsky_dir(&nested).is_none());
    }

    #[test]
    fn resolve_prefers_env_var_when_set_and_valid() {
        let tmp = tempfile::tempdir().unwrap();
        make_valid_checkout(tmp.path());
        let prior = std::env::var(ENV_NETSKY_DIR).ok();
        unsafe {
            std::env::set_var(ENV_NETSKY_DIR, tmp.path());
        }
        let resolved = resolve_netsky_dir().expect("env-var path should resolve");
        assert_eq!(
            fs::canonicalize(&resolved).unwrap(),
            fs::canonicalize(tmp.path()).unwrap()
        );
        unsafe {
            match prior {
                Some(v) => std::env::set_var(ENV_NETSKY_DIR, v),
                None => std::env::remove_var(ENV_NETSKY_DIR),
            }
        }
    }

    #[test]
    fn resolve_skips_env_var_when_invalid() {
        let tmp = tempfile::tempdir().unwrap();
        // Empty tmp (no sentinels) — env-var should be skipped, fall
        // through to $HOME/netsky default OR walk-up.
        let prior = std::env::var(ENV_NETSKY_DIR).ok();
        unsafe {
            std::env::set_var(ENV_NETSKY_DIR, tmp.path());
        }
        let resolved = resolve_netsky_dir();
        // The actual repo (the test runner's cwd ancestor) should still
        // resolve via walk-up. We don't assert WHICH dir wins, only that
        // the invalid env-var path is NOT what came back.
        if let Some(p) = resolved {
            assert_ne!(
                fs::canonicalize(&p).unwrap(),
                fs::canonicalize(tmp.path()).unwrap(),
                "invalid env-var path leaked through"
            );
        }
        unsafe {
            match prior {
                Some(v) => std::env::set_var(ENV_NETSKY_DIR, v),
                None => std::env::remove_var(ENV_NETSKY_DIR),
            }
        }
    }
}