Skip to main content

reddb_server/runtime/
impl_vcs.rs

1//! Runtime implementation of the VCS ("Git for Data") surface.
2//!
3//! Branches retain immutable ancestor snapshots and independently version
4//! subsequent writes. Native merge plans publish data and history together.
5//!
6//! Every VCS entity is stored as a plain TableRow in a `red_*`
7//! collection (same pattern as `red.queue.meta` / `red.query.stats_catalog`).
8//! Commits reuse the MVCC snapshot xid as their immutable root, and
9//! pin that xid so VACUUM cannot reclaim historical row versions.
10
11use std::collections::{BTreeSet, HashMap, HashSet};
12use std::sync::Arc;
13use std::time::{SystemTime, UNIX_EPOCH};
14
15use sha2::{Digest, Sha256};
16
17use crate::application::vcs::{
18    AsOfSpec, Author, CheckoutInput, CheckoutTarget, Commit, CommitHash, Conflict,
19    CreateBranchInput, CreateCommitInput, CreateTagInput, Diff, DiffChange, DiffEntry, DiffInput,
20    LogInput, LogRange, MergeInput, MergeOutcome, MergeStrategy, Ref, RefKind, RefName, ResetInput,
21    ResetMode, Status, StatusInput,
22};
23use crate::application::vcs_collections as vc;
24use crate::json::{Map, Value as JsonValue};
25use crate::runtime::RedDBRuntime;
26use crate::storage::transaction::snapshot::{Snapshot, SnapshotManager, Xid, XID_NONE};
27use crate::storage::unified::entity::{EntityData, EntityId, EntityKind, RowData, UnifiedEntity};
28use crate::storage::unified::UnifiedStore;
29use crate::{RedDBError, RedDBResult};
30use reddb_types::Value;
31
32#[path = "vcs_branches.rs"]
33mod branches;
34#[path = "vcs_merge_data.rs"]
35mod merge_data;
36#[cfg(test)]
37#[path = "vcs_metadata_tests.rs"]
38mod metadata_tests;
39
40impl RedDBRuntime {
41    pub(crate) fn vcs_live_graph_validation_contexts(
42        &self,
43        collection: &str,
44    ) -> RedDBResult<Vec<reddb_engine::transaction::read::SnapshotContext>> {
45        let (mut context, _retention) = self.native_read_snapshot()?;
46        context.snapshot = self.snapshot_manager().fresh_read_snapshot();
47        context.own_xids.clear();
48        if !self.vcs_is_versioned(collection)? {
49            return Ok(vec![context]);
50        }
51        let store = self.db().store();
52        let mut names = BTreeSet::from([vc::DEFAULT_BRANCH_REF.to_string()]);
53        if let Some(manager) = store.get_collection(vc::REFS) {
54            manager.try_for_each_entity(usize::MAX, |entity| {
55                if let Some(name) = entity.data.as_row().and_then(|row| row_text(row, "id")) {
56                    if name.starts_with(vc::BRANCH_REF_PREFIX) {
57                        names.insert(name);
58                    }
59                }
60                true
61            })?;
62        }
63        names
64            .into_iter()
65            .map(|name| {
66                let mut branch = match branches::load_view(&store, &name)? {
67                    Some(branch) => branch,
68                    None if name == vc::DEFAULT_BRANCH_REF => {
69                        reddb_engine::transaction::read::BranchReadView {
70                            writer_epoch: 0,
71                            epochs: Default::default(),
72                        }
73                    }
74                    None => {
75                        return Err(RedDBError::InvalidOperation(format!(
76                            "checkout legacy branch '{name}' before enabling a graph contract"
77                        )))
78                    }
79                };
80                branch
81                    .epochs
82                    .insert(branch.writer_epoch, context.snapshot.clone());
83                let mut snapshot = context.clone();
84                snapshot.branch = Some(Arc::new(branch));
85                Ok(snapshot)
86            })
87            .collect()
88    }
89}
90
91// ---------------------------------------------------------------------------
92// Utilities
93// ---------------------------------------------------------------------------
94
95fn now_ms() -> i64 {
96    SystemTime::now()
97        .duration_since(UNIX_EPOCH)
98        .map(|d| d.as_millis() as i64)
99        .unwrap_or(0)
100}
101
102fn row_text(row: &RowData, field: &str) -> Option<String> {
103    match row.get_field(field)?.clone() {
104        Value::Text(v) => Some(v.to_string()),
105        _ => None,
106    }
107}
108
109fn row_u64(row: &RowData, field: &str) -> Option<u64> {
110    match row.get_field(field)?.clone() {
111        Value::UnsignedInteger(v) => Some(v),
112        Value::Integer(v) if v >= 0 => Some(v as u64),
113        _ => None,
114    }
115}
116
117fn row_i64(row: &RowData, field: &str) -> Option<i64> {
118    match row.get_field(field)?.clone() {
119        Value::Integer(v) => Some(v),
120        Value::UnsignedInteger(v) => Some(v as i64),
121        Value::TimestampMs(v) | Value::Timestamp(v) => Some(v),
122        _ => None,
123    }
124}
125
126fn row_json(row: &RowData, field: &str) -> JsonValue {
127    match row.get_field(field) {
128        Some(Value::Json(bytes)) => {
129            crate::json::from_slice::<JsonValue>(bytes).unwrap_or(JsonValue::Null)
130        }
131        Some(Value::Text(s)) => crate::json::from_str::<JsonValue>(s)
132            .unwrap_or_else(|_| JsonValue::String(s.to_string())),
133        _ => JsonValue::Null,
134    }
135}
136
137fn row_string_list(row: &RowData, field: &str) -> Vec<String> {
138    match row.get_field(field) {
139        Some(Value::Array(items)) => items
140            .iter()
141            .filter_map(|v| match v {
142                Value::Text(s) => Some(s.to_string()),
143                _ => None,
144            })
145            .collect(),
146        _ => Vec::new(),
147    }
148}
149
150fn compute_commit_hash(
151    root_xid: Xid,
152    parents: &[CommitHash],
153    author: &Author,
154    message: &str,
155    timestamp_ms: i64,
156) -> CommitHash {
157    let mut h = Sha256::new();
158    h.update(b"reddb-commit-v1\n");
159    h.update(root_xid.to_be_bytes());
160    let mut sorted = parents.to_vec();
161    sorted.sort();
162    for p in &sorted {
163        h.update(b"\np=");
164        h.update(p.as_bytes());
165    }
166    h.update(b"\na=");
167    h.update(author.name.as_bytes());
168    h.update(b"\n");
169    h.update(author.email.as_bytes());
170    h.update(b"\nm=");
171    h.update(message.as_bytes());
172    h.update(b"\nt=");
173    h.update(timestamp_ms.to_be_bytes());
174    let digest = h.finalize();
175    hex::encode(digest)
176}
177
178fn normalize_branch_name(raw: &str) -> String {
179    if raw.starts_with(vc::BRANCH_REF_PREFIX) {
180        raw.to_string()
181    } else {
182        format!("{}{}", vc::BRANCH_REF_PREFIX, raw)
183    }
184}
185
186fn normalize_tag_name(raw: &str) -> String {
187    if raw.starts_with(vc::TAG_REF_PREFIX) {
188        raw.to_string()
189    } else {
190        format!("{}{}", vc::TAG_REF_PREFIX, raw)
191    }
192}
193
194fn head_ref_id(connection_id: u64) -> String {
195    format!("{}{}", vc::HEAD_ID_PREFIX, connection_id)
196}
197
198// ---------------------------------------------------------------------------
199// Commit load / save
200// ---------------------------------------------------------------------------
201
202fn load_metadata_entity(
203    store: &UnifiedStore,
204    collection: &str,
205    key: &str,
206) -> RedDBResult<Option<UnifiedEntity>> {
207    let mut result = None;
208    if let Some(manager) = store.get_collection(collection) {
209        super::function_budget::try_scan(
210            |visit| manager.try_for_each_entity(usize::MAX, visit),
211            |entity| {
212                if entity
213                    .data
214                    .as_row()
215                    .is_some_and(|row| row_text(row, "id").as_deref() == Some(key))
216                {
217                    result = Some(entity.clone());
218                    return false;
219                }
220                true
221            },
222        )?;
223    }
224    Ok(result)
225}
226
227fn load_commit_entity(store: &UnifiedStore, hash: &str) -> RedDBResult<Option<UnifiedEntity>> {
228    load_metadata_entity(store, vc::COMMITS, hash)
229}
230
231fn commit_from_row(row: &RowData) -> Option<Commit> {
232    Some(Commit {
233        hash: row_text(row, "id")?,
234        root_xid: row_u64(row, "root_xid")?,
235        parents: row_string_list(row, "parents"),
236        height: row_u64(row, "height").unwrap_or(0),
237        author: Author {
238            name: row_text(row, "author_name").unwrap_or_default(),
239            email: row_text(row, "author_email").unwrap_or_default(),
240        },
241        committer: Author {
242            name: row_text(row, "committer_name").unwrap_or_default(),
243            email: row_text(row, "committer_email").unwrap_or_default(),
244        },
245        message: row_text(row, "message").unwrap_or_default(),
246        timestamp_ms: row_i64(row, "timestamp_ms").unwrap_or(0),
247        signature: row_text(row, "signature"),
248    })
249}
250
251fn load_commit(store: &UnifiedStore, hash: &str) -> RedDBResult<Option<Commit>> {
252    load_commit_entity(store, hash)?
253        .map(|entity| {
254            entity
255                .data
256                .as_row()
257                .and_then(commit_from_row)
258                .ok_or_else(|| RedDBError::Internal(format!("vcs: invalid commit '{hash}'")))
259        })
260        .transpose()
261}
262
263struct CommitSnapshot<'a> {
264    manager: &'a SnapshotManager,
265    snapshot: Snapshot,
266    retained: bool,
267}
268
269impl std::ops::Deref for CommitSnapshot<'_> {
270    type Target = Snapshot;
271    fn deref(&self) -> &Snapshot {
272        &self.snapshot
273    }
274}
275
276impl Drop for CommitSnapshot<'_> {
277    fn drop(&mut self) {
278        if !self.retained {
279            self.manager.unpin(
280                self.snapshot
281                    .in_progress
282                    .iter()
283                    .copied()
284                    .fold(self.snapshot.xid, Xid::min),
285            );
286        }
287    }
288}
289
290fn capture_commit_snapshot(manager: &SnapshotManager) -> CommitSnapshot<'_> {
291    let xid = manager.begin();
292    let mut snapshot = manager.snapshot(xid);
293    snapshot.in_progress.retain(|pending| *pending < xid);
294    // An excluded writer may later delete a version visible to this commit.
295    // Pin its horizon before committing the temporary xid releases protection.
296    let horizon = snapshot.in_progress.iter().copied().fold(xid, Xid::min);
297    manager.pin(horizon);
298    manager.commit(xid);
299    CommitSnapshot {
300        manager,
301        snapshot,
302        retained: false,
303    }
304}
305
306fn commit_snapshot_from_row(row: &RowData) -> RedDBResult<Snapshot> {
307    let xid = row_u64(row, "root_xid")
308        .ok_or_else(|| RedDBError::Internal("vcs: commit has no root snapshot".to_string()))?;
309    let mut in_progress = HashSet::new();
310    // Legacy commits recorded only the root xid; their exclusions are unknown.
311    if let Some(value) = row.get_field("snapshot_in_progress") {
312        let Value::Array(values) = value else {
313            return Err(RedDBError::Internal(
314                "vcs: invalid commit snapshot exclusions".to_string(),
315            ));
316        };
317        for value in values {
318            let pending = match value {
319                Value::UnsignedInteger(value) => *value,
320                Value::Integer(value) if *value > 0 => *value as u64,
321                _ => {
322                    return Err(RedDBError::Internal(
323                        "vcs: invalid commit snapshot exclusion".to_string(),
324                    ));
325                }
326            };
327            if pending == XID_NONE || pending >= xid {
328                return Err(RedDBError::Internal(
329                    "vcs: commit snapshot exclusion outside its horizon".to_string(),
330                ));
331            }
332            in_progress.insert(pending);
333        }
334    }
335    Ok(Snapshot { xid, in_progress })
336}
337
338fn snapshot_sees_entity(
339    context: &reddb_engine::transaction::read::SnapshotContext,
340    entity: &UnifiedEntity,
341) -> bool {
342    reddb_engine::transaction::read::entity_visibility_check(context, entity)
343}
344
345fn commit_fields(
346    commit: &Commit,
347    snapshot: &Snapshot,
348    view: &reddb_engine::transaction::read::BranchReadView,
349) -> HashMap<String, Value> {
350    let mut fields: HashMap<String, Value> = HashMap::new();
351    fields.insert("branch_lineage".into(), branches::encode_epochs(view));
352    fields.insert(
353        "writer_epoch".into(),
354        Value::UnsignedInteger(view.writer_epoch),
355    );
356    fields.insert("id".to_string(), Value::text(commit.hash.as_str()));
357    fields.insert(
358        "root_xid".to_string(),
359        Value::UnsignedInteger(commit.root_xid),
360    );
361    let mut pending: Vec<Xid> = snapshot.in_progress.iter().copied().collect();
362    pending.sort_unstable();
363    fields.insert(
364        "snapshot_in_progress".to_string(),
365        Value::Array(pending.into_iter().map(Value::UnsignedInteger).collect()),
366    );
367    fields.insert(
368        "parents".to_string(),
369        Value::Array(
370            commit
371                .parents
372                .iter()
373                .map(|p| Value::text(p.as_str()))
374                .collect(),
375        ),
376    );
377    fields.insert("height".to_string(), Value::UnsignedInteger(commit.height));
378    fields.insert(
379        "author_name".to_string(),
380        Value::text(commit.author.name.as_str()),
381    );
382    fields.insert(
383        "author_email".to_string(),
384        Value::text(commit.author.email.as_str()),
385    );
386    fields.insert(
387        "committer_name".to_string(),
388        Value::text(commit.committer.name.as_str()),
389    );
390    fields.insert(
391        "committer_email".to_string(),
392        Value::text(commit.committer.email.as_str()),
393    );
394    fields.insert("message".to_string(), Value::text(commit.message.as_str()));
395    fields.insert(
396        "timestamp_ms".to_string(),
397        Value::TimestampMs(commit.timestamp_ms),
398    );
399    if let Some(sig) = &commit.signature {
400        fields.insert("signature".to_string(), Value::text(sig.as_str()));
401    }
402    fields
403}
404
405// ---------------------------------------------------------------------------
406// Ref load / save / delete
407// ---------------------------------------------------------------------------
408
409fn ref_kind_from_str(s: &str) -> Option<RefKind> {
410    match s {
411        "branch" => Some(RefKind::Branch),
412        "tag" => Some(RefKind::Tag),
413        "head" => Some(RefKind::Head),
414        _ => None,
415    }
416}
417
418fn ref_from_row(row: &RowData) -> Option<Ref> {
419    Some(Ref {
420        name: row_text(row, "id")?,
421        kind: ref_kind_from_str(&row_text(row, "type")?)?,
422        target: row_text(row, "target")?,
423        protected: row
424            .get_field("protected")
425            .and_then(|v| match v {
426                Value::Boolean(b) => Some(*b),
427                _ => None,
428            })
429            .unwrap_or(false),
430    })
431}
432
433fn load_ref_entity(
434    store: &UnifiedStore,
435    name: &str,
436) -> RedDBResult<Option<(EntityId, UnifiedEntity)>> {
437    Ok(load_metadata_entity(store, vc::REFS, name)?.map(|entity| (entity.id, entity)))
438}
439
440fn load_ref(store: &UnifiedStore, name: &str) -> RedDBResult<Option<Ref>> {
441    load_ref_entity(store, name)?
442        .map(|(_, entity)| {
443            entity
444                .data
445                .as_row()
446                .and_then(ref_from_row)
447                .ok_or_else(|| RedDBError::Internal(format!("vcs: invalid reference '{name}'")))
448        })
449        .transpose()
450}
451
452fn stage_ref(
453    store: &UnifiedStore,
454    publication: &mut crate::storage::unified::store::RowPublication,
455    reference: &Ref,
456) -> RedDBResult<()> {
457    let kind = match reference.kind {
458        RefKind::Branch => "branch",
459        RefKind::Tag => "tag",
460        RefKind::Head => "head",
461    };
462    branches::stage_metadata(
463        store,
464        publication,
465        vc::REFS,
466        "id",
467        &reference.name,
468        HashMap::from([
469            ("id".into(), Value::text(reference.name.as_str())),
470            ("type".into(), Value::text(kind)),
471            ("target".into(), Value::text(reference.target.as_str())),
472            ("protected".into(), Value::Boolean(reference.protected)),
473        ]),
474    )
475}
476
477fn save_ref(store: &UnifiedStore, reference: &Ref) -> RedDBResult<()> {
478    let mut publication = crate::storage::unified::store::RowPublication::default();
479    stage_ref(store, &mut publication, reference)?;
480    store.publish_rows(publication)?;
481    Ok(())
482}
483
484fn delete_ref(store: &UnifiedStore, name: &str) -> RedDBResult<bool> {
485    let Some((id, _)) = load_ref_entity(store, name)? else {
486        return Ok(false);
487    };
488    let mut publication = crate::storage::unified::store::RowPublication::default();
489    publication.deletes.push((vc::REFS.into(), id));
490    store.publish_rows(publication)?;
491    Ok(true)
492}
493
494// ---------------------------------------------------------------------------
495// Opt-in per-collection versioning (Phase 7 — disk-cost isolation)
496// ---------------------------------------------------------------------------
497
498/// Is this user collection opted in to Git-for-Data?
499///
500/// Default is `false`: a fresh collection stays outside the VCS so
501/// transactional churn (sessions, caches, queues) doesn't pin
502/// extra row versions. Internal `red_*` collections are never
503/// versioned — they store VCS metadata itself.
504fn is_versioned(store: &UnifiedStore, name: &str) -> RedDBResult<bool> {
505    if name.starts_with("red_") || name.starts_with("red.") {
506        return Ok(false);
507    }
508    Ok(versioned_collections_shared(store)?
509        .iter()
510        .any(|versioned| versioned == name))
511}
512
513/// Enumerate every user collection currently opted in. Order
514/// undefined — callers that need a deterministic iteration should
515/// sort the returned list.
516fn versioned_collections(store: &UnifiedStore) -> RedDBResult<Vec<String>> {
517    Ok(versioned_collections_shared(store)?.to_vec())
518}
519
520fn versioned_collections_shared(store: &UnifiedStore) -> RedDBResult<Arc<Vec<String>>> {
521    let Some(manager) = store.get_collection(vc::SETTINGS) else {
522        return Ok(Arc::new(Vec::new()));
523    };
524    // Every statement asks this. The answer only changes with the settings
525    // collection, so it is read once per state of it instead of walking that
526    // collection under the publication fence each time.
527    store.versioned_collections_cached(&manager, || scan_versioned_collections(store, &manager))
528}
529
530fn scan_versioned_collections(
531    store: &UnifiedStore,
532    manager: &Arc<crate::storage::SegmentManager>,
533) -> RedDBResult<Vec<String>> {
534    let _publication = manager
535        .has_backing()
536        .then(|| store.vault_publication_lock.lock());
537    let mut collections = Vec::new();
538    super::function_budget::try_scan(
539        |visit| manager.try_for_each_entity(usize::MAX, visit),
540        |entity| {
541            if let Some(row) = entity.data.as_row() {
542                if matches!(row.get_field("versioned"), Some(Value::Boolean(true))) {
543                    if let Some(name) = row_text(row, "id") {
544                        collections.push(name);
545                    }
546                }
547            }
548            true
549        },
550    )?;
551    Ok(collections)
552}
553
554fn list_refs_by_prefix(store: &UnifiedStore, prefix: Option<&str>) -> RedDBResult<Vec<Ref>> {
555    let mut refs = Vec::new();
556    if let Some(manager) = store.get_collection(vc::REFS) {
557        super::function_budget::try_scan_result(
558            |visit| manager.try_for_each_entity(usize::MAX, visit),
559            |entity| {
560                let row = entity
561                    .data
562                    .as_row()
563                    .ok_or_else(|| RedDBError::Internal("vcs: invalid reference row".into()))?;
564                let reference = ref_from_row(row)
565                    .ok_or_else(|| RedDBError::Internal("vcs: invalid reference".into()))?;
566                if prefix.is_none_or(|prefix| reference.name.starts_with(prefix)) {
567                    refs.push(reference);
568                }
569                Ok(true)
570            },
571        )?;
572    }
573    Ok(refs)
574}
575
576// ---------------------------------------------------------------------------
577// Ancestry helpers
578// ---------------------------------------------------------------------------
579
580fn ancestor_set(
581    store: &UnifiedStore,
582    start: &str,
583    max_steps: usize,
584) -> RedDBResult<HashSet<CommitHash>> {
585    let mut visited: HashSet<CommitHash> = HashSet::new();
586    let mut stack: Vec<CommitHash> = vec![start.to_string()];
587    let mut steps = 0usize;
588    while let Some(hash) = stack.pop() {
589        if !visited.insert(hash.clone()) {
590            continue;
591        }
592        {
593            let c = load_commit(store, &hash)?
594                .ok_or_else(|| RedDBError::Internal(format!("vcs: missing ancestor '{hash}'")))?;
595            for p in c.parents {
596                if !visited.contains(&p) {
597                    stack.push(p);
598                }
599            }
600        }
601        steps += 1;
602        if steps >= max_steps && !stack.is_empty() {
603            return Err(RedDBError::InvalidOperation(
604                "vcs: ancestry exceeds traversal budget".into(),
605            ));
606        }
607    }
608    Ok(visited)
609}
610
611fn topo_walk(store: &UnifiedStore, start: &str, range: &LogRange) -> RedDBResult<Vec<Commit>> {
612    let limit = range.limit.unwrap_or(usize::MAX);
613    let skip = range.skip.unwrap_or(0);
614    let exclude = range
615        .from
616        .as_ref()
617        .map(|h| ancestor_set(store, h, 100_000))
618        .transpose()?
619        .unwrap_or_default();
620
621    let mut visited: HashSet<CommitHash> = HashSet::new();
622    let mut stack: Vec<CommitHash> = vec![start.to_string()];
623    let mut out: Vec<Commit> = Vec::new();
624    let mut skipped = 0usize;
625    while let Some(hash) = stack.pop() {
626        if !visited.insert(hash.clone()) {
627            continue;
628        }
629        if exclude.contains(&hash) {
630            continue;
631        }
632        let commit = load_commit(store, &hash)?
633            .ok_or_else(|| RedDBError::Internal(format!("vcs: missing ancestor '{hash}'")))?;
634        if range.no_merges && commit.parents.len() > 1 {
635            for p in &commit.parents {
636                if !visited.contains(p) {
637                    stack.push(p.clone());
638                }
639            }
640            continue;
641        }
642        for p in &commit.parents {
643            if !visited.contains(p) {
644                stack.push(p.clone());
645            }
646        }
647        if skipped < skip {
648            skipped += 1;
649            continue;
650        }
651        if out.len() >= limit {
652            break;
653        }
654        out.push(commit);
655    }
656    // Highest height first (newest commits on top).
657    out.sort_by(|a, b| {
658        b.height
659            .cmp(&a.height)
660            .then(b.timestamp_ms.cmp(&a.timestamp_ms))
661    });
662    Ok(out)
663}
664
665// ---------------------------------------------------------------------------
666// Commitish resolution
667// ---------------------------------------------------------------------------
668
669fn resolve_ref_chain(store: &UnifiedStore, name: &str) -> RedDBResult<Option<CommitHash>> {
670    let mut current = name.to_string();
671    for _ in 0..4 {
672        let Some(reference) = load_ref(store, &current)? else {
673            return Ok(None);
674        };
675        match reference.kind {
676            RefKind::Branch | RefKind::Tag => return Ok(Some(reference.target)),
677            RefKind::Head => current = reference.target,
678        }
679    }
680    Err(RedDBError::InvalidOperation(
681        "vcs: reference chain exceeds four levels".into(),
682    ))
683}
684
685fn resolve_short_commit(store: &UnifiedStore, prefix: &str) -> RedDBResult<Option<CommitHash>> {
686    if prefix.len() < 4 {
687        return Ok(None);
688    }
689    let mut found = None;
690    let mut ambiguous = false;
691    if let Some(manager) = store.get_collection(vc::COMMITS) {
692        super::function_budget::try_scan(
693            |visit| manager.try_for_each_entity(usize::MAX, visit),
694            |entity| {
695                if let Some(hash) = entity.data.as_row().and_then(|row| row_text(row, "id")) {
696                    if hash.starts_with(prefix) {
697                        ambiguous = found.is_some();
698                        found = Some(hash);
699                    }
700                }
701                !ambiguous
702            },
703        )?;
704    }
705    Ok(if ambiguous { None } else { found })
706}
707
708// ---------------------------------------------------------------------------
709// Workset helpers (lightweight — full WIP tracking lands in Phase 3)
710// ---------------------------------------------------------------------------
711
712fn stage_workset(
713    store: &UnifiedStore,
714    publication: &mut crate::storage::unified::store::RowPublication,
715    connection_id: u64,
716    branch: &str,
717    base_commit: Option<&str>,
718    working_xid: Xid,
719) -> RedDBResult<()> {
720    let connection = connection_id.to_string();
721    let mut fields = HashMap::from([
722        ("id".into(), Value::text(connection.as_str())),
723        ("branch".into(), Value::text(branch)),
724        ("working_xid".into(), Value::UnsignedInteger(working_xid)),
725    ]);
726    if let Some(base) = base_commit {
727        fields.insert("base_commit".into(), Value::text(base));
728    }
729    branches::stage_metadata(store, publication, vc::WORKSETS, "id", &connection, fields)
730}
731
732fn load_workset(
733    store: &UnifiedStore,
734    connection_id: u64,
735) -> RedDBResult<Option<(RefName, Option<CommitHash>)>> {
736    Ok(load_workset_state(store, connection_id)?.map(|(branch, base, _)| (branch, base)))
737}
738
739fn load_workset_state(
740    store: &UnifiedStore,
741    connection_id: u64,
742) -> RedDBResult<Option<(RefName, Option<CommitHash>, Option<String>)>> {
743    let Some(entity) = load_metadata_entity(store, vc::WORKSETS, &connection_id.to_string())?
744    else {
745        return Ok(None);
746    };
747    let row = entity
748        .data
749        .as_row()
750        .ok_or_else(|| RedDBError::Internal("vcs: invalid workset".into()))?;
751    let branch = row_text(row, "branch")
752        .ok_or_else(|| RedDBError::Internal("vcs: workset has no branch".into()))?;
753    let base = row_text(row, "base_commit");
754    let pending_merge = row_text(row, "merge_state_id");
755    let head = if branch.starts_with(vc::BRANCH_REF_PREFIX) && pending_merge.is_none() {
756        load_ref(store, &branch)?
757            .map(|reference| reference.target)
758            .or(base)
759    } else {
760        base
761    };
762    Ok(Some((branch, head, pending_merge)))
763}
764
765fn ensure_no_pending_merge(store: &UnifiedStore, connection_id: u64) -> RedDBResult<()> {
766    let branch = load_workset(store, connection_id)?
767        .map(|(branch, _)| branch)
768        .unwrap_or_else(|| vc::DEFAULT_BRANCH_REF.into());
769    let mut pending = None;
770    if let Some(manager) = store.get_collection(vc::WORKSETS) {
771        manager.try_for_each_entity(usize::MAX, |entity| {
772            if let Some(row) = entity
773                .data
774                .as_row()
775                .filter(|row| row_text(row, "branch").as_deref() == Some(&branch))
776            {
777                pending = row_text(row, "merge_state_id");
778            }
779            pending.is_none()
780        })?;
781    }
782    if let Some(state) = pending {
783        return Err(RedDBError::InvalidOperation(format!(
784            "cannot change branch data or HEAD while merge `{state}` is pending"
785        )));
786    }
787    Ok(())
788}
789
790// ---------------------------------------------------------------------------
791// Runtime impl
792// ---------------------------------------------------------------------------
793
794impl RedDBRuntime {
795    pub(crate) fn vcs_has_versioned_collections(&self) -> RedDBResult<bool> {
796        Ok(!versioned_collections_shared(&self.db().store())?.is_empty())
797    }
798
799    pub(crate) fn vcs_reject_destructive_ddl(&self, collection: &str) -> RedDBResult<()> {
800        if self.vcs_is_versioned(collection)? {
801            return Err(RedDBError::InvalidOperation(format!(
802                "cannot physically drop or truncate versioned collection '{collection}'; use versioned deletes or QUEUE PURGE"
803            )));
804        }
805        Ok(())
806    }
807
808    pub(super) fn rehydrate_vcs_snapshot_pins(&self) -> RedDBResult<()> {
809        let store = self.inner.db.store();
810        let Some(commits) = store.get_collection(vc::COMMITS) else {
811            return Ok(());
812        };
813        let manager = self.inner.transaction_state.snapshot_manager();
814        let mut failure = None;
815        commits.try_for_each_entity(usize::MAX, |entity| {
816            let Some(row) = entity.data.as_row() else {
817                failure = Some(RedDBError::Internal(
818                    "vcs: invalid commit record".to_string(),
819                ));
820                return false;
821            };
822            match commit_snapshot_from_row(row) {
823                Ok(snapshot) => {
824                    manager.observe_committed_xid(snapshot.xid);
825                    let horizon = snapshot
826                        .in_progress
827                        .iter()
828                        .copied()
829                        .fold(snapshot.xid, Xid::min);
830                    manager.pin(horizon);
831                    true
832                }
833                Err(error) => {
834                    failure = Some(error);
835                    false
836                }
837            }
838        })?;
839        match failure {
840            Some(error) => Err(error),
841            None => Ok(()),
842        }
843    }
844
845    pub fn vcs_commit(&self, input: CreateCommitInput) -> RedDBResult<Commit> {
846        let store_arc = self.inner.db.store();
847        let store: &UnifiedStore = &store_arc;
848        let _publication = store.vault_publication_lock.lock();
849
850        if let Some((_, _, Some(state))) = load_workset_state(store, input.connection_id)? {
851            return merge_data::finish_pending(self, input, &state);
852        }
853
854        ensure_no_pending_merge(store, input.connection_id)?;
855
856        // Resolve current HEAD for this connection: workset -> HEAD:<conn>
857        // -> default branch.
858        let workset = load_workset(store, input.connection_id)?;
859        let branch_ref = workset
860            .as_ref()
861            .map(|(b, _)| b.clone())
862            .unwrap_or_else(|| vc::DEFAULT_BRANCH_REF.to_string());
863
864        if !branch_ref.starts_with(vc::BRANCH_REF_PREFIX) {
865            return Err(RedDBError::InvalidOperation(
866                "cannot commit a detached or tag checkout".into(),
867            ));
868        }
869        let parent_hash = load_ref(store, &branch_ref)?
870            .map(|reference| reference.target)
871            .or_else(|| workset.as_ref().and_then(|(_, base)| base.clone()));
872
873        let parents: Vec<CommitHash> = match parent_hash.clone() {
874            Some(h) if !h.is_empty() => vec![h],
875            _ => Vec::new(),
876        };
877
878        let mut parent_height = 0;
879        for parent in &parents {
880            let commit = load_commit(store, parent)?
881                .ok_or_else(|| RedDBError::Internal("vcs: missing parent commit".into()))?;
882            parent_height = parent_height.max(commit.height);
883        }
884        let height = if parents.is_empty() {
885            0
886        } else {
887            parent_height + 1
888        };
889
890        // Allocate a fresh xid for this commit and immediately mark
891        // it committed so all future snapshots see the commit record.
892        // Each commit therefore has a unique, monotonic root_xid — a
893        // prerequisite for `AS OF BRANCH` to map to distinct
894        // snapshots across divergent branches.
895        let snapshot_manager = self.inner.transaction_state.snapshot_manager();
896        let mut snapshot = capture_commit_snapshot(&snapshot_manager);
897        let root_xid = snapshot.xid;
898        let timestamp_ms = now_ms();
899        let committer = input.committer.unwrap_or_else(|| input.author.clone());
900
901        let hash = compute_commit_hash(
902            root_xid,
903            &parents,
904            &input.author,
905            &input.message,
906            timestamp_ms,
907        );
908
909        if load_commit(store, &hash)?.is_some() {
910            return Err(RedDBError::InvalidConfig(format!(
911                "commit {hash} already exists (duplicate timestamp+content)"
912            )));
913        }
914
915        let commit = Commit {
916            hash: hash.clone(),
917            root_xid,
918            parents,
919            height,
920            author: input.author,
921            committer,
922            message: input.message,
923            timestamp_ms,
924            signature: None,
925        };
926
927        if !branch_ref.starts_with(vc::BRANCH_REF_PREFIX) {
928            return Err(RedDBError::InvalidOperation(
929                "cannot commit a detached or tag checkout".into(),
930            ));
931        }
932        merge_data::publish_commit(
933            self,
934            input.connection_id,
935            &branch_ref,
936            &commit,
937            &snapshot,
938            None,
939        )?;
940
941        snapshot.retained = true;
942        Ok(commit)
943    }
944
945    pub fn vcs_branch_create(&self, input: CreateBranchInput) -> RedDBResult<Ref> {
946        let store_arc = self.inner.db.store();
947        let store: &UnifiedStore = &store_arc;
948        let _publication = store.vault_publication_lock.lock();
949        let full_name = normalize_branch_name(&input.name);
950        if load_ref(store, &full_name)?.is_some() {
951            return Err(RedDBError::InvalidConfig(format!(
952                "branch `{full_name}` already exists"
953            )));
954        }
955        let target_hash = match &input.from {
956            Some(spec) => RedDBRuntime::vcs_resolve_commitish(self, spec)?,
957            None => {
958                // Fall back to the connection's current HEAD branch, then default.
959                let workset = load_workset(store, input.connection_id)?;
960
961                workset
962                    .and_then(|(_, base)| base)
963                    .or(load_ref(store, vc::DEFAULT_BRANCH_REF)?.map(|r| r.target))
964                    .unwrap_or_default()
965            }
966        };
967        let r = Ref {
968            name: full_name,
969            kind: RefKind::Branch,
970            target: target_hash,
971            protected: false,
972        };
973        let mut publication = crate::storage::unified::store::RowPublication::default();
974        branches::stage_new_view(store, &mut publication, &r.name, &r.target)?;
975        stage_ref(store, &mut publication, &r)?;
976        store.publish_rows(publication)?;
977        Ok(r)
978    }
979
980    pub fn vcs_branch_delete(&self, name: &str) -> RedDBResult<()> {
981        let store_arc = self.inner.db.store();
982        let store: &UnifiedStore = &store_arc;
983        let _publication = store.vault_publication_lock.lock();
984        let full = normalize_branch_name(name);
985        let existing = load_ref(store, &full)?
986            .ok_or_else(|| RedDBError::NotFound(format!("branch `{full}` does not exist")))?;
987        if existing.protected {
988            return Err(RedDBError::ReadOnly(format!(
989                "branch `{full}` is protected"
990            )));
991        }
992        if full == vc::DEFAULT_BRANCH_REF {
993            return Err(RedDBError::InvalidOperation(
994                "cannot delete the default branch".into(),
995            ));
996        }
997        let mut publication = crate::storage::unified::store::RowPublication::default();
998        if let Some((id, _)) = load_ref_entity(store, &full)? {
999            publication.deletes.push((vc::REFS.into(), id));
1000        }
1001        branches::stage_delete_view(store, &mut publication, &full)?;
1002        store.publish_rows(publication)?;
1003        Ok(())
1004    }
1005
1006    pub fn vcs_tag_create(&self, input: CreateTagInput) -> RedDBResult<Ref> {
1007        let store_arc = self.inner.db.store();
1008        let store: &UnifiedStore = &store_arc;
1009        let _publication = store.vault_publication_lock.lock();
1010        let full_name = normalize_tag_name(&input.name);
1011        if load_ref(store, &full_name)?.is_some() {
1012            return Err(RedDBError::InvalidConfig(format!(
1013                "tag `{full_name}` already exists"
1014            )));
1015        }
1016        let target_hash = RedDBRuntime::vcs_resolve_commitish(self, &input.target)?;
1017        let r = Ref {
1018            name: full_name,
1019            kind: RefKind::Tag,
1020            target: target_hash,
1021            protected: false,
1022        };
1023        save_ref(store, &r)?;
1024        Ok(r)
1025    }
1026
1027    pub fn vcs_tag_delete(&self, name: &str) -> RedDBResult<()> {
1028        let store_arc = self.inner.db.store();
1029        let store: &UnifiedStore = &store_arc;
1030        let _publication = store.vault_publication_lock.lock();
1031        let full = normalize_tag_name(name);
1032        let existing = load_ref(store, &full)?
1033            .ok_or_else(|| RedDBError::NotFound(format!("tag `{full}` does not exist")))?;
1034        if existing.protected {
1035            return Err(RedDBError::ReadOnly(format!("tag `{full}` is protected")));
1036        }
1037        delete_ref(store, &full)?;
1038        Ok(())
1039    }
1040
1041    pub fn vcs_list_refs(&self, prefix: Option<&str>) -> RedDBResult<Vec<Ref>> {
1042        let store_arc = self.inner.db.store();
1043        let store: &UnifiedStore = &store_arc;
1044        list_refs_by_prefix(store, prefix)
1045    }
1046
1047    pub fn vcs_checkout(&self, input: CheckoutInput) -> RedDBResult<Ref> {
1048        let store_arc = self.inner.db.store();
1049        let store: &UnifiedStore = &store_arc;
1050        let _publication = store.vault_publication_lock.lock();
1051        if self
1052            .inner
1053            .transaction_state
1054            .context(input.connection_id)
1055            .is_some()
1056        {
1057            return Err(RedDBError::InvalidOperation(
1058                "cannot checkout during an active transaction".into(),
1059            ));
1060        }
1061        if !input.force {
1062            ensure_no_pending_merge(store, input.connection_id)?;
1063        }
1064        let mut publication = crate::storage::unified::store::RowPublication::default();
1065        let (branch_ref, target_hash) = match &input.target {
1066            CheckoutTarget::Branch(name) => {
1067                let full = normalize_branch_name(name);
1068                let r = load_ref(store, &full)?.ok_or_else(|| {
1069                    RedDBError::NotFound(format!("branch `{full}` does not exist"))
1070                })?;
1071                if full != vc::DEFAULT_BRANCH_REF && branches::load_view(store, &full)?.is_none() {
1072                    branches::stage_new_view(store, &mut publication, &full, &r.target)?;
1073                }
1074                (full, r.target)
1075            }
1076            CheckoutTarget::Tag(name) => {
1077                let full = normalize_tag_name(name);
1078                let r = load_ref(store, &full)?
1079                    .ok_or_else(|| RedDBError::NotFound(format!("tag `{full}` does not exist")))?;
1080                (full, r.target)
1081            }
1082            CheckoutTarget::Commit(hash) => {
1083                let resolved = RedDBRuntime::vcs_resolve_commitish(self, hash)?;
1084                // Detached HEAD — we point HEAD directly at a commit via
1085                // the workset base; no branch ref is updated.
1086                (String::new(), resolved)
1087            }
1088        };
1089
1090        stage_workset(
1091            store,
1092            &mut publication,
1093            input.connection_id,
1094            &branch_ref,
1095            Some(&target_hash),
1096            self.inner
1097                .transaction_state
1098                .snapshot_manager()
1099                .peek_next_xid(),
1100        )?;
1101
1102        // Update per-connection HEAD pointer for status/introspection.
1103        stage_ref(
1104            store,
1105            &mut publication,
1106            &Ref {
1107                name: head_ref_id(input.connection_id),
1108                kind: RefKind::Head,
1109                target: if branch_ref.is_empty() {
1110                    target_hash.clone()
1111                } else {
1112                    branch_ref.clone()
1113                },
1114                protected: false,
1115            },
1116        )?;
1117
1118        store.publish_rows(publication)?;
1119        Ok(Ref {
1120            name: if branch_ref.is_empty() {
1121                format!("detached:{target_hash}")
1122            } else {
1123                branch_ref
1124            },
1125            kind: if target_hash.is_empty() {
1126                RefKind::Head
1127            } else {
1128                RefKind::Branch
1129            },
1130            target: target_hash,
1131            protected: false,
1132        })
1133    }
1134
1135    pub fn vcs_merge(&self, input: MergeInput) -> RedDBResult<MergeOutcome> {
1136        let store_arc = self.inner.db.store();
1137        let store: &UnifiedStore = &store_arc;
1138        let _publication = store.vault_publication_lock.lock();
1139        ensure_no_pending_merge(store, input.connection_id)?;
1140
1141        // Resolve source commit (the one being merged in).
1142        let from_hash = RedDBRuntime::vcs_resolve_commitish(self, &input.from)?;
1143        let from_commit = load_commit(store, &from_hash)?.ok_or_else(|| {
1144            RedDBError::NotFound(format!("source commit `{from_hash}` not found"))
1145        })?;
1146
1147        // Resolve current HEAD for the connection.
1148        let workset = load_workset(store, input.connection_id)?;
1149        let (head_branch, head_hash) = match workset {
1150            Some((branch, Some(head))) => (branch, head),
1151            Some((branch, None)) => {
1152                let head = load_ref(store, &branch)?
1153                    .map(|r| r.target)
1154                    .unwrap_or_default();
1155                (branch, head)
1156            }
1157            None => {
1158                let head = load_ref(store, vc::DEFAULT_BRANCH_REF)?
1159                    .map(|r| r.target)
1160                    .unwrap_or_default();
1161                (vc::DEFAULT_BRANCH_REF.to_string(), head)
1162            }
1163        };
1164        if head_hash.is_empty() {
1165            return Err(RedDBError::InvalidConfig(
1166                "cannot merge: HEAD has no commits".to_string(),
1167            ));
1168        }
1169
1170        // Fast-forward check: is HEAD an ancestor of `from`?
1171        let from_ancestors = ancestor_set(store, &from_hash, 100_000)?;
1172        let can_fast_forward = from_ancestors.contains(&head_hash);
1173
1174        match input.opts.strategy {
1175            MergeStrategy::FastForwardOnly if !can_fast_forward => {
1176                return Err(RedDBError::InvalidConfig(
1177                    "not a fast-forward — use --strategy auto or no-ff".to_string(),
1178                ));
1179            }
1180            _ => {}
1181        }
1182
1183        if can_fast_forward && input.opts.strategy != MergeStrategy::NoFastForward {
1184            if head_branch.is_empty() {
1185                return Err(RedDBError::InvalidConfig(
1186                    "cannot fast-forward a detached HEAD".to_string(),
1187                ));
1188            }
1189            branches::ensure_entity_history_supported(self)?;
1190            branches::ensure_clean(self, input.connection_id, &head_hash)?;
1191            merge_data::plan(self, &head_hash, &head_hash, &from_hash, "head-change")?;
1192            branches::publish_head(
1193                store,
1194                input.connection_id,
1195                &head_branch,
1196                &from_commit,
1197                branches::commit_view(store, &from_hash)?,
1198            )?;
1199            return Ok(MergeOutcome {
1200                merge_commit: Some(from_commit),
1201                fast_forward: true,
1202                conflicts: Vec::new(),
1203                merge_state_id: None,
1204            });
1205        }
1206
1207        if !head_branch.starts_with(vc::BRANCH_REF_PREFIX) {
1208            return Err(RedDBError::InvalidOperation(
1209                "cannot merge into a detached or tag checkout".into(),
1210            ));
1211        }
1212        branches::ensure_entity_history_supported(self)?;
1213        branches::ensure_clean(self, input.connection_id, &head_hash)?;
1214        let lca = RedDBRuntime::vcs_lca(self, &head_hash, &from_hash)?.ok_or_else(|| {
1215            RedDBError::InvalidOperation("cannot merge unrelated histories".into())
1216        })?;
1217
1218        let message = input
1219            .opts
1220            .message
1221            .unwrap_or_else(|| format!("Merge {} into {}", input.from, head_branch));
1222        let author = input.author.clone();
1223        let timestamp_ms = now_ms();
1224        let parents = vec![head_hash.clone(), from_hash.clone()];
1225        let mut parent_height = 0;
1226        for parent in &parents {
1227            let commit = load_commit(store, parent)?
1228                .ok_or_else(|| RedDBError::Internal("vcs: missing parent commit".into()))?;
1229            parent_height = parent_height.max(commit.height);
1230        }
1231        let height = parent_height + 1;
1232        let snapshot_manager = self.inner.transaction_state.snapshot_manager();
1233        let mut snapshot = capture_commit_snapshot(&snapshot_manager);
1234        let root_xid = snapshot.xid;
1235
1236        let hash = compute_commit_hash(root_xid, &parents, &author, &message, timestamp_ms);
1237
1238        let merge_commit = Commit {
1239            hash: hash.clone(),
1240            root_xid,
1241            parents,
1242            height,
1243            author: author.clone(),
1244            committer: author,
1245            message,
1246            timestamp_ms,
1247            signature: None,
1248        };
1249
1250        let merge_state_id = format!("ms:{}", &hash[..16]);
1251
1252        let plan = merge_data::plan(self, &lca, &head_hash, &from_hash, &merge_state_id)?;
1253        let conflicts = plan.conflicts.clone();
1254        if conflicts.is_empty() {
1255            let result = merge_data::publish_commit(
1256                self,
1257                input.connection_id,
1258                &head_branch,
1259                &merge_commit,
1260                &snapshot,
1261                Some(plan),
1262            );
1263            result?;
1264            snapshot.retained = true;
1265            return Ok(MergeOutcome {
1266                merge_commit: Some(merge_commit),
1267                fast_forward: false,
1268                conflicts,
1269                merge_state_id: None,
1270            });
1271        }
1272        let mut publication = crate::storage::unified::store::RowPublication::default();
1273        stage_merge_conflicts(store, &mut publication, &conflicts)?;
1274
1275        let mut ms_fields: HashMap<String, Value> = HashMap::new();
1276        ms_fields.insert("id".to_string(), Value::text(merge_state_id.as_str()));
1277        ms_fields.insert("kind".to_string(), Value::text("merge"));
1278        ms_fields.insert("branch".to_string(), Value::text(head_branch.as_str()));
1279        ms_fields.insert("base".to_string(), Value::text(lca.as_str()));
1280        ms_fields.insert("ours".to_string(), Value::text(head_hash.as_str()));
1281        ms_fields.insert("theirs".to_string(), Value::text(from_hash.as_str()));
1282        ms_fields.insert(
1283            "conflicts_count".to_string(),
1284            Value::UnsignedInteger(conflicts.len() as u64),
1285        );
1286        branches::stage_metadata(
1287            store,
1288            &mut publication,
1289            vc::MERGE_STATE,
1290            "id",
1291            &merge_state_id,
1292            ms_fields,
1293        )?;
1294
1295        let head_xid = self.vcs_resolve_as_of(AsOfSpec::Commit(head_hash.clone()))?;
1296        let conn_id = input.connection_id.to_string();
1297        branches::stage_metadata(
1298            store,
1299            &mut publication,
1300            vc::WORKSETS,
1301            "id",
1302            &conn_id,
1303            HashMap::from([
1304                ("id".into(), Value::text(conn_id.as_str())),
1305                ("branch".into(), Value::text(head_branch.as_str())),
1306                ("base_commit".into(), Value::text(head_hash.as_str())),
1307                ("working_xid".into(), Value::UnsignedInteger(head_xid)),
1308                (
1309                    "merge_state_id".into(),
1310                    Value::text(merge_state_id.as_str()),
1311                ),
1312            ]),
1313        )?;
1314        store.publish_rows(publication)?;
1315        Ok(MergeOutcome {
1316            merge_commit: None,
1317            fast_forward: false,
1318            conflicts,
1319            merge_state_id: Some(merge_state_id),
1320        })
1321    }
1322
1323    pub fn vcs_cherry_pick(
1324        &self,
1325        connection_id: u64,
1326        commit: &str,
1327        author: Author,
1328    ) -> RedDBResult<MergeOutcome> {
1329        let store_arc = self.inner.db.store();
1330        let store: &UnifiedStore = &store_arc;
1331        let _publication = store.vault_publication_lock.lock();
1332        ensure_no_pending_merge(store, connection_id)?;
1333
1334        // Resolve the commit being cherry-picked and its parent.
1335        let src_hash = RedDBRuntime::vcs_resolve_commitish(self, commit)?;
1336        let src_commit = load_commit(store, &src_hash)?.ok_or_else(|| {
1337            RedDBError::NotFound(format!("cherry-pick source `{src_hash}` not found"))
1338        })?;
1339        if src_commit.parents.is_empty() {
1340            return Err(RedDBError::InvalidConfig(
1341                "cannot cherry-pick a root commit".to_string(),
1342            ));
1343        }
1344        if src_commit.parents.len() > 1 {
1345            return Err(RedDBError::InvalidConfig(
1346                "cannot cherry-pick a merge commit; resolve manually".to_string(),
1347            ));
1348        }
1349        let parent_hash = src_commit.parents[0].clone();
1350
1351        let picked = merge_data::apply_delta(
1352            self,
1353            connection_id,
1354            &parent_hash,
1355            &src_hash,
1356            author,
1357            format!("cherry-pick: {}", src_commit.message),
1358        )?;
1359        Ok(MergeOutcome {
1360            merge_commit: Some(picked),
1361            fast_forward: false,
1362            conflicts: Vec::new(),
1363            merge_state_id: None,
1364        })
1365    }
1366
1367    pub fn vcs_revert(
1368        &self,
1369        connection_id: u64,
1370        commit: &str,
1371        author: Author,
1372    ) -> RedDBResult<Commit> {
1373        let store_arc = self.inner.db.store();
1374        let store: &UnifiedStore = &store_arc;
1375        let _publication = store.vault_publication_lock.lock();
1376        ensure_no_pending_merge(store, connection_id)?;
1377
1378        let src_hash = RedDBRuntime::vcs_resolve_commitish(self, commit)?;
1379        let src_commit = load_commit(store, &src_hash)?
1380            .ok_or_else(|| RedDBError::NotFound(format!("revert source `{src_hash}` not found")))?;
1381        if src_commit.parents.is_empty() {
1382            return Err(RedDBError::InvalidConfig(
1383                "cannot revert a root commit".to_string(),
1384            ));
1385        }
1386        let parent_hash = src_commit.parents[0].clone();
1387
1388        if src_commit.parents.len() != 1 {
1389            return Err(RedDBError::InvalidOperation(
1390                "cannot revert a merge commit without selecting a parent".into(),
1391            ));
1392        }
1393        merge_data::apply_delta(
1394            self,
1395            connection_id,
1396            &src_hash,
1397            &parent_hash,
1398            author,
1399            format!("Revert \"{}\"", src_commit.message),
1400        )
1401    }
1402
1403    pub fn vcs_reset(&self, input: ResetInput) -> RedDBResult<()> {
1404        let store_arc = self.inner.db.store();
1405        let store: &UnifiedStore = &store_arc;
1406        let _publication = store.vault_publication_lock.lock();
1407        ensure_no_pending_merge(store, input.connection_id)?;
1408        let target_hash = RedDBRuntime::vcs_resolve_commitish(self, &input.target)?;
1409        let target_commit = load_commit(store, &target_hash)?.ok_or_else(|| {
1410            RedDBError::NotFound(format!("target commit `{target_hash}` not found"))
1411        })?;
1412
1413        // Find the current branch for this connection.
1414        let workset = load_workset(store, input.connection_id)?;
1415        let branch = workset
1416            .as_ref()
1417            .map(|(b, _)| b.clone())
1418            .unwrap_or_else(|| vc::DEFAULT_BRANCH_REF.to_string());
1419
1420        if !branch.starts_with(vc::BRANCH_REF_PREFIX) {
1421            return Err(RedDBError::InvalidOperation(
1422                "reset requires a branch".into(),
1423            ));
1424        }
1425        if self.snapshot_manager().oldest_active_xid().is_some() {
1426            return Err(RedDBError::InvalidOperation(
1427                "finish active transactions before reset".into(),
1428            ));
1429        }
1430        // Soft and Mixed retain working data; Hard installs the target view.
1431        match input.mode {
1432            ResetMode::Soft | ResetMode::Mixed => {
1433                let mut publication = crate::storage::unified::store::RowPublication::default();
1434                branches::stage_head(
1435                    store,
1436                    &mut publication,
1437                    input.connection_id,
1438                    &branch,
1439                    &target_commit,
1440                    None,
1441                )?;
1442                store.publish_rows(publication)?;
1443                Ok(())
1444            }
1445            ResetMode::Hard => {
1446                branches::ensure_entity_history_supported(self)?;
1447                merge_data::validate_head_change(self, input.connection_id, &target_hash)?;
1448                branches::publish_head(
1449                    store,
1450                    input.connection_id,
1451                    &branch,
1452                    &target_commit,
1453                    branches::commit_view(store, &target_hash)?,
1454                )
1455            }
1456        }
1457    }
1458
1459    pub fn vcs_log(&self, input: LogInput) -> RedDBResult<Vec<Commit>> {
1460        let store_arc = self.inner.db.store();
1461        let store: &UnifiedStore = &store_arc;
1462        let start = match &input.range.to {
1463            Some(spec) => RedDBRuntime::vcs_resolve_commitish(self, spec)?,
1464            None => {
1465                let workset = load_workset(store, input.connection_id)?;
1466                workset
1467                    .and_then(|(_, base)| base)
1468                    .or(load_ref(store, vc::DEFAULT_BRANCH_REF)?.map(|r| r.target))
1469                    .unwrap_or_default()
1470            }
1471        };
1472        if start.is_empty() {
1473            return Ok(Vec::new());
1474        }
1475        topo_walk(store, &start, &input.range)
1476    }
1477
1478    pub fn vcs_diff(&self, input: DiffInput) -> RedDBResult<Diff> {
1479        let store_arc = self.inner.db.store();
1480        let store: &UnifiedStore = &store_arc;
1481        let from_hash = RedDBRuntime::vcs_resolve_commitish(self, &input.from)?;
1482        let to_hash = RedDBRuntime::vcs_resolve_commitish(self, &input.to)?;
1483        let from_snap = self.vcs_commit_read_context(&from_hash)?;
1484        let to_snap = self.vcs_commit_read_context(&to_hash)?;
1485
1486        // Iterate every *user* collection (skip internal red_*).
1487        let mut entries: Vec<DiffEntry> = Vec::new();
1488        let mut added = 0usize;
1489        let mut removed = 0usize;
1490        let mut modified = 0usize;
1491        let collections = store.list_collections();
1492        for coll in collections {
1493            if coll.starts_with("red_") || coll.starts_with("red.") {
1494                continue;
1495            }
1496            if !is_versioned(store, &coll)? {
1497                continue;
1498            }
1499            if let Some(filter) = &input.collection {
1500                if filter != &coll {
1501                    continue;
1502                }
1503            }
1504            let Some(manager) = store.get_collection(&coll) else {
1505                continue;
1506            };
1507            self.check_collection_privilege(reddb_rql::ast::PolicyAction::Select, &coll)?;
1508            let mut entities = Vec::new();
1509            manager.try_for_each_entity(usize::MAX, |entity| {
1510                entities.push(entity.clone());
1511                true
1512            })?;
1513            // Compare physical versions under the stable logical identity.
1514            for entity in &entities {
1515                let in_from = snapshot_sees_entity(&from_snap, entity);
1516                let in_to = snapshot_sees_entity(&to_snap, entity);
1517                if in_from == in_to {
1518                    continue;
1519                }
1520                ensure_vcs_entity_access(
1521                    self,
1522                    &coll,
1523                    entity,
1524                    reddb_rql::ast::PolicyAction::Select,
1525                )?;
1526                let entity_id = entity.logical_id().raw().to_string();
1527                let payload = if input.summary_only {
1528                    JsonValue::Null
1529                } else {
1530                    vcs_entity_body(self, &coll, entity)
1531                };
1532                let change = match (in_from, in_to) {
1533                    (false, true) => {
1534                        added += 1;
1535                        DiffChange::Added { after: payload }
1536                    }
1537                    (true, false) => {
1538                        removed += 1;
1539                        DiffChange::Removed { before: payload }
1540                    }
1541                    _ => unreachable!(),
1542                };
1543                entries.push(DiffEntry {
1544                    collection: coll.clone(),
1545                    entity_id,
1546                    change,
1547                });
1548            }
1549        }
1550
1551        // Modified rows in an append-only MVCC are expressed as a pair
1552        // (remove old version + add new version sharing entity_id);
1553        // collapse them into DiffChange::Modified so the wire format
1554        // matches user intuition.
1555        entries = coalesce_modifications(entries, &mut added, &mut removed, &mut modified);
1556
1557        Ok(Diff {
1558            from: from_hash,
1559            to: to_hash,
1560            entries,
1561            added,
1562            removed,
1563            modified,
1564        })
1565    }
1566
1567    pub fn vcs_status(&self, input: StatusInput) -> RedDBResult<Status> {
1568        let store_arc = self.inner.db.store();
1569        let store: &UnifiedStore = &store_arc;
1570        let workset = load_workset_state(store, input.connection_id)?;
1571        let (head_ref, head_commit, merge_state_id) = match workset {
1572            Some((branch, base, merge_state_id)) => {
1573                let base = base.or(load_ref(store, &branch)?.map(|r| r.target));
1574                (Some(branch), base, merge_state_id)
1575            }
1576            None => {
1577                let base = load_ref(store, vc::DEFAULT_BRANCH_REF)?.map(|r| r.target);
1578                (Some(vc::DEFAULT_BRANCH_REF.to_string()), base, None)
1579            }
1580        };
1581        let detached = matches!(&head_ref, Some(s) if s.is_empty());
1582        let unresolved_conflicts = match &merge_state_id {
1583            Some(id) => self.vcs_conflicts_list(id)?.len(),
1584            None => 0,
1585        };
1586        Ok(Status {
1587            connection_id: input.connection_id,
1588            head_ref: head_ref.filter(|s| !s.is_empty()),
1589            head_commit,
1590            detached,
1591            staged_changes: 0,
1592            working_changes: 0,
1593            unresolved_conflicts,
1594            merge_state_id,
1595        })
1596    }
1597
1598    pub fn vcs_lca(&self, a: &str, b: &str) -> RedDBResult<Option<CommitHash>> {
1599        let store_arc = self.inner.db.store();
1600        let store: &UnifiedStore = &store_arc;
1601        let a_hash = RedDBRuntime::vcs_resolve_commitish(self, a)?;
1602        let b_hash = RedDBRuntime::vcs_resolve_commitish(self, b)?;
1603        let a_ancestors = ancestor_set(store, &a_hash, 100_000)?;
1604
1605        // BFS from b, return first hit in a_ancestors with the greatest
1606        // height (closest common ancestor to b).
1607        let mut visited: HashSet<CommitHash> = HashSet::new();
1608        let mut stack: Vec<CommitHash> = vec![b_hash];
1609        let mut best: Option<(u64, CommitHash)> = None;
1610        while let Some(hash) = stack.pop() {
1611            if !visited.insert(hash.clone()) {
1612                continue;
1613            }
1614            if a_ancestors.contains(&hash) {
1615                let height = load_commit(store, &hash)?.map(|c| c.height).unwrap_or(0);
1616                match &best {
1617                    Some((h, _)) if *h >= height => {}
1618                    _ => best = Some((height, hash.clone())),
1619                }
1620                // Don't descend below an ancestor; higher-height hits
1621                // further from root are already captured.
1622                continue;
1623            }
1624            {
1625                let commit = load_commit(store, &hash)?.ok_or_else(|| {
1626                    RedDBError::Internal(format!("vcs: missing ancestor '{hash}'"))
1627                })?;
1628                for p in commit.parents {
1629                    if !visited.contains(&p) {
1630                        stack.push(p);
1631                    }
1632                }
1633            }
1634        }
1635        Ok(best.map(|(_, h)| h))
1636    }
1637
1638    pub fn vcs_conflicts_list(&self, merge_state_id: &str) -> RedDBResult<Vec<Conflict>> {
1639        let store = self.db().store();
1640        let _publication = store.vault_publication_lock.lock();
1641        merge_data::read_conflicts(self, merge_state_id)
1642    }
1643
1644    pub fn vcs_conflict_resolve(&self, conflict_id: &str, resolved: JsonValue) -> RedDBResult<()> {
1645        let store = self.db().store();
1646        let _publication = store.vault_publication_lock.lock();
1647        let row = merge_data::metadata_row(&store, vc::CONFLICTS, conflict_id)?
1648            .ok_or_else(|| RedDBError::NotFound(format!("conflict `{conflict_id}` not found")))?;
1649        let choice = match &resolved {
1650            JsonValue::String(choice)
1651                if matches!(choice.as_str(), "ours" | "theirs" | "base" | "delete") =>
1652            {
1653                choice
1654            }
1655            _ => {
1656                return Err(RedDBError::InvalidOperation(
1657                    "resolve with ours, theirs, base or delete; conflict retained".into(),
1658                ))
1659            }
1660        };
1661        let connection = crate::runtime::impl_core::current_connection_id();
1662        let active_state = load_workset_state(&store, connection)?.and_then(|(_, _, state)| state);
1663        if active_state != row_text(&row, "merge_state_id") {
1664            return Err(RedDBError::InvalidOperation(
1665                "conflict belongs to another pending merge".into(),
1666            ));
1667        }
1668        let mut fields: HashMap<_, _> = row
1669            .iter_fields()
1670            .map(|(name, value)| (name.into(), value.clone()))
1671            .collect();
1672        fields.insert("resolution".into(), Value::text(choice.as_str()));
1673        let mut publication = crate::storage::unified::store::RowPublication::default();
1674        branches::stage_metadata(
1675            &store,
1676            &mut publication,
1677            vc::CONFLICTS,
1678            "id",
1679            conflict_id,
1680            fields,
1681        )?;
1682        store.publish_rows(publication)?;
1683        Ok(())
1684    }
1685
1686    pub fn vcs_resolve_as_of(&self, spec: AsOfSpec) -> RedDBResult<Xid> {
1687        Ok(self.vcs_resolve_snapshot(spec)?.xid)
1688    }
1689
1690    pub(super) fn vcs_resolve_snapshot(&self, spec: AsOfSpec) -> RedDBResult<Snapshot> {
1691        let store_arc = self.inner.db.store();
1692        let store: &UnifiedStore = &store_arc;
1693        match spec {
1694            AsOfSpec::Snapshot(xid) => Ok(Snapshot {
1695                xid,
1696                in_progress: HashSet::new(),
1697            }),
1698            AsOfSpec::Commit(h) => {
1699                let entity = load_commit_entity(store, &h)?
1700                    .ok_or_else(|| RedDBError::NotFound(format!("commit `{h}` not found")))?;
1701                let row = entity.data.as_row().ok_or_else(|| {
1702                    RedDBError::Internal("vcs: invalid commit record".to_string())
1703                })?;
1704                commit_snapshot_from_row(row)
1705            }
1706            AsOfSpec::Branch(name) => {
1707                let full = normalize_branch_name(&name);
1708                let r = load_ref(store, &full)?.ok_or_else(|| {
1709                    RedDBError::NotFound(format!("branch `{full}` does not exist"))
1710                })?;
1711                let entity = load_commit_entity(store, &r.target)?.ok_or_else(|| {
1712                    RedDBError::NotFound(format!("branch `{full}` points to missing commit"))
1713                })?;
1714                let row = entity.data.as_row().ok_or_else(|| {
1715                    RedDBError::Internal("vcs: invalid commit record".to_string())
1716                })?;
1717                commit_snapshot_from_row(row)
1718            }
1719            AsOfSpec::Tag(name) => {
1720                let full = normalize_tag_name(&name);
1721                let r = load_ref(store, &full)?
1722                    .ok_or_else(|| RedDBError::NotFound(format!("tag `{full}` does not exist")))?;
1723                let entity = load_commit_entity(store, &r.target)?.ok_or_else(|| {
1724                    RedDBError::NotFound(format!("tag `{full}` points to missing commit"))
1725                })?;
1726                let row = entity.data.as_row().ok_or_else(|| {
1727                    RedDBError::Internal("vcs: invalid commit record".to_string())
1728                })?;
1729                commit_snapshot_from_row(row)
1730            }
1731            AsOfSpec::TimestampMs(ts) => {
1732                let manager = store
1733                    .get_collection(vc::COMMITS)
1734                    .ok_or_else(|| RedDBError::NotFound("no commits exist yet".to_string()))?;
1735                // Find the commit with the greatest timestamp_ms <= ts.
1736                let mut best: Option<(i64, UnifiedEntity)> = None;
1737                let mut entities = Vec::new();
1738                manager.try_for_each_entity(usize::MAX, |entity| {
1739                    entities.push(entity.clone());
1740                    true
1741                })?;
1742                for entity in entities {
1743                    if let Some(row) = entity.data.as_row() {
1744                        let t = row_i64(row, "timestamp_ms").unwrap_or(0);
1745                        if t <= ts {
1746                            match &best {
1747                                Some((bt, _)) if *bt >= t => {}
1748                                _ => best = Some((t, entity)),
1749                            }
1750                        }
1751                    }
1752                }
1753                let (_, entity) = best.ok_or_else(|| {
1754                    RedDBError::NotFound(format!("no commit at or before ts={ts}"))
1755                })?;
1756                let row = entity.data.as_row().ok_or_else(|| {
1757                    RedDBError::Internal("vcs: invalid commit record".to_string())
1758                })?;
1759                commit_snapshot_from_row(row)
1760            }
1761        }
1762    }
1763
1764    pub fn vcs_set_versioned(&self, collection: &str, enabled: bool) -> RedDBResult<()> {
1765        let store_arc = self.inner.db.store();
1766        let store: &UnifiedStore = &store_arc;
1767        let _publication = store.vault_publication_lock.lock();
1768        if collection.starts_with("red_") || collection.starts_with("red.") {
1769            return Err(RedDBError::InvalidConfig(format!(
1770                "cannot version internal collection `{collection}`"
1771            )));
1772        }
1773        if is_versioned(store, collection)? == enabled {
1774            return Ok(());
1775        }
1776        if self.snapshot_manager().oldest_active_xid().is_some() {
1777            return Err(RedDBError::InvalidOperation(
1778                "finish active transactions before changing version history".into(),
1779            ));
1780        }
1781        if !enabled
1782            && self
1783                .db()
1784                .collection_contract(collection)
1785                .is_some_and(|contract| {
1786                    matches!(
1787                        contract.declared_model,
1788                        crate::catalog::CollectionModel::Hll
1789                            | crate::catalog::CollectionModel::Sketch
1790                            | crate::catalog::CollectionModel::Filter
1791                    )
1792                })
1793        {
1794            return Err(RedDBError::InvalidOperation(
1795                "export probabilistic state before discarding its version history".into(),
1796            ));
1797        }
1798        if !enabled && list_refs_by_prefix(store, Some(vc::BRANCH_REF_PREFIX))?.len() > 1 {
1799            return Err(RedDBError::InvalidOperation(
1800                "cannot disable history while branches share versions".into(),
1801            ));
1802        }
1803        if enabled && store.format_version() < reddb_file::native_store::STORE_VERSION_V14 {
1804            let previous_format = store.format_version();
1805            store.set_format_version(reddb_file::native_store::STORE_VERSION_V14);
1806            if store.pager().is_some() {
1807                if let Err(error) = store.persist() {
1808                    store.set_format_version(previous_format);
1809                    return Err(RedDBError::Internal(error.to_string()));
1810                }
1811            }
1812        }
1813        let mut publication = crate::storage::unified::store::RowPublication::default();
1814        if enabled {
1815            if let Some(mut entity) = self.vcs_initial_probabilistic_state(collection)? {
1816                entity.id = store.next_entity_id();
1817                publication.inserts.push((collection.into(), entity, None));
1818            }
1819        }
1820        if self
1821            .db()
1822            .collection_contract(collection)
1823            .is_some_and(|contract| {
1824                contract.declared_model == crate::catalog::CollectionModel::Queue
1825            })
1826        {
1827            super::vcs_queue::stage_metadata_scope(store, &mut publication, collection, enabled)?;
1828        }
1829        if let Some(manager) = store.get_collection(collection) {
1830            if !enabled {
1831                let mut shared = false;
1832                manager.try_for_each_entity(usize::MAX, |entity| {
1833                    shared = entity.branch_version().is_some_and(|version| {
1834                        version.origin != 0 || !version.deletions.is_empty()
1835                    });
1836                    !shared
1837                })?;
1838                if shared {
1839                    return Err(RedDBError::InvalidOperation("cannot discard branch provenance; export the selected branch to an unversioned collection".into()));
1840                }
1841            }
1842            let mut ids = Vec::new();
1843            manager.try_for_each_entity(usize::MAX, |entity| {
1844                if entity.branch_version().is_some() != enabled {
1845                    ids.push(entity.id);
1846                }
1847                true
1848            })?;
1849            for id in ids {
1850                let mut entity = manager
1851                    .try_get(id, usize::MAX)?
1852                    .ok_or_else(|| RedDBError::NotFound(id.to_string()))?;
1853                if enabled {
1854                    entity.set_branch_origin(0);
1855                } else {
1856                    entity.clear_branch_version();
1857                }
1858                let metadata = store.try_get_metadata(collection, id, usize::MAX)?;
1859                publication
1860                    .replacements
1861                    .push((collection.into(), entity, metadata));
1862            }
1863        }
1864        branches::stage_metadata(
1865            store,
1866            &mut publication,
1867            vc::SETTINGS,
1868            "id",
1869            collection,
1870            HashMap::from([
1871                ("id".into(), Value::text(collection)),
1872                ("versioned".into(), Value::Boolean(enabled)),
1873                ("ts_ms".into(), Value::TimestampMs(now_ms())),
1874            ]),
1875        )?;
1876        store.publish_rows(publication)?;
1877        self.invalidate_result_cache();
1878        Ok(())
1879    }
1880
1881    pub fn vcs_list_versioned(&self) -> RedDBResult<Vec<String>> {
1882        let store_arc = self.inner.db.store();
1883        let store: &UnifiedStore = &store_arc;
1884        let mut list = versioned_collections(store)?;
1885        list.sort();
1886        Ok(list)
1887    }
1888
1889    pub fn vcs_is_versioned(&self, collection: &str) -> RedDBResult<bool> {
1890        let store_arc = self.inner.db.store();
1891        let store: &UnifiedStore = &store_arc;
1892        is_versioned(store, collection)
1893    }
1894
1895    pub fn vcs_resolve_commitish(&self, spec: &str) -> RedDBResult<CommitHash> {
1896        let store_arc = self.inner.db.store();
1897        let store: &UnifiedStore = &store_arc;
1898        if spec.is_empty() {
1899            return Err(RedDBError::InvalidConfig("empty commitish".to_string()));
1900        }
1901
1902        // 1. Exact commit hash.
1903        if spec.len() == 64
1904            && spec.chars().all(|c| c.is_ascii_hexdigit())
1905            && load_commit(store, spec)?.is_some()
1906        {
1907            return Ok(spec.to_string());
1908        }
1909
1910        // 2. Full ref name (refs/heads/..., refs/tags/...).
1911        if spec.starts_with("refs/") {
1912            if let Some(hash) = resolve_ref_chain(store, spec)? {
1913                return Ok(hash);
1914            }
1915        }
1916
1917        // 3. Short branch / tag name.
1918        let normalized_branch = normalize_branch_name(spec);
1919        if let Some(hash) = resolve_ref_chain(store, &normalized_branch)? {
1920            return Ok(hash);
1921        }
1922        let normalized_tag = normalize_tag_name(spec);
1923        if let Some(hash) = resolve_ref_chain(store, &normalized_tag)? {
1924            return Ok(hash);
1925        }
1926
1927        // 4. Short commit hash prefix (≥ 4 chars, unique match).
1928        if let Some(hash) = resolve_short_commit(store, spec)? {
1929            return Ok(hash);
1930        }
1931
1932        Err(RedDBError::NotFound(format!(
1933            "commitish `{spec}` did not resolve to any ref or commit"
1934        )))
1935    }
1936}
1937
1938/// Stage a paused merge's conflicts in the same publication as its workset.
1939fn stage_merge_conflicts(
1940    store: &UnifiedStore,
1941    publication: &mut crate::storage::unified::store::RowPublication,
1942    conflicts: &[Conflict],
1943) -> RedDBResult<()> {
1944    for conflict in conflicts {
1945        let fields = HashMap::from([
1946            ("id".into(), Value::text(conflict.id.as_str())),
1947            (
1948                "collection".into(),
1949                Value::text(conflict.collection.as_str()),
1950            ),
1951            ("entity_id".into(), Value::text(conflict.entity_id.as_str())),
1952            (
1953                "merge_state_id".into(),
1954                Value::text(conflict.merge_state_id.as_str()),
1955            ),
1956            (
1957                "conflicting_paths".into(),
1958                Value::Array(
1959                    conflict
1960                        .conflicting_paths
1961                        .iter()
1962                        .map(|path| Value::text(path.as_str()))
1963                        .collect(),
1964                ),
1965            ),
1966            (
1967                "base_json".into(),
1968                Value::Json(
1969                    crate::json::to_vec(&conflict.base)
1970                        .map_err(|e| RedDBError::Internal(e.to_string()))?,
1971                ),
1972            ),
1973            (
1974                "ours_json".into(),
1975                Value::Json(
1976                    crate::json::to_vec(&conflict.ours)
1977                        .map_err(|e| RedDBError::Internal(e.to_string()))?,
1978                ),
1979            ),
1980            (
1981                "theirs_json".into(),
1982                Value::Json(
1983                    crate::json::to_vec(&conflict.theirs)
1984                        .map_err(|e| RedDBError::Internal(e.to_string()))?,
1985                ),
1986            ),
1987        ]);
1988        branches::stage_metadata(
1989            store,
1990            publication,
1991            vc::CONFLICTS,
1992            "id",
1993            &conflict.id,
1994            fields,
1995        )?;
1996    }
1997    Ok(())
1998}
1999
2000fn ensure_vcs_entity_access(
2001    runtime: &RedDBRuntime,
2002    collection: &str,
2003    entity: &UnifiedEntity,
2004    action: reddb_rql::ast::PolicyAction,
2005) -> RedDBResult<()> {
2006    use reddb_rql::ast::PolicyAction;
2007    runtime.check_collection_privilege(action, collection)?;
2008    if !crate::runtime::rls_injection::entity_passes_rls_action(runtime, collection, action, entity)
2009    {
2010        return Err(RedDBError::Query(format!(
2011            "VCS access to collection '{collection}' denied by row-level security"
2012        )));
2013    }
2014    if let Some(row) = entity.data.as_row() {
2015        if let Some(key) = row_text(row, "key") {
2016            match runtime
2017                .db()
2018                .collection_contract(collection)
2019                .map(|c| c.declared_model)
2020            {
2021                Some(crate::catalog::CollectionModel::Vault) => {
2022                    let capability = if action == PolicyAction::Select {
2023                        "vault:read_metadata"
2024                    } else {
2025                        "vault:write"
2026                    };
2027                    runtime
2028                        .check_vault_capability_in_tenant(
2029                            capability,
2030                            collection,
2031                            &key,
2032                            row_text(row, "_vault_tenant").as_deref(),
2033                        )
2034                        .map_err(RedDBError::Query)?;
2035                }
2036                Some(crate::catalog::CollectionModel::Config) => {
2037                    let capability = if action == PolicyAction::Select {
2038                        "config:read"
2039                    } else {
2040                        "config:write"
2041                    };
2042                    runtime
2043                        .check_config_capability(capability, collection, &key)
2044                        .map_err(RedDBError::Query)?;
2045                }
2046                _ => {}
2047            }
2048        }
2049    }
2050    Ok(())
2051}
2052
2053fn vcs_entity_body(runtime: &RedDBRuntime, collection: &str, entity: &UnifiedEntity) -> JsonValue {
2054    if runtime
2055        .db()
2056        .collection_contract(collection)
2057        .is_some_and(|contract| contract.declared_model == crate::catalog::CollectionModel::Vault)
2058    {
2059        // VCS exposes secret metadata, never the encrypted envelope. Native
2060        // merge images retain the original sealed bytes without rendering them.
2061        let mut fields = Map::new();
2062        fields.insert(
2063            "id".into(),
2064            JsonValue::String(entity.logical_id().raw().to_string()),
2065        );
2066        if let Some(row) = entity.data.as_row() {
2067            for name in ["key", "version", "tombstone"] {
2068                if let Some(value) = row.get_field(name) {
2069                    fields.insert(name.into(), value.to_json());
2070                }
2071            }
2072        }
2073        return JsonValue::Object(fields);
2074    }
2075    let mut body = crate::entity_render::compact_entity_json(entity);
2076    if let JsonValue::Object(fields) = &mut body {
2077        fields.insert(
2078            "id".to_string(),
2079            JsonValue::Number(entity.logical_id().raw() as f64),
2080        );
2081        match &entity.kind {
2082            EntityKind::GraphNode(node) => {
2083                fields.insert("label".to_string(), JsonValue::String(node.label.clone()));
2084                fields.insert(
2085                    "node_type".to_string(),
2086                    JsonValue::String(node.node_type.clone()),
2087                );
2088            }
2089            EntityKind::GraphEdge(edge) => {
2090                fields.insert("label".to_string(), JsonValue::String(edge.label.clone()));
2091                fields.insert(
2092                    "from_node".to_string(),
2093                    JsonValue::String(edge.from_node.clone()),
2094                );
2095                fields.insert(
2096                    "to_node".to_string(),
2097                    JsonValue::String(edge.to_node.clone()),
2098                );
2099            }
2100            _ => {}
2101        }
2102        if let EntityData::Row(row) = &entity.data {
2103            if row.named.is_none() {
2104                fields.insert(
2105                    "row".to_string(),
2106                    JsonValue::Object(
2107                        row.iter_fields()
2108                            .map(|(key, value)| (key.to_string(), value.to_json()))
2109                            .collect(),
2110                    ),
2111                );
2112            }
2113        }
2114    }
2115    body
2116}
2117
2118// Collapse Add+Remove pairs sharing the same (collection, entity_id)
2119// into a single `Modified` entry. Called by `vcs_diff` after the
2120// naive pass so the caller sees one row per change, not two.
2121fn coalesce_modifications(
2122    entries: Vec<DiffEntry>,
2123    added: &mut usize,
2124    removed: &mut usize,
2125    modified: &mut usize,
2126) -> Vec<DiffEntry> {
2127    let mut by_key: HashMap<(String, String), Vec<DiffEntry>> = HashMap::new();
2128    for e in entries {
2129        by_key
2130            .entry((e.collection.clone(), e.entity_id.clone()))
2131            .or_default()
2132            .push(e);
2133    }
2134    let mut out: Vec<DiffEntry> = Vec::new();
2135    for ((coll, eid), group) in by_key {
2136        if group.len() >= 2 {
2137            let mut before = JsonValue::Null;
2138            let mut after = JsonValue::Null;
2139            for item in group {
2140                match item.change {
2141                    DiffChange::Removed { before: b } => before = b,
2142                    DiffChange::Added { after: a } => after = a,
2143                    DiffChange::Modified { .. } => {}
2144                }
2145            }
2146            *added = added.saturating_sub(1);
2147            *removed = removed.saturating_sub(1);
2148            *modified += 1;
2149            out.push(DiffEntry {
2150                collection: coll,
2151                entity_id: eid,
2152                change: DiffChange::Modified { before, after },
2153            });
2154        } else {
2155            out.extend(group);
2156        }
2157    }
2158    out.sort_by(|a, b| {
2159        a.collection
2160            .cmp(&b.collection)
2161            .then(a.entity_id.cmp(&b.entity_id))
2162    });
2163    out
2164}
2165
2166// Unused-import guards for stubs that reference types via `_`.
2167#[allow(dead_code)]
2168fn _touch_types(_: BTreeSet<()>) {}