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.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, and make it one line (an identity is a
30/// name or a handle: any run of whitespace inside it, a line break
31/// included, becomes one space, so the value is the same single line
32/// in every record that carries it). Length validation is the
33/// surface's job (typed refusal against [`IDENTITY_MAX_LEN`]); this
34/// helper canonicalises presence and shape, so "no identity" and any
35/// given identity have exactly one recorded form everywhere.
36pub fn normalise_identity(raw: Option<&str>) -> Option<String> {
37    let one_line = raw?.split_whitespace().collect::<Vec<_>>().join(" ");
38    (!one_line.is_empty()).then_some(one_line)
39}
40
41/// One line of a batch commit's note record for the entry of `id`:
42/// `<id>: <note>`, with every further line of the note indented by two
43/// spaces. The indent is what keeps the record unambiguous: a line of
44/// one entry's note that happens to begin with another entry's id
45/// cannot be read as that entry's line.
46pub fn batch_note_line(id: &str, note: &str) -> String {
47    format!("{id}: {}", note.replace('\n', "\n  "))
48}
49
50/// Caller categories for the `Actor:` trailer and for picking an author
51/// signature. `Agent`, `Cli`, and `App` get their author from the paired
52/// `ClientId` when one is present; `External` always uses the synthetic
53/// `external <external@memstead.com>` identity (no client is known); `Unknown`
54/// falls back to the committer identity.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Actor {
57    Agent,
58    Cli,
59    /// A human-driven application embedding or fronting the engine —
60    /// the node app's HTTP surface, any future UI
61    /// consumer. Distinct from `Agent` (an LLM speaking MCP) and `Cli`
62    /// (the memstead binary): ambient provenance needs "a human did
63    /// this through app software" as its own category, with the
64    /// paired [`ClientId`] naming which software spoke.
65    App,
66    External,
67    Unknown,
68}
69
70impl Actor {
71    /// String form used for the `Actor:` trailer. Stable; downstream LLMs
72    /// grep on these values.
73    pub fn as_trailer(&self) -> &'static str {
74        match self {
75            Actor::Agent => "agent",
76            Actor::Cli => "cli",
77            Actor::App => "app",
78            Actor::External => "external",
79            Actor::Unknown => "unknown",
80        }
81    }
82
83    /// Inverse of [`Self::as_trailer`]. Returns `None` for any string
84    /// outside the five canonical wire forms — readers that may
85    /// encounter older or malformed values choose how to handle the
86    /// absence (default to [`Actor::Unknown`], surface a warning, …).
87    pub fn from_trailer(s: &str) -> Option<Self> {
88        match s {
89            "agent" => Some(Actor::Agent),
90            "cli" => Some(Actor::Cli),
91            "app" => Some(Actor::App),
92            "external" => Some(Actor::External),
93            "unknown" => Some(Actor::Unknown),
94            _ => None,
95        }
96    }
97}
98
99/// Identity of the process speaking to the engine. For MCP, this is the
100/// `clientInfo` from the initialize handshake (e.g.
101/// `ClientId { name: "claude-code", version: "2.1.0" }`). For CLI-direct
102/// mutations, the crate populates it with its own name and version.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct ClientId {
105    pub name: String,
106    pub version: String,
107}
108
109/// The caller-declared ROLE a mutation was performed in — a closed vocabulary recorded immutably alongside every
110/// mutation (commit trailer / ledger field). Caller-declared but
111/// tamper-evident: bound to specific operations in append-only
112/// history, so it cannot be edited after the fact and identities can
113/// be cross-checked across operations — which no self-written
114/// metadata field can provide. `Unspecified` is legal forever: old
115/// clients, casual sessions, and humans at the CLI are never refused
116/// for not declaring; absence is recorded as absence (no trailer),
117/// and downstream gates treat it as "cannot confirm", never as any
118/// specific role.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
120#[serde(rename_all = "snake_case")]
121pub enum Role {
122    Author,
123    Checker,
124    Verifier,
125    #[default]
126    Unspecified,
127}
128
129impl Role {
130    /// The declared-role wire vocabulary — what a `role` parameter
131    /// accepts. `unspecified` is deliberately NOT declarable: it is
132    /// the recorded absence of a declaration, not a value.
133    pub const DECLARABLE: &'static [&'static str] = &["author", "checker", "verifier"];
134
135    /// Trailer/wire form. `None` for `Unspecified` — absence is
136    /// recorded as absence (no `Role:` trailer, no ledger field).
137    pub fn as_trailer(&self) -> Option<&'static str> {
138        match self {
139            Role::Author => Some("author"),
140            Role::Checker => Some("checker"),
141            Role::Verifier => Some("verifier"),
142            Role::Unspecified => None,
143        }
144    }
145
146    /// Parse a caller-declared role. Returns `None` for anything
147    /// outside [`Self::DECLARABLE`] — the surface refuses typed with
148    /// the vocabulary named rather than defaulting.
149    pub fn from_wire(s: &str) -> Option<Self> {
150        match s {
151            "author" => Some(Role::Author),
152            "checker" => Some(Role::Checker),
153            "verifier" => Some(Role::Verifier),
154            _ => None,
155        }
156    }
157}
158
159/// Provenance bundle for a single commit. Produced at the caller boundary
160/// (`memstead-mcp` tool handler, `memstead-cli` subcommand, engine-internal drift
161/// flush) and threaded through to the VCS commit path.
162#[derive(Debug, Clone)]
163pub struct CommitContext<'a> {
164    pub actor: Actor,
165    pub client: Option<ClientId>,
166    /// Name of the MCP tool that initiated the commit (e.g.
167    /// `"memstead_update"`). Present for MCP-sourced commits; CLI-direct and
168    /// external-drift commits leave this `None`.
169    pub tool: Option<&'a str>,
170    /// Agent-authored one-sentence provenance note. When present and
171    /// non-empty it lands in the commit body between the caller's prose
172    /// and the `Tool:/Actor:/Client:` trailer block. Whitespace-only
173    /// values are treated as absent. The MCP layer validates length
174    /// (`NOTE_MAX_LEN`, 280 chars) before the mutation touches disk;
175    /// callers must not feed unbounded input to this field.
176    pub note: Option<String>,
177    /// The caller-declared role this mutation is performed in.
178    /// `Unspecified` (the default) emits no
179    /// trailer — absence recorded as absence; declared roles emit
180    /// `Role: <value>` in the trailer block.
181    pub role: Role,
182    /// The caller-declared identity performing this mutation:
183    /// an opaque caller-chosen string — an
184    /// agent name, a session handle, a person's tag. Same trust model
185    /// as the role: caller-declared, unverified, tamper-evident
186    /// (bound into append-only history). `None` emits no trailer —
187    /// absence recorded as absence; present values emit
188    /// `Identity: <value>`.
189    pub identity: Option<String>,
190    /// Correlation id linking every commit produced by a single
191    /// logical operation (notably multi-mem `memstead_rename`). When
192    /// `Some`, [`format_commit_message`] emits a `Logical-Op: <id>`
193    /// trailer alongside `Tool:` / `Actor:` / `Client:`. The git-
194    /// branch backend's `parse_commit_message` recovers the value
195    /// from the trailer block so `read_provenance` reconstructs
196    /// `Provenance::logical_operation_id` round-trip-clean. `None`
197    /// for legacy or single-call mutations that don't participate
198    /// in correlation; consumers branch on whether the id recurs to
199    /// identify a multi-commit logical operation.
200    pub logical_operation_id: Option<&'a str>,
201    /// Entity ids this commit touched, when one commit covers more than
202    /// one entity (notably `batch_update`, whose subject collapses to
203    /// `(N entities)`). When `Some` and non-empty, [`format_commit_message`]
204    /// emits an `Entities: id1, id2, …` trailer that `parse_commit_message`
205    /// recovers into `CommitNote::entity_ids`, so an `--include-notes`
206    /// consumer can name every entity a batch changed from the note record
207    /// alone. `None`/empty for single-entity commits — those name their
208    /// one id in the subject (and thus `entity_id`), so no list is needed.
209    pub entity_ids: Option<Vec<String>>,
210    /// The proposal a merge commit applies, when this commit is one.
211    /// [`format_commit_message`] emits `Proposal: <id>`, `Merged-By:
212    /// <merger>` and, for the entities the commit created, `Created:
213    /// id1, id2, …`; `parse_commit_message` recovers all three. The
214    /// trailers are additive beside `Identity:` (the proposer on a
215    /// merge commit, the merger on the amend commit that follows an
216    /// `adopt_with_changes`) and are never compared by the checks
217    /// independence gate. `None` for every other commit.
218    pub proposal: Option<ProposalTrailers>,
219}
220
221/// The trailers a proposal merge adds to a commit: the proposal's id
222/// (the fork's name and base sha), the merger's identity, and the ids
223/// the commit created (so the entity story reads a merge that brought
224/// an entity into the target as its creation).
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub struct ProposalTrailers {
227    pub proposal: String,
228    pub merged_by: String,
229    pub created: Vec<String>,
230    /// `(entity id, identity)`: every fork identity that wrote an entity
231    /// this commit lands, beside the proposer the commit is attributed to.
232    /// One `Co-Writer: <id> <identity>` trailer each; independence counts
233    /// them as writers of the landed entity.
234    pub co_writers: Vec<(String, String)>,
235    /// Ids of landed entities a fork write without an identity touched:
236    /// one `Unattributed-Writer: <id>` trailer each, read as a write with
237    /// no identity (the independence reading then cannot confirm).
238    pub unattributed: Vec<String>,
239    /// `old → new` id pairs: an entry the fork renamed, landed by this
240    /// commit as the old id's deletion and the new id's creation. One
241    /// `Renamed: <old> → <new>` trailer each, so the landed entry's story
242    /// continues the old id's.
243    pub renamed: Vec<(String, String)>,
244}
245
246impl<'a> CommitContext<'a> {
247    /// Author-neutral context: no actor, no client, no tool. The author
248    /// signature falls back to the committer identity — preserving the
249    /// pre-provenance behaviour. Used by engine tests and by call sites
250    /// that have not yet been taught to build a real context.
251    pub fn internal() -> Self {
252        Self {
253            actor: Actor::Unknown,
254            client: None,
255            tool: None,
256            note: None,
257            role: Role::Unspecified,
258            identity: None,
259            logical_operation_id: None,
260            entity_ids: None,
261            proposal: None,
262        }
263    }
264}
265
266/// Inverse of the `name@version` rendering used in both the commit
267/// trailer block (`Client: <name>@<version>`) and the folder-backend
268/// JSONL changelog (`"client": "<name>@<version>"`). Splits on the
269/// **last** `@` because client names may legitimately contain `.`
270/// and `-`; versions never contain `@`. Returns `None` for malformed
271/// input (no `@`, empty name, empty version) so tolerant readers
272/// drop the field rather than constructing a half-record.
273pub fn parse_client_id(s: &str) -> Option<ClientId> {
274    let (name, version) = s.rsplit_once('@')?;
275    if name.is_empty() || version.is_empty() {
276        return None;
277    }
278    Some(ClientId {
279        name: name.to_string(),
280        version: version.to_string(),
281    })
282}
283
284/// Sanitise a raw client name to a git-safe local-part matching
285/// `[a-z0-9._-]+`. Empty/whitespace-only input falls back to `"unknown"`.
286///
287/// - Lowercase ASCII.
288/// - Anything outside `[a-z0-9._-]` becomes `-` (spaces, `/`, `@`, …).
289/// - Non-ASCII bytes also collapse to `-` rather than being dropped, so
290///   the output length still tracks the input coarsely (useful for
291///   debugging a garbled clientInfo).
292pub fn sanitise_client_name(raw: &str) -> String {
293    let mut out = String::with_capacity(raw.len());
294    for ch in raw.chars() {
295        let lower = ch.to_ascii_lowercase();
296        if lower.is_ascii_alphanumeric() || matches!(lower, '.' | '_' | '-') {
297            out.push(lower);
298        } else {
299            out.push('-');
300        }
301    }
302    if out.chars().all(|c| c == '-' || c.is_whitespace()) {
303        return "unknown".to_string();
304    }
305    out
306}
307
308/// Build the per-commit author `(name, email)` pair from the context.
309/// `None` means "fall back to the committer identity" — adapters then
310/// reuse the committer signature for the author slot.
311///
312/// Public so both the legacy disk adapter and the git-tree adapter can
313/// build byte-identical commit objects without re-implementing the
314/// trailer + author convention.
315pub fn author_identity(ctx: &CommitContext<'_>) -> Option<(String, String)> {
316    match (ctx.actor, ctx.client.as_ref()) {
317        (Actor::Agent | Actor::Cli | Actor::App, Some(c)) => {
318            let local = sanitise_client_name(&c.name);
319            let email = format!("{local}@{PROVENANCE_EMAIL_DOMAIN}");
320            Some((local, email))
321        }
322        (Actor::External, _) => Some((
323            "external".to_string(),
324            format!("external@{PROVENANCE_EMAIL_DOMAIN}"),
325        )),
326        // Agent/Cli/App without a ClientId, or Unknown: no derived
327        // identity; caller falls back to the committer signature.
328        _ => None,
329    }
330}
331
332/// Append the trailer block to the caller's prose, separated by exactly
333/// one blank line. Normalises trailing newlines so `"subject"` and
334/// `"subject\n"` both produce `"subject\n\nActor: …\n…"`.
335///
336/// When `ctx.note` carries a non-blank string, it is inserted between the
337/// prose and the trailer block — with exactly one blank line on each
338/// side. Whitespace-only notes are treated as absent (callers that want
339/// an empty note must pass `None`). The final layout is:
340///
341/// ```text
342/// <prose>
343///
344/// <note, if present>
345///
346/// <trailer block>
347/// ```
348///
349/// `Actor:` is always emitted. `Tool:` is emitted when `ctx.tool` is set.
350/// `Client:` is emitted when `ctx.client` is set. Order: `Tool`, `Actor`,
351/// `Client`.
352///
353/// Public so both adapters share the same trailer block — the two paths
354/// must produce byte-identical commit messages for the same logical
355/// input.
356impl<'a> CommitContext<'a> {
357    /// The one place a commit context is built. Every commit the engine
358    /// writes carries the same provenance: the tool that caused it, the
359    /// actor and client of the transport, the agent-authored note, and
360    /// the session's declared role and identity. `logical_operation_id`
361    /// and `entity_ids` start absent; a multi-commit operation sets them
362    /// on the value it gets back.
363    pub fn new(
364        tool: Option<&'a str>,
365        actor: Actor,
366        client: Option<ClientId>,
367        note: Option<String>,
368        role: Role,
369        identity: Option<String>,
370    ) -> Self {
371        CommitContext {
372            actor,
373            client,
374            tool,
375            note,
376            role,
377            identity,
378            logical_operation_id: None,
379            entity_ids: None,
380            proposal: None,
381        }
382    }
383}
384
385pub fn format_commit_message(prose: &str, ctx: &CommitContext<'_>) -> String {
386    let trimmed = prose.trim_end_matches('\n');
387    let mut trailers: Vec<String> = Vec::with_capacity(4);
388    if let Some(tool) = ctx.tool {
389        trailers.push(format!("Tool: {tool}"));
390    }
391    trailers.push(format!("Actor: {}", ctx.actor.as_trailer()));
392    if let Some(c) = ctx.client.as_ref() {
393        trailers.push(format!("Client: {}@{}", c.name, c.version));
394    }
395    // `Role:` records the caller-declared role; omitted for
396    // `Unspecified` — the absent trailer IS the record of absence.
397    if let Some(role) = ctx.role.as_trailer() {
398        trailers.push(format!("Role: {role}"));
399    }
400    // `Identity:` records the caller-declared identity;
401    // omitted when absent — the absent trailer IS the record of
402    // absence, same posture as `Role:`.
403    if let Some(identity) = ctx.identity.as_deref() {
404        trailers.push(format!("Identity: {identity}"));
405    }
406    // `Logical-Op:` is the wire-stable trailer key. Recognised by
407    // `parse_commit_message` and threaded back into
408    // `Provenance::logical_operation_id` so the multi-mem rename
409    // correlation survives a commit-log round-trip through the
410    // git-branch backend.
411    if let Some(id) = ctx.logical_operation_id {
412        trailers.push(format!("Logical-Op: {id}"));
413    }
414    // `Entities:` lists every id a multi-entity commit touched (batch
415    // update), comma-separated. Recovered by `parse_commit_message` into
416    // `CommitNote::entity_ids` so a note read in isolation names the
417    // entities even though the subject only says `(N entities)`. Omitted
418    // when absent or empty — single-entity commits carry their id in the
419    // subject. Ids never contain `, ` so the join is unambiguous.
420    if let Some(ids) = ctx.entity_ids.as_ref().filter(|v| !v.is_empty()) {
421        trailers.push(format!("Entities: {}", ids.join(", ")));
422    }
423    // `Merged-By:`, `Proposal:` and `Created:` mark a proposal merge:
424    // the merger beside the proposer's `Identity:`, the proposal the
425    // commit applies, and the ids it created (recovered by
426    // `parse_commit_message`; the entity story treats such a commit as
427    // those entities' creation).
428    if let Some(p) = ctx.proposal.as_ref() {
429        trailers.push(format!("Merged-By: {}", p.merged_by));
430        trailers.push(format!("Proposal: {}", p.proposal));
431        if !p.created.is_empty() {
432            trailers.push(format!("Created: {}", p.created.join(", ")));
433        }
434        for (id, identity) in &p.co_writers {
435            trailers.push(format!("Co-Writer: {id} {identity}"));
436        }
437        for id in &p.unattributed {
438            trailers.push(format!("Unattributed-Writer: {id}"));
439        }
440        for (old, new) in &p.renamed {
441            trailers.push(format!("Renamed: {old} → {new}"));
442        }
443    }
444    // A trailer is one line. A value with a line break in it (a client
445    // name from a handshake, an identity built by a program that links
446    // the engine) would end its trailer early and start a line a reader
447    // could take for another trailer, so every break becomes a space.
448    for trailer in &mut trailers {
449        if trailer.contains(['\n', '\r']) {
450            *trailer = trailer.replace(['\n', '\r'], " ");
451        }
452    }
453    let note_body = ctx.note.as_deref().map(str::trim).filter(|n| !n.is_empty());
454    match note_body {
455        Some(note) => format!("{trimmed}\n\n{note}\n\n{}", trailers.join("\n")),
456        None => format!("{trimmed}\n\n{}", trailers.join("\n")),
457    }
458}