Skip to main content

testing_conventions/
agents.rs

1//! `install` (#232): write the testing contract into the repository's agent
2//! context file (`AGENTS.md`) as a marker-delimited, hash-versioned block —
3//! the beads (`bd init`) pattern. Idempotent: re-running refreshes the owned
4//! region and touches nothing outside it.
5
6use std::fs;
7use std::io::ErrorKind;
8use std::path::Path;
9
10use anyhow::{bail, Context};
11use sha2::{Digest, Sha256};
12
13const SCHEMA_VERSION: u32 = 1;
14const BEGIN_OPEN: &str = "<!-- testing-conventions:begin ";
15const END_MARKER: &str = "<!-- testing-conventions:end -->";
16
17/// The managed region's content — the few non-negotiables plus pointers to
18/// the docs site and the machine-readable contract. Thin on purpose: the
19/// consumer's file is theirs; the full contract lives on the docs site.
20const TEMPLATE: &str = "\
21## Testing conventions
22
23This repository enforces [testing-conventions](https://thekevinscott.github.io/testing-conventions/) in CI. The contract:
24
25- Start every change with the docs update and red integration/e2e tests; CI witnesses them fail before the implementation lands.
26- Colocate a unit test with every source file, and mock every collaborator in unit tests.
27- Clear the coverage floor and kill the mutants on every line you touch.
28- Ship each capability at parity across Python, TypeScript, and Rust.
29- An exemption carries a written reason showing the isolation techniques you tried; near-zero is the bar.
30
31Machine-readable contract: https://thekevinscott.github.io/testing-conventions/llms.txt
32";
33
34/// The begin marker carries the schema version and the first 12 hex chars of
35/// the SHA-256 of the region content, so staleness is visible at a glance.
36fn begin_marker() -> String {
37    let hex = Sha256::digest(TEMPLATE.as_bytes())
38        .iter()
39        .map(|b| format!("{b:02x}"))
40        .collect::<String>();
41    format!("{BEGIN_OPEN}v{SCHEMA_VERSION} hash={} -->", &hex[..12])
42}
43
44/// Upsert the managed block into the file at `path`: create the file when
45/// absent, append when the markers are missing, otherwise replace only the
46/// region between the markers. A current block is a byte-identical no-op.
47pub fn install(path: &Path) -> anyhow::Result<()> {
48    if path
49        .symlink_metadata()
50        .map(|meta| meta.file_type().is_symlink())
51        .unwrap_or(false)
52    {
53        bail!(
54            "{} is a symlink; refusing to write through it",
55            path.display()
56        );
57    }
58
59    let existing = match fs::read_to_string(path) {
60        Ok(text) => Some(text),
61        Err(err) if err.kind() == ErrorKind::NotFound => None,
62        Err(err) => return Err(err).with_context(|| format!("reading {}", path.display())),
63    };
64
65    let region = format!("{}\n{TEMPLATE}{END_MARKER}", begin_marker());
66    let new = match &existing {
67        None => format!("{region}\n"),
68        Some(text) => {
69            let bounds = text.find(BEGIN_OPEN).and_then(|start| {
70                let end = text[start..].find(END_MARKER)?;
71                Some((start, start + end + END_MARKER.len()))
72            });
73            match bounds {
74                Some((start, end)) => format!("{}{region}{}", &text[..start], &text[end..]),
75                None => {
76                    let mut out = text.clone();
77                    if !out.is_empty() && !out.ends_with('\n') {
78                        out.push('\n');
79                    }
80                    if !out.is_empty() {
81                        out.push('\n');
82                    }
83                    format!("{out}{region}\n")
84                }
85            }
86        }
87    };
88
89    if existing.as_deref() == Some(new.as_str()) {
90        return Ok(());
91    }
92
93    // Atomic write: temp file in the target's directory, then rename, so a
94    // crash mid-write leaves the original intact.
95    let name = path
96        .file_name()
97        .with_context(|| format!("{} has no file name", path.display()))?;
98    let tmp = path
99        .parent()
100        .filter(|dir| !dir.as_os_str().is_empty())
101        .unwrap_or_else(|| Path::new("."))
102        .join(format!(
103            ".{}.tc-tmp-{}",
104            name.to_string_lossy(),
105            std::process::id()
106        ));
107    fs::write(&tmp, &new).with_context(|| format!("writing {}", tmp.display()))?;
108    fs::rename(&tmp, path)
109        .with_context(|| format!("renaming {} over {}", tmp.display(), path.display()))
110}