Skip to main content

greengate_runtime/
agents_md.rs

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