Skip to main content

greengate_runtime/
agents_md.rs

1//! `amont agents-md` — a self-verifying pointer for coding agents.
2//!
3//! Deliberately NOT a prose contract and NOT a list of check names: both
4//! drift from what the registry actually enforces the moment a check is
5//! added, removed, or its severity changes — see `amont-fleet`'s
6//! `severities` module doc for the canonical shape of that failure. This
7//! generates a short block that instead tells an agent to ask
8//! `amont list --json`, which cannot go stale because it IS the registry.
9//!
10//! Never touches anything outside its own markers. An `AGENTS.md` a
11//! repository already wrote is the repository's, not this tool's, to
12//! rewrite — matching `amont.conf`'s "declared, never assumed" posture.
13
14use std::ops::Range;
15use std::path::Path;
16
17pub const START: &str = "<!-- amont:start -->";
18pub const END: &str = "<!-- amont:end -->";
19
20/// The block, START and END inclusive, always ending in exactly one newline.
21///
22/// The branch paragraph is rendered from `vocabulary::BRANCH_PREFIXES` — the
23/// table `pre-push-branch-pattern` enforces — precisely so this file cannot
24/// become a second, driftable copy of the rule. What the block says and what
25/// the hook rejects are the same constant.
26pub fn generate_block(settings: &crate::config::Settings) -> String {
27    let clocks = |secs: u64| match secs {
28        0 => "no limit".to_string(),
29        s => crate::hooks::common::human_secs(s),
30    };
31    let idle = clocks(crate::hooks::common::idle_timeout(settings));
32    let ceiling = clocks(crate::hooks::common::check_timeout(settings));
33    let prefixes = crate::vocabulary::BRANCH_PREFIXES
34        .iter()
35        .map(|p| p.name)
36        .collect::<Vec<_>>()
37        .join(", ");
38    format!(
39        "{START}\n\
40\n\
41## Git hooks (amont)\n\
42\n\
43This repository enforces pre-commit / pre-push checks. Ask the registry\n\
44rather than guessing before assuming a change is safe:\n\
45\n\
46```sh\n\
47amont list --json\n\
48amont list --json --stage pre-push --pushed  # exactly what pushing next gates\n\
49```\n\
50\n\
51Each check reports its _effective_ severity (`block`/`warn`, including any\n\
52`amont.severity.*` override) and whether it fires here. The same output\n\
53carries `commit_style`: the subject and description limits `commit-msg`\n\
54enforces, and where the type's gitmoji is placed. It also carries\n\
55`branch_style`: name a branch `<prefix>/<name>` BEFORE creating it —\n\
56prefixes are {prefixes} — because `pre-push` refuses a\n\
57new branch that breaks the pattern, at the end of the work instead of the\n\
58start.\n\
59\n\
60`git commit` and `git push` both run their checks first, and neither is\n\
61instant: pre-commit can invoke formatters, linters or clippy (a workspace\n\
62build), and pre-push gates include the test suite. Push with `amont land`:\n\
63it runs every push gate the push owes on a snapshot of the exact commit,\n\
64with no connection open, then pushes, and the push itself skips them (git\n\
65connects before pre-push runs, and a remote may drop the idle session while a\n\
66suite runs). A bare `git push` whose push gates have not run on its tree is\n\
67refused at once (`amont.pushGates refuse`, the default): run `amont land`, or\n\
68`amont rehearse --wait` (or `amont run --stamp`) first and push again. Push a\n\
69release tag with `amont land --tag <name>`: it runs the release audits on the\n\
70tagged commit first, which a branch rehearsal never does. Where\n\
71`amont.rehearseOnCommit` is on, every commit already starts that rehearsal in\n\
72the background and `--wait` only follows it. Give these commands the\n\
73longest timeout your tooling allows, never its default: here a check is\n\
74killed only after {idle} of silence or {ceiling} in total\n\
75(`amont.idleTimeout` / `amont.timeout`) — and on Linux and macOS a silent\n\
76check whose processes are busy on CPU is not \"silent\": it can run to the\n\
77{ceiling} ceiling. A check waiting on a cargo or uv lock answers to\n\
78`amont.lockWait` instead, the silence budget stretches with the machine's\n\
79load (`amont.idleLoadScale`), and a heavy check (clippy, a test suite) may\n\
80first queue for a host slot (`amont.hostSlots`) while other worktrees run\n\
81theirs. A test suite may legitimately run for most of that. If your tooling caps a foreground command below it,\n\
82run the command in the background and read its result when it exits —\n\
83while it runs, a line a minute on stderr says which check is alive and\n\
84when it last printed. A push killed mid-suite pushed nothing; a commit\n\
85killed mid-check committed nothing, and your unstaged work stays parked\n\
86until the next run says how to recover it. Neither is the checks failing —\n\
87it is the timeout. Run both bare and check the effect (`git log --oneline\n\
88-1`, `git ls-remote origin <branch>`): trimming their output with `| tail`\n\
89reports the pipe's exit status, so a killed or rejected run reads as\n\
90success.\n\
91\n\
92Never bypass with `--no-verify`. To change enforcement, downgrade it\n\
93intentionally instead:\n\
94\n\
95```sh\n\
96git config amont.severity.<check-id> warn\n\
97```\n\
98\n\
99`commit-msg` takes neither `hook.skip` nor a severity override. Write the\n\
100message it asks for, or change what it asks for — `amont setup`, or\n\
101`amont.commit.*` directly.\n\
102\n\
103{END}\n"
104    )
105}
106
107/// The `CLAUDE.md` pointer, START and END inclusive.
108///
109/// Claude Code loads `CLAUDE.md`; the tool-neutral convention is
110/// `AGENTS.md`. Writing the whole block into both would be two copies to
111/// drift apart, so the guidance keeps ONE home and this is a generated
112/// signpost to it — inside the same markers, so `--check` reports a stale
113/// pointer exactly as it reports a stale block. A hand-written "see
114/// AGENTS.md" line is the one part that could rot silently; this cannot.
115pub fn generate_pointer() -> String {
116    format!(
117        "{START}\n\
118\n\
119## Git hooks (amont)\n\
120\n\
121This repository enforces pre-commit / pre-push checks that can REJECT a\n\
122commit or a push. What runs, the branch-name rule, and why `git commit`\n\
123and `git push` both need a long timeout — or a background run — are in\n\
124[AGENTS.md](AGENTS.md) — read it before committing. Both files are\n\
125generated: run `amont agents-md` after changing either.\n\
126\n\
127{END}\n"
128    )
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum MarkerState {
133    /// Exactly one marker present, or `END` appears before `START` — a state
134    /// this tool refuses to guess its way out of.
135    Malformed,
136}
137
138/// The byte range to replace (markers inclusive, one trailing newline
139/// consumed), or `None` when neither marker is present at all.
140///
141/// `start`/`end` are searched INDEPENDENTLY — not `end` searched only within
142/// the text after a found `start` — so a file holding `END` with no `START`
143/// at all (searching from `start`'s position finds nothing, because there is
144/// no `start`) still surfaces as `(None, Some(_))` rather than silently
145/// reading as "no markers, nothing to guard against."
146fn marker_range(text: &str) -> Result<Option<Range<usize>>, MarkerState> {
147    let start = text.find(START);
148    let end = text.find(END);
149
150    match (start, end) {
151        (None, None) => Ok(None),
152        (Some(s), Some(e)) if e >= s + START.len() => {
153            let mut range_end = e + END.len();
154            if text[range_end..].starts_with('\n') {
155                range_end += 1; // swallow exactly one trailing newline
156            }
157            Ok(Some(s..range_end))
158        }
159        // Exactly one present, or END appears before START.
160        _ => Err(MarkerState::Malformed),
161    }
162}
163
164/// What writing would produce, given what is on disk today.
165///
166/// - no file / empty file → the block alone.
167/// - file, no markers → block appended, separated by exactly one blank line.
168/// - file, markers found → everything outside the markers is byte-for-byte
169///   untouched; the marked span is replaced.
170/// - markers malformed (exactly one present, or out of order) → refused.
171pub fn desired_file_content(
172    settings: &crate::config::Settings,
173    existing: &str,
174) -> Result<String, MarkerState> {
175    desired_with(existing, &generate_block(settings))
176}
177
178/// The same splice, for the pointer.
179pub fn desired_pointer_content(existing: &str) -> Result<String, MarkerState> {
180    desired_with(existing, &generate_pointer())
181}
182
183/// The splice itself, with the text to splice as a parameter — block and
184/// pointer differ only in what goes between the markers, and two copies of
185/// this logic would be two places for the "append vs replace" rules to
186/// disagree.
187fn desired_with(existing: &str, block: &str) -> Result<String, MarkerState> {
188    match marker_range(existing)? {
189        Some(range) => Ok(format!(
190            "{}{}{}",
191            &existing[..range.start],
192            block,
193            &existing[range.end..]
194        )),
195        None if existing.is_empty() => Ok(block.to_string()),
196        None => {
197            let sep = if existing.ends_with("\n\n") {
198                ""
199            } else if existing.ends_with('\n') {
200                "\n"
201            } else {
202                "\n\n"
203            };
204            Ok(format!("{existing}{sep}{block}"))
205        }
206    }
207}
208
209pub fn write(settings: &crate::config::Settings, path: &Path) -> Result<(), String> {
210    write_with(path, &generate_block(settings))
211}
212
213/// Write the CLAUDE.md signpost.
214pub fn write_pointer(path: &Path) -> Result<(), String> {
215    write_with(path, &generate_pointer())
216}
217
218fn write_with(path: &Path, block: &str) -> Result<(), String> {
219    let existing = std::fs::read_to_string(path).unwrap_or_default();
220    let content = desired_with(&existing, block).map_err(|_| {
221        format!(
222            "{}: has an unpaired amont marker — fix or remove it by hand, \
223             then re-run `amont agents-md`",
224            path.display()
225        )
226    })?;
227    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
228        std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
229    }
230    std::fs::write(path, content).map_err(|e| format!("{}: {e}", path.display()))
231}
232
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub enum CheckResult {
235    /// No file, or a file with no markers at all — opt-in tooling, so this
236    /// is not drift.
237    NotPresent,
238    MatchesGenerated,
239    Drifted,
240}
241
242pub fn check(settings: &crate::config::Settings, path: &Path) -> Result<CheckResult, String> {
243    check_with(path, &generate_block(settings))
244}
245
246/// Is the CLAUDE.md signpost the one this binary generates?
247pub fn check_pointer(path: &Path) -> Result<CheckResult, String> {
248    check_with(path, &generate_pointer())
249}
250
251fn check_with(path: &Path, block: &str) -> Result<CheckResult, String> {
252    let existing = std::fs::read_to_string(path).unwrap_or_default();
253    match marker_range(&existing) {
254        Err(_) => Err(format!(
255            "{}: has an unpaired amont marker — fix or remove it by hand",
256            path.display()
257        )),
258        Ok(None) => Ok(CheckResult::NotPresent),
259        Ok(Some(range)) => {
260            if &existing[range] == block {
261                Ok(CheckResult::MatchesGenerated)
262            } else {
263                Ok(CheckResult::Drifted)
264            }
265        }
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    /// The block documents the CONFIGURED budgets; with no policy and no git
274    /// config in these tests that means the shipped defaults.
275    fn test_settings() -> crate::config::Settings {
276        crate::config::Settings::default()
277    }
278
279    #[test]
280    fn no_file_produces_just_the_block() {
281        assert_eq!(
282            desired_file_content(&test_settings(), "").unwrap(),
283            generate_block(&test_settings())
284        );
285    }
286
287    /// Both generated files must satisfy Prettier's markdown defaults,
288    /// because amont ALSO ships `pre-commit-prettier`: when the two
289    /// disagree, every JS repository is left choosing between two amont
290    /// checks, and `prettier --write` on a generated file is what
291    /// `agents-md --check` then reports as drift. Encoding the three rules
292    /// that bit us — blank line after an HTML comment, `_emphasis_` not
293    /// `*emphasis*`, blank line before a trailing HTML comment — keeps the
294    /// unit suite honest without making it shell out to node.
295    #[test]
296    fn the_generated_markdown_satisfies_prettier() {
297        for (what, text) in [
298            ("block", generate_block(&test_settings())),
299            ("pointer", generate_pointer()),
300        ] {
301            assert!(
302                text.starts_with(&format!("{START}\n\n")),
303                "{what}: prettier wants a blank line after the opening comment"
304            );
305            assert!(
306                text.ends_with(&format!("\n\n{END}\n")),
307                "{what}: prettier wants a blank line before the closing comment"
308            );
309            // A `*` OPENING emphasis is what prettier rewrites. A trailing
310            // one inside a code span (`amont.severity.*`) is untouched, so
311            // the rule is "no `*` immediately followed by a letter" rather
312            // than "no `*`".
313            let opener = text
314                .as_bytes()
315                .windows(2)
316                .any(|w| w[0] == b'*' && w[1].is_ascii_alphanumeric());
317            assert!(
318                !opener,
319                "{what}: prettier rewrites *emphasis* into _emphasis_, and a \
320                 formatted file then reads as drift — emit underscores"
321            );
322        }
323    }
324
325    /// The signpost is generated and self-checking — the whole reason it is
326    /// a marked block rather than a hand-written "see AGENTS.md" line, which
327    /// would be the one part of the pair able to rot in silence.
328    #[test]
329    fn the_pointer_is_generated_and_therefore_checkable() {
330        let p = generate_pointer();
331        assert!(p.starts_with(START) && p.ends_with(&format!("{END}\n")));
332        assert!(p.contains("AGENTS.md"), "it has to name where to look");
333        assert_ne!(
334            p,
335            generate_block(&test_settings()),
336            "a signpost, not a second copy"
337        );
338        assert!(
339            !p.contains("amont list --json"),
340            "the registry command lives in ONE place; duplicating it here is \
341             the drift this design avoids"
342        );
343        // Round-trips through the same splice as the block: appended to a
344        // repo's existing CLAUDE.md, then replaced in place next time.
345        let existing = "# Notes\n\nsomething the repo wrote\n";
346        let once = desired_pointer_content(existing).unwrap();
347        assert!(once.starts_with(existing), "never touches what was there");
348        assert!(once.ends_with(&p));
349        assert_eq!(
350            desired_pointer_content(&once).unwrap(),
351            once,
352            "re-running is a no-op, so `--check` can be trusted"
353        );
354    }
355
356    #[test]
357    fn no_markers_appends_with_one_blank_line() {
358        let got = desired_file_content(&test_settings(), "# My Project\n\nSome docs.\n").unwrap();
359        assert!(got.starts_with("# My Project\n\nSome docs.\n\n"));
360        assert!(got.ends_with(&generate_block(&test_settings())));
361    }
362
363    #[test]
364    fn no_markers_and_no_trailing_newline_still_gets_a_blank_line() {
365        let got = desired_file_content(&test_settings(), "# My Project").unwrap();
366        assert!(got.starts_with("# My Project\n\n"));
367    }
368
369    #[test]
370    fn existing_markers_are_replaced_and_everything_else_survives() {
371        let before = format!("before\n\n{START}\nstale\n{END}\n\nafter\n");
372        let got = desired_file_content(&test_settings(), &before).unwrap();
373        assert!(got.starts_with("before\n\n"));
374        assert!(got.ends_with("\n\nafter\n"));
375        assert!(got.contains(&generate_block(&test_settings())));
376        assert!(!got.contains("stale"));
377    }
378
379    #[test]
380    fn applying_twice_is_idempotent() {
381        let once = desired_file_content(&test_settings(), "preamble\n").unwrap();
382        let twice = desired_file_content(&test_settings(), &once).unwrap();
383        assert_eq!(once, twice);
384    }
385
386    #[test]
387    fn an_unpaired_marker_is_refused_not_guessed_at() {
388        assert_eq!(
389            desired_file_content(&test_settings(), &format!("{START}\nno end here\n")),
390            Err(MarkerState::Malformed)
391        );
392        assert_eq!(
393            desired_file_content(&test_settings(), &format!("no start\n{END}\n")),
394            Err(MarkerState::Malformed)
395        );
396    }
397
398    /// The bug the fix above was for: searching for `END` only within the
399    /// text AFTER a found `START` meant an `END`-with-no-`START` file
400    /// searched from a `start` that did not exist — finding nothing, and
401    /// reading as "no markers at all" rather than "unpaired."
402    #[test]
403    fn end_appearing_before_start_is_malformed_not_reordered() {
404        assert_eq!(
405            desired_file_content(&test_settings(), &format!("{END}\n...\n{START}\n...\n")),
406            Err(MarkerState::Malformed)
407        );
408    }
409
410    #[test]
411    fn check_reports_not_present_for_a_missing_file() {
412        let tmp = std::env::temp_dir().join("amont-agents-md-test-nonexistent-xyz");
413        let _ = std::fs::remove_file(&tmp);
414        assert_eq!(
415            check(&test_settings(), &tmp).unwrap(),
416            CheckResult::NotPresent
417        );
418    }
419
420    #[test]
421    fn check_reports_matches_generated_after_a_write() {
422        let tmp =
423            std::env::temp_dir().join(format!("amont-agents-md-test-{}-match", std::process::id()));
424        std::fs::write(&tmp, generate_block(&test_settings())).unwrap();
425        assert_eq!(
426            check(&test_settings(), &tmp).unwrap(),
427            CheckResult::MatchesGenerated
428        );
429        let _ = std::fs::remove_file(&tmp);
430    }
431
432    #[test]
433    fn check_reports_drifted_for_a_stale_block() {
434        let tmp =
435            std::env::temp_dir().join(format!("amont-agents-md-test-{}-drift", std::process::id()));
436        std::fs::write(&tmp, format!("{START}\nstale\n{END}\n")).unwrap();
437        assert_eq!(check(&test_settings(), &tmp).unwrap(), CheckResult::Drifted);
438        let _ = std::fs::remove_file(&tmp);
439    }
440}