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