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
//! `mnem branch` - the `refs/heads/<name>` convenience verb.
//!
//! `branch` is a thin shell over [`super::refs`] that writes into the
//! `refs/heads/` namespace. It's split out as its own command so a Git
//! user's muscle memory (`git branch`, `git branch feature`,
//! `git branch -D old`) lands where they expect.
//!
//! Semantics:
//!
//! - `branch list` - every ref whose name begins with `refs/heads/`,
//! plus the current head-commit CID marked with `*`.
//! - `branch create <name> [--from <cid>]` - writes
//! `refs/heads/<name> -> <cid>`. `--from` accepts any commit CID in
//! the repo; when absent, it defaults to the current head commit.
//! Fails if the ref already exists or the repo has no commits yet.
//! - `branch delete <name>` - removes `refs/heads/<name>`. Fails if
//! the ref does not exist. Does NOT refuse to delete the "current"
//! branch in Q2 - mnem has no symbolic-ref-to-HEAD analog yet;
//! every commit targets the heads list directly.
//!
//! Branches are named heads in the op-log graph (+
//! ). Every ref update goes through
//! `ReadonlyRepo::update_ref` (which wraps the write in an Operation
//! ), so `mnem branch create feat` shows up in
//! `mnem log` just like any other mutation.
//!
//! # Examples
//!
//! ```text
//! mnem branch list
//! mnem branch create feature/oauth
//! mnem branch create hotfix --from 01HZ...
//! mnem branch delete old-experiment
//! ```
use std::sync::Arc;
use mnem_core::HEADS_PREFIX;
use mnem_core::store::Blockstore;
use super::*;
/// `mnem branch` subcommand dispatcher.
#[derive(clap::Subcommand, Debug)]
pub(crate) enum BranchCmd {
/// List every `refs/heads/<name>` ref, marking the head commit.
List,
/// Create a new branch. Fails if the name already exists.
Create {
/// Branch name. Stored as `refs/heads/<name>` in the View.
name: String,
/// Optional positional start-point: a commit CID, ref name,
/// branch shortname, or `HEAD`. Mirrors `git branch <name>
/// <start-point>`. When omitted (and `--from` also absent),
/// defaults to the current head commit.
///
/// audit-2026-04-25 C3-6: Pass-2 found Git users hit a wall
/// with `mnem branch create feat main`; we now accept that
/// shape as syntactic sugar for `--from main` and resolve
/// the start-point through `resolve_commitish` so any commit
/// CID, ref, or branch name works.
start_point: Option<String>,
/// Commit CID / ref / branch shortname to point the new
/// branch at. Same resolver as the positional `start_point`.
/// Conflicts with the positional form -- pass one or the
/// other, not both.
#[arg(long, conflicts_with = "start_point")]
from: Option<String>,
},
/// Delete a branch. Fails if the name does not exist.
Delete {
/// Branch name to delete.
name: String,
},
}
pub(crate) fn run(override_path: Option<&Path>, cmd: BranchCmd) -> Result<()> {
let data_dir = repo::locate_data_dir(override_path)?;
let cfg = config::load(&data_dir)?;
let (_dir, r, bs, _ohs) = repo::open_all(Some(data_dir.as_path()))?;
match cmd {
BranchCmd::List => list_branches(&r),
BranchCmd::Create {
name,
start_point,
from,
} => {
// C3-6: positional start-point is sugar for --from. The
// clap `conflicts_with` annotation prevents both being
// set, so an `or` is sufficient here.
let resolved = from.or(start_point);
create_branch(&r, &bs, &cfg, &name, resolved.as_deref())
}
BranchCmd::Delete { name } => delete_branch(&r, &cfg, &name),
}
}
fn list_branches(r: &ReadonlyRepo) -> Result<()> {
let refs = &r.view().refs;
// BUG-38: use the active_branch pointer from View.extra as the
// primary source of truth for which branch is current. Fall back
// to head-CID matching for repos that predate BUG-38 (old Views
// have no active_branch in extra).
let active_branch = r.view().active_branch().map(str::to_string);
let head = r.view().heads.first().cloned();
let mut any = false;
for (name, target) in refs {
let Some(short) = name.strip_prefix(HEADS_PREFIX) else {
continue;
};
any = true;
let marker = if active_branch.as_deref() == Some(name.as_str()) {
"*"
} else if active_branch.is_none() {
// Legacy fallback: mark whichever branch points at the current head.
match target {
RefTarget::Normal { target } if Some(target) == head.as_ref() => "*",
_ => " ",
}
} else {
" "
};
let summary = match target {
RefTarget::Normal { target } => format!("-> {target}"),
RefTarget::Conflicted { adds, removes } => {
format!("conflicted(+{} -{})", adds.len(), removes.len())
}
};
println!("{marker} {short} {summary}");
}
if !any {
println!("<no branches>");
}
Ok(())
}
fn create_branch(
r: &ReadonlyRepo,
bs: &Arc<dyn Blockstore>,
cfg: &config::Config,
name: &str,
from: Option<&str>,
) -> Result<()> {
if name.is_empty() {
bail!("branch name must not be empty");
}
// G6: reject refname characters that are invalid in most VCS tooling.
// Extended in G6-patch to cover the full git check-ref-format spec.
if name.contains(' ')
|| name.contains('\t')
|| name.contains('\n')
|| name.contains('\x00')
|| name.contains('~')
|| name.contains('^')
|| name.contains(':')
|| name.contains('?')
|| name.contains('*')
|| name.contains('[')
|| name.contains('\\')
|| name.contains("@{")
|| name.contains("..")
|| name.contains("//")
|| name.starts_with('/')
|| name.ends_with('/')
|| name.ends_with('.')
|| name.ends_with(".lock")
{
bail!(
"invalid branch name `{name}`: branch names may not contain spaces, \
control characters, `~`, `^`, `:`, `?`, `*`, `[`, `\\`, `@{{`, `..`, \
`//`, trailing `.`, `.lock` suffix, or start/end with `/`"
);
}
// Accept either a raw name (common) or a fully-qualified refname.
// A raw name gets the `refs/heads/` prefix; a refname passes
// through unchanged. This matches git's `git branch refs/foo` UX
// loosely while preserving "happy path = bare name".
let full = if name.starts_with(HEADS_PREFIX) {
name.to_string()
} else {
format!("{HEADS_PREFIX}{name}")
};
if r.view().refs.contains_key(&full) {
bail!("branch `{name}` already exists");
}
// C3-6: route the start-point through the shared `resolve_commitish`
// resolver so a CID, a ref name (`refs/heads/main`), a branch
// shortname (`main`), or `HEAD` all work identically. This is what
// makes `mnem branch create feat main` behave like `git branch feat
// main` instead of raising a "parsing CID" error.
let target_cid = match from {
Some(s) => super::resolve_commitish(r, s).context("resolving start-point")?,
None => r
.view()
.heads
.first()
.cloned()
.ok_or_else(|| anyhow!("repository has no commits yet; pass --from <cid>"))?,
};
// G_BUG: validate that target_cid actually points to a Commit block.
// `mnem log --format=json` returns op-log CIDs, which are Operations,
// not Commits. Without this check, the CID is accepted silently and
// causes a deterministic crash in `mnem merge` later
// ("missing field `change_id`"). Fetch the block and attempt a
// Commit decode now so the user gets an actionable error immediately.
{
let bytes = bs
.get(&target_cid)?
.ok_or_else(|| anyhow!("block {target_cid} not found in blockstore"))?;
if from_canonical_bytes::<Commit>(&bytes).is_err() {
bail!(
"`{target_cid}` does not decode as a commit.\n\
`mnem log --format=json` returns op CIDs; use \
`mnem show <op-cid>` to see the commit CID, or use \
`HEAD` / a branch name as the --from argument."
);
}
}
let new_r = r.update_ref(
&full,
None,
Some(RefTarget::normal(target_cid.clone())),
&config::author_string(cfg),
)?;
println!("created branch {name} -> {target_cid}");
println!(" op_id {}", new_r.op_id());
Ok(())
}
fn delete_branch(r: &ReadonlyRepo, cfg: &config::Config, name: &str) -> Result<()> {
if name.is_empty() {
bail!("branch name must not be empty");
}
let full = if name.starts_with(HEADS_PREFIX) {
name.to_string()
} else {
format!("{HEADS_PREFIX}{name}")
};
// BUG-40: refuse to delete the currently checked-out branch.
if let Some(active) = r.view().active_branch() {
if active == full.as_str() {
bail!(
"cannot delete branch '{name}': it is the currently checked-out branch; \
switch to another branch first"
);
}
}
let prev = r
.view()
.refs
.get(&full)
.ok_or_else(|| anyhow!("branch `{name}` does not exist"))?;
let new_r = r.update_ref(&full, Some(prev), None, &config::author_string(cfg))?;
println!("deleted branch {name}");
println!(" op_id {}", new_r.op_id());
Ok(())
}