nodus 0.15.0

Local-first CLI for managing project-scoped agent packages.
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
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result, bail};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use tokio::sync::mpsc;

use super::{
    RelaySummary, dependency_context, display_relative, load_workspace, mappings,
    relay_dependency_in_dir, resolve_existing_link,
};
use crate::adapters::Adapter;
use crate::lockfile::LOCKFILE_NAME;
use crate::manifest::MANIFEST_FILE;
use crate::report::Reporter;

#[derive(Debug, Clone, PartialEq, Eq)]
struct RelayWatchState {
    config: BTreeMap<PathBuf, PathFingerprint>,
    managed: BTreeMap<String, BTreeMap<PathBuf, PathFingerprint>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum PathFingerprint {
    Missing,
    Directory,
    File([u8; 32]),
}

#[derive(Debug, Clone, Copy)]
pub(super) struct RelayWatchOptions {
    pub(super) debounce: Duration,
    pub(super) fallback_interval: Duration,
    pub(super) max_events: Option<usize>,
    pub(super) timeout: Option<Duration>,
}

impl Default for RelayWatchOptions {
    fn default() -> Self {
        Self {
            debounce: Duration::from_millis(100),
            fallback_interval: Duration::from_secs(30),
            max_events: None,
            timeout: None,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub(super) struct RelayWatchInvocation<'a> {
    pub(super) repo_path_override: Option<&'a Path>,
    pub(super) via_override: Option<Adapter>,
    pub(super) create_missing: bool,
    pub(super) options: RelayWatchOptions,
}

pub(super) async fn watch_dependency_in_dir_with_options(
    project_root: &Path,
    cache_root: &Path,
    package: &str,
    invocation: RelayWatchInvocation<'_>,
    reporter: &Reporter,
) -> Result<Vec<RelaySummary>> {
    let packages = vec![package.to_string()];
    watch_dependencies_in_dir_impl_with_options(
        project_root,
        cache_root,
        &packages,
        invocation,
        reporter,
    )
    .await
}

pub(super) async fn watch_dependencies_in_dir_with_options(
    project_root: &Path,
    cache_root: &Path,
    packages: &[String],
    invocation: RelayWatchInvocation<'_>,
    reporter: &Reporter,
) -> Result<Vec<RelaySummary>> {
    watch_dependencies_in_dir_impl_with_options(
        project_root,
        cache_root,
        packages,
        invocation,
        reporter,
    )
    .await
}

async fn watch_dependencies_in_dir_impl_with_options(
    project_root: &Path,
    cache_root: &Path,
    packages: &[String],
    invocation: RelayWatchInvocation<'_>,
    reporter: &Reporter,
) -> Result<Vec<RelaySummary>> {
    if packages.is_empty() {
        bail!("relay watch requires at least one dependency");
    }
    if packages.len() > 1 && invocation.repo_path_override.is_some() {
        bail!("`nodus relay --repo-path` requires exactly one dependency");
    }

    // Initial relay pass.
    let mut summaries = Vec::with_capacity(packages.len());
    for package in packages {
        let summary = relay_dependency_in_dir(
            project_root,
            cache_root,
            package,
            invocation.repo_path_override,
            invocation.via_override,
            invocation.create_missing,
            reporter,
        )?;
        reporter.finish(format!(
            "relayed {} into {}; created {} and updated {} source files",
            summary.alias,
            display_relative(project_root, &summary.linked_repo),
            summary.created_file_count,
            summary.updated_file_count,
        ))?;
        summaries.push(summary);
    }

    let mut state = capture_watch_state(project_root, cache_root, packages, reporter)?;

    // Set up notify watcher.
    let (tx, mut rx) = mpsc::channel(256);
    let watcher_result = setup_watcher(&state, project_root, tx);
    let _watcher = match watcher_result {
        Ok(watcher) => {
            reporter.note("watching managed outputs for changes; press Ctrl-C to stop")?;
            Some(watcher)
        }
        Err(err) => {
            reporter.warning(format!(
                "failed to initialize file watcher ({err:#}); falling back to periodic polling"
            ))?;
            reporter.note("watching managed outputs for changes; press Ctrl-C to stop")?;
            None
        }
    };

    let deadline = invocation
        .options
        .timeout
        .map(|t| tokio::time::Instant::now() + t);

    loop {
        if invocation
            .options
            .max_events
            .is_some_and(|max| summaries.len() >= max)
        {
            return Ok(summaries);
        }

        let remaining_until_deadline =
            deadline.map(|instant| instant.saturating_duration_since(tokio::time::Instant::now()));
        let fallback_wait = fallback_wait_interval(
            invocation.options.fallback_interval,
            remaining_until_deadline,
        );

        // Wait for a notify event, fallback timeout, deadline, or ctrl-c.
        tokio::select! {
            _ = rx.recv() => {
                // Debounce: wait briefly then drain any queued events.
                tokio::time::sleep(invocation.options.debounce).await;
                while rx.try_recv().is_ok() {}
            }
            _ = tokio::time::sleep(fallback_wait) => {}
            _ = async {
                match deadline {
                    Some(d) => tokio::time::sleep_until(d).await,
                    None => std::future::pending().await,
                }
            } => {
                return Ok(summaries);
            }
            _ = tokio::signal::ctrl_c() => {
                return Ok(summaries);
            }
        }

        let next_state = capture_watch_state(project_root, cache_root, packages, reporter)?;
        let config_changed = next_state.config != state.config;
        let changed_packages = changed_watch_packages(&state, &next_state);
        if !config_changed && changed_packages.is_empty() {
            continue;
        }

        state = next_state;
        if changed_packages.is_empty() {
            reporter.note("reloaded relay watch inputs")?;
            continue;
        }

        for package in changed_packages {
            reporter.status("Watching", format!("detected managed edits for {package}"))?;
            let summary = relay_dependency_in_dir(
                project_root,
                cache_root,
                &package,
                None,
                None,
                invocation.create_missing,
                reporter,
            )?;
            reporter.finish(format!(
                "relayed {} into {}; created {} and updated {} source files",
                summary.alias,
                display_relative(project_root, &summary.linked_repo),
                summary.created_file_count,
                summary.updated_file_count,
            ))?;
            summaries.push(summary);
        }
    }
}

fn setup_watcher(
    state: &RelayWatchState,
    project_root: &Path,
    tx: mpsc::Sender<()>,
) -> Result<RecommendedWatcher> {
    let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
        if res.is_ok() {
            let _ = tx.blocking_send(());
        }
    })?;

    // Watch config files (non-recursive).
    for path in state.config.keys() {
        if path.exists() {
            let watch_path = if path.is_file() {
                path.parent().unwrap_or(project_root)
            } else {
                path.as_path()
            };
            let _ = watcher.watch(watch_path, RecursiveMode::NonRecursive);
        }
    }

    // Watch managed output directories (recursive).
    let mut watched_dirs = BTreeSet::new();
    for package_managed in state.managed.values() {
        for path in package_managed.keys() {
            if let Some(parent) = path.parent() {
                let mut candidate = parent;
                while let Some(grandparent) = candidate.parent() {
                    if grandparent == project_root || !grandparent.starts_with(project_root) {
                        break;
                    }
                    candidate = grandparent;
                }
                if watched_dirs.insert(candidate.to_path_buf()) && candidate.exists() {
                    watcher.watch(candidate, RecursiveMode::Recursive)?;
                }
            }
        }
    }

    Ok(watcher)
}

fn changed_watch_packages(previous: &RelayWatchState, next: &RelayWatchState) -> Vec<String> {
    let mut aliases = previous
        .managed
        .keys()
        .chain(next.managed.keys())
        .cloned()
        .collect::<BTreeSet<_>>();
    aliases.retain(|alias| previous.managed.get(alias) != next.managed.get(alias));
    aliases.into_iter().collect()
}

fn capture_watch_state(
    project_root: &Path,
    cache_root: &Path,
    packages: &[String],
    reporter: &Reporter,
) -> Result<RelayWatchState> {
    let workspace = load_workspace(project_root, cache_root, reporter)?;
    let managed_names = crate::adapters::ManagedArtifactNames::from_resolved_packages(
        workspace.resolution.packages.iter(),
    );
    let mut managed = BTreeMap::new();
    for package in packages {
        let dependency = dependency_context(&workspace, package)?;
        let linked_repo = resolve_existing_link(&workspace.local_config, &dependency)?;
        let mappings = mappings::build_mappings(
            &managed_names,
            &workspace.resolution.packages,
            &dependency,
            &workspace.project_root,
            workspace.selected_adapters,
            &linked_repo,
        )?;

        let mut package_managed = BTreeMap::new();
        for path in mappings.into_iter().map(|mapping| mapping.managed_path) {
            package_managed
                .entry(path.clone())
                .or_insert(path_fingerprint(&path)?);
        }
        managed.insert(dependency.alias.clone(), package_managed);
    }

    let adapter_markers = [
        ".agents",
        ".claude",
        ".codex",
        ".github/skills",
        ".github/agents",
        ".cursor",
        ".opencode",
        "AGENTS.md",
    ];
    let mut config = BTreeMap::new();
    for path in [
        project_root.join(MANIFEST_FILE),
        project_root.join(LOCKFILE_NAME),
        crate::local_config::config_path(project_root),
    ] {
        config.insert(path.clone(), path_fingerprint(&path)?);
    }
    for marker in adapter_markers {
        let path = project_root.join(marker);
        config.insert(path.clone(), path_fingerprint(&path)?);
    }

    Ok(RelayWatchState { config, managed })
}

fn fallback_wait_interval(
    fallback_interval: Duration,
    remaining_until_deadline: Option<Duration>,
) -> Duration {
    const MIN_DEADLINE_POLL_INTERVAL: Duration = Duration::from_millis(50);

    match remaining_until_deadline {
        None => fallback_interval,
        Some(remaining) if remaining.is_zero() => Duration::ZERO,
        Some(remaining) => {
            let deadline_interval = (remaining / 2)
                .max(MIN_DEADLINE_POLL_INTERVAL)
                .min(remaining);
            fallback_interval.min(deadline_interval)
        }
    }
}

fn path_fingerprint(path: &Path) -> Result<PathFingerprint> {
    let metadata = match fs::metadata(path) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Ok(PathFingerprint::Missing);
        }
        Err(error) => {
            return Err(error).with_context(|| format!("failed to inspect {}", path.display()));
        }
    };

    if metadata.is_dir() {
        return Ok(PathFingerprint::Directory);
    }
    if !metadata.is_file() {
        return Ok(PathFingerprint::Missing);
    }

    let contents = fs::read(path)
        .with_context(|| format!("failed to read watched file {}", path.display()))?;
    let hash: [u8; 32] = *blake3::hash(&contents).as_bytes();
    Ok(PathFingerprint::File(hash))
}

#[cfg(test)]
mod tests {
    use super::fallback_wait_interval;
    use std::time::Duration;

    #[test]
    fn keeps_configured_poll_interval_without_deadline() {
        assert_eq!(
            fallback_wait_interval(Duration::from_secs(30), None),
            Duration::from_secs(30)
        );
    }

    #[test]
    fn caps_poll_interval_to_leave_time_before_deadline() {
        assert_eq!(
            fallback_wait_interval(Duration::from_secs(30), Some(Duration::from_secs(5))),
            Duration::from_millis(2500)
        );
    }

    #[test]
    fn keeps_shorter_poll_interval_when_it_already_fits_before_deadline() {
        assert_eq!(
            fallback_wait_interval(Duration::from_millis(100), Some(Duration::from_secs(5))),
            Duration::from_millis(100)
        );
    }
}