roteiro 0.0.18

Roteiro: a provenance-tagged knowledge graph for your codebase — structure, intent, and context in one queryable store
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
//! `roteiro init`: scaffold the graph and install the automation around it — the
//! `post-checkout` / `post-merge` / `post-commit` freshness hooks, a `pre-commit`
//! drift gate (Stage 16), and an `AGENTS.md` snippet.
//!
//! Everything written here is *managed*: each artifact carries a marker so a
//! re-run updates Roteiro's own content in place and never clobbers a user's
//! existing (foreign) hook or notes.

use std::fs;
use std::io;
use std::path::Path;

/// Marker identifying a Roteiro-managed git hook.
const HOOK_MARKER: &str = "roteiro-managed";
/// Marker identifying the Roteiro block in `AGENTS.md`.
const AGENTS_MARKER: &str = "<!-- roteiro-managed -->";

/// The git hooks Roteiro installs. `post-checkout`/`post-merge`/`post-commit`
/// keep the graph fresh after `HEAD` moves; `pre-commit` gates a commit that
/// introduces authored-vs-code drift (Stage 16).
pub const MANAGED_HOOKS: &[&str] = &["post-checkout", "post-merge", "post-commit", "pre-commit"];

/// The content of a managed hook `name`. Every hook guards on `roteiro` being
/// installed, so it is safe on machines without the tool.
///
/// `pre-commit` runs the **worktree-aware** `check` and blocks the commit on
/// drift (non-zero exit); `git commit --no-verify` skips it. The freshness hooks
/// run `sync --committed` and never fail the git operation.
///
/// When `fetch` is set (`roteiro init --fetch`), the freshness hooks first try to
/// download the CI-published graph artifact and `load` it — a fast path that
/// skips local extraction — falling back to a rebuild if `gh` is absent, the
/// download fails, or the artifact's tree does not match `HEAD` (`load` refuses a
/// stale artifact). Network only happens with this opt-in.
///
/// When `vault` is set (`roteiro init --vault`), the freshness hooks additionally
/// regenerate the local Obsidian vault from the fresh graph. `pre-commit` is
/// unaffected by either flag.
#[must_use]
pub fn hook_script(name: &str, fetch: bool, vault: bool) -> String {
    let header = format!(
        "#!/bin/sh\n\
         # {HOOK_MARKER}: Roteiro knowledge-graph automation.\n\
         # Delete this file to disable. Re-run `roteiro init` to reinstall.\n"
    );
    if name == "pre-commit" {
        return format!(
            "{header}\
             # Block a commit that introduces ADR/annotation drift. Validates the\n\
             # staged index — exactly what this commit will record. Skip once with\n\
             # `git commit --no-verify`.\n\
             command -v roteiro >/dev/null 2>&1 || exit 0\n\
             roteiro check --staged || {{\n\
             \techo 'roteiro: commit blocked by knowledge-graph drift (see above); \
             use `git commit --no-verify` to override.' >&2\n\
             \texit 1\n\
             }}\n"
        );
    }
    // Freshness hook: refresh the graph after HEAD moves, then — when
    // `roteiro init --vault` opted in — regenerate the local Obsidian vault so it
    // tracks the graph (a gitignored build-output, never committed).
    let mut body = if fetch {
        FETCH_REFRESH.to_owned()
    } else {
        "# Keep the Roteiro knowledge graph fresh after HEAD changes.\n\
         command -v roteiro >/dev/null 2>&1 && roteiro sync --committed >/dev/null 2>&1 || true\n"
            .to_owned()
    };
    if vault {
        body.push_str(VAULT_REFRESH);
    }
    format!("{header}{body}")
}

/// Appended to the freshness hooks by `--vault`: rebuild the local Obsidian vault
/// from the now-fresh graph. `render obsidian` syncs the graph itself and writes
/// to the gitignored `vault/` dir; best-effort, never failing the git operation.
const VAULT_REFRESH: &str = concat!(
    "# Regenerate the local Obsidian vault (gitignored build-output) to match.\n",
    "command -v roteiro >/dev/null 2>&1 && roteiro render obsidian >/dev/null 2>&1 || true\n",
);

/// The freshness-hook body used with `--fetch`: try the CI artifact, else rebuild.
/// Kept as a literal (no interpolation) so the shell `$tmp`/braces stay verbatim.
const FETCH_REFRESH: &str = concat!(
    "# Keep the Roteiro knowledge graph fresh after HEAD changes.\n",
    "command -v roteiro >/dev/null 2>&1 || exit 0\n",
    "# Opt-in fast path (`roteiro init --fetch`): try the CI-published graph\n",
    "# artifact before rebuilding. `roteiro load` refuses an artifact whose tree\n",
    "# does not match HEAD, so a stale asset falls through to a local rebuild.\n",
    "# A flag records success rather than `exit`ing, so any step appended below\n",
    "# (e.g. --vault's render) still runs.\n",
    "loaded=0\n",
    "if command -v gh >/dev/null 2>&1; then\n",
    "\t# Portable temp file: GNU `mktemp` needs no args; BSD/macOS needs a\n",
    "\t# template, so fall back to `-t`.\n",
    "\ttmp=$(mktemp 2>/dev/null || mktemp -t roteiro-graph 2>/dev/null) || tmp=\"\"\n",
    "\tif [ -n \"$tmp\" ] && \\\n",
    "\t\tgh release download graph-latest --pattern roteiro-graph.json \\\n",
    "\t\t\t--output \"$tmp\" --clobber >/dev/null 2>&1 && \\\n",
    "\t\troteiro load \"$tmp\" >/dev/null 2>&1; then\n",
    "\t\tloaded=1\n",
    "\tfi\n",
    "\t[ -n \"$tmp\" ] && rm -f \"$tmp\"\n",
    "fi\n",
    "# Rebuild locally only if the fast path didn't load a matching artifact.\n",
    "[ \"$loaded\" = 1 ] || roteiro sync --committed >/dev/null 2>&1 || true\n",
);

/// Whether `content` is a Roteiro-managed hook (safe to overwrite).
#[must_use]
pub fn is_managed_hook(content: &str) -> bool {
    content.contains(HOOK_MARKER)
}

/// The outcome of installing one hook.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookOutcome {
    /// The hook was newly created.
    Installed,
    /// An existing Roteiro-managed hook was refreshed.
    Updated,
    /// A pre-existing foreign hook was left untouched.
    SkippedForeign,
}

/// Install (or refresh) one managed hook in `hooks_dir`, without clobbering a
/// foreign hook of the same name. `fetch` selects the artifact-fast-path freshness
/// hooks, and `vault` appends local Obsidian-vault regeneration (see
/// [`hook_script`]).
///
/// # Errors
/// Returns [`io::Error`] on filesystem failure.
pub fn install_hook(
    hooks_dir: &Path,
    name: &str,
    fetch: bool,
    vault: bool,
) -> io::Result<HookOutcome> {
    fs::create_dir_all(hooks_dir)?;
    let path = hooks_dir.join(name);
    let outcome = match fs::read_to_string(&path) {
        Ok(existing) if is_managed_hook(&existing) => HookOutcome::Updated,
        Ok(_) => return Ok(HookOutcome::SkippedForeign),
        Err(e) if e.kind() == io::ErrorKind::NotFound => HookOutcome::Installed,
        Err(e) => return Err(e),
    };
    fs::write(&path, hook_script(name, fetch, vault))?;
    set_executable(&path)?;
    Ok(outcome)
}

#[cfg(unix)]
fn set_executable(path: &Path) -> io::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = fs::metadata(path)?.permissions();
    perms.set_mode(0o755);
    fs::set_permissions(path, perms)
}

#[cfg(not(unix))]
fn set_executable(_path: &Path) -> io::Result<()> {
    Ok(())
}

/// The Roteiro section for `AGENTS.md`, delimited by the managed marker so it
/// can be replaced in place on re-run.
#[must_use]
pub fn agents_section() -> String {
    format!(
        "{AGENTS_MARKER}\n\
         ## Roteiro knowledge graph\n\
         \n\
         This repository has a Roteiro knowledge graph — code structure, ADR intent,\n\
         and their links in one provenance-tagged store. Prefer querying it over\n\
         grepping when orienting:\n\
         \n\
         - `roteiro query <key> --json` — a node and its provenance-labelled edges.\n\
         Keys: `sym:<lang>:<path>#<Name>`, `file:<path>`, `adr:<id>`.\n\
         - `roteiro query --kind <kind> --json` — list nodes of a kind (`fn`, `adr`, …).\n\
         - `roteiro sync` — refresh the graph (git hooks do this automatically).\n\
         - `roteiro check` — validate ADR/annotation drift in the working tree.\n\
         Run it before finishing a change; a managed `pre-commit` hook also runs\n\
         it and blocks a drift-introducing commit (`git commit --no-verify` skips).\n\
         - `roteiro review [--json]` — a graph-grounded review of your current\n\
         change: each touched symbol's callers/callees and governing ADRs, the\n\
         drift and intent-debt it adds, and the dependents to re-check. Run it\n\
         before finishing to review against the graph, not just the diff.\n\
         {AGENTS_MARKER}\n"
    )
}

/// Ensure `AGENTS.md` at `path` contains the managed Roteiro section, replacing
/// an existing managed block or appending a new one. Returns `true` if the file
/// was created or changed.
///
/// # Errors
/// Returns [`io::Error`] on filesystem failure.
pub fn ensure_agents(path: &Path) -> io::Result<bool> {
    let section = agents_section();
    let existing = match fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) if e.kind() == io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e),
    };

    let updated = match managed_block_range(&existing) {
        Some((start, end)) => {
            let mut s = String::with_capacity(existing.len());
            s.push_str(&existing[..start]);
            s.push_str(section.trim_end());
            s.push_str(&existing[end..]);
            s
        }
        None if existing.is_empty() => section,
        None => {
            let mut s = existing.clone();
            if !s.ends_with('\n') {
                s.push('\n');
            }
            s.push('\n');
            s.push_str(&section);
            s
        }
    };

    if updated == existing {
        return Ok(false);
    }
    fs::write(path, updated)?;
    Ok(true)
}

/// Byte range of the managed block (marker … marker, inclusive), if present.
fn managed_block_range(content: &str) -> Option<(usize, usize)> {
    let start = content.find(AGENTS_MARKER)?;
    let after = start + AGENTS_MARKER.len();
    let second = content[after..].find(AGENTS_MARKER)? + after;
    Some((start, second + AGENTS_MARKER.len()))
}

#[cfg(test)]
mod tests {
    use super::{
        HookOutcome, agents_section, ensure_agents, hook_script, install_hook, is_managed_hook,
    };

    fn tmp(name: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("roteiro-init-{}-{name}", std::process::id()));
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).expect("mkdir");
        dir
    }

    #[test]
    fn hook_is_recognisable_and_self_guarding() {
        let s = hook_script("post-checkout", false, false);
        assert!(is_managed_hook(&s));
        assert!(s.starts_with("#!/bin/sh"));
        assert!(s.contains("command -v roteiro"));
        assert!(
            s.contains("roteiro sync --committed"),
            "freshness hook syncs"
        );
        // The default freshness hook does not touch the network or render a vault.
        assert!(!s.contains("gh release download"));
        assert!(!s.contains("render obsidian"), "vault render is opt-in");
        assert!(!is_managed_hook("#!/bin/sh\necho other\n"));
    }

    #[test]
    fn vault_flag_appends_vault_render_to_freshness_hooks_only() {
        // `--vault` adds a vault regeneration step to the freshness hooks…
        let fresh = hook_script("post-merge", false, true);
        assert!(
            fresh.contains("roteiro render obsidian"),
            "freshness hook regenerates the vault with --vault"
        );
        assert!(
            fresh.contains("roteiro sync --committed"),
            "still syncs first"
        );
        // …and composes with --fetch. The fetch fast path must set a flag on a
        // successful load rather than `exit`ing, or the appended vault render would
        // be unreachable (regression guard, Copilot on #173).
        let fetch_vault = hook_script("post-checkout", true, true);
        assert!(
            fetch_vault.contains("roteiro render obsidian"),
            "vault render is present with --fetch --vault"
        );
        assert!(
            fetch_vault.contains("loaded=1"),
            "fetch success records a flag, not an early exit"
        );
        assert!(
            !fetch_vault.contains("; exit 0"),
            "no early `exit 0` that would short-circuit the appended vault render"
        );
        // …but never touches the pre-commit gate.
        assert!(!hook_script("pre-commit", false, true).contains("render obsidian"));
    }

    #[test]
    fn fetch_hook_tries_artifact_then_falls_back_to_sync() {
        let s = hook_script("post-merge", true, false);
        assert!(is_managed_hook(&s));
        assert!(s.contains("command -v gh"), "guards on gh being installed");
        assert!(
            s.contains("gh release download graph-latest"),
            "fetches the CI artifact"
        );
        assert!(s.contains("roteiro load"), "loads the fetched artifact");
        assert!(
            s.contains("roteiro sync --committed"),
            "falls back to a local rebuild"
        );
        // Neither `--fetch` nor `--vault` alters the pre-commit gate.
        assert_eq!(
            hook_script("pre-commit", true, true),
            hook_script("pre-commit", false, false)
        );
    }

    #[test]
    fn pre_commit_hook_gates_on_check_and_is_skippable() {
        let s = hook_script("pre-commit", false, false);
        assert!(is_managed_hook(&s));
        assert!(s.contains("command -v roteiro"), "guards on install");
        assert!(s.contains("roteiro check"), "runs the worktree-aware check");
        assert!(s.contains("exit 1"), "blocks the commit on drift");
        assert!(s.contains("--no-verify"), "documents the escape hatch");
        // Distinct from the freshness hooks — it must not just sync.
        assert!(!s.contains("roteiro sync"));
    }

    #[test]
    fn install_creates_updates_and_skips_foreign() {
        let dir = tmp("hooks");
        let hooks = dir.join("hooks");

        // First install → created.
        assert_eq!(
            install_hook(&hooks, "post-checkout", false, false).expect("install"),
            HookOutcome::Installed
        );
        let path = hooks.join("post-checkout");
        assert!(path.exists());
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o111, 0o111, "hook should be executable");
        }

        // Second install → updated (managed).
        assert_eq!(
            install_hook(&hooks, "post-checkout", false, false).expect("reinstall"),
            HookOutcome::Updated
        );

        // A foreign hook is left untouched.
        let foreign = hooks.join("post-merge");
        std::fs::write(&foreign, "#!/bin/sh\necho mine\n").unwrap();
        assert_eq!(
            install_hook(&hooks, "post-merge", false, false).expect("skip"),
            HookOutcome::SkippedForeign
        );
        assert_eq!(
            std::fs::read_to_string(&foreign).unwrap(),
            "#!/bin/sh\necho mine\n"
        );

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn agents_created_updated_and_idempotent() {
        let dir = tmp("agents");
        let path = dir.join("AGENTS.md");

        // Created.
        assert!(ensure_agents(&path).expect("create"));
        let first = std::fs::read_to_string(&path).unwrap();
        assert!(first.contains("Roteiro knowledge graph"));

        // Idempotent: no change on re-run.
        assert!(!ensure_agents(&path).expect("noop"));
        assert_eq!(std::fs::read_to_string(&path).unwrap(), first);

        // Appends after pre-existing content, and replaces only the managed block.
        std::fs::write(&path, "# My agents\n\nHello.\n").unwrap();
        assert!(ensure_agents(&path).expect("append"));
        let merged = std::fs::read_to_string(&path).unwrap();
        assert!(merged.starts_with("# My agents"));
        assert!(merged.contains("Roteiro knowledge graph"));
        // Exactly one managed block (two markers).
        assert_eq!(merged.matches("<!-- roteiro-managed -->").count(), 2);

        // Re-running after manual edits still yields a single managed block.
        assert!(!ensure_agents(&path).expect("noop2"));
        assert_eq!(
            agents_section().matches("<!-- roteiro-managed -->").count(),
            2
        );

        std::fs::remove_dir_all(&dir).ok();
    }
}