notarai 0.2.0

CLI validator for NotarAI spec files
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
use std::fs;
use std::path::Path;

const HOOK_COMMAND: &str = "notarai hook validate";

const RECONCILE_MD: &str = include_str!("../../commands/notarai-reconcile.md");
const BOOTSTRAP_MD: &str = include_str!("../../commands/notarai-bootstrap.md");
const NOTARAI_README_TEMPLATE: &str = include_str!("../../templates/notarai-readme.md");
const SCHEMA_JSON: &str = include_str!("../../notarai.spec.json");

/// The section written to / replaced in CLAUDE.md. Exactly 3 lines plus trailing newline.
const NOTARAI_SECTION: &str = "## NotarAI\n@.notarai/README.md\n@.notarai/notarai.spec.json\n";

fn has_notarai_hook(matchers: &[serde_json::Value]) -> bool {
    matchers.iter().any(|m| {
        m.get("hooks")
            .and_then(|h| h.as_array())
            .is_some_and(|hooks| {
                hooks
                    .iter()
                    .any(|h| h.get("command").and_then(|c| c.as_str()) == Some(HOOK_COMMAND))
            })
    })
}

/// Replace the `## NotarAI` section in `content` with `new_section`.
///
/// The section spans from the `## NotarAI` line up to (but not including) the
/// next `## ` heading, or EOF. If no section is found, `content` is returned
/// unchanged.
pub fn replace_notarai_section(content: &str, new_section: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();

    let start = match lines.iter().position(|&l| l == "## NotarAI") {
        Some(i) => i,
        None => return content.to_string(),
    };

    let end = lines[start + 1..]
        .iter()
        .position(|l| l.starts_with("## "))
        .map(|i| start + 1 + i)
        .unwrap_or(lines.len());

    let before_lines = &lines[..start];
    let after_lines = &lines[end..];

    let mut result = String::new();

    for line in before_lines {
        result.push_str(line);
        result.push('\n');
    }

    result.push_str(new_section);
    if !new_section.ends_with('\n') {
        result.push('\n');
    }

    if !after_lines.is_empty() {
        for line in after_lines {
            result.push_str(line);
            result.push('\n');
        }
    }

    result
}

/// Find `## NotarAI` at the start of a line and return the section content
/// up to the next `## ` heading or EOF. Used only in tests.
#[cfg(test)]
fn extract_notarai_section(content: &str) -> String {
    let start = content
        .lines()
        .enumerate()
        .find(|(_, line)| *line == "## NotarAI")
        .map(|(i, _)| i);

    let start = match start {
        Some(s) => s,
        None => return String::new(),
    };

    let lines: Vec<&str> = content.lines().collect();

    let end = lines[start + 1..]
        .iter()
        .enumerate()
        .find(|(_, line)| line.starts_with("## "))
        .map(|(i, _)| start + 1 + i)
        .unwrap_or(lines.len());

    let section: Vec<&str> = lines[start..end].to_vec();
    let result = section.join("\n");
    format!("{}\n", result.trim_end())
}

/// Set up NotarAI in the target project directory.
pub fn run(project_root: Option<&Path>) -> i32 {
    let root = match project_root {
        Some(p) => p.to_path_buf(),
        None => std::env::current_dir().unwrap_or_else(|_| Path::new(".").to_path_buf()),
    };

    let claude_dir = root.join(".claude");
    let notarai_dir = root.join(".notarai");

    if !claude_dir.exists()
        && let Err(e) = fs::create_dir_all(&claude_dir)
    {
        eprintln!("Error: could not create .claude/ directory: {e}");
        return 1;
    }

    let mut settings: serde_json::Value = {
        let settings_path = claude_dir.join("settings.json");
        if settings_path.exists() {
            match fs::read_to_string(&settings_path) {
                Ok(content) => match serde_json::from_str(&content) {
                    Ok(v) => v,
                    Err(_) => {
                        eprintln!("Error: could not parse existing .claude/settings.json");
                        return 1;
                    }
                },
                Err(_) => {
                    eprintln!("Error: could not read .claude/settings.json");
                    return 1;
                }
            }
        } else {
            serde_json::json!({})
        }
    };

    // Ensure hooks.PostToolUse exists
    if settings.get("hooks").is_none() {
        settings["hooks"] = serde_json::json!({});
    }
    if settings["hooks"].get("PostToolUse").is_none() {
        settings["hooks"]["PostToolUse"] = serde_json::json!([]);
    }

    let post_tool_use = settings["hooks"]["PostToolUse"]
        .as_array()
        .cloned()
        .unwrap_or_default();

    if has_notarai_hook(&post_tool_use) {
        println!("NotarAI hook already configured in .claude/settings.json");
    } else {
        let hook_entry = serde_json::json!({
            "matcher": "Write|Edit",
            "hooks": [{
                "type": "command",
                "command": HOOK_COMMAND
            }]
        });

        settings["hooks"]["PostToolUse"]
            .as_array_mut()
            .unwrap()
            .push(hook_entry);

        let settings_path = claude_dir.join("settings.json");
        let content = serde_json::to_string_pretty(&settings).unwrap() + "\n";
        if let Err(e) = fs::write(&settings_path, content) {
            eprintln!("Error: could not write .claude/settings.json: {e}");
            return 1;
        }
        println!("Added NotarAI validation hook to .claude/settings.json");
    }

    // Create .notarai/ if it doesn't exist
    if !notarai_dir.exists()
        && let Err(e) = fs::create_dir_all(&notarai_dir)
    {
        eprintln!("Error: could not create .notarai/ directory: {e}");
        return 1;
    }

    setup_schema(&notarai_dir);
    setup_notarai_readme(&notarai_dir);
    setup_command("notarai-reconcile", RECONCILE_MD, &claude_dir);
    setup_command("notarai-bootstrap", BOOTSTRAP_MD, &claude_dir);
    setup_claude_context(&root);
    setup_gitignore(&root);
    setup_mcp_json(&root);

    0
}

fn setup_schema(notarai_dir: &Path) {
    let dest_path = notarai_dir.join("notarai.spec.json");

    if let Err(e) = fs::write(&dest_path, SCHEMA_JSON) {
        eprintln!("Warning: could not write notarai.spec.json: {e}");
        return;
    }

    println!("Copied schema to .notarai/notarai.spec.json");
}

fn setup_notarai_readme(notarai_dir: &Path) {
    let version = env!("CARGO_PKG_VERSION");
    let content = NOTARAI_README_TEMPLATE.replace("{{VERSION}}", version);
    let dest_path = notarai_dir.join("README.md");

    if let Err(e) = fs::write(&dest_path, content) {
        eprintln!("Warning: could not write .notarai/README.md: {e}");
        return;
    }

    println!("Wrote .notarai/README.md");
}

fn setup_claude_context(project_dir: &Path) {
    let claude_md_path = project_dir.join("CLAUDE.md");

    if claude_md_path.exists() {
        let existing = match fs::read_to_string(&claude_md_path) {
            Ok(c) => c,
            Err(_) => return,
        };

        let has_section = existing.lines().any(|line| line == "## NotarAI");

        let new_content = if has_section {
            replace_notarai_section(&existing, NOTARAI_SECTION)
        } else {
            let mut content = existing;
            if !content.is_empty() && !content.ends_with('\n') {
                content.push('\n');
            }
            content.push('\n');
            content.push_str(NOTARAI_SECTION);
            content
        };

        if let Err(e) = fs::write(&claude_md_path, new_content) {
            eprintln!("Warning: could not update CLAUDE.md: {e}");
            return;
        }
        if has_section {
            println!("Updated NotarAI section in CLAUDE.md");
        } else {
            println!("Added NotarAI context to CLAUDE.md");
        }
    } else {
        if let Err(e) = fs::write(&claude_md_path, NOTARAI_SECTION) {
            eprintln!("Warning: could not create CLAUDE.md: {e}");
            return;
        }
        println!("Added NotarAI context to CLAUDE.md");
    }
}

fn setup_command(name: &str, content: &str, claude_dir: &Path) {
    let commands_dir = claude_dir.join("commands");

    if let Err(e) = fs::create_dir_all(&commands_dir) {
        eprintln!("Warning: could not create .claude/commands/ directory: {e}");
        return;
    }

    let dest_path = commands_dir.join(format!("{name}.md"));

    if let Err(e) = fs::write(&dest_path, content) {
        eprintln!("Warning: could not write {name}.md: {e}");
        return;
    }

    println!("Updated .claude/commands/{name}.md");
}

fn setup_gitignore(project_dir: &Path) {
    let gitignore_path = project_dir.join(".gitignore");
    let cache_entry = ".notarai/.cache/";

    let existing = if gitignore_path.exists() {
        match fs::read_to_string(&gitignore_path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("Warning: could not read .gitignore: {e}");
                return;
            }
        }
    } else {
        String::new()
    };

    if existing.lines().any(|line| line == cache_entry) {
        println!(".notarai/.cache/ already in .gitignore");
        return;
    }

    let mut content = existing;
    if !content.is_empty() && !content.ends_with('\n') {
        content.push('\n');
    }
    content.push_str(cache_entry);
    content.push('\n');

    if let Err(e) = fs::write(&gitignore_path, content) {
        eprintln!("Warning: could not update .gitignore: {e}");
        return;
    }

    println!("Added .notarai/.cache/ to .gitignore");
}

fn setup_mcp_json(project_root: &Path) {
    let mcp_path = project_root.join(".mcp.json");

    let notarai_entry = serde_json::json!({
        "type": "stdio",
        "command": "notarai",
        "args": ["mcp"]
    });

    if mcp_path.exists() {
        let content = match fs::read_to_string(&mcp_path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("Warning: could not read .mcp.json: {e}");
                return;
            }
        };

        let mut json: serde_json::Value =
            serde_json::from_str(&content).unwrap_or(serde_json::json!({}));

        if json
            .get("mcpServers")
            .and_then(|s| s.get("notarai"))
            .is_some()
        {
            println!("NotarAI MCP server already configured in .mcp.json");
            return;
        }

        if json.get("mcpServers").is_none() {
            json["mcpServers"] = serde_json::json!({});
        }
        json["mcpServers"]["notarai"] = notarai_entry;

        let out = serde_json::to_string_pretty(&json).unwrap() + "\n";
        if let Err(e) = fs::write(&mcp_path, out) {
            eprintln!("Warning: could not update .mcp.json: {e}");
            return;
        }
        println!("Added notarai MCP server to .mcp.json");
    } else {
        let content = serde_json::to_string_pretty(&serde_json::json!({
            "mcpServers": {
                "notarai": notarai_entry
            }
        }))
        .unwrap()
            + "\n";

        if let Err(e) = fs::write(&mcp_path, content) {
            eprintln!("Warning: could not write .mcp.json: {e}");
            return;
        }
        println!("Added NotarAI MCP server to .mcp.json");
    }
}

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

    #[test]
    fn extracts_section_from_start_to_eof() {
        let content = "## NotarAI\n\nSome content here.\n";
        let result = extract_notarai_section(content);
        assert_eq!(result, "## NotarAI\n\nSome content here.\n");
    }

    #[test]
    fn extracts_section_between_headings() {
        let content = "## Intro\n\nIntro text.\n\n## NotarAI\n\nNotarAI content.\n\n## Other\n\nOther content.\n";
        let result = extract_notarai_section(content);
        assert_eq!(result, "## NotarAI\n\nNotarAI content.\n");
    }

    #[test]
    fn returns_empty_when_not_found() {
        let content = "## Intro\n\nNo notarai here.\n";
        let result = extract_notarai_section(content);
        assert_eq!(result, "");
    }

    #[test]
    fn replace_section_at_eof() {
        let content = "# Project\n\n## NotarAI\n\nOld content.\n";
        let result = replace_notarai_section(content, "## NotarAI\nnew\n");
        assert_eq!(result, "# Project\n\n## NotarAI\nnew\n");
    }

    #[test]
    fn replace_section_with_following_heading() {
        let content = "# Project\n\n## NotarAI\n\nOld.\n\n## Other\n\nAfter.\n";
        let result = replace_notarai_section(content, "## NotarAI\nnew\n");
        assert_eq!(result, "# Project\n\n## NotarAI\nnew\n## Other\n\nAfter.\n");
    }

    #[test]
    fn replace_returns_unchanged_when_no_section() {
        let content = "## Intro\n\nNo notarai.\n";
        let result = replace_notarai_section(content, "## NotarAI\nnew\n");
        assert_eq!(result, content);
    }
}