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.com";
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.com>` 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 five 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 /// The proposal a merge commit applies, when this commit is one.
200 /// [`format_commit_message`] emits `Proposal: <id>`, `Merged-By:
201 /// <merger>` and, for the entities the commit created, `Created:
202 /// id1, id2, …`; `parse_commit_message` recovers all three. The
203 /// trailers are additive beside `Identity:` (the proposer on a
204 /// merge commit, the merger on the amend commit that follows an
205 /// `adopt_with_changes`) and are never compared by the checks
206 /// independence gate. `None` for every other commit.
207 pub proposal: Option<ProposalTrailers>,
208}
209
210/// The trailers a proposal merge adds to a commit: the proposal's id
211/// (the fork's name and base sha), the merger's identity, and the ids
212/// the commit created (so the entity story reads a merge that brought
213/// an entity into the target as its creation).
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct ProposalTrailers {
216 pub proposal: String,
217 pub merged_by: String,
218 pub created: Vec<String>,
219 /// `(entity id, identity)`: every fork identity that wrote an entity
220 /// this commit lands, beside the proposer the commit is attributed to.
221 /// One `Co-Writer: <id> <identity>` trailer each; independence counts
222 /// them as writers of the landed entity.
223 pub co_writers: Vec<(String, String)>,
224 /// Ids of landed entities a fork write without an identity touched:
225 /// one `Unattributed-Writer: <id>` trailer each, read as a write with
226 /// no identity (the independence reading then cannot confirm).
227 pub unattributed: Vec<String>,
228 /// `old → new` id pairs: an entry the fork renamed, landed by this
229 /// commit as the old id's deletion and the new id's creation. One
230 /// `Renamed: <old> → <new>` trailer each, so the landed entry's story
231 /// continues the old id's.
232 pub renamed: Vec<(String, String)>,
233}
234
235impl<'a> CommitContext<'a> {
236 /// Author-neutral context: no actor, no client, no tool. The author
237 /// signature falls back to the committer identity — preserving the
238 /// pre-provenance behaviour. Used by engine tests and by call sites
239 /// that have not yet been taught to build a real context.
240 pub fn internal() -> Self {
241 Self {
242 actor: Actor::Unknown,
243 client: None,
244 tool: None,
245 note: None,
246 role: Role::Unspecified,
247 identity: None,
248 logical_operation_id: None,
249 entity_ids: None,
250 proposal: None,
251 }
252 }
253}
254
255/// Inverse of the `name@version` rendering used in both the commit
256/// trailer block (`Client: <name>@<version>`) and the folder-backend
257/// JSONL changelog (`"client": "<name>@<version>"`). Splits on the
258/// **last** `@` because client names may legitimately contain `.`
259/// and `-`; versions never contain `@`. Returns `None` for malformed
260/// input (no `@`, empty name, empty version) so tolerant readers
261/// drop the field rather than constructing a half-record.
262pub fn parse_client_id(s: &str) -> Option<ClientId> {
263 let (name, version) = s.rsplit_once('@')?;
264 if name.is_empty() || version.is_empty() {
265 return None;
266 }
267 Some(ClientId {
268 name: name.to_string(),
269 version: version.to_string(),
270 })
271}
272
273/// Sanitise a raw client name to a git-safe local-part matching
274/// `[a-z0-9._-]+`. Empty/whitespace-only input falls back to `"unknown"`.
275///
276/// - Lowercase ASCII.
277/// - Anything outside `[a-z0-9._-]` becomes `-` (spaces, `/`, `@`, …).
278/// - Non-ASCII bytes also collapse to `-` rather than being dropped, so
279/// the output length still tracks the input coarsely (useful for
280/// debugging a garbled clientInfo).
281pub fn sanitise_client_name(raw: &str) -> String {
282 let mut out = String::with_capacity(raw.len());
283 for ch in raw.chars() {
284 let lower = ch.to_ascii_lowercase();
285 if lower.is_ascii_alphanumeric() || matches!(lower, '.' | '_' | '-') {
286 out.push(lower);
287 } else {
288 out.push('-');
289 }
290 }
291 if out.chars().all(|c| c == '-' || c.is_whitespace()) {
292 return "unknown".to_string();
293 }
294 out
295}
296
297/// Build the per-commit author `(name, email)` pair from the context.
298/// `None` means "fall back to the committer identity" — adapters then
299/// reuse the committer signature for the author slot.
300///
301/// Public so both the legacy disk adapter and the git-tree adapter can
302/// build byte-identical commit objects without re-implementing the
303/// trailer + author convention.
304pub fn author_identity(ctx: &CommitContext<'_>) -> Option<(String, String)> {
305 match (ctx.actor, ctx.client.as_ref()) {
306 (Actor::Agent | Actor::Cli | Actor::App, Some(c)) => {
307 let local = sanitise_client_name(&c.name);
308 let email = format!("{local}@{PROVENANCE_EMAIL_DOMAIN}");
309 Some((local, email))
310 }
311 (Actor::External, _) => Some((
312 "external".to_string(),
313 format!("external@{PROVENANCE_EMAIL_DOMAIN}"),
314 )),
315 // Agent/Cli/App without a ClientId, or Unknown: no derived
316 // identity; caller falls back to the committer signature.
317 _ => None,
318 }
319}
320
321/// Append the trailer block to the caller's prose, separated by exactly
322/// one blank line. Normalises trailing newlines so `"subject"` and
323/// `"subject\n"` both produce `"subject\n\nActor: …\n…"`.
324///
325/// When `ctx.note` carries a non-blank string, it is inserted between the
326/// prose and the trailer block — with exactly one blank line on each
327/// side. Whitespace-only notes are treated as absent (callers that want
328/// an empty note must pass `None`). The final layout is:
329///
330/// ```text
331/// <prose>
332///
333/// <note, if present>
334///
335/// <trailer block>
336/// ```
337///
338/// `Actor:` is always emitted. `Tool:` is emitted when `ctx.tool` is set.
339/// `Client:` is emitted when `ctx.client` is set. Order: `Tool`, `Actor`,
340/// `Client`.
341///
342/// Public so both adapters share the same trailer block — the two paths
343/// must produce byte-identical commit messages for the same logical
344/// input.
345impl<'a> CommitContext<'a> {
346 /// The one place a commit context is built. Every commit the engine
347 /// writes carries the same provenance: the tool that caused it, the
348 /// actor and client of the transport, the agent-authored note, and
349 /// the session's declared role and identity. `logical_operation_id`
350 /// and `entity_ids` start absent; a multi-commit operation sets them
351 /// on the value it gets back.
352 pub fn new(
353 tool: Option<&'a str>,
354 actor: Actor,
355 client: Option<ClientId>,
356 note: Option<String>,
357 role: Role,
358 identity: Option<String>,
359 ) -> Self {
360 CommitContext {
361 actor,
362 client,
363 tool,
364 note,
365 role,
366 identity,
367 logical_operation_id: None,
368 entity_ids: None,
369 proposal: None,
370 }
371 }
372}
373
374pub fn format_commit_message(prose: &str, ctx: &CommitContext<'_>) -> String {
375 let trimmed = prose.trim_end_matches('\n');
376 let mut trailers: Vec<String> = Vec::with_capacity(4);
377 if let Some(tool) = ctx.tool {
378 trailers.push(format!("Tool: {tool}"));
379 }
380 trailers.push(format!("Actor: {}", ctx.actor.as_trailer()));
381 if let Some(c) = ctx.client.as_ref() {
382 trailers.push(format!("Client: {}@{}", c.name, c.version));
383 }
384 // `Role:` records the caller-declared role; omitted for
385 // `Unspecified` — the absent trailer IS the record of absence.
386 if let Some(role) = ctx.role.as_trailer() {
387 trailers.push(format!("Role: {role}"));
388 }
389 // `Identity:` records the caller-declared identity;
390 // omitted when absent — the absent trailer IS the record of
391 // absence, same posture as `Role:`.
392 if let Some(identity) = ctx.identity.as_deref() {
393 trailers.push(format!("Identity: {identity}"));
394 }
395 // `Logical-Op:` is the wire-stable trailer key. Recognised by
396 // `parse_commit_message` and threaded back into
397 // `Provenance::logical_operation_id` so the multi-mem rename
398 // correlation survives a commit-log round-trip through the
399 // git-branch backend.
400 if let Some(id) = ctx.logical_operation_id {
401 trailers.push(format!("Logical-Op: {id}"));
402 }
403 // `Entities:` lists every id a multi-entity commit touched (batch
404 // update), comma-separated. Recovered by `parse_commit_message` into
405 // `CommitNote::entity_ids` so a note read in isolation names the
406 // entities even though the subject only says `(N entities)`. Omitted
407 // when absent or empty — single-entity commits carry their id in the
408 // subject. Ids never contain `, ` so the join is unambiguous.
409 if let Some(ids) = ctx.entity_ids.as_ref().filter(|v| !v.is_empty()) {
410 trailers.push(format!("Entities: {}", ids.join(", ")));
411 }
412 // `Merged-By:`, `Proposal:` and `Created:` mark a proposal merge:
413 // the merger beside the proposer's `Identity:`, the proposal the
414 // commit applies, and the ids it created (recovered by
415 // `parse_commit_message`; the entity story treats such a commit as
416 // those entities' creation).
417 if let Some(p) = ctx.proposal.as_ref() {
418 trailers.push(format!("Merged-By: {}", p.merged_by));
419 trailers.push(format!("Proposal: {}", p.proposal));
420 if !p.created.is_empty() {
421 trailers.push(format!("Created: {}", p.created.join(", ")));
422 }
423 for (id, identity) in &p.co_writers {
424 trailers.push(format!("Co-Writer: {id} {identity}"));
425 }
426 for id in &p.unattributed {
427 trailers.push(format!("Unattributed-Writer: {id}"));
428 }
429 for (old, new) in &p.renamed {
430 trailers.push(format!("Renamed: {old} → {new}"));
431 }
432 }
433 let note_body = ctx.note.as_deref().map(str::trim).filter(|n| !n.is_empty());
434 match note_body {
435 Some(note) => format!("{trimmed}\n\n{note}\n\n{}", trailers.join("\n")),
436 None => format!("{trimmed}\n\n{}", trailers.join("\n")),
437 }
438}