Skip to main content

memstead_base/
vcs.rs

1//! Backend-agnostic VCS provenance types and trailer-block helpers.
2//!
3//! The engine's git-bound bits — the [`Vcs`] trait, gix-using
4//! repository helpers, [`VcsError`] and its `From<gix::*>` conversions
5//! — live in `memstead_git_branch::vcs`. What stays
6//! here is the data model that travels through every commit (caller
7//! actor, client identity, optional tool name and provenance note) and
8//! the deterministic helpers that turn that data into the author
9//! signature and trailer block. Both adapters (legacy disk + git-tree)
10//! call the helpers so two paths produce byte-identical commit
11//! messages for the same logical input.
12//!
13//! [`Vcs`]: ../../memstead_git_branch/vcs/trait.Vcs.html
14//! [`VcsError`]: ../../memstead_git_branch/vcs/enum.VcsError.html
15
16/// Generic email domain for derived author addresses. No PII: the
17/// local-part is a sanitised client name (or `external`), never a user.
18const PROVENANCE_EMAIL_DOMAIN: &str = "memstead.io";
19
20/// Caller categories for the `Actor:` trailer and for picking an author
21/// signature. `Agent` and `Cli` get their author from the paired
22/// `ClientId` when one is present; `External` always uses the synthetic
23/// `external <external@memstead.io>` identity (no client is known); `Unknown`
24/// falls back to the committer identity.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum Actor {
27    Agent,
28    Cli,
29    External,
30    Unknown,
31}
32
33impl Actor {
34    /// String form used for the `Actor:` trailer. Stable; downstream LLMs
35    /// grep on these values.
36    pub fn as_trailer(&self) -> &'static str {
37        match self {
38            Actor::Agent => "agent",
39            Actor::Cli => "cli",
40            Actor::External => "external",
41            Actor::Unknown => "unknown",
42        }
43    }
44
45    /// Inverse of [`Self::as_trailer`]. Returns `None` for any string
46    /// outside the four canonical wire forms — readers that may
47    /// encounter older or malformed values choose how to handle the
48    /// absence (default to [`Actor::Unknown`], surface a warning, …).
49    pub fn from_trailer(s: &str) -> Option<Self> {
50        match s {
51            "agent" => Some(Actor::Agent),
52            "cli" => Some(Actor::Cli),
53            "external" => Some(Actor::External),
54            "unknown" => Some(Actor::Unknown),
55            _ => None,
56        }
57    }
58}
59
60/// Identity of the process speaking to the engine. For MCP, this is the
61/// `clientInfo` from the initialize handshake (e.g.
62/// `ClientId { name: "claude-code", version: "2.1.0" }`). For CLI-direct
63/// mutations, the crate populates it with its own name and version.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct ClientId {
66    pub name: String,
67    pub version: String,
68}
69
70/// Provenance bundle for a single commit. Produced at the caller boundary
71/// (`memstead-mcp` tool handler, `memstead-cli` subcommand, engine-internal drift
72/// flush) and threaded through to the VCS commit path.
73#[derive(Debug, Clone)]
74pub struct CommitContext<'a> {
75    pub actor: Actor,
76    pub client: Option<ClientId>,
77    /// Name of the MCP tool that initiated the commit (e.g.
78    /// `"memstead_update"`). Present for MCP-sourced commits; CLI-direct and
79    /// external-drift commits leave this `None`.
80    pub tool: Option<&'a str>,
81    /// Agent-authored one-sentence provenance note. When present and
82    /// non-empty it lands in the commit body between the caller's prose
83    /// and the `Tool:/Actor:/Client:` trailer block. Whitespace-only
84    /// values are treated as absent. The MCP layer validates length
85    /// (`NOTE_MAX_LEN`, 280 chars) before the mutation touches disk;
86    /// callers must not feed unbounded input to this field.
87    pub note: Option<String>,
88    /// Correlation id linking every commit produced by a single
89    /// logical operation (notably multi-mem `memstead_rename`). When
90    /// `Some`, [`format_commit_message`] emits a `Logical-Op: <id>`
91    /// trailer alongside `Tool:` / `Actor:` / `Client:`. The git-
92    /// branch backend's `parse_commit_message` recovers the value
93    /// from the trailer block so `read_provenance` reconstructs
94    /// `Provenance::logical_operation_id` round-trip-clean. `None`
95    /// for legacy or single-call mutations that don't participate
96    /// in correlation; consumers branch on whether the id recurs to
97    /// identify a multi-commit logical operation.
98    pub logical_operation_id: Option<&'a str>,
99    /// Entity ids this commit touched, when one commit covers more than
100    /// one entity (notably `batch_update`, whose subject collapses to
101    /// `(N entities)`). When `Some` and non-empty, [`format_commit_message`]
102    /// emits an `Entities: id1, id2, …` trailer that `parse_commit_message`
103    /// recovers into `CommitNote::entity_ids`, so an `--include-notes`
104    /// consumer can name every entity a batch changed from the note record
105    /// alone. `None`/empty for single-entity commits — those name their
106    /// one id in the subject (and thus `entity_id`), so no list is needed.
107    pub entity_ids: Option<Vec<String>>,
108}
109
110impl<'a> CommitContext<'a> {
111    /// Author-neutral context: no actor, no client, no tool. The author
112    /// signature falls back to the committer identity — preserving the
113    /// pre-provenance behaviour. Used by engine tests and by call sites
114    /// that have not yet been taught to build a real context.
115    pub fn internal() -> Self {
116        Self {
117            actor: Actor::Unknown,
118            client: None,
119            tool: None,
120            note: None,
121            logical_operation_id: None,
122            entity_ids: None,
123        }
124    }
125}
126
127/// Inverse of the `name@version` rendering used in both the commit
128/// trailer block (`Client: <name>@<version>`) and the folder-backend
129/// JSONL changelog (`"client": "<name>@<version>"`). Splits on the
130/// **last** `@` because client names may legitimately contain `.`
131/// and `-`; versions never contain `@`. Returns `None` for malformed
132/// input (no `@`, empty name, empty version) so tolerant readers
133/// drop the field rather than constructing a half-record.
134pub fn parse_client_id(s: &str) -> Option<ClientId> {
135    let (name, version) = s.rsplit_once('@')?;
136    if name.is_empty() || version.is_empty() {
137        return None;
138    }
139    Some(ClientId {
140        name: name.to_string(),
141        version: version.to_string(),
142    })
143}
144
145/// Sanitise a raw client name to a git-safe local-part matching
146/// `[a-z0-9._-]+`. Empty/whitespace-only input falls back to `"unknown"`.
147///
148/// - Lowercase ASCII.
149/// - Anything outside `[a-z0-9._-]` becomes `-` (spaces, `/`, `@`, …).
150/// - Non-ASCII bytes also collapse to `-` rather than being dropped, so
151///   the output length still tracks the input coarsely (useful for
152///   debugging a garbled clientInfo).
153pub fn sanitise_client_name(raw: &str) -> String {
154    let mut out = String::with_capacity(raw.len());
155    for ch in raw.chars() {
156        let lower = ch.to_ascii_lowercase();
157        if lower.is_ascii_alphanumeric() || matches!(lower, '.' | '_' | '-') {
158            out.push(lower);
159        } else {
160            out.push('-');
161        }
162    }
163    if out.chars().all(|c| c == '-' || c.is_whitespace()) {
164        return "unknown".to_string();
165    }
166    out
167}
168
169/// Build the per-commit author `(name, email)` pair from the context.
170/// `None` means "fall back to the committer identity" — adapters then
171/// reuse the committer signature for the author slot.
172///
173/// Public so both the legacy disk adapter and the git-tree adapter can
174/// build byte-identical commit objects without re-implementing the
175/// trailer + author convention.
176pub fn author_identity(ctx: &CommitContext<'_>) -> Option<(String, String)> {
177    match (ctx.actor, ctx.client.as_ref()) {
178        (Actor::Agent | Actor::Cli, Some(c)) => {
179            let local = sanitise_client_name(&c.name);
180            let email = format!("{local}@{PROVENANCE_EMAIL_DOMAIN}");
181            Some((local, email))
182        }
183        (Actor::External, _) => Some((
184            "external".to_string(),
185            format!("external@{PROVENANCE_EMAIL_DOMAIN}"),
186        )),
187        // Agent/Cli without a ClientId, or Unknown: no derived identity;
188        // caller falls back to the committer signature.
189        _ => None,
190    }
191}
192
193/// Append the trailer block to the caller's prose, separated by exactly
194/// one blank line. Normalises trailing newlines so `"subject"` and
195/// `"subject\n"` both produce `"subject\n\nActor: …\n…"`.
196///
197/// When `ctx.note` carries a non-blank string, it is inserted between the
198/// prose and the trailer block — with exactly one blank line on each
199/// side. Whitespace-only notes are treated as absent (callers that want
200/// an empty note must pass `None`). The final layout is:
201///
202/// ```text
203/// <prose>
204///
205/// <note, if present>
206///
207/// <trailer block>
208/// ```
209///
210/// `Actor:` is always emitted. `Tool:` is emitted when `ctx.tool` is set.
211/// `Client:` is emitted when `ctx.client` is set. Order: `Tool`, `Actor`,
212/// `Client`.
213///
214/// Public so both adapters share the same trailer block — the two paths
215/// must produce byte-identical commit messages for the same logical
216/// input.
217pub fn format_commit_message(prose: &str, ctx: &CommitContext<'_>) -> String {
218    let trimmed = prose.trim_end_matches('\n');
219    let mut trailers: Vec<String> = Vec::with_capacity(4);
220    if let Some(tool) = ctx.tool {
221        trailers.push(format!("Tool: {tool}"));
222    }
223    trailers.push(format!("Actor: {}", ctx.actor.as_trailer()));
224    if let Some(c) = ctx.client.as_ref() {
225        trailers.push(format!("Client: {}@{}", c.name, c.version));
226    }
227    // `Logical-Op:` is the wire-stable trailer key. Recognised by
228    // `parse_commit_message` and threaded back into
229    // `Provenance::logical_operation_id` so the multi-mem rename
230    // correlation survives a commit-log round-trip through the
231    // git-branch backend.
232    if let Some(id) = ctx.logical_operation_id {
233        trailers.push(format!("Logical-Op: {id}"));
234    }
235    // `Entities:` lists every id a multi-entity commit touched (batch
236    // update), comma-separated. Recovered by `parse_commit_message` into
237    // `CommitNote::entity_ids` so a note read in isolation names the
238    // entities even though the subject only says `(N entities)`. Omitted
239    // when absent or empty — single-entity commits carry their id in the
240    // subject. Ids never contain `, ` so the join is unambiguous.
241    if let Some(ids) = ctx.entity_ids.as_ref().filter(|v| !v.is_empty()) {
242        trailers.push(format!("Entities: {}", ids.join(", ")));
243    }
244    let note_body = ctx.note.as_deref().map(str::trim).filter(|n| !n.is_empty());
245    match note_body {
246        Some(note) => format!("{trimmed}\n\n{note}\n\n{}", trailers.join("\n")),
247        None => format!("{trimmed}\n\n{}", trailers.join("\n")),
248    }
249}