ctb_formats_dcdata/support/graph_ledger/
inbox.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Manual and staged `.ctbnode-incoming` node allocation pipeline (`nodes/inbox/` -> `nodes/allocated/`),
21//! dynamic effective-state prevalidation, `BATCH_COMMITTED` provenance verification, and
22//! cross-ownership protection between `csv` and `manual` graph nodes.
23
24#[allow(
25    unused_imports,
26    clippy::wildcard_imports,
27    reason = "Standard workspace module prelude"
28)]
29use crate::utilities::*;
30
31use super::write_state::{DuplicatePolicy, SystemGraphWriteState};
32use super::{DcShorthand, LedgerNode, sh};
33use crate::ctbnbdl::{
34    DurableTransactionOutcome, FaultInjectionPoint, JournalRecord,
35    LEDGER_JOURNAL_REL_PATH, LedgerReadGuard, PlannedLedgerItem,
36    chunk_filename_for_node_id, ensure_ledger_journal_clean,
37    execute_durable_ledger_transaction_with_planner, inspect_ledger_journal,
38    load_ledger_nodes_from_dir, sha256_bytes_hex,
39};
40use std::collections::{BTreeMap, HashMap, HashSet};
41use std::fs;
42use std::path::Path;
43
44/// Highest node ID in the initial pre-journal baseline (`17,833` nodes).
45pub const PRE_JOURNAL_BASELINE_LAST_ID: u128 = 8_589_952_424;
46
47/// Provenance ownership classification of a ledger node.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub enum NodeProvenance {
50    /// Derived from or reconciled by the CSV data tables in `src/formats/dcdata/data-src/`.
51    Csv,
52    /// Manually authored via `nodes/inbox/` and protected from automatic CSV withdrawal.
53    Manual,
54}
55
56impl NodeProvenance {
57    /// Parses `"csv"` or `"manual"`.
58    pub fn parse(raw: &str) -> Result<Self> {
59        match raw.trim() {
60            "csv" => Ok(Self::Csv),
61            "manual" => Ok(Self::Manual),
62            other => bail!(
63                "Invalid # @provenance value {other:?}; expected 'csv' or 'manual'"
64            ),
65        }
66    }
67
68    /// Canonical string representation (`"csv"` or `"manual"`).
69    #[must_use]
70    pub const fn as_str(self) -> &'static str {
71        match self {
72            Self::Csv => "csv",
73            Self::Manual => "manual",
74        }
75    }
76}
77
78/// Verified provenance metadata for an allocated node (`> BOOTSTRAP_BASELINE_LAST_ID`).
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct NodeProvenanceEntry {
81    /// Allocated node ID (`l<node_id>`).
82    pub node_id: u128,
83    /// Ownership (`Csv` or `Manual`).
84    pub provenance: NodeProvenance,
85    /// Optional human-readable rationale (required when `Manual`).
86    pub rationale: Option<String>,
87    /// Allocated `.ctbnode-incoming` filename in `nodes/allocated/`, if allocated via inbox in an open chunk.
88    pub allocated_file: Option<String>,
89}
90
91/// Verified provenance ownership map across the committed ledger.
92#[derive(Debug, Clone, Default)]
93pub struct NodeProvenanceMap {
94    entries: HashMap<u128, NodeProvenanceEntry>,
95}
96
97impl NodeProvenanceMap {
98    /// Returns the provenance owner of `node_id` (nodes `<= BOOTSTRAP_BASELINE_LAST_ID` are `Csv`).
99    #[must_use]
100    pub fn owner(&self, node_id: u128) -> NodeProvenance {
101        // Reason for fallback: all pre-journal baseline nodes (<= BOOTSTRAP_BASELINE_LAST_ID) are CSV-derived.
102        self.entries
103            .get(&node_id)
104            .map_or(NodeProvenance::Csv, |e| e.provenance)
105    }
106
107    /// Returns the full provenance entry for `node_id`, if recorded above the bootstrap baseline.
108    #[must_use]
109    pub fn get(&self, node_id: u128) -> Option<&NodeProvenanceEntry> {
110        self.entries.get(&node_id)
111    }
112
113    /// Inserts a provenance entry (used by in-memory unit tests).
114    pub fn insert(&mut self, entry: NodeProvenanceEntry) {
115        self.entries.insert(entry.node_id, entry);
116    }
117}
118
119/// Parsed contents of a single `.ctbnode-incoming` file in `nodes/inbox/` or `nodes/allocated/`.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct ParsedCtbNodeIncomingFile {
122    /// Declared `# @provenance: csv | manual`.
123    pub provenance: NodeProvenance,
124    /// Optional `# @rationale: ...` (guaranteed `Some` when `provenance == Manual`).
125    pub rationale: Option<String>,
126    /// Optional `# @comment: ...` (or trailing `# comment` on the body line).
127    pub comment: Option<String>,
128    /// Sorted, deduplicated list of `# @allow-duplicate-of: l<id1>, ...` node IDs.
129    pub allow_duplicate_of: Vec<u128>,
130    /// Parsed `DcShorthand` token sequence from the body line.
131    pub tokens: Vec<DcShorthand>,
132}
133
134/// Parses and validates the headers and body of a `.ctbnode-incoming` inbox/allocated file.
135pub fn parse_ctbnode_incoming_file(
136    content: &str,
137    filename: &str,
138) -> Result<ParsedCtbNodeIncomingFile> {
139    let mut provenance: Option<NodeProvenance> = None;
140    let mut rationale: Option<String> = None;
141    let mut header_comment: Option<String> = None;
142    let mut allow_duplicate_of: Vec<u128> = Vec::new();
143    let mut body_lines: Vec<(usize, &str)> = Vec::new();
144
145    for (idx, raw_line) in content.lines().enumerate() {
146        let line_no = idx.saturating_add(1);
147        let trimmed = raw_line.trim();
148        if trimmed.is_empty() {
149            continue;
150        }
151        if let Some(rest) = trimmed.strip_prefix('#') {
152            let directive = rest.trim();
153            if let Some(val) = directive.strip_prefix("@provenance:") {
154                ensure!(
155                    provenance.is_none(),
156                    "{filename}:{line_no}: duplicate # @provenance directive"
157                );
158                provenance =
159                    Some(NodeProvenance::parse(val).with_context(|| {
160                        format!("{filename}:{line_no}: invalid # @provenance")
161                    })?);
162            } else if let Some(val) = directive.strip_prefix("@rationale:") {
163                let clean = val.trim();
164                ensure!(
165                    !clean.is_empty(),
166                    "{filename}:{line_no}: # @rationale cannot be empty"
167                );
168                rationale = Some(clean.to_string());
169            } else if let Some(val) = directive.strip_prefix("@comment:") {
170                let clean = val.trim();
171                if !clean.is_empty() {
172                    header_comment = Some(clean.to_string());
173                }
174            } else if let Some(val) =
175                directive.strip_prefix("@allow-duplicate-of:")
176            {
177                for part in val.split([',', ' ']) {
178                    let p = part.trim();
179                    if p.is_empty() {
180                        continue;
181                    }
182                    let Some(digits) = p.strip_prefix('l') else {
183                        bail!(
184                            "{filename}:{line_no}: # @allow-duplicate-of target {p:?} must use 'l<id>' syntax"
185                        );
186                    };
187                    let id: u128 = digits.parse().with_context(|| {
188                        format!(
189                            "{filename}:{line_no}: invalid node ID in # @allow-duplicate-of: {p:?}"
190                        )
191                    })?;
192                    allow_duplicate_of.push(id);
193                }
194            }
195            continue;
196        }
197        body_lines.push((line_no, trimmed));
198    }
199
200    let prov = provenance.with_context(|| {
201        format!(
202            "{filename}: missing required '# @provenance: csv|manual' header"
203        )
204    })?;
205    if prov == NodeProvenance::Manual {
206        ensure!(
207            rationale.as_ref().is_some_and(|r| !r.trim().is_empty()),
208            "{filename}: '# @provenance: manual' requires a non-empty '# @rationale: <explanation>' header"
209        );
210    }
211
212    ensure!(
213        body_lines.len() == 1,
214        "{filename}: expected exactly 1 non-comment node body line, found {}",
215        body_lines.len()
216    );
217    let &(line_no, raw_body) = body_lines
218        .first()
219        .with_context(|| format!("{filename}: missing node body line"))?;
220    let (token_part, inline_comment) =
221        if let Some((lhs, rhs)) = raw_body.split_once('#') {
222            let c = rhs.trim();
223            (
224                lhs.trim(),
225                if c.is_empty() {
226                    None
227                } else {
228                    Some(c.to_string())
229                },
230            )
231        } else {
232            (raw_body, None)
233        };
234
235    let mut tokens = Vec::new();
236    for tok_str in token_part.split_whitespace() {
237        let sh_tok = DcShorthand::parse(tok_str).with_context(|| {
238            format!(
239                "{filename}:{line_no}: invalid DcShorthand token {tok_str:?}"
240            )
241        })?;
242        tokens.push(sh_tok);
243    }
244    ensure!(
245        !tokens.is_empty(),
246        "{filename}:{line_no}: node body line contains zero tokens"
247    );
248
249    allow_duplicate_of.sort_unstable();
250    allow_duplicate_of.dedup();
251
252    Ok(ParsedCtbNodeIncomingFile {
253        provenance: prov,
254        rationale,
255        comment: header_comment.or(inline_comment),
256        allow_duplicate_of,
257        tokens,
258    })
259}
260
261/// Validates that all committed nodes above the `bootstrap_checkpoint` in `nodes` have matching
262/// `BATCH_COMMITTED` entries in `committed_pairs` and (for `inbox_allocation` batches in open chunks)
263/// matching `.ctbnode-incoming` files in `src/formats/dcdata/data-src/nodes/allocated/`, with zero
264/// unrecorded files in `nodes/allocated/`.
265///
266/// Note: Here "committed entry" means a `BATCH_PENDING` + `BATCH_COMMITTED` pair in `ledger-journal.jsonl`,
267/// not a Git commit. Pending recovery (`recover_pending_ledger_journal_with_guard`) must always run
268/// before calling this function.
269pub fn load_and_validate_node_provenance(
270    repo_root: &Path,
271    nodes: &[LedgerNode],
272    committed_pairs: &[(JournalRecord, JournalRecord)],
273) -> Result<NodeProvenanceMap> {
274    let allocated_dir =
275        repo_root.join("src/formats/dcdata/data-src/nodes/allocated");
276    let mut node_by_id: HashMap<u128, &LedgerNode> =
277        HashMap::with_capacity(nodes.len());
278    for node in nodes {
279        node_by_id.insert(node.id, node);
280    }
281
282    let mut map = NodeProvenanceMap::default();
283    let mut expected_allocated_files: HashSet<String> = HashSet::new();
284
285    for (pending, committed) in committed_pairs {
286        ensure!(
287            pending.batch_id == committed.batch_id,
288            "Mismatched committed journal pair: {} vs {}",
289            pending.batch_id,
290            committed.batch_id
291        );
292        for item in &pending.items {
293            let Some(&ledger_node) = node_by_id.get(&item.node_id) else {
294                bail!(
295                    "CRITICAL: Journal BATCH_COMMITTED ({}) records node l{}, which is missing from .ctbnodes!",
296                    committed.batch_id,
297                    item.node_id
298                );
299            };
300            let actual_line = ledger_node.format_line();
301            ensure!(
302                actual_line == item.raw_line,
303                "CRITICAL: Node l{} in .ctbnodes ({:?}) does not match BATCH_COMMITTED ({}) raw_line ({:?})",
304                item.node_id,
305                actual_line,
306                committed.batch_id,
307                item.raw_line
308            );
309            let prov = NodeProvenance::parse(if item.provenance.is_empty() {
310                "csv"
311            } else {
312                &item.provenance
313            })?;
314
315            if pending.kind == "inbox_allocation" {
316                let alloc_name =
317                    item.allocated_name.as_deref().with_context(|| {
318                        format!(
319                            "BATCH_COMMITTED ({}) inbox_allocation item l{} is missing allocated_name",
320                            committed.batch_id, item.node_id
321                        )
322                    })?;
323                let expected_prefix = format!("{}_", item.node_id);
324                ensure!(
325                    alloc_name.starts_with(&expected_prefix)
326                        && alloc_name.ends_with(".ctbnode-incoming"),
327                    "Allocated filename {alloc_name:?} for l{} must start with {expected_prefix:?} and end with '.ctbnode-incoming'",
328                    item.node_id
329                );
330                let alloc_path = allocated_dir.join(alloc_name);
331                ensure!(
332                    alloc_path.is_file(),
333                    "CRITICAL: Allocated .ctbnode-incoming file {} for committed node l{} is missing from disk!",
334                    alloc_path.display(),
335                    item.node_id
336                );
337                let raw_bytes = fs::read(&alloc_path).with_context(|| {
338                    format!("Failed to read {}", alloc_path.display())
339                })?;
340                if let Some(exp_sha) = item.inbox_sha256.as_deref() {
341                    let actual_sha = sha256_bytes_hex(&raw_bytes);
342                    ensure!(
343                        actual_sha == exp_sha,
344                        "CRITICAL: Allocated file {} SHA-256 {} does not match committed inbox_sha256 {}",
345                        alloc_path.display(),
346                        actual_sha,
347                        exp_sha
348                    );
349                }
350                let content =
351                    String::from_utf8(raw_bytes).with_context(|| {
352                        format!("Invalid UTF-8 in {}", alloc_path.display())
353                    })?;
354                let parsed_incoming =
355                    parse_ctbnode_incoming_file(&content, alloc_name)?;
356                ensure!(
357                    parsed_incoming.provenance == prov,
358                    "CRITICAL: Provenance mismatch for l{} between {} ({:?}) and BATCH_COMMITTED ({:?})",
359                    item.node_id,
360                    alloc_path.display(),
361                    parsed_incoming.provenance,
362                    prov
363                );
364                ensure!(
365                    parsed_incoming.tokens == ledger_node.tokens,
366                    "CRITICAL: Token body mismatch for l{} between {} and .ctbnodes",
367                    item.node_id,
368                    alloc_path.display()
369                );
370                expected_allocated_files.insert(alloc_name.to_string());
371            }
372
373            ensure!(
374                map.entries
375                    .insert(
376                        item.node_id,
377                        NodeProvenanceEntry {
378                            node_id: item.node_id,
379                            provenance: prov,
380                            rationale: item.rationale.clone(),
381                            allocated_file: item.allocated_name.clone(),
382                        },
383                    )
384                    .is_none(),
385                "CRITICAL: Duplicate provenance entry for node l{} in ledger-journal.jsonl",
386                item.node_id
387            );
388        }
389    }
390
391    // Also populate in-graph provenance (`Dc 635` -> `Dc 636` Csv / `Dc 637` Manual) from the graph itself.
392    let single_props = super::single_valued_property_set();
393    let seed_idx =
394        crate::seed_graph::SeedGraphIndex::from_nodes_with_single_props(
395            nodes.to_vec(),
396            &single_props,
397        );
398    for (&node_id, &src_tok) in &seed_idx.node_data_source {
399        let in_graph_prov = if src_tok
400            == sh(crate::dc::DC_COLLECTIVE_TOOLBOX_DC_CSV_SEED_DATABASE)
401        {
402            Some(NodeProvenance::Csv)
403        } else if src_tok == sh(crate::dc::DC_MANUAL_ENTRY) {
404            Some(NodeProvenance::Manual)
405        } else {
406            None
407        };
408        if let Some(prov) = in_graph_prov {
409            map.entries
410                .entry(node_id)
411                .or_insert_with(|| NodeProvenanceEntry {
412                    node_id,
413                    provenance: prov,
414                    rationale: None,
415                    allocated_file: None,
416                });
417        }
418    }
419
420    // Reason for fallback: when no bootstrap_checkpoint record is present in in-memory unit tests, default to PRE_JOURNAL_BASELINE_LAST_ID.
421    let bootstrap_last_id = committed_pairs
422        .iter()
423        .find(|(p, _)| p.kind == "bootstrap_checkpoint")
424        .map_or(PRE_JOURNAL_BASELINE_LAST_ID, |(p, _)| p.final_last_id);
425
426    // Every node > bootstrap_last_id must have a committed journal record or in-graph provenance.
427    for node in nodes {
428        if node.id > bootstrap_last_id
429            && !seed_idx.provenance_stmt_ids.contains(&node.id)
430        {
431            ensure!(
432                map.entries.contains_key(&node.id),
433                "CRITICAL: Ledger node l{} (> l{bootstrap_last_id}) has no BATCH_COMMITTED or in-graph provenance entry!",
434                node.id
435            );
436        }
437    }
438
439    // Every .ctbnode-incoming (or legacy .dcsh) file in nodes/allocated/ must correspond to an open-chunk BATCH_COMMITTED inbox_allocation item.
440    if allocated_dir.is_dir() {
441        for entry in fs::read_dir(&allocated_dir)? {
442            let entry = entry?;
443            let path = entry.path();
444            let ext = path.extension().and_then(|e| e.to_str());
445            if ext == Some("ctbnode-incoming") || ext == Some("dcsh") {
446                let Some(name) = path.file_name().and_then(|n| n.to_str())
447                else {
448                    continue;
449                };
450                ensure!(
451                    expected_allocated_files.contains(name),
452                    "CRITICAL: Unrecorded incoming node file {} found in {} with no matching open-chunk BATCH_COMMITTED journal entry!",
453                    path.display(),
454                    allocated_dir.display()
455                );
456            }
457        }
458    }
459
460    Ok(map)
461}
462
463/// Convenience wrapper for external callers/tests to validate committed node provenance from `repo_root`.
464pub fn verify_repo_committed_node_provenance(
465    repo_root: &Path,
466) -> Result<NodeProvenanceMap> {
467    let read_guard = LedgerReadGuard::acquire(repo_root)?;
468    ensure_ledger_journal_clean(repo_root, &read_guard)?;
469    let graph_dir = repo_root.join("assets/data/graph");
470    let journal_path = repo_root.join(LEDGER_JOURNAL_REL_PATH);
471    let nodes = load_ledger_nodes_from_dir(&graph_dir)?;
472    let parsed = inspect_ledger_journal(&journal_path)?;
473    load_and_validate_node_provenance(
474        repo_root,
475        &nodes,
476        &parsed.committed_pairs,
477    )
478}
479
480/// Prevalidates a batch of `.dcsh` inbox files `(inbox_name, inbox_sha256, content)` in memory
481/// against `existing_nodes` and `provenance_map`, returning the planned `PlannedLedgerItem`s.
482///
483/// Any validation failure aborts before `BATCH_PENDING` is written.
484pub fn prevalidate_and_plan_inbox_items(
485    existing_nodes: &[LedgerNode],
486    provenance_map: &NodeProvenanceMap,
487    inbox_files: &[(String, String, String)],
488) -> Result<Vec<PlannedLedgerItem>> {
489    prevalidate_and_plan_inbox_items_with_timestamps(
490        existing_nodes,
491        provenance_map,
492        inbox_files,
493        None,
494        None,
495    )
496}
497
498fn prevalidate_and_plan_inbox_items_with_timestamps(
499    existing_nodes: &[LedgerNode],
500    provenance_map: &NodeProvenanceMap,
501    inbox_files: &[(String, String, String)],
502    default_created_ns: Option<i128>,
503    pinned_created_ns_by_id: Option<HashMap<u128, Option<i128>>>,
504) -> Result<Vec<PlannedLedgerItem>> {
505    let mut write_state = SystemGraphWriteState::from_nodes_and_provenance(
506        existing_nodes,
507        provenance_map.clone(),
508    )
509    .with_creation_timestamps(default_created_ns, pinned_created_ns_by_id);
510    let mut planned_items: Vec<PlannedLedgerItem> =
511        Vec::with_capacity(inbox_files.len());
512
513    for (inbox_name, inbox_sha256, content) in inbox_files {
514        let parsed = parse_ctbnode_incoming_file(content, inbox_name)?;
515        let predicted_id = write_state.next_node_id(inbox_name)?;
516        let allocated_name = format!("{predicted_id}_{inbox_name}");
517        let next_id = write_state.validate_and_append_node(
518            parsed.tokens,
519            parsed.provenance,
520            parsed.rationale.clone(),
521            Some(allocated_name.clone()),
522            DuplicatePolicy::RequireAllowDuplicateOf(&parsed.allow_duplicate_of),
523            inbox_name,
524        )?;
525        let raw_line = write_state
526            .get_node(next_id)
527            .context("Newly appended inbox node missing from write_state")?
528            .format_line();
529        let target_chunk = chunk_filename_for_node_id(next_id);
530
531        planned_items.push(PlannedLedgerItem {
532            node_id: next_id,
533            raw_line,
534            target_chunk,
535            tokens: Vec::new(),
536            comment: String::new(),
537            provenance: parsed.provenance.as_str().to_string(),
538            rationale: parsed.rationale,
539            allow_duplicate_of: parsed.allow_duplicate_of,
540            inbox_name: Some(inbox_name.clone()),
541            allocated_name: Some(allocated_name),
542            inbox_sha256: Some(inbox_sha256.clone()),
543            dcsh_content: None,
544        });
545    }
546
547    Ok(planned_items)
548}
549
550/// Processes all `.ctbnode-incoming` files in `<repo_root>/src/formats/dcdata/data-src/nodes/inbox/`
551/// inside a single durable ledger transaction under `LedgerWriteGuard` (`LOCK_EX`).
552pub fn process_inbox_nodes(
553    repo_root: &Path,
554    required_manifest_path: Option<&Path>,
555    dry_run: bool,
556) -> Result<DurableTransactionOutcome<()>> {
557    process_inbox_nodes_with_fault(
558        repo_root,
559        required_manifest_path,
560        dry_run,
561        None,
562    )
563}
564
565/// Same as [`process_inbox_nodes`], with optional [`FaultInjectionPoint`] for crash/recovery testing.
566pub fn process_inbox_nodes_with_fault(
567    repo_root: &Path,
568    required_manifest_path: Option<&Path>,
569    dry_run: bool,
570    fault: Option<FaultInjectionPoint>,
571) -> Result<DurableTransactionOutcome<()>> {
572    let pinned_created_ns =
573        super::extract_manifest_created_ns_map(required_manifest_path)?;
574    let inbox_dir = repo_root.join("src/formats/dcdata/data-src/nodes/inbox");
575    let outcome = execute_durable_ledger_transaction_with_planner(
576        repo_root,
577        "inbox_allocation",
578        "inbox",
579        required_manifest_path,
580        dry_run,
581        fault,
582        |_write_guard, baseline_nodes, committed_pairs| {
583            let prov_map = load_and_validate_node_provenance(
584                repo_root,
585                baseline_nodes,
586                committed_pairs,
587            )?;
588
589            let mut sorted_files: BTreeMap<String, (String, String)> =
590                BTreeMap::new();
591            if inbox_dir.is_dir() {
592                for entry in fs::read_dir(&inbox_dir).with_context(|| {
593                    format!("Failed to read {}", inbox_dir.display())
594                })? {
595                    let entry = entry?;
596                    let path = entry.path();
597                    if !path.is_file() {
598                        continue;
599                    }
600                    if path.extension().and_then(|e| e.to_str())
601                        != Some("ctbnode-incoming")
602                    {
603                        continue;
604                    }
605                    let Some(name) = path.file_name().and_then(|n| n.to_str())
606                    else {
607                        continue;
608                    };
609                    let raw_bytes = fs::read(&path).with_context(|| {
610                        format!("Failed to read {}", path.display())
611                    })?;
612                    let sha = sha256_bytes_hex(&raw_bytes);
613                    let text =
614                        String::from_utf8(raw_bytes).with_context(|| {
615                            format!("Invalid UTF-8 in {}", path.display())
616                        })?;
617                    sorted_files.insert(name.to_string(), (sha, text));
618                }
619            }
620
621            let mut pinned_input_sha256s = BTreeMap::new();
622            let mut inbox_vec = Vec::with_capacity(sorted_files.len());
623            for (name, (sha, text)) in sorted_files {
624                pinned_input_sha256s.insert(name.clone(), sha.clone());
625                inbox_vec.push((name, sha, text));
626            }
627
628            let default_created_ns =
629                if super::resolve_ctbnbdl_framing_dcs_from_nodes(baseline_nodes)
630                    .is_ok_and(|f| f.section_node_creation_time.is_some())
631                {
632                    Some(super::current_unix_timestamp_ns())
633                } else {
634                    None
635                };
636
637            let planned = prevalidate_and_plan_inbox_items_with_timestamps(
638                baseline_nodes,
639                &prov_map,
640                &inbox_vec,
641                default_created_ns,
642                pinned_created_ns,
643            )?;
644            Ok((planned, pinned_input_sha256s, ()))
645        },
646    )?;
647
648    if !dry_run {
649        let _ = verify_repo_committed_node_provenance(repo_root)?;
650    }
651
652    Ok(outcome)
653}
654
655#[cfg(test)]
656#[allow(
657    clippy::panic,
658    clippy::expect_used,
659    clippy::unwrap_used,
660    clippy::unwrap_in_result,
661    clippy::panic_in_result_fn,
662    clippy::indexing_slicing,
663    clippy::arithmetic_side_effects,
664    reason = "Standard repository test boilerplate"
665)]
666mod tests {
667    use super::super::{
668        DC_HAS_A, DC_HAS_VALUE, DC_PREFERRED, default_ctbnbdl_framing_dcs,
669    };
670    use ctb_storage_minimal::global_graph_layout::SYSTEM_REGION_START;
671    use super::*;
672    use crate::ctbnbdl::{
673        JOURNAL_INITIALIZED_REL_PATH, LedgerWriteGuard, TransactionManifest,
674        compile_nodes_slice_to_ctbnbdl_with_write_guard,
675        compute_ledger_dir_sha256, compute_nodes_slice_ledger_sha256,
676        format_chunk_filename, load_ledger_nodes_from_str,
677        recover_pending_ledger_journal, sync_highwater_shadow_ledgers,
678        write_ledger_nodes_to_dir,
679    };
680    use crate::dc::DC_CANONICAL_NAME;
681    use crate::dc_def::DcDefn;
682    use crate::graph_ledger::{
683        encode_statement_tokens, encode_string_value_tokens,
684        update_ledger_in_memory, update_ledger_in_memory_with_provenance,
685    };
686    use crate::shared::{BidiClass, GeneralCategory};
687    use crate::syntax::parse_dc_syntax;
688    use std::collections::BTreeSet;
689    use tempfile::TempDir;
690
691    fn sample_dc_defn(short_id: usize, name: &str, desc: &str) -> DcDefn {
692        DcDefn {
693            dc_id: 1_114_112 + u128::try_from(short_id).unwrap(),
694            short_id: Some(short_id),
695            ident: Some(format!("DC_TEST_{short_id}")),
696            stable_ident: false,
697            title: None,
698            name: name.to_string(),
699            category: "semantic".to_string(),
700            combining_class: 0,
701            bidi_class: BidiClass::BN,
702            casing_partner: None,
703            general_category: GeneralCategory::NonUnicodeControl,
704            script: ".Semantic".to_string(),
705            is_deprecated: false,
706            decompositions: Vec::new(),
707            aliases: vec!["test-alias".to_string()],
708            formal_aliases: Vec::new(),
709            cross_references: Vec::new(),
710            annotations: Vec::new(),
711            implies: vec!["571".to_string()],
712            based_on: Vec::new(),
713            os_associations: Vec::new(),
714            magic_names: Vec::new(),
715            syntax: Some(parse_dc_syntax(":~").unwrap()),
716            closes: None,
717            description: desc.to_string(),
718            format: None,
719            source_file: "test.csv".to_string(),
720            line_number: 2,
721        }
722    }
723
724    fn setup_minimal_repo_for_inbox_tests() -> Result<(TempDir, Vec<LedgerNode>)>
725    {
726        let tmp = TempDir::new()?;
727        let root = tmp.path();
728        fs::write(root.join(".ctoolbox_workspace_root"), b"")?;
729        fs::write(root.join("Cargo.toml"), b"[workspace]\n")?;
730        fs::create_dir_all(
731            root.join("src/formats/dcdata/data-src/nodes/inbox"),
732        )?;
733        fs::create_dir_all(
734            root.join("src/formats/dcdata/data-src/nodes/allocated"),
735        )?;
736        fs::create_dir_all(root.join("assets/data/graph"))?;
737        fs::create_dir_all(root.join(".git"))?;
738
739        // Build a minimal self-bootstrapping framing graph
740        let framing = default_ctbnbdl_framing_dcs();
741        let required_idents: &[(&str, DcShorthand)] = &[
742            ("ProgrammaticIdentifier", DcShorthand::Short(574)),
743            ("BeginGraphNodeDefinition", framing.begin_node),
744            ("EndGraphNodeDefinition", framing.end_node),
745            ("BeginChecksummedSection", framing.begin_checksummed_section),
746            ("EndChecksummedSection", framing.end_checksummed_section),
747            ("SectionDigest", framing.section_digest),
748            ("BeginTimeMoment", framing.begin_time_moment),
749            ("EndTimeMoment", framing.end_time_moment),
750            (
751                "SectionTimestampNodeCreationTime",
752                DcShorthand::Short(1941),
753            ),
754            ("NsSinceEpoch", framing.ns_since_epoch_format),
755            ("Sha256", framing.sha256_format),
756            ("Escape", framing.escape),
757            ("EvaluateValueAsAtom", framing.evaluate_as_atom),
758            ("HasA", framing.has_a),
759            ("HasValue", framing.has_value),
760            ("Preferred", framing.preferred),
761            ("Supersedes", framing.supersedes),
762            ("Retracts", framing.retracts),
763            ("EnclosingDocument", framing.enclosing_document),
764            ("IsInstanceOf", framing.is_instance_of),
765            ("IsSubtypeOf", framing.is_subtype_of),
766            ("IsBasedOn", framing.is_based_on),
767            ("IsDeprecated", framing.is_deprecated),
768            ("IsClosingDelimiterFor", framing.is_closing_delimiter_for),
769            ("IsAssociatedWith", framing.is_associated_with),
770        ];
771
772        let mut nodes = Vec::new();
773        let mut next_id = SYSTEM_REGION_START;
774        let sh_prog_ident = DcShorthand::Short(574);
775        for &(ident, subj) in required_idents {
776            let str_id = next_id;
777            nodes.push(LedgerNode {
778                id: str_id,
779                tokens: encode_string_value_tokens(ident),
780                comment: format!("{ident:?}"),
781                created_ns: None,
782            });
783            next_id += 1;
784
785            let has_a_id = next_id;
786            nodes.push(LedgerNode {
787                id: has_a_id,
788                tokens: encode_statement_tokens(
789                    framing.has_a,
790                    subj,
791                    sh_prog_ident,
792                ),
793                comment: format!("Has a ({subj}, 574)"),
794                created_ns: None,
795            });
796            next_id += 1;
797
798            let has_val_id = next_id;
799            nodes.push(LedgerNode {
800                id: has_val_id,
801                tokens: encode_statement_tokens(
802                    framing.has_value,
803                    DcShorthand::Long(has_a_id),
804                    DcShorthand::Long(str_id),
805                ),
806                comment: format!("Has value (l{has_a_id}, l{str_id})"),
807                created_ns: None,
808            });
809            next_id += 1;
810        }
811
812        let graph_dir = root.join("assets/data/graph");
813        let write_guard = LedgerWriteGuard::acquire(root)?;
814        write_ledger_nodes_to_dir(&graph_dir, &nodes)?;
815        sync_highwater_shadow_ledgers(root, &nodes)?;
816        let digests = compile_nodes_slice_to_ctbnbdl_with_write_guard(
817            &write_guard,
818            &nodes,
819            &graph_dir,
820            framing,
821        )?;
822
823        let sha = compute_ledger_dir_sha256(&graph_dir)?;
824        let last_id = nodes.last().unwrap().id;
825        let pending = JournalRecord {
826            state: "BATCH_PENDING".to_string(),
827            batch_id: "bootstrap-test".to_string(),
828            kind: "bootstrap_checkpoint".to_string(),
829            baseline_last_id: last_id,
830            baseline_ledger_sha256: sha.clone(),
831            final_last_id: last_id,
832            final_ledger_sha256: sha.clone(),
833            manifest_sha256: None,
834            items: Vec::new(),
835            unsplit_bundles_sha256: BTreeMap::new(),
836            active_bundles_sha256: BTreeMap::new(),
837            history_bundles_sha256: BTreeMap::new(),
838            record_sha256: String::new(),
839        }
840        .with_computed_sha256()?;
841        let committed = JournalRecord {
842            state: "BATCH_COMMITTED".to_string(),
843            batch_id: "bootstrap-test".to_string(),
844            kind: "bootstrap_checkpoint".to_string(),
845            baseline_last_id: last_id,
846            baseline_ledger_sha256: sha.clone(),
847            final_last_id: last_id,
848            final_ledger_sha256: sha,
849            manifest_sha256: None,
850            items: Vec::new(),
851            unsplit_bundles_sha256: digests.unsplit_bundles_sha256,
852            active_bundles_sha256: digests.active_bundles_sha256,
853            history_bundles_sha256: digests.history_bundles_sha256,
854            record_sha256: String::new(),
855        }
856        .with_computed_sha256()?;
857        let journal_content = format!(
858            "{}\n{}\n",
859            serde_json::to_string(&pending)?,
860            serde_json::to_string(&committed)?
861        );
862        fs::write(root.join(LEDGER_JOURNAL_REL_PATH), journal_content)?;
863        fs::write(root.join(JOURNAL_INITIALIZED_REL_PATH), b"initialized\n")?;
864
865        Ok((tmp, nodes))
866    }
867
868    #[crate::ctb_test]
869    fn test_inbox_prevalidation_rejects_malformed_and_invalid_dcsh_inputs()
870    -> Result<()> {
871        let (_tmp, baseline_nodes) = setup_minimal_repo_for_inbox_tests()?;
872        let prov_map = NodeProvenanceMap::default();
873        let next_id =
874            SYSTEM_REGION_START + u128::try_from(baseline_nodes.len()).unwrap();
875
876        // 1. Missing `# @provenance`
877        prevalidate_and_plan_inbox_items(
878            &baseline_nodes,
879            &prov_map,
880            &[(
881                "01.ctbnode-incoming".to_string(),
882                "sha".to_string(),
883                "u61 u62\n".to_string(),
884            )],
885        )
886        .unwrap_err();
887
888        // 2. `# @provenance: manual` without `# @rationale:`
889        prevalidate_and_plan_inbox_items(
890            &baseline_nodes,
891            &prov_map,
892            &[(
893                "01.ctbnode-incoming".to_string(),
894                "sha".to_string(),
895                "# @provenance: manual\nu61 u62\n".to_string(),
896            )],
897        )
898        .unwrap_err();
899
900        // 3. Self-reference (`l<next_id>`) and forward reference (`l<next_id + 1>`)
901        prevalidate_and_plan_inbox_items(
902            &baseline_nodes,
903            &prov_map,
904            &[(
905                "01.ctbnode-incoming".to_string(),
906                "sha".to_string(),
907                format!("# @provenance: csv\n586 l{next_id} 571\n"),
908            )],
909        )
910        .unwrap_err();
911        prevalidate_and_plan_inbox_items(
912            &baseline_nodes,
913            &prov_map,
914            &[(
915                "01.ctbnode-incoming".to_string(),
916                "sha".to_string(),
917                format!("# @provenance: csv\n586 l{} 571\n", next_id + 1),
918            )],
919        )
920        .unwrap_err();
921
922        // 4. Malformed `Dc 348 "Ambiguous values"` list (< 2 candidates or duplicate candidates)
923        prevalidate_and_plan_inbox_items(
924                &baseline_nodes,
925                &prov_map,
926                &[(
927                    "01.ctbnode-incoming".to_string(),
928                    "sha".to_string(),
929                    format!(
930                        "# @provenance: csv\n348 310 275 l{SYSTEM_REGION_START} 311\n"
931                    ),
932                )],
933            ).unwrap_err();
934        prevalidate_and_plan_inbox_items(
935                &baseline_nodes,
936                &prov_map,
937                &[(
938                    "01.ctbnode-incoming".to_string(),
939                    "sha".to_string(),
940                    format!(
941                        "# @provenance: csv\n348 310 275 l{SYSTEM_REGION_START} 312 l{SYSTEM_REGION_START} 311\n"
942                    ),
943                )],
944            ).unwrap_err();
945
946        // 5. Attaching `610` (`Has value`) to a non-`584` (`Has a`) node (`l8589934592` is a string value node)
947        prevalidate_and_plan_inbox_items(
948                &baseline_nodes,
949                &prov_map,
950                &[(
951                    "01.ctbnode-incoming".to_string(),
952                    "sha".to_string(),
953                    format!(
954                        "# @provenance: csv\n610 l{SYSTEM_REGION_START} l{SYSTEM_REGION_START}\n"
955                    ),
956                )],
957            ).unwrap_err();
958
959        // 6. Unauthorized active duplicate (`"ProgrammaticIdentifier"` string tokens already exist at `l8589934592`)
960        let dup_body = baseline_nodes[0]
961            .tokens
962            .iter()
963            .map(ToString::to_string)
964            .collect::<Vec<_>>()
965            .join(" ");
966        prevalidate_and_plan_inbox_items(
967            &baseline_nodes,
968            &prov_map,
969            &[(
970                "01.ctbnode-incoming".to_string(),
971                "sha".to_string(),
972                format!("# @provenance: csv\n{dup_body}\n"),
973            )],
974        )
975        .unwrap_err();
976
977        // 7. Authorized active duplicate succeeds when `# @allow-duplicate-of: l8589934592` is declared
978        let planned = prevalidate_and_plan_inbox_items(
979            &baseline_nodes,
980            &prov_map,
981            &[(
982                "01.ctbnode-incoming".to_string(),
983                "sha".to_string(),
984                format!(
985                    "# @provenance: csv\n# @allow-duplicate-of: l{SYSTEM_REGION_START}\n{dup_body}\n"
986                ),
987            )],
988        )?;
989        assert_eq!(planned.len(), 1);
990        assert_eq!(planned[0].node_id, next_id);
991
992        // 8. Pure value nodes cannot be retracted or superseded (Approach A), whereas relationship
993        // statements CAN be retracted (`592 615 l<stmt_id>`) and cancelled (`592 615 l<retract_stmt_id>`),
994        // so a subsequent duplicate of that reactivated statement must specify `# @allow-duplicate-of`!
995        prevalidate_and_plan_inbox_items(
996            &baseline_nodes,
997            &prov_map,
998            &[
999                (
1000                    "01_val.ctbnode-incoming".to_string(),
1001                    "s1".to_string(),
1002                    "# @provenance: csv\nu78 u79\n".to_string(),
1003                ),
1004                (
1005                    "02_retract_val.ctbnode-incoming".to_string(),
1006                    "s2".to_string(),
1007                    format!("# @provenance: csv\n592 615 l{next_id}\n"),
1008                ),
1009            ],
1010        )
1011        .unwrap_err();
1012
1013        let mut batch = Vec::new();
1014        // Item 0 (`next_id`): new unique relationship statement `588 900 571`
1015        batch.push((
1016            "01_stmt.ctbnode-incoming".to_string(),
1017            "s1".to_string(),
1018            "# @provenance: csv\n588 900 571\n".to_string(),
1019        ));
1020        // Item 1 (`next_id + 1`): retract `next_id` (`592 615 l<next_id>`)
1021        batch.push((
1022            "02_retract.ctbnode-incoming".to_string(),
1023            "s2".to_string(),
1024            format!("# @provenance: csv\n592 615 l{next_id}\n"),
1025        ));
1026        // Item 2 (`next_id + 2`): cancel the retraction (`592 615 l<next_id + 1>`) -> reactivates `next_id`!
1027        batch.push((
1028            "03_cancel_retract.ctbnode-incoming".to_string(),
1029            "s3".to_string(),
1030            format!("# @provenance: csv\n592 615 l{}\n", next_id + 1),
1031        ));
1032        // Item 3 (`next_id + 3`): `588 900 571` WITHOUT `# @allow-duplicate-of` must FAIL because `next_id` is active again!
1033        let mut bad_batch = batch.clone();
1034        bad_batch.push((
1035            "04_dup_unauth.ctbnode-incoming".to_string(),
1036            "s4".to_string(),
1037            "# @provenance: csv\n588 900 571\n".to_string(),
1038        ));
1039        prevalidate_and_plan_inbox_items(
1040            &baseline_nodes,
1041            &prov_map,
1042            &bad_batch,
1043        )
1044        .unwrap_err();
1045
1046        // With `# @allow-duplicate-of: l<next_id>`, item 3 succeeds!
1047        batch.push((
1048            "04_dup_auth.ctbnode-incoming".to_string(),
1049            "s4".to_string(),
1050            format!(
1051                "# @provenance: csv\n# @allow-duplicate-of: l{next_id}\n588 900 571\n"
1052            ),
1053        ));
1054        let ok_planned = prevalidate_and_plan_inbox_items(
1055            &baseline_nodes,
1056            &prov_map,
1057            &batch,
1058        )?;
1059        assert_eq!(ok_planned.len(), 4);
1060
1061        Ok(())
1062    }
1063
1064    #[crate::ctb_test]
1065    fn test_repository_state_and_reconstructible_highwater_cache() -> Result<()>
1066    {
1067        let (temp_dir, baseline_nodes) = setup_minimal_repo_for_inbox_tests()?;
1068        let root = temp_dir.path();
1069        let graph_dir = root.join("assets/data/graph");
1070        let marker_path = root.join(JOURNAL_INITIALIZED_REL_PATH);
1071        let lock_path = root.join(crate::ctbnbdl::LOCK_CANARY_REL_PATH);
1072        let cache_path = root.join(crate::ctbnbdl::HIGHWATER_LEDGER_REL_PATH);
1073        let marker_bytes = fs::read(&marker_path)?;
1074        let lock_bytes = fs::read(&lock_path)?;
1075        assert_eq!(fs::read_dir(root.join(".git"))?.count(), 0);
1076        assert!(cache_path.is_dir());
1077
1078        fs::remove_dir_all(&cache_path)?;
1079        fs::remove_file(&marker_path)?;
1080        assert_eq!(load_ledger_nodes_from_dir(&graph_dir)?, baseline_nodes);
1081        assert!(!marker_path.exists());
1082        assert!(!cache_path.exists());
1083        fs::write(&marker_path, &marker_bytes)?;
1084
1085        fs::write(
1086            root.join("src/formats/dcdata/data-src/nodes/inbox/cache.ctbnode-incoming"),
1087            "# @provenance: csv\nu61 u62\n",
1088        )?;
1089        assert_eq!(process_inbox_nodes(root, None, false)?.appended_count, 1);
1090        let nodes = load_ledger_nodes_from_dir(&graph_dir)?;
1091        assert_eq!(&nodes[..baseline_nodes.len()], baseline_nodes.as_slice());
1092        assert_eq!(load_ledger_nodes_from_dir(&cache_path)?, nodes);
1093        assert_eq!(fs::read(&marker_path)?, marker_bytes);
1094        assert_eq!(fs::read(&lock_path)?, lock_bytes);
1095        assert_eq!(fs::read_dir(root.join(".git"))?.count(), 0);
1096        Ok(())
1097    }
1098
1099    #[crate::ctb_test]
1100    fn test_utf8_interrupted_writes_recover_without_hiding_corruption()
1101    -> Result<()> {
1102        for character in ["\u{e9}", "\u{20ac}", "\u{1f642}"] {
1103            for partial_bytes in 1..character.len() {
1104                let (temp_dir, baseline_nodes) =
1105                    setup_minimal_repo_for_inbox_tests()?;
1106                let root = temp_dir.path();
1107                let graph_dir = root.join("assets/data/graph");
1108                let inbox_dir =
1109                    root.join("src/formats/dcdata/data-src/nodes/inbox");
1110                let journal_path = root.join(LEDGER_JOURNAL_REL_PATH);
1111                let baseline_journal = fs::read(&journal_path)?;
1112                fs::write(
1113                    inbox_dir.join("01_journal.ctbnode-incoming"),
1114                    format!(
1115                        "# @provenance: csv\n# @rationale: {character}\nu61 u62\n"
1116                    ),
1117                )?;
1118                let err = process_inbox_nodes_with_fault(
1119                    root,
1120                    None,
1121                    false,
1122                    Some(FaultInjectionPoint::TornPendingRecord {
1123                        bytes_to_keep: usize::MAX,
1124                    }),
1125                )
1126                .unwrap_err();
1127                assert!(
1128                    format!("{err:#}").contains("Simulated fault injection")
1129                );
1130                let parsed =
1131                    crate::ctbnbdl::inspect_ledger_journal(&journal_path)?;
1132                let fragment = parsed.torn_trailing_fragment.unwrap();
1133                let split_at =
1134                    std::str::from_utf8(&fragment)?.find(character).unwrap()
1135                        + partial_bytes;
1136                let torn_fragment = &fragment[..split_at];
1137                std::str::from_utf8(torn_fragment).unwrap_err();
1138                let mut torn_journal = baseline_journal.clone();
1139                torn_journal.extend_from_slice(torn_fragment);
1140                fs::write(&journal_path, &torn_journal)?;
1141                let parsed =
1142                    crate::ctbnbdl::inspect_ledger_journal(&journal_path)?;
1143                assert_eq!(parsed.valid_prefix_len, baseline_journal.len());
1144                assert_eq!(
1145                    parsed.torn_trailing_fragment.as_deref(),
1146                    Some(torn_fragment)
1147                );
1148                load_ledger_nodes_from_dir(&graph_dir).unwrap_err();
1149                recover_pending_ledger_journal(root, None, false)?;
1150                assert_eq!(fs::read(&journal_path)?, baseline_journal);
1151                assert_eq!(
1152                    process_inbox_nodes(root, None, false)?.appended_count,
1153                    1
1154                );
1155
1156                fs::write(
1157                    inbox_dir.join("02_chunk.ctbnode-incoming"),
1158                    format!(
1159                        "# @provenance: csv\n# @comment: \"{character}\"\nu63 u64\n"
1160                    ),
1161                )?;
1162                let err = process_inbox_nodes_with_fault(
1163                    root,
1164                    None,
1165                    false,
1166                    Some(FaultInjectionPoint::AfterItemAppendedAndMoved {
1167                        item_index: 0,
1168                    }),
1169                )
1170                .unwrap_err();
1171                assert!(
1172                    format!("{err:#}").contains("Simulated fault injection")
1173                );
1174                let pending =
1175                    crate::ctbnbdl::inspect_ledger_journal(&journal_path)?
1176                        .open_pending
1177                        .unwrap();
1178                let item = &pending.items[0];
1179                let chunk_path = graph_dir.join(&item.target_chunk);
1180                let complete_chunk = fs::read(&chunk_path)?;
1181                let line_start = complete_chunk.len() - item.raw_line.len() - 1;
1182                let torn_chunk = &complete_chunk[..line_start + 3];
1183
1184                let partial_utf8 = &character.as_bytes()[..partial_bytes];
1185                std::str::from_utf8(partial_utf8).unwrap_err();
1186                let mut corrupt_complete_chunk = torn_chunk.to_vec();
1187                corrupt_complete_chunk.extend_from_slice(partial_utf8);
1188                corrupt_complete_chunk.push(b'\n');
1189                fs::write(&chunk_path, &corrupt_complete_chunk)?;
1190                let err = recover_pending_ledger_journal(root, None, false)
1191                    .unwrap_err();
1192                assert!(
1193                    format!("{err:#}")
1194                        .contains("Invalid UTF-8 in complete .ctbnodes lines")
1195                );
1196                assert_eq!(fs::read(&chunk_path)?, corrupt_complete_chunk);
1197
1198                fs::write(&chunk_path, torn_chunk)?;
1199                assert!(recover_pending_ledger_journal(root, None, false)?);
1200                assert_eq!(fs::read(&chunk_path)?, complete_chunk);
1201                let nodes = load_ledger_nodes_from_dir(&graph_dir)?;
1202                assert_eq!(
1203                    &nodes[..baseline_nodes.len()],
1204                    baseline_nodes.as_slice()
1205                );
1206                assert_eq!(nodes.len(), baseline_nodes.len() + 2);
1207                assert!(
1208                    nodes.last().unwrap().comment.is_empty(),
1209                    "Newly appended .ctbnodes entries must not write explanation comments"
1210                );
1211                let parsed =
1212                    crate::ctbnbdl::inspect_ledger_journal(&journal_path)?;
1213                assert!(parsed.open_pending.is_none());
1214                assert!(parsed.torn_trailing_fragment.is_none());
1215                verify_repo_committed_node_provenance(root)?;
1216                assert_eq!(
1217                    process_inbox_nodes(root, None, false)?.appended_count,
1218                    0
1219                );
1220
1221                let mut corrupt_journal = fs::read(&journal_path)?;
1222                corrupt_journal.extend_from_slice(&[0xc3, b'\n']);
1223                fs::write(&journal_path, &corrupt_journal)?;
1224                let err = recover_pending_ledger_journal(root, None, false)
1225                    .unwrap_err();
1226                assert!(
1227                    format!("{err:#}")
1228                        .contains("Invalid UTF-8 in complete journal line")
1229                );
1230                assert_eq!(fs::read(&journal_path)?, corrupt_journal);
1231            }
1232        }
1233        Ok(())
1234    }
1235
1236    #[crate::ctb_test]
1237    fn test_inbox_and_manifest_resume_after_partial_append_and_move()
1238    -> Result<()> {
1239        let (temp_dir, baseline_nodes) = setup_minimal_repo_for_inbox_tests()?;
1240        let root = temp_dir.path();
1241        let inbox_dir = root.join("src/formats/dcdata/data-src/nodes/inbox");
1242        let alloc_dir =
1243            root.join("src/formats/dcdata/data-src/nodes/allocated");
1244        let graph_dir = root.join("assets/data/graph");
1245
1246        let f1_content =
1247            "# @provenance: csv\n# @comment: \"item1\"\nu61 u62\n".to_string();
1248        let f2_content =
1249            "# @provenance: csv\n# @comment: \"item2\"\nu63 u64\n".to_string();
1250        let f3_content =
1251            "# @provenance: csv\n# @comment: \"item3\"\nu65 u66\n".to_string();
1252
1253        fs::write(inbox_dir.join("001_a.ctbnode-incoming"), &f1_content)?;
1254        fs::write(inbox_dir.join("002_b.ctbnode-incoming"), &f2_content)?;
1255        fs::write(inbox_dir.join("003_c.ctbnode-incoming"), &f3_content)?;
1256
1257        // Build an approved manifest for the 3-item inbox batch
1258        let prov_map = NodeProvenanceMap::default();
1259        let inbox_vec = vec![
1260            (
1261                "001_a.ctbnode-incoming".to_string(),
1262                sha256_bytes_hex(f1_content.as_bytes()),
1263                f1_content.clone(),
1264            ),
1265            (
1266                "002_b.ctbnode-incoming".to_string(),
1267                sha256_bytes_hex(f2_content.as_bytes()),
1268                f2_content.clone(),
1269            ),
1270            (
1271                "003_c.ctbnode-incoming".to_string(),
1272                sha256_bytes_hex(f3_content.as_bytes()),
1273                f3_content.clone(),
1274            ),
1275        ];
1276        let planned = prevalidate_and_plan_inbox_items(
1277            &baseline_nodes,
1278            &prov_map,
1279            &inbox_vec,
1280        )?;
1281        let mut final_nodes = baseline_nodes.clone();
1282        for item in &planned {
1283            let parsed = load_ledger_nodes_from_str(
1284                &format!("{}\n", item.raw_line),
1285                &item.target_chunk,
1286            )?;
1287            final_nodes.extend(parsed);
1288        }
1289        let mut pinned_input_sha256s = BTreeMap::new();
1290        for (name, sha, _) in &inbox_vec {
1291            pinned_input_sha256s.insert(name.clone(), sha.clone());
1292        }
1293        let manifest = TransactionManifest {
1294            manifest_id: "test-inbox-3".to_string(),
1295            kind: "inbox_allocation".to_string(),
1296            baseline_last_id: baseline_nodes.last().unwrap().id,
1297            baseline_node_count: baseline_nodes.len(),
1298            baseline_ledger_sha256: compute_nodes_slice_ledger_sha256(
1299                &baseline_nodes,
1300            ),
1301            final_last_id: final_nodes.last().unwrap().id,
1302            final_node_count: final_nodes.len(),
1303            final_ledger_sha256: compute_nodes_slice_ledger_sha256(
1304                &final_nodes,
1305            ),
1306            pinned_input_sha256s,
1307            planned_items: planned.clone(),
1308        };
1309        let manifest_path = root.join("manifest.json");
1310        fs::write(
1311            &manifest_path,
1312            serde_json::to_string_pretty(&manifest).unwrap(),
1313        )?;
1314
1315        // 1. Dry-run with `--require-manifest` mutates zero files
1316        let dry_outcome =
1317            process_inbox_nodes(root, Some(&manifest_path), true)?;
1318        assert_eq!(dry_outcome.appended_count, 3);
1319        assert_eq!(dry_outcome.files_written, 0);
1320        assert!(inbox_dir.join("001_a.ctbnode-incoming").is_file());
1321
1322        // 2. Inject a crash after item 0 (`001_a.ctbnode-incoming`) is appended to `.ctbnodes`, synced to shadows,
1323        // AND moved from `nodes/inbox/001_a.ctbnode-incoming` to `nodes/allocated/<id>_001_a.ctbnode-incoming`!
1324        let err = process_inbox_nodes_with_fault(
1325            root,
1326            Some(&manifest_path),
1327            false,
1328            Some(FaultInjectionPoint::AfterItemAppendedAndMoved {
1329                item_index: 0,
1330            }),
1331        )
1332        .unwrap_err();
1333        assert!(format!("{err:#}").contains("Simulated fault injection"));
1334
1335        // Verify item 0 was moved out of `inbox/` into `allocated/`, while items 1 and 2 remain in `inbox/`
1336        assert!(!inbox_dir.join("001_a.ctbnode-incoming").exists());
1337        assert!(
1338            alloc_dir
1339                .join(planned[0].allocated_name.as_deref().unwrap())
1340                .is_file()
1341        );
1342        assert!(inbox_dir.join("002_b.ctbnode-incoming").is_file());
1343        assert!(inbox_dir.join("003_c.ctbnode-incoming").is_file());
1344
1345        // External gated reader (`load_ledger_nodes_from_dir`) MUST reject the open `BATCH_PENDING` journal!
1346        load_ledger_nodes_from_dir(&graph_dir).unwrap_err();
1347
1348        // 3. Retry the EXACT SAME `process_inbox_nodes(root, Some(&manifest_path), false)` call!
1349        // It must take the Manifest-Enforced Resume Path (accepting the partially appended ledger
1350        // and the already-moved `001_a.ctbnode-incoming` file without replanning or allocating new IDs) and finish!
1351        let resumed_outcome =
1352            process_inbox_nodes(root, Some(&manifest_path), false)?;
1353        assert!(resumed_outcome.resumed_or_already_committed);
1354        assert_eq!(resumed_outcome.total_nodes, final_nodes.len());
1355
1356        // All 3 inbox files are now in `nodes/allocated/`, `nodes/inbox/` is empty,
1357        // and external gated reader + provenance validator succeed!
1358        assert!(!inbox_dir.join("002_b.ctbnode-incoming").exists());
1359        assert!(!inbox_dir.join("003_c.ctbnode-incoming").exists());
1360        let loaded = load_ledger_nodes_from_dir(&graph_dir)?;
1361        assert_eq!(loaded.len(), final_nodes.len());
1362        let prov = verify_repo_committed_node_provenance(root)?;
1363        assert_eq!(prov.owner(planned[0].node_id), NodeProvenance::Csv);
1364        assert_eq!(prov.owner(planned[1].node_id), NodeProvenance::Csv);
1365        assert_eq!(prov.owner(planned[2].node_id), NodeProvenance::Csv);
1366
1367        // 4. Re-running the exact same `--require-manifest` command after commit is a clean idempotent no-op!
1368        let idempotent_outcome =
1369            process_inbox_nodes(root, Some(&manifest_path), false)?;
1370        assert!(idempotent_outcome.resumed_or_already_committed);
1371        assert_eq!(idempotent_outcome.total_nodes, final_nodes.len());
1372
1373        // 5. Also test torn `BATCH_COMMITTED` recovery on a subsequent manual node
1374        let next_manual_id = final_nodes.last().unwrap().id + 1;
1375        let manual_incoming = "# @provenance: manual\n# @rationale: Manual test node\n# @comment: \"manual\"\nu6d u6e\n";
1376        fs::write(
1377            inbox_dir.join("004_manual.ctbnode-incoming"),
1378            manual_incoming,
1379        )?;
1380        let err = process_inbox_nodes_with_fault(
1381            root,
1382            None,
1383            false,
1384            Some(FaultInjectionPoint::TornCommittedRecord {
1385                bytes_to_keep: 24,
1386            }),
1387        )
1388        .unwrap_err();
1389        assert!(format!("{err:#}").contains("Simulated fault injection"));
1390        load_ledger_nodes_from_dir(&graph_dir).unwrap_err();
1391
1392        // Standalone recovery finishes the torn `BATCH_COMMITTED` record!
1393        assert!(recover_pending_ledger_journal(root, None, false)?);
1394        let prov2 = verify_repo_committed_node_provenance(root)?;
1395        assert_eq!(prov2.owner(next_manual_id), NodeProvenance::Manual);
1396        assert_eq!(
1397            prov2.get(next_manual_id).unwrap().rationale.as_deref(),
1398            Some("Manual test node")
1399        );
1400
1401        // 6. Tampering with an allocated `.ctbnode-incoming` file in `nodes/allocated/` is caught by `verify_repo_committed_node_provenance`!
1402        let manual_alloc_path = alloc_dir
1403            .join(format!("{next_manual_id}_004_manual.ctbnode-incoming"));
1404        let orig_bytes = fs::read(&manual_alloc_path)?;
1405        fs::write(&manual_alloc_path, b"# tampered\n")?;
1406        verify_repo_committed_node_provenance(root).unwrap_err();
1407        fs::write(&manual_alloc_path, orig_bytes)?;
1408        verify_repo_committed_node_provenance(root).unwrap();
1409
1410        // 7. Adding an unrecorded `.ctbnode-incoming` file in `nodes/allocated/` is caught!
1411        let rogue_path = alloc_dir.join("9999999999_rogue.ctbnode-incoming");
1412        fs::write(&rogue_path, manual_incoming)?;
1413        verify_repo_committed_node_provenance(root).unwrap_err();
1414        fs::remove_file(&rogue_path)?;
1415        verify_repo_committed_node_provenance(root).unwrap();
1416
1417        // 8. Pad chunk 1 to 100 nodes + 1 node in chunk 2 (101 total nodes), closing chunk 1!
1418        // Verify that all allocated `.ctbnode-incoming` files from closed chunk 1 (nodes 1..=100)
1419        // are automatically cleaned up from `nodes/allocated/`, `ledger-journal.jsonl` is truncated/compacted
1420        // to the closed chunk boundary, only the 101st node's `.ctbnode-incoming` file in open chunk 2
1421        // remains in `nodes/allocated/`, and `next_manual_id`'s `Manual` provenance + rationale are preserved!
1422        let current_count = final_nodes.len() + 1;
1423        let needed_for_101 = 101 - current_count;
1424        for idx in 0..needed_for_101 {
1425            let name = format!("pad_close_{idx:03}.ctbnode-incoming");
1426            let body = format!(
1427                "# @provenance: csv\n# @comment: \"pad-close-{idx}\"\nu{:x} u{:x}\n",
1428                0x500 + idx,
1429                0x600 + idx
1430            );
1431            fs::write(inbox_dir.join(name), body)?;
1432        }
1433        let close_outcome = process_inbox_nodes(root, None, false)?;
1434        assert_eq!(close_outcome.total_nodes, 101);
1435        assert!(!manual_alloc_path.exists());
1436        let remaining_alloc_files: Vec<String> = fs::read_dir(&alloc_dir)?
1437            .filter_map(std::result::Result::ok)
1438            .filter(|e| {
1439                e.path().extension().and_then(|s| s.to_str())
1440                    == Some("ctbnode-incoming")
1441            })
1442            .filter_map(|e| e.file_name().into_string().ok())
1443            .collect();
1444        assert_eq!(remaining_alloc_files.len(), 1);
1445        let node_101_id = SYSTEM_REGION_START + 100;
1446        assert!(
1447            remaining_alloc_files[0].starts_with(&format!("{node_101_id}_"))
1448        );
1449        let prov3 = verify_repo_committed_node_provenance(root)?;
1450        assert_eq!(prov3.owner(next_manual_id), NodeProvenance::Manual);
1451        assert_eq!(
1452            prov3.get(next_manual_id).unwrap().rationale.as_deref(),
1453            Some("Manual test node")
1454        );
1455        assert_eq!(prov3.owner(node_101_id), NodeProvenance::Csv);
1456
1457        Ok(())
1458    }
1459
1460    #[crate::ctb_test]
1461    fn test_manual_vs_csv_cross_ownership_protection() -> Result<()> {
1462        let mut defn =
1463            sample_dc_defn(900, "Original name", "Original description");
1464        let scripts = BTreeSet::from([".Semantic".to_string()]);
1465
1466        let (mut nodes, _) = update_ledger_in_memory(
1467            Vec::new(),
1468            &[defn.clone()],
1469            &[],
1470            &scripts,
1471            None,
1472        )?;
1473
1474        // Append a manual direct statement node (`586 c900 571` is already CSV; add `588 c900 571` as Manual)
1475        let manual_stmt_id =
1476            SYSTEM_REGION_START + u128::try_from(nodes.len()).unwrap();
1477        nodes.push(LedgerNode {
1478            id: manual_stmt_id,
1479            tokens: encode_statement_tokens(
1480                DcShorthand::Short(588),
1481                DcShorthand::Short(900),
1482                DcShorthand::Short(571),
1483            ),
1484            comment: "Manual based_on".to_string(),
1485            created_ns: None,
1486        });
1487        let mut prov_map = NodeProvenanceMap::default();
1488        prov_map.insert(NodeProvenanceEntry {
1489            node_id: manual_stmt_id,
1490            provenance: NodeProvenance::Manual,
1491            rationale: Some("Manual domain link".to_string()),
1492            allocated_file: Some(format!(
1493                "{manual_stmt_id}_manual.ctbnode-incoming"
1494            )),
1495        });
1496
1497        // 1. Running CSV reconciliation preserves the `Manual` statement untouched (0 retractions!)
1498        let (nodes_after, stats) = update_ledger_in_memory_with_provenance(
1499            nodes.clone(),
1500            prov_map.clone(),
1501            &[defn.clone()],
1502            &[],
1503            &scripts,
1504            None,
1505        )?;
1506        assert_eq!(stats.nodes_appended, 0);
1507        assert_eq!(stats.nodes_retracted, 0);
1508        assert_eq!(nodes_after.len(), nodes.len());
1509
1510        // 2. Manual inbox node attempting to retract or supersede a CSV node is rejected in prevalidation
1511        let csv_node_id = nodes[0].id;
1512        prevalidate_and_plan_inbox_items(
1513                &nodes,
1514                &prov_map,
1515                &[(
1516                    "bad_manual_retract.ctbnode-incoming".to_string(),
1517                    "sha".to_string(),
1518                    format!(
1519                        "# @provenance: manual\n# @rationale: try retract csv\n592 615 l{csv_node_id}\n"
1520                    ),
1521                )],
1522            ).unwrap_err();
1523
1524        // 3. If an active Manual node references a CSV statement node that CSV reconciliation wants to retract,
1525        // CSV reconciliation aborts with a Cross-ownership conflict error!
1526        let csv_implies_id = nodes
1527            .iter()
1528            .find(|n| {
1529                n.tokens
1530                    == encode_statement_tokens(
1531                        DcShorthand::Short(587),
1532                        DcShorthand::Short(900),
1533                        DcShorthand::Short(571),
1534                    )
1535            })
1536            .unwrap()
1537            .id;
1538        let manual_ref_id =
1539            SYSTEM_REGION_START + u128::try_from(nodes.len()).unwrap();
1540        let mut nodes_with_ref = nodes.clone();
1541        nodes_with_ref.push(LedgerNode {
1542            id: manual_ref_id,
1543            tokens: encode_statement_tokens(
1544                DcShorthand::Short(588),
1545                DcShorthand::Short(900),
1546                DcShorthand::Long(csv_implies_id),
1547            ),
1548            comment: "Manual referencing CSV implies stmt".to_string(),
1549            created_ns: None,
1550        });
1551        let mut prov_with_ref = prov_map.clone();
1552        prov_with_ref.insert(NodeProvenanceEntry {
1553            node_id: manual_ref_id,
1554            provenance: NodeProvenance::Manual,
1555            rationale: Some("References CSV statement".to_string()),
1556            allocated_file: None,
1557        });
1558
1559        // Removing `implies` from `defn` causes CSV reconciliation to try to retract `csv_implies_id`, which must fail!
1560        let mut defn_no_implies = defn.clone();
1561        defn_no_implies.implies.clear();
1562        let err = update_ledger_in_memory_with_provenance(
1563            nodes_with_ref,
1564            prov_with_ref,
1565            &[defn_no_implies],
1566            &[],
1567            &scripts,
1568            None,
1569        )
1570        .unwrap_err();
1571        assert!(format!("{err:#}").contains("Cross-ownership conflict"));
1572
1573        // 4. If a single-valued property (`572` `Canonical name`) is owned by a `Manual` node and CSV
1574        // changes the name to a different value, CSV reconciliation aborts with Cross-ownership conflict!
1575        let canon_name_sh = sh(DC_CANONICAL_NAME);
1576        let name_has_a_id = nodes
1577            .iter()
1578            .find(|n| {
1579                n.tokens
1580                    == encode_statement_tokens(
1581                        DcShorthand::Short(584),
1582                        DcShorthand::Short(900),
1583                        canon_name_sh,
1584                    )
1585            })
1586            .unwrap()
1587            .id;
1588        for (owner, provenance) in [
1589            (NodeProvenance::Manual, "manual"),
1590            (NodeProvenance::Csv, "csv"),
1591        ] {
1592            let mut owned_prov = prov_map.clone();
1593            owned_prov.insert(NodeProvenanceEntry {
1594                node_id: name_has_a_id,
1595                provenance: owner,
1596                rationale: Some("Ownership test".to_string()),
1597                allocated_file: None,
1598            });
1599            for body in [
1600                format!("592 615 l{name_has_a_id}"),
1601                format!("591 l{manual_stmt_id} l{name_has_a_id}"),
1602                format!("{} l{name_has_a_id} u78", sh(DC_HAS_VALUE)),
1603                format!(
1604                    "{} l{name_has_a_id} {}",
1605                    sh(DC_HAS_A),
1606                    sh(DC_PREFERRED)
1607                ),
1608            ] {
1609                for input_provenance in ["manual", "csv"] {
1610                    let content = format!(
1611                        "# @provenance: {input_provenance}\n# @rationale: Ownership test\n{body}\n"
1612                    );
1613                    let planned = prevalidate_and_plan_inbox_items(
1614                        &nodes,
1615                        &owned_prov,
1616                        &[(
1617                            "ownership.ctbnode-incoming".to_string(),
1618                            "sha".to_string(),
1619                            content,
1620                        )],
1621                    );
1622                    if input_provenance == provenance {
1623                        assert!(planned.is_ok(), "{body}: {planned:?}");
1624                    } else {
1625                        let err = planned.unwrap_err();
1626                        assert!(
1627                            format!("{err:#}")
1628                                .contains("cross-ownership violation")
1629                        );
1630                    }
1631                }
1632            }
1633        }
1634        let mut prov_manual_name = prov_map;
1635        prov_manual_name.insert(NodeProvenanceEntry {
1636            node_id: name_has_a_id,
1637            provenance: NodeProvenance::Manual,
1638            rationale: Some("Manual canonical name".to_string()),
1639            allocated_file: None,
1640        });
1641        defn.name = "Conflicting CSV name".to_string();
1642        let err = update_ledger_in_memory_with_provenance(
1643            nodes,
1644            prov_manual_name,
1645            &[defn],
1646            &[],
1647            &scripts,
1648            None,
1649        )
1650        .unwrap_err();
1651        assert!(format!("{err:#}").contains("Cross-ownership conflict"));
1652
1653        Ok(())
1654    }
1655
1656    #[crate::ctb_test]
1657    fn test_100th_line_torn_write_and_watcher_sealing_interaction() -> Result<()>
1658    {
1659        let (temp_dir, baseline_nodes) = setup_minimal_repo_for_inbox_tests()?;
1660        let root = temp_dir.path();
1661        let inbox_dir = root.join("src/formats/dcdata/data-src/nodes/inbox");
1662        let graph_dir = root.join("assets/data/graph");
1663
1664        // Pad chunk 1 (`85899_34592.ctbnodes`) to 99 lines so the next inbox item is the 100th line!
1665        assert!(baseline_nodes.len() < 99);
1666        let needed_for_99 = 99 - baseline_nodes.len();
1667        for idx in 0..needed_for_99 {
1668            let name = format!("pad_{idx:03}.ctbnode-incoming");
1669            let body = format!(
1670                "# @provenance: csv\n# @comment: \"pad-{idx}\"\nu{:x} u{:x}\n",
1671                0x100 + idx,
1672                0x200 + idx
1673            );
1674            fs::write(inbox_dir.join(name), body)?;
1675        }
1676        let outcome = process_inbox_nodes(root, None, false)?;
1677        assert_eq!(outcome.total_nodes, 99);
1678
1679        // Now stage the 100th node (`line_100.ctbnode-incoming`) and inject a torn chunk write on item 0!
1680        fs::write(
1681            inbox_dir.join("line_100.ctbnode-incoming"),
1682            "# @provenance: csv\n# @comment: \"node-100\"\nu300 u301\n",
1683        )?;
1684        let err = process_inbox_nodes_with_fault(
1685            root,
1686            None,
1687            false,
1688            Some(FaultInjectionPoint::TornChunkLine {
1689                item_index: 0,
1690                bytes_to_keep: 10,
1691            }),
1692        )
1693        .unwrap_err();
1694        assert!(format!("{err:#}").contains("Simulated fault injection"));
1695
1696        // Verify the chunk file has 99 complete `\n`-terminated lines + 1 unterminated trailing fragment
1697        let chunk_path =
1698            graph_dir.join(format_chunk_filename(SYSTEM_REGION_START));
1699        let raw_chunk = fs::read(&chunk_path)?;
1700        assert_ne!(raw_chunk.last().copied(), Some(b'\n'));
1701        let newline_count = raw_chunk.iter().filter(|&&b| b == b'\n').count();
1702        assert_eq!(newline_count, 99);
1703
1704        // Because the 100th line is NOT `\n`-terminated and `BATCH_PENDING` is open, the chunk is NOT sealed
1705        // and `recover_pending_ledger_journal` can repair the torn 100th line in place and commit!
1706        assert!(recover_pending_ledger_journal(root, None, false)?);
1707        let repaired_chunk = fs::read(&chunk_path)?;
1708        assert_eq!(repaired_chunk.last().copied(), Some(b'\n'));
1709        let repaired_newlines =
1710            repaired_chunk.iter().filter(|&&b| b == b'\n').count();
1711        assert_eq!(repaired_newlines, 100);
1712
1713        let loaded = load_ledger_nodes_from_dir(&graph_dir)?;
1714        assert_eq!(loaded.len(), 100);
1715        Ok(())
1716    }
1717
1718    #[crate::ctb_test]
1719    fn test_in_graph_provenance_for_each_and_manual_protection() -> Result<()> {
1720        let mut defn = sample_dc_defn(900, "Test Dc", "Desc");
1721        let scripts = BTreeSet::from([".Semantic".to_string()]);
1722        let (mut nodes, _) = update_ledger_in_memory(
1723            Vec::new(),
1724            &[defn.clone()],
1725            &[],
1726            &scripts,
1727            None,
1728        )?;
1729
1730        let idx1 = crate::seed_graph::SeedGraphIndex::from_nodes(nodes.clone());
1731        assert!(idx1.has_in_graph_provenance());
1732        for node in &nodes[..nodes.len() - 2] {
1733            assert_eq!(
1734                idx1.node_data_source(node.id),
1735                Some(sh(crate::dc::DC_COLLECTIVE_TOOLBOX_DC_CSV_SEED_DATABASE))
1736            );
1737        }
1738
1739        // Append a manual alias via in-graph `Dc 635` (`Collective Toolbox seed graph data source`) -> `Dc 637` (`Manual entry`)
1740        // without using any external `NodeProvenanceMap`.
1741        let str_id = SYSTEM_REGION_START + u128::try_from(nodes.len()).unwrap();
1742        nodes.push(LedgerNode {
1743            id: str_id,
1744            tokens: encode_string_value_tokens("in-graph-manual-alias"),
1745            comment: "\"in-graph-manual-alias\"".to_string(),
1746            created_ns: None,
1747        });
1748        let has_a_id = str_id + 1;
1749        nodes.push(LedgerNode {
1750            id: has_a_id,
1751            tokens: encode_statement_tokens(
1752                sh(DC_HAS_A),
1753                DcShorthand::Short(900),
1754                sh(crate::dc::DC_INFORMAL_ALIAS),
1755            ),
1756            comment: "Manual Has a".to_string(),
1757            created_ns: None,
1758        });
1759        let has_val_id = str_id + 2;
1760        nodes.push(LedgerNode {
1761            id: has_val_id,
1762            tokens: encode_statement_tokens(
1763                sh(DC_HAS_VALUE),
1764                DcShorthand::Long(has_a_id),
1765                DcShorthand::Long(str_id),
1766            ),
1767            comment: "Manual Has value".to_string(),
1768            created_ns: None,
1769        });
1770        let prov_for_each_id = str_id + 3;
1771        nodes.push(LedgerNode {
1772            id: prov_for_each_id,
1773            tokens: crate::graph_ledger::encode_for_each_statement_tokens(
1774                sh(DC_HAS_A),
1775                sh(crate::dc::DC_THIS_ELEMENT),
1776                sh(crate::dc::DC_COLLECTIVE_TOOLBOX_SEED_GRAPH_DATA_SOURCE),
1777                sh(crate::dc::DC_TYPE_ATOM_DC),
1778                &[
1779                    DcShorthand::Long(str_id),
1780                    DcShorthand::Long(has_a_id),
1781                    DcShorthand::Long(has_val_id),
1782                ],
1783            ),
1784            comment: "Manual For each provenance".to_string(),
1785            created_ns: None,
1786        });
1787        let prov_has_val_id = str_id + 4;
1788        nodes.push(LedgerNode {
1789            id: prov_has_val_id,
1790            tokens: encode_statement_tokens(
1791                sh(DC_HAS_VALUE),
1792                DcShorthand::Long(prov_for_each_id),
1793                sh(crate::dc::DC_MANUAL_ENTRY),
1794            ),
1795            comment: "Manual provenance value".to_string(),
1796            created_ns: None,
1797        });
1798
1799        // Running CSV reconciliation with an empty `NodeProvenanceMap::default()` must preserve the manual alias
1800        // while retracting the removed CSV alias (`csv-alias`).
1801        defn.aliases.clear();
1802        let (nodes_after, stats_after) =
1803            update_ledger_in_memory(nodes, &[defn], &[], &scripts, None)?;
1804        assert_eq!(stats_after.nodes_retracted, 2);
1805        let idx2 = crate::seed_graph::SeedGraphIndex::from_nodes(nodes_after);
1806        assert_eq!(
1807            idx2.get_multi_properties(
1808                DcShorthand::Short(900),
1809                sh(crate::dc::DC_INFORMAL_ALIAS)
1810            )
1811            .len(),
1812            1
1813        );
1814        assert_eq!(
1815            idx2.node_data_source(has_a_id),
1816            Some(sh(crate::dc::DC_MANUAL_ENTRY))
1817        );
1818        Ok(())
1819    }
1820}