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
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
123pub 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 Malformed,
152}
153
154fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176enum Pair {
177 New,
179 Old,
181}
182
183fn 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
195fn 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; }
211 Ok(Some(s..range_end))
212 }
213 _ => Err(MarkerState::Malformed),
215 }
216}
217
218pub 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
232pub fn desired_pointer_content(existing: &str) -> Result<String, MarkerState> {
234 desired_with(existing, &generate_pointer())
235}
236
237fn 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
267pub 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 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
300pub 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 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 #[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 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 #[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 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 #[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); }
459
460 #[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 #[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); 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); }
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); }
537}