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