nodus 0.15.1

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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
use std::fs;
use std::path::Path;

use anyhow::{Context, Result, bail};
use serde_json::{Map, Value, json};

use crate::adapters::{
    ArtifactKind, ManagedActivationHook, ManagedArtifactNames, ManagedFile, ManagedHookSpec,
    hook_tool_matchers_for_adapter, managed_artifact_id, managed_artifact_path, managed_skill_root,
};
use crate::agent_format::{
    default_codex_agent_description, emitted_codex_agent_toml,
    emitted_codex_agent_toml_from_markdown,
};
use crate::hashing::blake3_hex;
use crate::lockfile::LockedPackage;
use crate::manifest::{AgentEntry, FileEntry, SkillEntry};
use crate::manifest::{HookEvent, HookHandlerType, HookSessionSource};
use crate::paths::strip_path_prefix;
use crate::resolver::ResolvedPackage;

pub const SYNTHETIC_COMMAND_SKILL_PREFIX: &str = "__cmd_";
const SYNTHETIC_COMMAND_BODY_MARKER: &str = "<!-- nodus:command-body -->";

pub fn skill_files(
    names: &ManagedArtifactNames,
    project_root: &Path,
    package: &ResolvedPackage,
    snapshot_root: &Path,
    skill: &SkillEntry,
) -> Result<Vec<ManagedFile>> {
    copy_directory(
        managed_skill_root(
            names,
            project_root,
            crate::adapters::Adapter::Codex,
            package,
            &skill.id,
        ),
        snapshot_root.join(&skill.path),
    )
}

pub fn agent_file(
    names: &ManagedArtifactNames,
    project_root: &Path,
    package: &ResolvedPackage,
    snapshot_root: &Path,
    agent: &AgentEntry,
) -> Result<ManagedFile> {
    let target_path = managed_artifact_path(
        names,
        project_root,
        crate::adapters::Adapter::Codex,
        ArtifactKind::Agent,
        package,
        &agent.id,
    )
    .expect("codex agent path");
    let source_path = snapshot_root.join(&agent.path);
    let source_contents = fs::read(&source_path)
        .with_context(|| format!("failed to read snapshot file {}", source_path.display()))?;
    let managed_name = managed_artifact_id(names, package, ArtifactKind::Agent, &agent.id);
    let contents = if agent.is_toml() {
        let runtime_name = (managed_name != agent.id).then_some(managed_name.as_str());
        emitted_codex_agent_toml(
            &source_contents,
            runtime_name,
            &format!("Codex agent source {}", source_path.display()),
        )?
    } else {
        emitted_codex_agent_toml_from_markdown(
            &source_contents,
            &managed_name,
            &default_codex_agent_description(&agent.id),
            &format!("Codex agent source {}", source_path.display()),
        )?
    };

    Ok(ManagedFile {
        path: target_path,
        contents,
    })
}

pub fn command_skill_file(
    names: &ManagedArtifactNames,
    project_root: &Path,
    package: &ResolvedPackage,
    snapshot_root: &Path,
    command: &FileEntry,
) -> Result<ManagedFile> {
    let skill_id = synthetic_command_skill_id(names, package, &command.id);
    let source_path = snapshot_root.join(&command.path);
    let source_contents = fs::read(&source_path)
        .with_context(|| format!("failed to read snapshot file {}", source_path.display()))?;
    let contents = emitted_command_skill_markdown(
        &source_contents,
        &skill_id,
        &command.id,
        &format!("Codex command source {}", source_path.display()),
    )?;

    Ok(ManagedFile {
        path: managed_skill_root(
            names,
            project_root,
            crate::adapters::Adapter::Codex,
            package,
            &skill_id,
        )
        .join("SKILL.md"),
        contents,
    })
}

pub fn synthetic_command_skill_id(
    names: &ManagedArtifactNames,
    package: &ResolvedPackage,
    command_id: &str,
) -> String {
    synthetic_command_skill_id_from_managed_command_id(&managed_artifact_id(
        names,
        package,
        ArtifactKind::Command,
        command_id,
    ))
}

pub fn synthetic_locked_command_skill_id(
    names: &ManagedArtifactNames,
    package: &LockedPackage,
    command_id: &str,
) -> String {
    synthetic_command_skill_id_from_managed_command_id(
        &crate::adapters::locked_managed_artifact_id(
            names,
            package,
            ArtifactKind::Command,
            command_id,
        ),
    )
}

pub fn synthetic_command_skill_id_from_managed_command_id(managed_command_id: &str) -> String {
    format!("{SYNTHETIC_COMMAND_SKILL_PREFIX}{managed_command_id}")
}

pub fn source_command_id_from_synthetic_skill_id(skill_id: &str) -> Result<&str> {
    skill_id.strip_prefix(SYNTHETIC_COMMAND_SKILL_PREFIX).ok_or_else(|| {
        anyhow::anyhow!(
            "synthetic Codex command skill id `{skill_id}` must start with `{SYNTHETIC_COMMAND_SKILL_PREFIX}`"
        )
    })
}

pub fn emitted_command_skill_markdown(
    source: &[u8],
    skill_id: &str,
    command_id: &str,
    source_label: &str,
) -> Result<Vec<u8>> {
    source_command_id_from_synthetic_skill_id(skill_id)?;
    let source = std::str::from_utf8(source)
        .with_context(|| format!("{source_label} must be UTF-8 to emit a Codex skill"))?;

    let mut emitted = format!(
        concat!(
            "---\n",
            "name: {skill_id}\n",
            "description: Synthetic Codex compatibility skill generated from the `{command_id}` command.\n",
            "---\n",
            "# {skill_id}\n\n",
            "This skill is generated by Nodus from the `{command_id}` command for Codex compatibility.\n",
            "Edit the command body below to relay changes back to the source command.\n\n",
            "{marker}\n"
        ),
        skill_id = skill_id,
        command_id = command_id,
        marker = SYNTHETIC_COMMAND_BODY_MARKER,
    )
    .into_bytes();
    emitted.extend_from_slice(source.as_bytes());
    Ok(emitted)
}

pub fn command_body_from_synthetic_skill(
    managed: &[u8],
    skill_id: &str,
    source_label: &str,
) -> Result<Vec<u8>> {
    source_command_id_from_synthetic_skill_id(skill_id)?;
    let managed =
        std::str::from_utf8(managed).with_context(|| format!("{source_label} must be UTF-8"))?;
    let Some(marker_start) = managed.find(SYNTHETIC_COMMAND_BODY_MARKER) else {
        bail!("{source_label} is missing the `{SYNTHETIC_COMMAND_BODY_MARKER}` marker");
    };
    let after_marker = &managed[marker_start + SYNTHETIC_COMMAND_BODY_MARKER.len()..];
    let body_start = if after_marker.starts_with("\r\n") {
        2
    } else if after_marker.starts_with('\n') {
        1
    } else if after_marker.is_empty() {
        0
    } else {
        bail!("{source_label} must place `{SYNTHETIC_COMMAND_BODY_MARKER}` on its own line");
    };
    Ok(after_marker.as_bytes()[body_start..].to_vec())
}

fn copy_directory(
    target_root: impl AsRef<Path>,
    source_root: impl AsRef<Path>,
) -> Result<Vec<ManagedFile>> {
    let target_root = target_root.as_ref();
    let source_root = source_root.as_ref();
    let mut files = Vec::new();

    for entry in walkdir::WalkDir::new(source_root) {
        let entry = entry?;
        if entry.file_type().is_file() {
            let relative = entry.path();
            let relative = strip_path_prefix(relative, source_root)
                .with_context(|| format!("failed to make {} relative", entry.path().display()))?;
            files.push(ManagedFile {
                path: target_root.join(relative),
                contents: fs::read(entry.path()).with_context(|| {
                    format!("failed to read snapshot file {}", entry.path().display())
                })?,
            });
        }
    }

    files.sort_by(|left, right| left.path.cmp(&right.path));
    Ok(files)
}

pub fn hook_files(
    project_root: &Path,
    hooks: &[ManagedHookSpec],
    activation_hooks: &[ManagedActivationHook],
) -> Result<Vec<ManagedFile>> {
    let hooks_path = project_root.join(".codex/hooks.json");
    let mut files = hooks
        .iter()
        .map(|hook| ManagedFile {
            path: project_root.join(managed_script_relative_path(hook)),
            contents: hook_script_contents(hook),
        })
        .collect::<Vec<_>>();
    for activation_hook in activation_hooks {
        files.push(ManagedFile {
            path: project_root.join(activation_script_relative_path(activation_hook)),
            contents: activation_script_contents(activation_hook)?,
        });
    }
    files.push(ManagedFile {
        path: hooks_path.clone(),
        contents: merged_hooks_contents(&hooks_path, hooks, activation_hooks)?,
    });
    Ok(files)
}

fn merged_hooks_contents(
    path: &Path,
    hooks: &[ManagedHookSpec],
    activation_hooks: &[ManagedActivationHook],
) -> Result<Vec<u8>> {
    let mut root = if path.exists() {
        serde_json::from_slice::<Value>(
            &fs::read(path)
                .with_context(|| format!("failed to read existing {}", path.display()))?,
        )
        .with_context(|| format!("failed to parse existing {}", path.display()))?
    } else {
        Value::Object(Map::new())
    };

    let root_object = root
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("{} must contain a JSON object", path.display()))?;
    let hooks_object = object_field(root_object, "hooks", path)?;
    remove_managed_hook_entries(hooks_object);
    for hook in hooks {
        array_field(hooks_object, event_name(hook), path)?.push(hook_entry(hook));
    }
    for activation_hook in activation_hooks {
        array_field(hooks_object, "SessionStart", path)?
            .push(activation_hook_entry(activation_hook));
    }

    let mut contents =
        serde_json::to_vec_pretty(&root).context("failed to serialize Codex hooks")?;
    contents.push(b'\n');
    Ok(contents)
}

fn object_field<'a>(
    object: &'a mut Map<String, Value>,
    key: &str,
    path: &Path,
) -> Result<&'a mut Map<String, Value>> {
    let value = object
        .entry(key.to_string())
        .or_insert_with(|| Value::Object(Map::new()));
    value.as_object_mut().ok_or_else(|| {
        anyhow::anyhow!(
            "{} field `{key}` must contain a JSON object",
            path.display()
        )
    })
}

fn array_field<'a>(
    object: &'a mut Map<String, Value>,
    key: &str,
    path: &Path,
) -> Result<&'a mut Vec<Value>> {
    let value = object
        .entry(key.to_string())
        .or_insert_with(|| Value::Array(Vec::new()));
    value.as_array_mut().ok_or_else(|| {
        anyhow::anyhow!("{} field `{key}` must contain a JSON array", path.display())
    })
}

fn hook_entry(hook: &ManagedHookSpec) -> Value {
    let hook_value = json!({
        "type": "command",
        "command": managed_hook_command(hook),
    });
    if let Some(matcher) = matcher_string(hook) {
        json!({
            "matcher": matcher,
            "hooks": [hook_value],
        })
    } else {
        json!({
            "hooks": [hook_value],
        })
    }
}

fn activation_hook_entry(hook: &ManagedActivationHook) -> Value {
    json!({
        "matcher": "startup|resume",
        "hooks": [{
            "type": "command",
            "command": activation_hook_command(hook),
        }],
    })
}

fn remove_managed_hook_entries(hooks: &mut Map<String, Value>) {
    for event in [
        "SessionStart",
        "UserPromptSubmit",
        "PreToolUse",
        "PermissionRequest",
        "PostToolUse",
        "Stop",
    ] {
        let Some(entries) = hooks.get_mut(event).and_then(Value::as_array_mut) else {
            continue;
        };
        entries.retain(|entry| !entry_is_managed(entry));
    }
}

fn entry_is_managed(entry: &Value) -> bool {
    entry
        .get("hooks")
        .and_then(Value::as_array)
        .is_some_and(|hooks| {
            hooks.iter().any(|hook| {
                hook.get("type").and_then(Value::as_str) == Some("command")
                    && hook
                        .get("command")
                        .and_then(Value::as_str)
                        .is_some_and(|command| command.contains("/.codex/hooks/nodus-hook-"))
            })
        })
}

fn managed_hook_command(hook: &ManagedHookSpec) -> String {
    managed_hook_command_from_relative_path(&managed_script_relative_path(hook))
}

fn activation_hook_command(hook: &ManagedActivationHook) -> String {
    managed_hook_command_from_relative_path(&activation_script_relative_path(hook))
}

fn managed_hook_command_from_relative_path(relative_path: &str) -> String {
    format!(
        r#"sh "$(git rev-parse --show-toplevel 2>/dev/null || pwd)/{}""#,
        relative_path
    )
}

fn managed_script_relative_path(hook: &ManagedHookSpec) -> String {
    format!(".codex/hooks/{}.sh", managed_script_stem(hook))
}

fn activation_script_relative_path(hook: &ManagedActivationHook) -> String {
    format!(".codex/hooks/{}.sh", activation_script_stem(hook))
}

fn managed_script_stem(hook: &ManagedHookSpec) -> String {
    let sanitized = hook
        .hook
        .id
        .chars()
        .map(|character| match character {
            'a'..='z' | '0'..='9' => character,
            'A'..='Z' => character.to_ascii_lowercase(),
            _ => '-',
        })
        .collect::<String>();
    if hook.emitted_from_root {
        format!(
            "nodus-hook-{sanitized}-{}",
            &blake3_hex(hook.hook.id.as_bytes())[..8]
        )
    } else {
        let package = hook
            .package_alias
            .chars()
            .map(|character| match character {
                'a'..='z' | '0'..='9' => character,
                'A'..='Z' => character.to_ascii_lowercase(),
                _ => '-',
            })
            .collect::<String>();
        format!(
            "nodus-hook-{package}-{sanitized}-{}",
            &blake3_hex(format!("{}:{}", hook.package_alias, hook.hook.id).as_bytes())[..8]
        )
    }
}

fn activation_script_stem(hook: &ManagedActivationHook) -> String {
    let package = sanitized_script_segment(&hook.package_alias);
    format!(
        "nodus-hook-activation-{package}-{}",
        &blake3_hex(format!("activation:{}", hook.package_alias).as_bytes())[..8]
    )
}

fn sanitized_script_segment(value: &str) -> String {
    value
        .chars()
        .map(|character| match character {
            'a'..='z' | '0'..='9' => character,
            'A'..='Z' => character.to_ascii_lowercase(),
            _ => '-',
        })
        .collect()
}

fn event_name(hook: &ManagedHookSpec) -> &'static str {
    match hook.hook.event {
        HookEvent::SessionStart => "SessionStart",
        HookEvent::UserPromptSubmit => "UserPromptSubmit",
        HookEvent::PreToolUse => "PreToolUse",
        HookEvent::PermissionRequest => "PermissionRequest",
        HookEvent::PostToolUse => "PostToolUse",
        HookEvent::Stop => "Stop",
        HookEvent::SubagentStop | HookEvent::SessionEnd => {
            unreachable!("unsupported hook event for Codex")
        }
    }
}

fn matcher_string(hook: &ManagedHookSpec) -> Option<String> {
    match hook.hook.event {
        HookEvent::SessionStart => {
            let matcher = hook
                .hook
                .matcher
                .as_ref()
                .map(|matcher| matcher.sources.as_slice())
                .unwrap_or_default();
            let sources = if matcher.is_empty() {
                vec![HookSessionSource::Startup, HookSessionSource::Resume]
            } else {
                matcher
                    .iter()
                    .copied()
                    .filter(|source| {
                        matches!(
                            source,
                            HookSessionSource::Startup | HookSessionSource::Resume
                        )
                    })
                    .collect::<Vec<_>>()
            };
            (!sources.is_empty()).then(|| {
                sources
                    .into_iter()
                    .map(|source| source.as_str())
                    .collect::<Vec<_>>()
                    .join("|")
            })
        }
        HookEvent::PreToolUse | HookEvent::PermissionRequest | HookEvent::PostToolUse => {
            let matcher =
                hook_tool_matchers_for_adapter(&hook.hook, crate::adapters::Adapter::Codex);
            if matcher.is_empty() {
                Some("*".to_string())
            } else {
                Some(matcher.join("|"))
            }
        }
        HookEvent::UserPromptSubmit | HookEvent::Stop => None,
        HookEvent::SubagentStop | HookEvent::SessionEnd => {
            unreachable!("unsupported hook event for Codex")
        }
    }
}

fn hook_script_contents(hook: &ManagedHookSpec) -> Vec<u8> {
    debug_assert!(matches!(
        hook.hook.handler.handler_type,
        HookHandlerType::Command
    ));
    format!(
        r#"#!/bin/sh
set -eu

project_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
if [ {cwd} = "git_root" ]; then
  cd "$project_root"
fi

export NODUS_HOOK_ID={hook_id}
export NODUS_HOOK_EVENT={hook_event}
{timeout_export}
if [ {blocking} = "true" ]; then
  exec sh -lc {command}
fi

if ! sh -lc {command}; then
  echo "nodus hook {hook_label} failed" >&2
fi
"#,
        cwd = shell_quote(match hook.hook.handler.cwd {
            crate::manifest::HookWorkingDirectory::GitRoot => "git_root",
            crate::manifest::HookWorkingDirectory::Session => "session",
        }),
        hook_id = shell_quote(&hook.hook.id),
        hook_event = shell_quote(hook.hook.event.as_str()),
        timeout_export = hook
            .hook
            .timeout_sec
            .map(|timeout_sec| format!(
                "export NODUS_HOOK_TIMEOUT_SEC={}\n",
                shell_quote(&timeout_sec.to_string())
            ))
            .unwrap_or_default(),
        blocking = shell_quote(if hook.hook.blocking { "true" } else { "false" }),
        command = shell_quote(&hook.hook.handler.command),
        hook_label = hook.hook.id,
    )
    .into_bytes()
}

fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', r#"'"'"'"#))
}

fn activation_script_contents(hook: &ManagedActivationHook) -> Result<Vec<u8>> {
    let output = json!({
        "hookSpecificOutput": {
            "hookEventName": "SessionStart",
            "additionalContext": hook.context,
        },
    });
    Ok(format!(
        "#!/bin/sh\nset -eu\n\ncat <<'NODUS_ACTIVATION_JSON'\n{}\nNODUS_ACTIVATION_JSON\n",
        serde_json::to_string(&output)
            .context("failed to serialize Codex activation hook output")?
    )
    .into_bytes())
}

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

    #[test]
    fn synthetic_command_skill_round_trips_command_body() {
        let managed = emitted_command_skill_markdown(
            b"# Build\ncargo test\n",
            "__cmd_build",
            "build",
            "Codex command source",
        )
        .unwrap();

        assert_eq!(
            command_body_from_synthetic_skill(&managed, "__cmd_build", "Codex command source")
                .unwrap(),
            b"# Build\ncargo test\n"
        );
    }

    #[test]
    fn synthetic_command_skill_requires_reserved_prefix() {
        let error = emitted_command_skill_markdown(
            b"cargo test\n",
            "build",
            "build",
            "Codex command source",
        )
        .unwrap_err()
        .to_string();

        assert!(error.contains(SYNTHETIC_COMMAND_SKILL_PREFIX));
    }
}