memstead-base 0.27.1

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Backend-agnostic VCS provenance types and trailer-block helpers.
//!
//! The engine's git-bound bits — the [`Vcs`] trait, gix-using
//! repository helpers, [`VcsError`] and its `From<gix::*>` conversions
//! — live in `memstead_git_branch::vcs`. What stays
//! here is the data model that travels through every commit (caller
//! actor, client identity, optional tool name and provenance note) and
//! the deterministic helpers that turn that data into the author
//! signature and trailer block. Both adapters (legacy disk + git-tree)
//! call the helpers so two paths produce byte-identical commit
//! messages for the same logical input.
//!
//! [`Vcs`]: ../../memstead_git_branch/vcs/trait.Vcs.html
//! [`VcsError`]: ../../memstead_git_branch/vcs/enum.VcsError.html

/// Generic email domain for derived author addresses. No PII: the
/// local-part is a sanitised client name (or `external`), never a user.
const PROVENANCE_EMAIL_DOMAIN: &str = "memstead.com";

/// Maximum length (in chars) of a caller-declared identity. Length-bounded like the provenance note: the engine
/// neither generates, interprets, nor enriches the value — it is an
/// opaque caller-chosen string (an agent name, a session handle, a
/// person's chosen tag), and the bound only keeps the append-only
/// record from carrying unbounded input. Surfaces validate against
/// this before the mutation touches disk.
pub const IDENTITY_MAX_LEN: usize = 128;

/// Normalise a caller-supplied identity: trim, treat empty /
/// whitespace-only as absent, and make it one line (an identity is a
/// name or a handle: any run of whitespace inside it, a line break
/// included, becomes one space, so the value is the same single line
/// in every record that carries it). Length validation is the
/// surface's job (typed refusal against [`IDENTITY_MAX_LEN`]); this
/// helper canonicalises presence and shape, so "no identity" and any
/// given identity have exactly one recorded form everywhere.
pub fn normalise_identity(raw: Option<&str>) -> Option<String> {
    let one_line = raw?.split_whitespace().collect::<Vec<_>>().join(" ");
    (!one_line.is_empty()).then_some(one_line)
}

/// One line of a batch commit's note record for the entry of `id`:
/// `<id>: <note>`, with every further line of the note indented by two
/// spaces. The indent is what keeps the record unambiguous: a line of
/// one entry's note that happens to begin with another entry's id
/// cannot be read as that entry's line.
pub fn batch_note_line(id: &str, note: &str) -> String {
    format!("{id}: {}", note.replace('\n', "\n  "))
}

/// Caller categories for the `Actor:` trailer and for picking an author
/// signature. `Agent`, `Cli`, and `App` get their author from the paired
/// `ClientId` when one is present; `External` always uses the synthetic
/// `external <external@memstead.com>` identity (no client is known); `Unknown`
/// falls back to the committer identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Actor {
    Agent,
    Cli,
    /// A human-driven application embedding or fronting the engine —
    /// the node app's HTTP surface, any future UI
    /// consumer. Distinct from `Agent` (an LLM speaking MCP) and `Cli`
    /// (the memstead binary): ambient provenance needs "a human did
    /// this through app software" as its own category, with the
    /// paired [`ClientId`] naming which software spoke.
    App,
    External,
    Unknown,
}

impl Actor {
    /// String form used for the `Actor:` trailer. Stable; downstream LLMs
    /// grep on these values.
    pub fn as_trailer(&self) -> &'static str {
        match self {
            Actor::Agent => "agent",
            Actor::Cli => "cli",
            Actor::App => "app",
            Actor::External => "external",
            Actor::Unknown => "unknown",
        }
    }

    /// Inverse of [`Self::as_trailer`]. Returns `None` for any string
    /// outside the five canonical wire forms — readers that may
    /// encounter older or malformed values choose how to handle the
    /// absence (default to [`Actor::Unknown`], surface a warning, …).
    pub fn from_trailer(s: &str) -> Option<Self> {
        match s {
            "agent" => Some(Actor::Agent),
            "cli" => Some(Actor::Cli),
            "app" => Some(Actor::App),
            "external" => Some(Actor::External),
            "unknown" => Some(Actor::Unknown),
            _ => None,
        }
    }
}

/// Identity of the process speaking to the engine. For MCP, this is the
/// `clientInfo` from the initialize handshake (e.g.
/// `ClientId { name: "claude-code", version: "2.1.0" }`). For CLI-direct
/// mutations, the crate populates it with its own name and version.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientId {
    pub name: String,
    pub version: String,
}

/// The caller-declared ROLE a mutation was performed in — a closed vocabulary recorded immutably alongside every
/// mutation (commit trailer / ledger field). Caller-declared but
/// tamper-evident: bound to specific operations in append-only
/// history, so it cannot be edited after the fact and identities can
/// be cross-checked across operations — which no self-written
/// metadata field can provide. `Unspecified` is legal forever: old
/// clients, casual sessions, and humans at the CLI are never refused
/// for not declaring; absence is recorded as absence (no trailer),
/// and downstream gates treat it as "cannot confirm", never as any
/// specific role.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
    Author,
    Checker,
    Verifier,
    #[default]
    Unspecified,
}

impl Role {
    /// The declared-role wire vocabulary — what a `role` parameter
    /// accepts. `unspecified` is deliberately NOT declarable: it is
    /// the recorded absence of a declaration, not a value.
    pub const DECLARABLE: &'static [&'static str] = &["author", "checker", "verifier"];

    /// Trailer/wire form. `None` for `Unspecified` — absence is
    /// recorded as absence (no `Role:` trailer, no ledger field).
    pub fn as_trailer(&self) -> Option<&'static str> {
        match self {
            Role::Author => Some("author"),
            Role::Checker => Some("checker"),
            Role::Verifier => Some("verifier"),
            Role::Unspecified => None,
        }
    }

    /// Parse a caller-declared role. Returns `None` for anything
    /// outside [`Self::DECLARABLE`] — the surface refuses typed with
    /// the vocabulary named rather than defaulting.
    pub fn from_wire(s: &str) -> Option<Self> {
        match s {
            "author" => Some(Role::Author),
            "checker" => Some(Role::Checker),
            "verifier" => Some(Role::Verifier),
            _ => None,
        }
    }
}

/// Provenance bundle for a single commit. Produced at the caller boundary
/// (`memstead-mcp` tool handler, `memstead-cli` subcommand, engine-internal drift
/// flush) and threaded through to the VCS commit path.
#[derive(Debug, Clone)]
pub struct CommitContext<'a> {
    pub actor: Actor,
    pub client: Option<ClientId>,
    /// Name of the MCP tool that initiated the commit (e.g.
    /// `"memstead_update"`). Present for MCP-sourced commits; CLI-direct and
    /// external-drift commits leave this `None`.
    pub tool: Option<&'a str>,
    /// Agent-authored one-sentence provenance note. When present and
    /// non-empty it lands in the commit body between the caller's prose
    /// and the `Tool:/Actor:/Client:` trailer block. Whitespace-only
    /// values are treated as absent. The MCP layer validates length
    /// (`NOTE_MAX_LEN`, 280 chars) before the mutation touches disk;
    /// callers must not feed unbounded input to this field.
    pub note: Option<String>,
    /// The caller-declared role this mutation is performed in.
    /// `Unspecified` (the default) emits no
    /// trailer — absence recorded as absence; declared roles emit
    /// `Role: <value>` in the trailer block.
    pub role: Role,
    /// The caller-declared identity performing this mutation:
    /// an opaque caller-chosen string — an
    /// agent name, a session handle, a person's tag. Same trust model
    /// as the role: caller-declared, unverified, tamper-evident
    /// (bound into append-only history). `None` emits no trailer —
    /// absence recorded as absence; present values emit
    /// `Identity: <value>`.
    pub identity: Option<String>,
    /// Correlation id linking every commit produced by a single
    /// logical operation (notably multi-mem `memstead_rename`). When
    /// `Some`, [`format_commit_message`] emits a `Logical-Op: <id>`
    /// trailer alongside `Tool:` / `Actor:` / `Client:`. The git-
    /// branch backend's `parse_commit_message` recovers the value
    /// from the trailer block so `read_provenance` reconstructs
    /// `Provenance::logical_operation_id` round-trip-clean. `None`
    /// for legacy or single-call mutations that don't participate
    /// in correlation; consumers branch on whether the id recurs to
    /// identify a multi-commit logical operation.
    pub logical_operation_id: Option<&'a str>,
    /// Entity ids this commit touched, when one commit covers more than
    /// one entity (notably `batch_update`, whose subject collapses to
    /// `(N entities)`). When `Some` and non-empty, [`format_commit_message`]
    /// emits an `Entities: id1, id2, …` trailer that `parse_commit_message`
    /// recovers into `CommitNote::entity_ids`, so an `--include-notes`
    /// consumer can name every entity a batch changed from the note record
    /// alone. `None`/empty for single-entity commits — those name their
    /// one id in the subject (and thus `entity_id`), so no list is needed.
    pub entity_ids: Option<Vec<String>>,
    /// The proposal a merge commit applies, when this commit is one.
    /// [`format_commit_message`] emits `Proposal: <id>`, `Merged-By:
    /// <merger>` and, for the entities the commit created, `Created:
    /// id1, id2, …`; `parse_commit_message` recovers all three. The
    /// trailers are additive beside `Identity:` (the proposer on a
    /// merge commit, the merger on the amend commit that follows an
    /// `adopt_with_changes`) and are never compared by the checks
    /// independence gate. `None` for every other commit.
    pub proposal: Option<ProposalTrailers>,
}

/// The trailers a proposal merge adds to a commit: the proposal's id
/// (the fork's name and base sha), the merger's identity, and the ids
/// the commit created (so the entity story reads a merge that brought
/// an entity into the target as its creation).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProposalTrailers {
    pub proposal: String,
    pub merged_by: String,
    pub created: Vec<String>,
    /// `(entity id, identity)`: every fork identity that wrote an entity
    /// this commit lands, beside the proposer the commit is attributed to.
    /// One `Co-Writer: <id> <identity>` trailer each; independence counts
    /// them as writers of the landed entity.
    pub co_writers: Vec<(String, String)>,
    /// Ids of landed entities a fork write without an identity touched:
    /// one `Unattributed-Writer: <id>` trailer each, read as a write with
    /// no identity (the independence reading then cannot confirm).
    pub unattributed: Vec<String>,
    /// `old → new` id pairs: an entry the fork renamed, landed by this
    /// commit as the old id's deletion and the new id's creation. One
    /// `Renamed: <old> → <new>` trailer each, so the landed entry's story
    /// continues the old id's.
    pub renamed: Vec<(String, String)>,
}

impl<'a> CommitContext<'a> {
    /// Author-neutral context: no actor, no client, no tool. The author
    /// signature falls back to the committer identity — preserving the
    /// pre-provenance behaviour. Used by engine tests and by call sites
    /// that have not yet been taught to build a real context.
    pub fn internal() -> Self {
        Self {
            actor: Actor::Unknown,
            client: None,
            tool: None,
            note: None,
            role: Role::Unspecified,
            identity: None,
            logical_operation_id: None,
            entity_ids: None,
            proposal: None,
        }
    }
}

/// Inverse of the `name@version` rendering used in both the commit
/// trailer block (`Client: <name>@<version>`) and the folder-backend
/// JSONL changelog (`"client": "<name>@<version>"`). Splits on the
/// **last** `@` because client names may legitimately contain `.`
/// and `-`; versions never contain `@`. Returns `None` for malformed
/// input (no `@`, empty name, empty version) so tolerant readers
/// drop the field rather than constructing a half-record.
pub fn parse_client_id(s: &str) -> Option<ClientId> {
    let (name, version) = s.rsplit_once('@')?;
    if name.is_empty() || version.is_empty() {
        return None;
    }
    Some(ClientId {
        name: name.to_string(),
        version: version.to_string(),
    })
}

/// Sanitise a raw client name to a git-safe local-part matching
/// `[a-z0-9._-]+`. Empty/whitespace-only input falls back to `"unknown"`.
///
/// - Lowercase ASCII.
/// - Anything outside `[a-z0-9._-]` becomes `-` (spaces, `/`, `@`, …).
/// - Non-ASCII bytes also collapse to `-` rather than being dropped, so
///   the output length still tracks the input coarsely (useful for
///   debugging a garbled clientInfo).
pub fn sanitise_client_name(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    for ch in raw.chars() {
        let lower = ch.to_ascii_lowercase();
        if lower.is_ascii_alphanumeric() || matches!(lower, '.' | '_' | '-') {
            out.push(lower);
        } else {
            out.push('-');
        }
    }
    if out.chars().all(|c| c == '-' || c.is_whitespace()) {
        return "unknown".to_string();
    }
    out
}

/// Build the per-commit author `(name, email)` pair from the context.
/// `None` means "fall back to the committer identity" — adapters then
/// reuse the committer signature for the author slot.
///
/// Public so both the legacy disk adapter and the git-tree adapter can
/// build byte-identical commit objects without re-implementing the
/// trailer + author convention.
pub fn author_identity(ctx: &CommitContext<'_>) -> Option<(String, String)> {
    match (ctx.actor, ctx.client.as_ref()) {
        (Actor::Agent | Actor::Cli | Actor::App, Some(c)) => {
            let local = sanitise_client_name(&c.name);
            let email = format!("{local}@{PROVENANCE_EMAIL_DOMAIN}");
            Some((local, email))
        }
        (Actor::External, _) => Some((
            "external".to_string(),
            format!("external@{PROVENANCE_EMAIL_DOMAIN}"),
        )),
        // Agent/Cli/App without a ClientId, or Unknown: no derived
        // identity; caller falls back to the committer signature.
        _ => None,
    }
}

/// Append the trailer block to the caller's prose, separated by exactly
/// one blank line. Normalises trailing newlines so `"subject"` and
/// `"subject\n"` both produce `"subject\n\nActor: …\n…"`.
///
/// When `ctx.note` carries a non-blank string, it is inserted between the
/// prose and the trailer block — with exactly one blank line on each
/// side. Whitespace-only notes are treated as absent (callers that want
/// an empty note must pass `None`). The final layout is:
///
/// ```text
/// <prose>
///
/// <note, if present>
///
/// <trailer block>
/// ```
///
/// `Actor:` is always emitted. `Tool:` is emitted when `ctx.tool` is set.
/// `Client:` is emitted when `ctx.client` is set. Order: `Tool`, `Actor`,
/// `Client`.
///
/// Public so both adapters share the same trailer block — the two paths
/// must produce byte-identical commit messages for the same logical
/// input.
impl<'a> CommitContext<'a> {
    /// The one place a commit context is built. Every commit the engine
    /// writes carries the same provenance: the tool that caused it, the
    /// actor and client of the transport, the agent-authored note, and
    /// the session's declared role and identity. `logical_operation_id`
    /// and `entity_ids` start absent; a multi-commit operation sets them
    /// on the value it gets back.
    pub fn new(
        tool: Option<&'a str>,
        actor: Actor,
        client: Option<ClientId>,
        note: Option<String>,
        role: Role,
        identity: Option<String>,
    ) -> Self {
        CommitContext {
            actor,
            client,
            tool,
            note,
            role,
            identity,
            logical_operation_id: None,
            entity_ids: None,
            proposal: None,
        }
    }
}

pub fn format_commit_message(prose: &str, ctx: &CommitContext<'_>) -> String {
    let trimmed = prose.trim_end_matches('\n');
    let mut trailers: Vec<String> = Vec::with_capacity(4);
    if let Some(tool) = ctx.tool {
        trailers.push(format!("Tool: {tool}"));
    }
    trailers.push(format!("Actor: {}", ctx.actor.as_trailer()));
    if let Some(c) = ctx.client.as_ref() {
        trailers.push(format!("Client: {}@{}", c.name, c.version));
    }
    // `Role:` records the caller-declared role; omitted for
    // `Unspecified` — the absent trailer IS the record of absence.
    if let Some(role) = ctx.role.as_trailer() {
        trailers.push(format!("Role: {role}"));
    }
    // `Identity:` records the caller-declared identity;
    // omitted when absent — the absent trailer IS the record of
    // absence, same posture as `Role:`.
    if let Some(identity) = ctx.identity.as_deref() {
        trailers.push(format!("Identity: {identity}"));
    }
    // `Logical-Op:` is the wire-stable trailer key. Recognised by
    // `parse_commit_message` and threaded back into
    // `Provenance::logical_operation_id` so the multi-mem rename
    // correlation survives a commit-log round-trip through the
    // git-branch backend.
    if let Some(id) = ctx.logical_operation_id {
        trailers.push(format!("Logical-Op: {id}"));
    }
    // `Entities:` lists every id a multi-entity commit touched (batch
    // update), comma-separated. Recovered by `parse_commit_message` into
    // `CommitNote::entity_ids` so a note read in isolation names the
    // entities even though the subject only says `(N entities)`. Omitted
    // when absent or empty — single-entity commits carry their id in the
    // subject. Ids never contain `, ` so the join is unambiguous.
    if let Some(ids) = ctx.entity_ids.as_ref().filter(|v| !v.is_empty()) {
        trailers.push(format!("Entities: {}", ids.join(", ")));
    }
    // `Merged-By:`, `Proposal:` and `Created:` mark a proposal merge:
    // the merger beside the proposer's `Identity:`, the proposal the
    // commit applies, and the ids it created (recovered by
    // `parse_commit_message`; the entity story treats such a commit as
    // those entities' creation).
    if let Some(p) = ctx.proposal.as_ref() {
        trailers.push(format!("Merged-By: {}", p.merged_by));
        trailers.push(format!("Proposal: {}", p.proposal));
        if !p.created.is_empty() {
            trailers.push(format!("Created: {}", p.created.join(", ")));
        }
        for (id, identity) in &p.co_writers {
            trailers.push(format!("Co-Writer: {id} {identity}"));
        }
        for id in &p.unattributed {
            trailers.push(format!("Unattributed-Writer: {id}"));
        }
        for (old, new) in &p.renamed {
            trailers.push(format!("Renamed: {old} → {new}"));
        }
    }
    // A trailer is one line. A value with a line break in it (a client
    // name from a handshake, an identity built by a program that links
    // the engine) would end its trailer early and start a line a reader
    // could take for another trailer, so every break becomes a space.
    for trailer in &mut trailers {
        if trailer.contains(['\n', '\r']) {
            *trailer = trailer.replace(['\n', '\r'], " ");
        }
    }
    let note_body = ctx.note.as_deref().map(str::trim).filter(|n| !n.is_empty());
    match note_body {
        Some(note) => format!("{trimmed}\n\n{note}\n\n{}", trailers.join("\n")),
        None => format!("{trimmed}\n\n{}", trailers.join("\n")),
    }
}