1use 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
20const OLD_START: &str = crate::names::old::AGENTS_START;
24const OLD_END: &str = crate::names::old::AGENTS_END;
25
26pub fn has_markers(text: &str) -> bool {
29 text.contains(START) || text.contains(OLD_START)
30}
31
32pub 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 (amont)\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\
59amont list --json\n\
60amont 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 `amont 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 `amont land`, or\n\
80`amont rehearse --wait` (or `amont run --stamp`) first and push again. Push a\n\
81release tag with `amont 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 — `amont setup`, or\n\
113`greengate.commit.*` directly.\n\
114\n\
115{END}\n"
116 )
117}
118
119pub fn generate_pointer() -> String {
128 format!(
129 "{START}\n\
130\n\
131## Git hooks (amont)\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 `amont 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 Malformed,
148}
149
150fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172enum Pair {
173 New,
175 Old,
177}
178
179fn 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
191fn 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; }
207 Ok(Some(s..range_end))
208 }
209 _ => Err(MarkerState::Malformed),
211 }
212}
213
214pub 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
228pub fn desired_pointer_content(existing: &str) -> Result<String, MarkerState> {
230 desired_with(existing, &generate_pointer())
231}
232
233fn 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
263pub 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 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
296pub 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 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 #[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 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 #[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("amont list --json"),
390 "the registry command lives in ONE place; duplicating it here is \
391 the drift this design avoids"
392 );
393 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 #[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); }
455
456 #[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 #[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); 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); }
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); }
533}