trusty_code/build_info.rs
1//! Build and version tracking.
2//!
3//! Why: We need a monotonic build counter that increments on every process
4//! start, independent of the semver version. The combined `vX.Y.Z build #N`
5//! string lets us correlate log lines and performance telemetry with the
6//! exact binary invocation that produced them. Keeping the counter on disk
7//! (rather than baked into the binary) lets a single `cargo build` produce
8//! many distinct "builds" across repeated `cargo run` invocations during
9//! development — which is exactly when we need the disambiguation.
10//!
11//! What: Reads `<state_dir>/build.json` (caller-supplied, e.g.
12//! `.trusty-code/state/build.json` relative to the current working
13//! directory), increments the `build` counter (defaulting to 0 if the file
14//! is missing or malformed), and writes the result back atomically via
15//! `rename(2)` from a sibling `.tmp` file.
16//!
17//! Test: `BuildInfo::load_and_increment` in an empty temp dir returns
18//! `build == 1`; calling it again returns `build == 2`; a corrupt
19//! `build.json` is treated as "build = 0" and replaced on the next call.
20
21use std::path::{Path, PathBuf};
22
23use anyhow::{Context, Result};
24use chrono::Utc;
25use serde::{Deserialize, Serialize};
26
27/// Compile-time semver from Cargo.toml.
28///
29/// Why: Canonical version string embedded in the binary so runtime code never
30/// needs to read Cargo.toml.
31/// What: `env!("CARGO_PKG_VERSION")` forwarded as a `'static str`.
32/// Test: Asserted non-empty in `version_string_contains_version`.
33pub const VERSION: &str = env!("CARGO_PKG_VERSION");
34
35/// The package name, resolved at compile time.
36///
37/// Why: Allows display strings to use the correct crate name without
38/// hardcoding it, so this module is reusable across trusty-agents and trusty-code.
39/// What: `env!("CARGO_PKG_NAME")` forwarded as a `'static str`.
40/// Test: Indirectly via `version_string_contains_version`.
41pub const PKG_NAME: &str = env!("CARGO_PKG_NAME");
42
43/// Short git commit hash captured at build time by `build.rs`.
44///
45/// Why: Correlates a running binary to the exact commit that produced it.
46/// What: Populated from `git rev-parse --short HEAD` during compilation;
47/// falls back to `"unknown"` when git is unavailable.
48/// Test: `version_string_contains_version` confirms both fields render.
49pub const GIT_HASH: &str = env!("GIT_COMMIT_HASH");
50
51/// Date of the git commit this binary was built from (`YYYY-MM-DD`).
52///
53/// Why: The SHA alone is opaque to a human scanning a run report; the date
54/// makes "is this artifact from before or after the fix?" answerable at a
55/// glance — the exact question that had to be settled by timestamp archaeology
56/// during the 2026-07-16 L4 validation (#2823).
57/// What: Populated from `git log -1 --date=short --format=%cd` during
58/// compilation; falls back to `"unknown"` when git is unavailable. Deliberately
59/// the COMMIT date, not the build wall-clock, so rebuilds stay reproducible.
60/// Test: `provenance_constants_are_well_formed`.
61pub const COMMIT_DATE: &str = env!("GIT_COMMIT_DATE");
62
63/// Full version string for `tcode --version`, e.g. `0.2.0 (b20adfca 2026-07-16)`.
64///
65/// Why: `--version` is the first thing anyone runs to identify a binary, and it
66/// is the ONLY provenance channel available for an already-installed `tcode`
67/// whose source tree is long gone. It must carry the SHA, not just the semver
68/// (#2823).
69/// What: A compile-time `concat!` of the semver, git SHA, and commit date —
70/// const rather than a function so clap's `version = …` attribute can take it
71/// directly. Degrades to `0.2.0 (unknown unknown)` outside a git checkout.
72/// Test: `long_version_carries_semver_and_provenance`, plus the
73/// `tests/cli_e2e.rs` binary-level `--version` assertion.
74pub const LONG_VERSION: &str = concat!(
75 env!("CARGO_PKG_VERSION"),
76 " (",
77 env!("GIT_COMMIT_HASH"),
78 " ",
79 env!("GIT_COMMIT_DATE"),
80 ")"
81);
82
83/// Human-readable banner used by the CTRL REPL and startup logs.
84///
85/// Why: One canonical format keeps log grep and support reports consistent.
86/// What: Returns `<pkg-name> vX.Y.Z (<git-hash>)`.
87/// Test: `version_string_contains_version` checks both substrings render.
88pub fn version_string() -> String {
89 format!("{PKG_NAME} v{VERSION} ({GIT_HASH})")
90}
91
92/// Build provenance as a JSON object for embedding in machine-readable reports.
93///
94/// Why: `tcode_report.json` must state which binary produced it. Without this,
95/// a run's artifacts cannot be attributed to a build and provenance has to be
96/// reverse-inferred from install mtimes — which produced a false "bug still
97/// recurs" conclusion during the 2026-07-16 L4 validation (#2823).
98/// What: Returns `{"version", "commit", "commit_date"}` sourced from the
99/// compile-time constants. `commit`/`commit_date` are the literal `"unknown"`
100/// for a non-git build rather than `null`, so the field is always present and
101/// consumers need no absent-key branch.
102/// Test: `provenance_json_carries_version_and_commit`,
103/// `run_task::report::tests::report_json_carries_build_provenance`.
104pub fn provenance_json() -> serde_json::Value {
105 serde_json::json!({
106 "version": VERSION,
107 "commit": GIT_HASH,
108 "commit_date": COMMIT_DATE,
109 })
110}
111
112/// On-disk shape of `build.json`.
113///
114/// Why: Kept as a private struct so callers go through `BuildInfo` for
115/// `started_at`/`version` handling instead of reading raw JSON.
116/// What: Just the two persisted fields; version is a compile-time constant
117/// and doesn't round-trip through disk.
118/// Test: Serialized/deserialized in unit tests below.
119#[derive(Debug, Serialize, Deserialize)]
120struct PersistedBuild {
121 build: u64,
122 started_at: String,
123}
124
125/// Runtime build metadata surfaced to logs, the `--version` flag, and
126/// downstream instrumentation.
127///
128/// Why: Centralizes "which binary + which invocation" so later instrumentation
129/// can tag every telemetry event with the same build stamp the startup log
130/// line shows.
131/// What: Holds the compile-time semver, the incremented build counter, and
132/// the ISO8601 UTC start timestamp.
133/// Test: `display_string` returns `<pkg-name> vX.Y.Z build #N`.
134#[derive(Debug, Clone)]
135pub struct BuildInfo {
136 pub version: &'static str,
137 pub build: u64,
138 // Exposed for the performance instrumentation module which will stamp
139 // telemetry events with the process start time.
140 #[allow(dead_code)]
141 pub started_at: String,
142}
143
144impl BuildInfo {
145 /// Load the persistent counter, increment it, and persist back using
146 /// the given state directory.
147 ///
148 /// Why: Single entry point ensures every process start gets a fresh
149 /// build number even if the caller forgets to save.
150 /// What: Uses `<state_dir>/build.json`. See `load_and_increment_in` for
151 /// the testable, directory-parameterized version.
152 /// Test: See `load_and_increment_in` tests.
153 pub async fn load_and_increment(state_dir: &Path) -> Result<Self> {
154 tokio::fs::create_dir_all(state_dir).await?;
155 Self::load_and_increment_in(state_dir).await
156 }
157
158 /// Same as `load_and_increment` but with an explicit base directory.
159 ///
160 /// Why: Tests need to drive the counter against a temp dir without
161 /// mutating the real state directory in the project.
162 /// What: Creates `<dir>` if missing, reads/parses `<dir>/build.json`
163 /// (treating missing or malformed as build=0), increments, writes back
164 /// atomically.
165 /// Test: See unit tests at the bottom of this file.
166 pub async fn load_and_increment_in(dir: &Path) -> Result<Self> {
167 tokio::fs::create_dir_all(dir)
168 .await
169 .with_context(|| format!("failed to create {}", dir.display()))?;
170
171 let file = dir.join("build.json");
172 let previous = read_previous(&file).await;
173
174 let next = previous.saturating_add(1);
175 let started_at = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
176
177 let persisted = PersistedBuild {
178 build: next,
179 started_at: started_at.clone(),
180 };
181 write_atomic(dir, &file, &persisted).await?;
182
183 Ok(Self {
184 version: env!("CARGO_PKG_VERSION"),
185 build: next,
186 started_at,
187 })
188 }
189
190 /// Human-readable banner used by the startup log line and `--version`.
191 ///
192 /// Why: Single canonical format so grep/tooling can match it uniformly.
193 /// What: `<pkg-name> vX.Y.Z build #N`.
194 /// Test: Asserted directly in unit tests.
195 pub fn display_string(&self) -> String {
196 format!("{PKG_NAME} v{} build #{}", self.version, self.build)
197 }
198}
199
200/// Read the previous `build` counter from `file`, returning 0 if the file
201/// is missing, unreadable, or corrupt.
202///
203/// Why: We never want to fail startup just because the counter file got
204/// wedged; treating it as 0 means the next write replaces the bad content.
205/// What: Async read + `serde_json` parse.
206/// Test: `load_and_increment_in` tests cover missing + corrupt cases.
207async fn read_previous(file: &Path) -> u64 {
208 match tokio::fs::read(file).await {
209 Ok(bytes) => match serde_json::from_slice::<PersistedBuild>(&bytes) {
210 Ok(p) => p.build,
211 Err(_) => 0,
212 },
213 Err(_) => 0,
214 }
215}
216
217/// Atomic write: serialize to `<file>.tmp`, fsync implicit via rename.
218///
219/// Why: A crash during write must never leave `build.json` half-written —
220/// `rename(2)` on the same filesystem is atomic, so readers always see a
221/// complete file.
222/// What: Writes to `<dir>/build.json.tmp`, renames over the target path.
223/// Test: Covered by `load_and_increment_in` tests.
224async fn write_atomic(dir: &Path, file: &Path, payload: &PersistedBuild) -> Result<()> {
225 let tmp: PathBuf = dir.join("build.json.tmp");
226 let bytes = serde_json::to_vec_pretty(payload).context("serialize build.json")?;
227 tokio::fs::write(&tmp, &bytes)
228 .await
229 .with_context(|| format!("failed to write {}", tmp.display()))?;
230 tokio::fs::rename(&tmp, file)
231 .await
232 .with_context(|| format!("failed to rename {} -> {}", tmp.display(), file.display()))?;
233 Ok(())
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 #[tokio::test]
241 async fn starts_at_one_when_missing() {
242 let dir = tempfile::tempdir().unwrap();
243 let info = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
244 assert_eq!(info.build, 1);
245 assert_eq!(info.version, env!("CARGO_PKG_VERSION"));
246 assert!(info.started_at.ends_with('Z'));
247
248 // File exists and is valid JSON with build=1.
249 let bytes = tokio::fs::read(dir.path().join("build.json"))
250 .await
251 .unwrap();
252 let p: PersistedBuild = serde_json::from_slice(&bytes).unwrap();
253 assert_eq!(p.build, 1);
254 }
255
256 #[tokio::test]
257 async fn increments_across_calls() {
258 let dir = tempfile::tempdir().unwrap();
259 let a = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
260 let b = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
261 let c = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
262 assert_eq!(a.build, 1);
263 assert_eq!(b.build, 2);
264 assert_eq!(c.build, 3);
265 }
266
267 #[tokio::test]
268 async fn corrupt_file_resets_to_one() {
269 let dir = tempfile::tempdir().unwrap();
270 tokio::fs::create_dir_all(dir.path()).await.unwrap();
271 tokio::fs::write(dir.path().join("build.json"), b"not json at all")
272 .await
273 .unwrap();
274
275 let info = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
276 assert_eq!(info.build, 1, "corrupt file should be treated as build=0");
277 }
278
279 #[tokio::test]
280 async fn display_string_format() {
281 let info = BuildInfo {
282 version: "0.1.0",
283 build: 42,
284 started_at: "2026-04-22T17:31:30Z".to_string(),
285 };
286 // PKG_NAME is "trusty-code" in this crate.
287 let s = info.display_string();
288 assert!(s.contains("v0.1.0"), "got: {s}");
289 assert!(s.contains("build #42"), "got: {s}");
290 }
291
292 #[test]
293 fn version_string_contains_version() {
294 let s = version_string();
295 assert!(s.contains("v"));
296 assert!(s.contains(VERSION));
297 // GIT_HASH is either a short hash or "unknown"; rendered in parens.
298 assert!(s.contains(GIT_HASH));
299 }
300
301 /// Both provenance constants are populated and well-formed (#2823).
302 ///
303 /// Why: An empty or whitespace-only value would render a report field that
304 /// looks present but identifies nothing — worse than an explicit
305 /// `"unknown"`, because a consumer cannot tell it apart from a real value.
306 /// What: Assert each constant is non-empty, and that it is EITHER the
307 /// literal `"unknown"` fallback OR a well-formed real value (a lowercase
308 /// hex short SHA / a `YYYY-MM-DD` date). Deliberately accepts both so the
309 /// test passes in a git checkout AND in a crates.io tarball build, which is
310 /// exactly the fallback contract.
311 /// Test: this test.
312 #[test]
313 fn provenance_constants_are_well_formed() {
314 assert!(!GIT_HASH.is_empty(), "GIT_HASH must never be empty");
315 assert!(!COMMIT_DATE.is_empty(), "COMMIT_DATE must never be empty");
316
317 if GIT_HASH != "unknown" {
318 assert!(
319 GIT_HASH.len() >= 7 && GIT_HASH.chars().all(|c| c.is_ascii_hexdigit()),
320 "expected a short hex SHA or \"unknown\", got: {GIT_HASH}"
321 );
322 }
323 if COMMIT_DATE != "unknown" {
324 let parts: Vec<&str> = COMMIT_DATE.split('-').collect();
325 assert!(
326 parts.len() == 3 && parts.iter().all(|p| p.chars().all(|c| c.is_ascii_digit())),
327 "expected YYYY-MM-DD or \"unknown\", got: {COMMIT_DATE}"
328 );
329 }
330 }
331
332 /// `LONG_VERSION` carries the semver AND the provenance (#2823).
333 ///
334 /// Why: This exact string is what `tcode --version` prints. Regressing it
335 /// back to a bare semver would silently reopen the run→binary attribution
336 /// gap that caused the 2026-07-16 false conclusion.
337 /// What: Assert the rendered form is `<semver> (<sha> <date>)`.
338 /// Test: this test.
339 #[test]
340 fn long_version_carries_semver_and_provenance() {
341 assert_eq!(
342 LONG_VERSION,
343 format!("{VERSION} ({GIT_HASH} {COMMIT_DATE})")
344 );
345 assert!(LONG_VERSION.starts_with(VERSION));
346 assert!(LONG_VERSION.contains(GIT_HASH));
347 }
348
349 /// `provenance_json` emits the three always-present provenance fields.
350 ///
351 /// Why: `tcode_report.json` consumers (the bake-off harness) read these key
352 /// names; they are a wire contract.
353 /// What: Assert the object shape and that no field is null even when the
354 /// build had no git available.
355 /// Test: this test.
356 #[test]
357 fn provenance_json_carries_version_and_commit() {
358 let v = provenance_json();
359 assert_eq!(v["version"], VERSION);
360 assert_eq!(v["commit"], GIT_HASH);
361 assert_eq!(v["commit_date"], COMMIT_DATE);
362 // Always a string — never null — so consumers need no absent-key branch.
363 assert!(v["commit"].is_string(), "commit must be a string, not null");
364 }
365
366 /// The no-git fallback premise holds: outside a checkout, the probes
367 /// `build.rs` runs fail rather than returning a bogus value (#2823).
368 ///
369 /// Why: The `"unknown"` fallback exists for the crates.io-tarball build
370 /// (trusty-code IS published, so this path WILL be taken). That fallback is
371 /// only correct if the underlying git probe genuinely FAILS outside a
372 /// checkout — if it instead succeeded against some ambient parent repo, a
373 /// published build would stamp reports with a SHA that never produced it,
374 /// which is worse than `"unknown"`. This pins the premise the compile-time
375 /// constants rest on. (It cannot assert on `GIT_HASH` itself, which is
376 /// baked in at compile time; `provenance_constants_are_well_formed` covers
377 /// the value.)
378 /// What: Runs `git rev-parse --short HEAD` in a temp dir with
379 /// `GIT_CEILING_DIRECTORIES` set so the search cannot escape upward into a
380 /// real repo, and asserts it does not succeed.
381 /// Test: this test.
382 #[test]
383 fn git_probe_fails_outside_a_checkout_so_fallback_engages() {
384 let dir = tempfile::tempdir().unwrap();
385 let output = std::process::Command::new("git")
386 .args(["rev-parse", "--short", "HEAD"])
387 .current_dir(dir.path())
388 // Stop the repo discovery walking up into any ambient checkout.
389 .env("GIT_CEILING_DIRECTORIES", dir.path())
390 .env("GIT_DIR", dir.path().join("definitely-not-a-git-dir"))
391 .output();
392
393 // An `Err` means git isn't installed at all — also a fallback path
394 // `build.rs` handles, so only the "git ran" case has anything to assert.
395 if let Ok(o) = output {
396 assert!(
397 !o.status.success(),
398 "git must not resolve a SHA outside a checkout; got: {}",
399 String::from_utf8_lossy(&o.stdout)
400 );
401 }
402 }
403
404 /// With the branch ref PACKED, only the reflog witnesses a new commit —
405 /// the premise `build.rs`'s `logs/HEAD` watch rests on (#2823).
406 ///
407 /// Why: Emitting any `rerun-if-changed` opts `build.rs` out of Cargo's
408 /// default "re-run when any package file changes" heuristic, so ONLY
409 /// declared paths are watched. If the branch ref is packed (`git gc --auto`)
410 /// there is no loose ref file to watch, and a later commit rewrites neither
411 /// `HEAD` nor any other watched path — so the script would not re-run and
412 /// the embedded SHA would go SILENTLY STALE. A binary reporting a stale SHA
413 /// is precisely the failure this ticket exists to eliminate. This pins the
414 /// two facts that make watching `logs/HEAD` the right fix, so a future
415 /// "the reflog watch looks redundant" cleanup fails loudly here.
416 /// What: In a throwaway repo (never the real one), pack the refs, then
417 /// assert (a) the loose ref really is gone — so `rerun_if_exists` would skip
418 /// it — while `logs/HEAD` exists, and (b) a commit on the packed branch
419 /// leaves `HEAD`'s content untouched but appends to the reflog. Compares
420 /// CONTENT rather than mtime to stay fast and granularity-independent.
421 /// Test: this test.
422 #[test]
423 fn packed_branch_ref_leaves_only_the_reflog_witnessing_a_commit() {
424 let dir = tempfile::tempdir().unwrap();
425 let root = dir.path();
426 let run = |args: &[&str]| {
427 let out = std::process::Command::new("git")
428 .args(args)
429 .current_dir(root)
430 .env("GIT_AUTHOR_NAME", "t")
431 .env("GIT_AUTHOR_EMAIL", "t@t")
432 .env("GIT_COMMITTER_NAME", "t")
433 .env("GIT_COMMITTER_EMAIL", "t@t")
434 .output()
435 .expect("run git");
436 assert!(out.status.success(), "git {args:?} failed");
437 String::from_utf8_lossy(&out.stdout).trim().to_string()
438 };
439 // A git older than this, or none at all, simply skips the test.
440 if std::process::Command::new("git")
441 .arg("--version")
442 .output()
443 .is_err()
444 {
445 return;
446 }
447
448 run(&["init", "-q", "-b", "main", "."]);
449 std::fs::write(root.join("f"), "a").unwrap();
450 run(&["add", "-A"]);
451 run(&["commit", "-q", "-m", "one"]);
452 run(&["pack-refs", "--all"]);
453
454 // `--git-path` yields a CWD-relative path in a plain checkout (and an
455 // absolute one in a linked worktree), so resolve against the repo root
456 // rather than this test process's CWD. `join` keeps an absolute path
457 // as-is, so this is correct for both shapes.
458 let git_path = |spec: &str| root.join(run(&["rev-parse", "--git-path", spec]));
459 let loose = git_path("refs/heads/main");
460 let head = git_path("HEAD");
461 let reflog = git_path("logs/HEAD");
462
463 assert!(
464 !loose.exists(),
465 "expected the branch ref to be packed away; if git stopped packing \
466 here the premise for watching logs/HEAD needs rechecking"
467 );
468 assert!(reflog.exists(), "reflog must exist to be watchable");
469
470 let head_before = std::fs::read_to_string(&head).unwrap();
471 let reflog_before = std::fs::read_to_string(&reflog).unwrap();
472
473 std::fs::write(root.join("f"), "b").unwrap();
474 run(&["add", "-A"]);
475 run(&["commit", "-q", "-m", "two"]);
476
477 assert_eq!(
478 head_before,
479 std::fs::read_to_string(&head).unwrap(),
480 "HEAD still just says `ref: refs/heads/main` — watching it alone \
481 cannot catch a commit on a packed branch"
482 );
483 assert_ne!(
484 reflog_before,
485 std::fs::read_to_string(&reflog).unwrap(),
486 "the reflog must record the new commit — this is what makes \
487 logs/HEAD a sufficient watch when the ref is packed"
488 );
489 }
490
491 #[tokio::test]
492 async fn creates_missing_parent_dir() {
493 let root = tempfile::tempdir().unwrap();
494 let nested = root.path().join("deep").join(".state");
495 assert!(!nested.exists());
496
497 let info = BuildInfo::load_and_increment_in(&nested).await.unwrap();
498 assert_eq!(info.build, 1);
499 assert!(nested.join("build.json").exists());
500 }
501}