Skip to main content

supercode_harness/
git_metadata.rs

1//! P4e (COMPOSABLE-HARNESS-DESIGN.md §1.6/§3.1 `core.session.git_metadata`,
2//! catalog:331 "Git integration (metadata, diff, PR)"): a persisted, TYPED
3//! record of the git branch/sha/dirty state a session was RUNNING under,
4//! captured ONCE at session start (closes the loop catalog:331 flags —
5//! supercode already preserves a foreign session's own git-shaped fields
6//! byte-for-byte on IMPORT via `Session::raw`'s verbatim capture; this is
7//! the WRITE half: supercode's OWN sessions get the same provenance).
8//! Deliberately flat/typed (not a formatted string), the exact same
9//! rationale as [`crate::usage_log::UsageRecord`]/
10//! [`crate::model_change::ModelChangeRecord`] (§1.13): a translatable,
11//! lossless session-data channel, not a lossy notice — so it survives a
12//! save/load round trip byte-for-byte, and a future reader (a translator,
13//! `doctor`/`inspect stats`) can consume it without re-parsing prose.
14
15use serde::{Deserialize, Serialize};
16
17/// One session's git provenance, best-effort captured at construction time
18/// (`Agent::with_parts`, gated by `Config::session_git_metadata`).
19#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
20pub struct GitMetadataRecord {
21    /// `git rev-parse --abbrev-ref HEAD`, if `cwd` is inside a git repo and
22    /// `git` is on `PATH`. `None` otherwise — never blocks capture.
23    pub branch: Option<String>,
24    /// `git rev-parse HEAD` (the full 40-char sha), same availability as
25    /// [`Self::branch`].
26    pub sha: Option<String>,
27    /// Whether `git status --porcelain` reported any changes. `false` when
28    /// git information couldn't be read at all (an honest "unknown treated
29    /// as clean", matching `agent::env_context_git_status`'s existing
30    /// posture).
31    #[serde(default)]
32    pub dirty: bool,
33    /// Unix-ms wall-clock time the record was captured.
34    #[serde(default)]
35    pub captured_at_ms: i64,
36}
37
38/// Best-effort capture of `cwd`'s git branch/sha/dirty state. `None` when
39/// `cwd` isn't inside a git repo, `git` isn't on `PATH`, or the repo has no
40/// commits yet (`rev-parse HEAD` fails on an empty repo) — this is
41/// informational provenance, never worth failing agent construction over,
42/// the same posture `agent::env_context_git_status` already established.
43pub fn capture(cwd: &std::path::Path, timestamp_ms: i64) -> Option<GitMetadataRecord> {
44    let branch_out = std::process::Command::new("git")
45        .args(["rev-parse", "--abbrev-ref", "HEAD"])
46        .current_dir(cwd)
47        .output()
48        .ok()?;
49    if !branch_out.status.success() {
50        return None;
51    }
52    let branch = String::from_utf8_lossy(&branch_out.stdout)
53        .trim()
54        .to_string();
55    if branch.is_empty() {
56        return None;
57    }
58    let sha = std::process::Command::new("git")
59        .args(["rev-parse", "HEAD"])
60        .current_dir(cwd)
61        .output()
62        .ok()
63        .filter(|o| o.status.success())
64        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
65        .filter(|s| !s.is_empty());
66    let dirty = std::process::Command::new("git")
67        .args(["status", "--porcelain"])
68        .current_dir(cwd)
69        .output()
70        .ok()
71        .map(|o| !o.stdout.is_empty())
72        .unwrap_or(false);
73    Some(GitMetadataRecord {
74        branch: Some(branch),
75        sha,
76        dirty,
77        captured_at_ms: timestamp_ms,
78    })
79}
80
81/// Serialize a record as single-line JSON — the `<name>.git.json` sidecar
82/// shape [`crate::store::SessionStore::save_git_metadata`] writes (a
83/// single-record file, like `<name>.reduction.json`, not a JSONL log: git
84/// state is captured once per session, not once per turn).
85pub fn to_json(record: &GitMetadataRecord) -> crate::Result<String> {
86    serde_json::to_string(record).map_err(crate::Error::Decode)
87}
88
89/// Parse a `<name>.git.json` sidecar back into a record — the exact inverse
90/// of [`to_json`].
91pub fn from_json(text: &str) -> crate::Result<GitMetadataRecord> {
92    serde_json::from_str(text).map_err(crate::Error::Decode)
93}