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/// Maximum length (in chars) of a caller-declared identity. Length-bounded like the provenance note: the engine
21/// neither generates, interprets, nor enriches the value — it is an
22/// opaque caller-chosen string (an agent name, a session handle, a
23/// person's chosen tag), and the bound only keeps the append-only
24/// record from carrying unbounded input. Surfaces validate against
25/// this before the mutation touches disk.
26pub const IDENTITY_MAX_LEN: usize = 128;
27
28/// Normalise a caller-supplied identity: trim, treat empty /
29/// whitespace-only as absent. Length validation is the surface's job
30/// (typed refusal against [`IDENTITY_MAX_LEN`]); this helper only
31/// canonicalises presence, so "no identity" has exactly one recorded
32/// shape everywhere.
33pub fn normalise_identity(raw: Option<&str>) -> Option<String> {
34 raw.map(str::trim)
35 .filter(|s| !s.is_empty())
36 .map(str::to_string)
37}
38
39/// Caller categories for the `Actor:` trailer and for picking an author
40/// signature. `Agent`, `Cli`, and `App` get their author from the paired
41/// `ClientId` when one is present; `External` always uses the synthetic
42/// `external <external@memstead.io>` identity (no client is known); `Unknown`
43/// falls back to the committer identity.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Actor {
46 Agent,
47 Cli,
48 /// A human-driven application embedding or fronting the engine —
49 /// the node app's HTTP surface, any future UI
50 /// consumer. Distinct from `Agent` (an LLM speaking MCP) and `Cli`
51 /// (the memstead binary): ambient provenance needs "a human did
52 /// this through app software" as its own category, with the
53 /// paired [`ClientId`] naming which software spoke.
54 App,
55 External,
56 Unknown,
57}
58
59impl Actor {
60 /// String form used for the `Actor:` trailer. Stable; downstream LLMs
61 /// grep on these values.
62 pub fn as_trailer(&self) -> &'static str {
63 match self {
64 Actor::Agent => "agent",
65 Actor::Cli => "cli",
66 Actor::App => "app",
67 Actor::External => "external",
68 Actor::Unknown => "unknown",
69 }
70 }
71
72 /// Inverse of [`Self::as_trailer`]. Returns `None` for any string
73 /// outside the four canonical wire forms — readers that may
74 /// encounter older or malformed values choose how to handle the
75 /// absence (default to [`Actor::Unknown`], surface a warning, …).
76 pub fn from_trailer(s: &str) -> Option<Self> {
77 match s {
78 "agent" => Some(Actor::Agent),
79 "cli" => Some(Actor::Cli),
80 "app" => Some(Actor::App),
81 "external" => Some(Actor::External),
82 "unknown" => Some(Actor::Unknown),
83 _ => None,
84 }
85 }
86}
87
88/// Identity of the process speaking to the engine. For MCP, this is the
89/// `clientInfo` from the initialize handshake (e.g.
90/// `ClientId { name: "claude-code", version: "2.1.0" }`). For CLI-direct
91/// mutations, the crate populates it with its own name and version.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct ClientId {
94 pub name: String,
95 pub version: String,
96}
97
98/// The caller-declared ROLE a mutation was performed in — a closed vocabulary recorded immutably alongside every
99/// mutation (commit trailer / ledger field). Caller-declared but
100/// tamper-evident: bound to specific operations in append-only
101/// history, so it cannot be edited after the fact and identities can
102/// be cross-checked across operations — which no self-written
103/// metadata field can provide. `Unspecified` is legal forever: old
104/// clients, casual sessions, and humans at the CLI are never refused
105/// for not declaring; absence is recorded as absence (no trailer),
106/// and downstream gates treat it as "cannot confirm", never as any
107/// specific role.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum Role {
111 Author,
112 Checker,
113 Verifier,
114 #[default]
115 Unspecified,
116}
117
118impl Role {
119 /// The declared-role wire vocabulary — what a `role` parameter
120 /// accepts. `unspecified` is deliberately NOT declarable: it is
121 /// the recorded absence of a declaration, not a value.
122 pub const DECLARABLE: &'static [&'static str] = &["author", "checker", "verifier"];
123
124 /// Trailer/wire form. `None` for `Unspecified` — absence is
125 /// recorded as absence (no `Role:` trailer, no ledger field).
126 pub fn as_trailer(&self) -> Option<&'static str> {
127 match self {
128 Role::Author => Some("author"),
129 Role::Checker => Some("checker"),
130 Role::Verifier => Some("verifier"),
131 Role::Unspecified => None,
132 }
133 }
134
135 /// Parse a caller-declared role. Returns `None` for anything
136 /// outside [`Self::DECLARABLE`] — the surface refuses typed with
137 /// the vocabulary named rather than defaulting.
138 pub fn from_wire(s: &str) -> Option<Self> {
139 match s {
140 "author" => Some(Role::Author),
141 "checker" => Some(Role::Checker),
142 "verifier" => Some(Role::Verifier),
143 _ => None,
144 }
145 }
146}
147
148/// Provenance bundle for a single commit. Produced at the caller boundary
149/// (`memstead-mcp` tool handler, `memstead-cli` subcommand, engine-internal drift
150/// flush) and threaded through to the VCS commit path.
151#[derive(Debug, Clone)]
152pub struct CommitContext<'a> {
153 pub actor: Actor,
154 pub client: Option<ClientId>,
155 /// Name of the MCP tool that initiated the commit (e.g.
156 /// `"memstead_update"`). Present for MCP-sourced commits; CLI-direct and
157 /// external-drift commits leave this `None`.
158 pub tool: Option<&'a str>,
159 /// Agent-authored one-sentence provenance note. When present and
160 /// non-empty it lands in the commit body between the caller's prose
161 /// and the `Tool:/Actor:/Client:` trailer block. Whitespace-only
162 /// values are treated as absent. The MCP layer validates length
163 /// (`NOTE_MAX_LEN`, 280 chars) before the mutation touches disk;
164 /// callers must not feed unbounded input to this field.
165 pub note: Option<String>,
166 /// The caller-declared role this mutation is performed in
167 ///. `Unspecified` (the default) emits no
168 /// trailer — absence recorded as absence; declared roles emit
169 /// `Role: <value>` in the trailer block.
170 pub role: Role,
171 /// The caller-declared identity performing this mutation
172 ///: an opaque caller-chosen string — an
173 /// agent name, a session handle, a person's tag. Same trust model
174 /// as the role: caller-declared, unverified, tamper-evident
175 /// (bound into append-only history). `None` emits no trailer —
176 /// absence recorded as absence; present values emit
177 /// `Identity: <value>`.
178 pub identity: Option<String>,
179 /// Correlation id linking every commit produced by a single
180 /// logical operation (notably multi-mem `memstead_rename`). When
181 /// `Some`, [`format_commit_message`] emits a `Logical-Op: <id>`
182 /// trailer alongside `Tool:` / `Actor:` / `Client:`. The git-
183 /// branch backend's `parse_commit_message` recovers the value
184 /// from the trailer block so `read_provenance` reconstructs
185 /// `Provenance::logical_operation_id` round-trip-clean. `None`
186 /// for legacy or single-call mutations that don't participate
187 /// in correlation; consumers branch on whether the id recurs to
188 /// identify a multi-commit logical operation.
189 pub logical_operation_id: Option<&'a str>,
190 /// Entity ids this commit touched, when one commit covers more than
191 /// one entity (notably `batch_update`, whose subject collapses to
192 /// `(N entities)`). When `Some` and non-empty, [`format_commit_message`]
193 /// emits an `Entities: id1, id2, …` trailer that `parse_commit_message`
194 /// recovers into `CommitNote::entity_ids`, so an `--include-notes`
195 /// consumer can name every entity a batch changed from the note record
196 /// alone. `None`/empty for single-entity commits — those name their
197 /// one id in the subject (and thus `entity_id`), so no list is needed.
198 pub entity_ids: Option<Vec<String>>,
199}
200
201impl<'a> CommitContext<'a> {
202 /// Author-neutral context: no actor, no client, no tool. The author
203 /// signature falls back to the committer identity — preserving the
204 /// pre-provenance behaviour. Used by engine tests and by call sites
205 /// that have not yet been taught to build a real context.
206 pub fn internal() -> Self {
207 Self {
208 actor: Actor::Unknown,
209 client: None,
210 tool: None,
211 note: None,
212 role: Role::Unspecified,
213 identity: None,
214 logical_operation_id: None,
215 entity_ids: None,
216 }
217 }
218}
219
220/// Inverse of the `name@version` rendering used in both the commit
221/// trailer block (`Client: <name>@<version>`) and the folder-backend
222/// JSONL changelog (`"client": "<name>@<version>"`). Splits on the
223/// **last** `@` because client names may legitimately contain `.`
224/// and `-`; versions never contain `@`. Returns `None` for malformed
225/// input (no `@`, empty name, empty version) so tolerant readers
226/// drop the field rather than constructing a half-record.
227pub fn parse_client_id(s: &str) -> Option<ClientId> {
228 let (name, version) = s.rsplit_once('@')?;
229 if name.is_empty() || version.is_empty() {
230 return None;
231 }
232 Some(ClientId {
233 name: name.to_string(),
234 version: version.to_string(),
235 })
236}
237
238/// Sanitise a raw client name to a git-safe local-part matching
239/// `[a-z0-9._-]+`. Empty/whitespace-only input falls back to `"unknown"`.
240///
241/// - Lowercase ASCII.
242/// - Anything outside `[a-z0-9._-]` becomes `-` (spaces, `/`, `@`, …).
243/// - Non-ASCII bytes also collapse to `-` rather than being dropped, so
244/// the output length still tracks the input coarsely (useful for
245/// debugging a garbled clientInfo).
246pub fn sanitise_client_name(raw: &str) -> String {
247 let mut out = String::with_capacity(raw.len());
248 for ch in raw.chars() {
249 let lower = ch.to_ascii_lowercase();
250 if lower.is_ascii_alphanumeric() || matches!(lower, '.' | '_' | '-') {
251 out.push(lower);
252 } else {
253 out.push('-');
254 }
255 }
256 if out.chars().all(|c| c == '-' || c.is_whitespace()) {
257 return "unknown".to_string();
258 }
259 out
260}
261
262/// Build the per-commit author `(name, email)` pair from the context.
263/// `None` means "fall back to the committer identity" — adapters then
264/// reuse the committer signature for the author slot.
265///
266/// Public so both the legacy disk adapter and the git-tree adapter can
267/// build byte-identical commit objects without re-implementing the
268/// trailer + author convention.
269pub fn author_identity(ctx: &CommitContext<'_>) -> Option<(String, String)> {
270 match (ctx.actor, ctx.client.as_ref()) {
271 (Actor::Agent | Actor::Cli | Actor::App, Some(c)) => {
272 let local = sanitise_client_name(&c.name);
273 let email = format!("{local}@{PROVENANCE_EMAIL_DOMAIN}");
274 Some((local, email))
275 }
276 (Actor::External, _) => Some((
277 "external".to_string(),
278 format!("external@{PROVENANCE_EMAIL_DOMAIN}"),
279 )),
280 // Agent/Cli/App without a ClientId, or Unknown: no derived
281 // identity; caller falls back to the committer signature.
282 _ => None,
283 }
284}
285
286/// Append the trailer block to the caller's prose, separated by exactly
287/// one blank line. Normalises trailing newlines so `"subject"` and
288/// `"subject\n"` both produce `"subject\n\nActor: …\n…"`.
289///
290/// When `ctx.note` carries a non-blank string, it is inserted between the
291/// prose and the trailer block — with exactly one blank line on each
292/// side. Whitespace-only notes are treated as absent (callers that want
293/// an empty note must pass `None`). The final layout is:
294///
295/// ```text
296/// <prose>
297///
298/// <note, if present>
299///
300/// <trailer block>
301/// ```
302///
303/// `Actor:` is always emitted. `Tool:` is emitted when `ctx.tool` is set.
304/// `Client:` is emitted when `ctx.client` is set. Order: `Tool`, `Actor`,
305/// `Client`.
306///
307/// Public so both adapters share the same trailer block — the two paths
308/// must produce byte-identical commit messages for the same logical
309/// input.
310pub fn format_commit_message(prose: &str, ctx: &CommitContext<'_>) -> String {
311 let trimmed = prose.trim_end_matches('\n');
312 let mut trailers: Vec<String> = Vec::with_capacity(4);
313 if let Some(tool) = ctx.tool {
314 trailers.push(format!("Tool: {tool}"));
315 }
316 trailers.push(format!("Actor: {}", ctx.actor.as_trailer()));
317 if let Some(c) = ctx.client.as_ref() {
318 trailers.push(format!("Client: {}@{}", c.name, c.version));
319 }
320 // `Role:` records the caller-declared role (plan 13); omitted for
321 // `Unspecified` — the absent trailer IS the record of absence.
322 if let Some(role) = ctx.role.as_trailer() {
323 trailers.push(format!("Role: {role}"));
324 }
325 // `Identity:` records the caller-declared identity (plan 15);
326 // omitted when absent — the absent trailer IS the record of
327 // absence, same posture as `Role:`.
328 if let Some(identity) = ctx.identity.as_deref() {
329 trailers.push(format!("Identity: {identity}"));
330 }
331 // `Logical-Op:` is the wire-stable trailer key. Recognised by
332 // `parse_commit_message` and threaded back into
333 // `Provenance::logical_operation_id` so the multi-mem rename
334 // correlation survives a commit-log round-trip through the
335 // git-branch backend.
336 if let Some(id) = ctx.logical_operation_id {
337 trailers.push(format!("Logical-Op: {id}"));
338 }
339 // `Entities:` lists every id a multi-entity commit touched (batch
340 // update), comma-separated. Recovered by `parse_commit_message` into
341 // `CommitNote::entity_ids` so a note read in isolation names the
342 // entities even though the subject only says `(N entities)`. Omitted
343 // when absent or empty — single-entity commits carry their id in the
344 // subject. Ids never contain `, ` so the join is unambiguous.
345 if let Some(ids) = ctx.entity_ids.as_ref().filter(|v| !v.is_empty()) {
346 trailers.push(format!("Entities: {}", ids.join(", ")));
347 }
348 let note_body = ctx.note.as_deref().map(str::trim).filter(|n| !n.is_empty());
349 match note_body {
350 Some(note) => format!("{trimmed}\n\n{note}\n\n{}", trailers.join("\n")),
351 None => format!("{trimmed}\n\n{}", trailers.join("\n")),
352 }
353}