memstead-git-branch 0.7.0

Mem-repo engine for Memstead — multi-mem, git-backed typed entity graphs. Internal library surface consumed by the memstead binaries — pre-1.0, experimental, 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
//! Re-export shim over `memstead_base::storage` (the [`MemWriter`] trait
//! and [`MemWriterError`]) plus the git-tree adapter that stays in
//! this crate.
//!
//! The git-tree adapter ([`git_tree::GitTreeMemWriter`]) buffers
//! mutations and applies them via `gix::object::tree::Editor` against a
//! multi-root `mem-repo-git` repository, one branch per mem.

pub mod git_tree;

use std::path::PathBuf;

pub use memstead_base::storage::{CommitId, MemWriter, MemWriterError};

/// Construct a `Box<dyn MemWriter>` for the git-object-backed path.
/// `gitdir` points at the multi-root `mem-repo-git` repo; `ref_name`
/// is the per-mem branch (fully-qualified, e.g.
/// `refs/heads/<mem>`). The first commit creates the ref if it does
/// not yet exist.
#[cfg(feature = "git-object-storage")]
pub fn git_tree_mem_writer(gitdir: PathBuf, ref_name: String) -> Box<dyn MemWriter> {
    Box::new(git_tree::GitTreeMemWriter::new(gitdir, ref_name))
}

/// Full counterpart of [`memstead_base::instantiate_lean_backend`]: turns
/// any [`memstead_base::Mount`] into a `Box<dyn MemBackend>`, including
/// the git-branch variant that the lean flavour cannot construct.
///
/// Folder and Archive variants delegate to the lean function so the
/// instantiation paths share one implementation. The git-branch
/// variant constructs a [`git_tree::GitTreeMemWriter`] using the
/// mount's `gitdir` + `branch`, fully-qualifying the ref-name as
/// `refs/heads/<branch>` so the per-branch mutex inside the writer
/// keys consistently with what `agent_notes_since` and
/// `read_branch_blobs` expect.
pub fn instantiate_full_backend(
    mount: &memstead_base::Mount,
) -> Result<Box<dyn memstead_base::MemBackend>, memstead_base::InstantiateError> {
    use memstead_base::MountStorage;
    match &mount.storage {
        MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
            memstead_base::instantiate_lean_backend(mount)
        }
        MountStorage::GitBranch { gitdir, branch } => {
            let ref_name = if branch.starts_with("refs/") {
                branch.clone()
            } else {
                format!("refs/heads/{branch}")
            };
            Ok(Box::new(git_tree::GitTreeMemWriter::new(
                gitdir.clone(),
                ref_name,
            )))
        }
    }
}

/// The git-branch ops bundle installed on `memstead_base::Engine` by full
/// boot. Wraps `crate::ops::changes::changes_since` and
/// `crate::ops::export::export_mem_from_branch` so the engine can
/// dispatch from a [`MountStorage::GitBranch`] mount without an extra
/// trait or downcast.
pub const FULL_GIT_BRANCH_OPS: memstead_base::GitBranchOps = memstead_base::GitBranchOps {
    changes_since: changes_since_dispatch,
    diff: diff_dispatch,
    branch_reset: branch_reset_dispatch,
    fetch: fetch_dispatch,
    pull: pull_dispatch,
    push: push_dispatch,
    remote_add: remote_add_dispatch,
    read_tree: read_tree_dispatch,
    export: export_dispatch,
    export_to_bytes: export_to_bytes_dispatch,
    prune_residue: prune_residue_dispatch,
    rename_mem_storage: rename_mem_storage_dispatch,
    write_schema: write_schema_dispatch,
    read_schema_file: read_schema_file_dispatch,
    read_ref_schemas: read_ref_schemas_dispatch,
};

/// Dispatcher for `Engine::install_schema` on git-branch workspaces.
/// Writes the schema package onto the unified `__MEMSTEAD:schemas/` ref
/// and returns the resulting commit sha.
fn write_schema_dispatch(
    gitdir: &std::path::Path,
    name: &str,
    version: &str,
    files: &[(String, Vec<u8>)],
) -> Result<String, memstead_base::backend::BackendError> {
    crate::storage_memstead::write_schema_to_memstead_ref(gitdir, name, version, files)
        .map(|outcome| outcome.commit_sha)
        .map_err(|e| {
            memstead_base::backend::BackendError::Other(format!(
                "schema install onto __MEMSTEAD ref at {}: {e}",
                gitdir.display(),
            ))
        })
}

/// Dispatcher for `Engine::full_refresh`: re-read every schema sealed
/// on the `__MEMSTEAD:schemas/` ref so an out-of-band install becomes
/// resolvable warm. Absent ref/subtree resolves to empty.
fn read_ref_schemas_dispatch(
    workspace_root: &std::path::Path,
) -> Result<Vec<std::sync::Arc<memstead_schema::Schema>>, memstead_base::backend::BackendError> {
    use crate::mem_repo_schemas::LoadOutcome;
    match crate::mem_repo_schemas::load_schemas_from_ref(workspace_root) {
        Ok(LoadOutcome::Schemas(schemas)) => Ok(schemas),
        Ok(_) => Ok(Vec::new()),
        Err(e) => Err(memstead_base::backend::BackendError::Other(format!(
            "schema re-read from __MEMSTEAD ref at {}: {e}",
            workspace_root.display(),
        ))),
    }
}

/// Dispatcher for the authoring-drift health axis: read one file from
/// a sealed package on the `__MEMSTEAD:schemas/` ref. Absence is
/// `Ok(None)`, never an error.
fn read_schema_file_dispatch(
    gitdir: &std::path::Path,
    name: &str,
    version: &str,
    rel: &str,
) -> Result<Option<Vec<u8>>, memstead_base::backend::BackendError> {
    crate::storage_memstead::read_schema_file_from_memstead_ref(gitdir, name, version, rel).map_err(
        |e| {
            memstead_base::backend::BackendError::Other(format!(
                "schema file read from __MEMSTEAD ref at {}: {e}",
                gitdir.display(),
            ))
        },
    )
}

/// Dispatcher for
/// `RecoveryAction::ForceOverwrite` in `create_mem`. Drops the
/// per-mem branch + `__MEMSTEAD` config blob in one ref-edit
/// transaction by delegating to `delete_mem_artifacts_at_gitdir`
/// (the same helper `MemBackend::delete_artifacts` already wraps
/// for delete-files flows). Operates on an unmounted gitdir —
/// callers don't need an instantiated backend, which is why the
/// orchestrator reaches for this through `Engine::git_branch_ops()`
/// rather than constructing a backend just to call `delete_artifacts`.
fn prune_residue_dispatch(
    gitdir: &std::path::Path,
    branch_full_path: &str,
) -> Result<(), memstead_base::backend::BackendError> {
    let ctx = memstead_base::vcs::CommitContext {
        actor: memstead_base::vcs::Actor::Agent,
        client: None,
        tool: Some("memstead_mem_create (force_overwrite)"),
        note: None,
        role: Default::default(),
        logical_operation_id: None,
        entity_ids: None,
    };
    crate::storage_memstead::delete_mem_artifacts_at_gitdir(gitdir, branch_full_path, &ctx).map_err(
        |e| {
            memstead_base::backend::BackendError::Other(format!(
                "force_overwrite prune at {}: {e}",
                branch_full_path,
            ))
        },
    )
}

/// Dispatcher for `memstead_engine::rename_mem` on git-branch
/// workspaces: branch move + `__MEMSTEAD:mems/` config relocation in
/// one ref-edit transaction, history preserved.
fn rename_mem_storage_dispatch(
    gitdir: &std::path::Path,
    old_leaf: &str,
    new_leaf: &str,
) -> Result<(), memstead_base::backend::BackendError> {
    let ctx = memstead_base::vcs::CommitContext {
        actor: memstead_base::vcs::Actor::Agent,
        client: None,
        tool: Some("memstead mem rename"),
        note: None,
        role: Default::default(),
        logical_operation_id: None,
        entity_ids: None,
    };
    crate::storage_memstead::rename_mem_artifacts_at_gitdir(gitdir, old_leaf, new_leaf, &ctx)
        .map_err(|e| {
            memstead_base::backend::BackendError::Other(format!(
                "mem rename {old_leaf} -> {new_leaf}: {e}",
            ))
        })
}

fn changes_since_dispatch(
    gitdir: &std::path::Path,
    branch: &str,
    mem: &str,
    since: &str,
    rename_similarity: f32,
) -> Result<memstead_base::ops::BackendChanges, memstead_base::backend::BackendError> {
    let ref_name = if branch.starts_with("refs/") {
        branch.to_string()
    } else {
        format!("refs/heads/{branch}")
    };
    let empty_store = memstead_base::Store::new();
    let report = crate::ops::changes::changes_since(
        &empty_store,
        mem,
        gitdir,
        since,
        rename_similarity,
        Some(&ref_name),
    )
    .map_err(|e| {
        // A bad `since`
        // SHA (malformed or absent) is a recoverable caller-argument
        // fault, not a backend fault. Encode it as a typed prefix the
        // engine lifts to `COMMIT_NOT_FOUND` (carrying the untruncated
        // SHA), reserving the `MEM_ERROR` catch-all for genuine faults.
        match e {
            crate::vcs::VcsError::ObjectNotFound(_) => {
                memstead_base::backend::BackendError::Other(format!("COMMIT_NOT_FOUND:{since}"))
            }
            other => memstead_base::backend::BackendError::Other(format!(
                "git-branch changes_since: {other}"
            )),
        }
    })?;
    Ok(memstead_base::ops::BackendChanges {
        since: report.since,
        head: report.head,
        changes: report.changes,
        notes: report.notes.unwrap_or_default(),
        memstead_ref: report.memstead_ref,
    })
}

// Signature (arity included) is pinned by the `GitBranchOps.export`
// fn-pointer contract declared in memstead-base.
#[allow(clippy::too_many_arguments)]
fn export_dispatch(
    gitdir: &std::path::Path,
    branch: &str,
    mem: &str,
    config: &memstead_schema::MemConfig,
    output_path: &std::path::Path,
    workspace_root: Option<&std::path::Path>,
    workspace_schemas_dir: Option<&std::path::Path>,
    provenance_bytes: Option<&[u8]>,
    anchors_bytes: Option<&[u8]>,
) -> Result<memstead_base::ops::MemExportResult, memstead_base::backend::BackendError> {
    let _ = branch;
    crate::ops::export::export_mem_from_branch(
        gitdir,
        mem,
        config,
        output_path,
        workspace_root,
        workspace_schemas_dir,
        provenance_bytes,
        anchors_bytes,
    )
    .map_err(|e| {
        memstead_base::backend::BackendError::Other(format!("export_mem_from_branch: {e}"))
    })
}

fn read_tree_dispatch(
    gitdir: &std::path::Path,
    ref_name: &str,
) -> Result<Vec<(String, String)>, memstead_base::backend::BackendError> {
    #[cfg(feature = "git-object-storage")]
    {
        crate::ops::transport::read_md_blobs_at_ref(gitdir, ref_name)
    }
    #[cfg(not(feature = "git-object-storage"))]
    {
        let _ = (gitdir, ref_name);
        Err(memstead_base::backend::BackendError::Other(
            "read_tree: git-object-storage feature not enabled".to_string(),
        ))
    }
}

fn fetch_dispatch(
    gitdir: &std::path::Path,
    remote: &str,
    refspecs: &[String],
) -> Result<memstead_base::ops::FetchOutcome, memstead_base::backend::BackendError> {
    #[cfg(feature = "git-object-storage")]
    {
        crate::ops::transport::fetch_in_gitdir(gitdir, remote, refspecs)
    }
    #[cfg(not(feature = "git-object-storage"))]
    {
        let _ = (gitdir, remote, refspecs);
        Err(memstead_base::backend::BackendError::Other(
            "fetch: git-object-storage feature not enabled".to_string(),
        ))
    }
}

fn pull_dispatch(
    gitdir: &std::path::Path,
    remote: &str,
    mem: &str,
) -> Result<memstead_base::ops::PullOutcome, memstead_base::backend::BackendError> {
    #[cfg(feature = "git-object-storage")]
    {
        crate::ops::transport::pull_in_gitdir(gitdir, remote, mem)
    }
    #[cfg(not(feature = "git-object-storage"))]
    {
        let _ = (gitdir, remote, mem);
        Err(memstead_base::backend::BackendError::Other(
            "pull: git-object-storage feature not enabled".to_string(),
        ))
    }
}

fn push_dispatch(
    gitdir: &std::path::Path,
    remote: &str,
    mem: &str,
    force: bool,
) -> Result<memstead_base::ops::PushOutcome, memstead_base::backend::BackendError> {
    #[cfg(feature = "git-object-storage")]
    {
        crate::ops::transport::push_in_gitdir(gitdir, remote, mem, force)
    }
    #[cfg(not(feature = "git-object-storage"))]
    {
        let _ = (gitdir, remote, mem, force);
        Err(memstead_base::backend::BackendError::Other(
            "push: git-object-storage feature not enabled".to_string(),
        ))
    }
}

fn remote_add_dispatch(
    gitdir: &std::path::Path,
    name: &str,
    url: &str,
) -> Result<memstead_base::ops::RemoteAddOutcome, memstead_base::backend::BackendError> {
    #[cfg(feature = "git-object-storage")]
    {
        crate::ops::transport::remote_add_in_gitdir(gitdir, name, url)
    }
    #[cfg(not(feature = "git-object-storage"))]
    {
        let _ = (gitdir, name, url);
        Err(memstead_base::backend::BackendError::Other(
            "remote_add: git-object-storage feature not enabled".to_string(),
        ))
    }
}

fn branch_reset_dispatch(
    gitdir: &std::path::Path,
    branch: &str,
    target_sha: &str,
    expected_head: Option<&str>,
) -> Result<memstead_base::ops::BranchResetOutcome, memstead_base::backend::BackendError> {
    #[cfg(feature = "git-object-storage")]
    {
        crate::ops::branch_reset::branch_reset_in_gitdir(gitdir, branch, target_sha, expected_head)
    }
    #[cfg(not(feature = "git-object-storage"))]
    {
        let _ = (gitdir, branch, target_sha);
        Err(memstead_base::backend::BackendError::Other(
            "branch_reset: git-object-storage feature not enabled".to_string(),
        ))
    }
}

fn diff_dispatch(
    gitdir: &std::path::Path,
    mem: &str,
    ref_a: &str,
    ref_b: &str,
    config: &memstead_base::ops::DiffConfig,
) -> Result<memstead_base::ops::Diff, memstead_base::backend::BackendError> {
    #[cfg(feature = "git-object-storage")]
    {
        crate::ops::diff::diff_two_refs(gitdir, mem, ref_a, ref_b, config)
    }
    #[cfg(not(feature = "git-object-storage"))]
    {
        let _ = (gitdir, mem, ref_a, ref_b, config);
        Err(memstead_base::backend::BackendError::Other(
            "diff_two_refs: git-object-storage feature not enabled".to_string(),
        ))
    }
}

#[allow(clippy::too_many_arguments)]
fn export_to_bytes_dispatch(
    gitdir: &std::path::Path,
    branch: &str,
    mem: &str,
    config: &memstead_schema::MemConfig,
    workspace_root: Option<&std::path::Path>,
    workspace_schemas_dir: Option<&std::path::Path>,
    provenance_bytes: Option<&[u8]>,
    anchors_bytes: Option<&[u8]>,
) -> Result<memstead_base::ops::MemExportBytes, memstead_base::backend::BackendError> {
    let _ = branch;
    crate::ops::export::export_mem_from_branch_to_bytes(
        gitdir,
        mem,
        config,
        workspace_root,
        workspace_schemas_dir,
        provenance_bytes,
        anchors_bytes,
    )
    .map_err(|e| {
        memstead_base::backend::BackendError::Other(format!("export_mem_from_branch_to_bytes: {e}"))
    })
}