ctb_formats_dcdata/build_support/
ctbnbdl.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//! `.ctbnodes` (`CtbNodes`, `f639`) and `.ctbnbdl` (`CtbNodeBundle`, `f640`)
21//! node ledger parsing and binary compilation.
22
23#[path = "ctbnbdl/journal.rs"]
24pub mod journal;
25pub use journal::*;
26
27#[allow(
28    unused_imports,
29    clippy::wildcard_imports,
30    reason = "Standard workspace module prelude"
31)]
32use crate::utilities::*;
33
34use std::path::{Path, PathBuf};
35
36use crate::dctf::{decode_dctf_buf, decode_utf_8e_128_buf, encode_dctf_buf};
37use crate::global_graph_layout::{SYSTEM_REGION_END, SYSTEM_REGION_START};
38use crate::shorthand::DcShorthand;
39
40/// Maximum number of node declarations stored in a single `.ctbnodes` chunk file.
41pub const MAX_NODES_PER_CHUNK: usize = 100;
42
43/// Maximum number of `.ctbnodes` files stored directly in the top-level graph directory
44/// before sharding into 1000-file prefix subdirectories.
45pub const ROOT_CHUNKS_BEFORE_SUBFOLDER: usize = 999;
46
47/// Number of `.ctbnodes` files grouped into each prefix subdirectory starting at the 1000th file.
48pub const CHUNKS_PER_SUBFOLDER: usize = 1000;
49
50/// Relative repository path to the tracked unsplit `.ctbnbdl` bundle directory.
51pub const GRAPH_BUNDLES_REL_PATH: &str = "assets/data/graph-bundles";
52
53/// Subdirectory under `assets/data/graph-bundles/` holding gitignored live (active) `.ctbnbdl` bundles.
54pub const GRAPH_BUNDLES_SPLIT_LIVE_SUBDIR: &str = "split/live";
55
56/// Subdirectory under `assets/data/graph-bundles/` holding gitignored historical (inactive) `.ctbnbdl` bundles.
57pub const GRAPH_BUNDLES_SPLIT_HISTORY_SUBDIR: &str = "split/history";
58
59/// Maximum number of node definitions grouped into a single `.ctbnbdl` binary bundle file.
60pub const MAX_NODES_PER_BUNDLE: usize = 1_000_000;
61
62/// Maximum size in bytes of a single `.ctbnbdl` binary bundle file (50 MB).
63pub const MAX_BYTES_PER_BUNDLE: usize = 50_000_000;
64
65/// Leading 8-byte magic header for `.ctbnbdl` (`CtbNodeBundle2`, `f645`) files.
66pub const CTBNBDL_MAGIC: [u8; 8] = *b"CTBNBDL\x02";
67
68/// Legacy 8-byte magic header for v1 `.ctbnbdl` (`CtbNodeBundle1`, `f644`) files.
69pub const CTBNBDL_MAGIC_V1: [u8; 8] = *b"CTBNBDL\x01";
70
71/// Standard 21-byte `DcMixed2` (`f643`) header (`DcMM\0` + UUID `b0327a84-b745-492c-b39d-77c2827e3a6f`).
72pub const DCMM_HEADER: [u8; 21] = [
73    b'D', b'c', b'M', b'M', 0, 0xb0, 0x32, 0x7a, 0x84, 0xb7, 0x45, 0x49, 0x2c,
74    0xb3, 0x9d, 0x77, 0xc2, 0x82, 0x7e, 0x3a, 0x6f,
75];
76
77/// Legacy 21-byte `DcMixed1` (`f642`) header (`DcMM\0` + UUID `d5ab819e-9b8e-4d61-adbc-933e8851e79a`).
78pub const DCMM_HEADER_V1: [u8; 21] = [
79    b'D', b'c', b'M', b'M', 0, 0xd5, 0xab, 0x81, 0x9e, 0x9b, 0x8e, 0x4d, 0x61,
80    0xad, 0xbc, 0x93, 0x3e, 0x88, 0x51, 0xe7, 0x9a,
81];
82
83const DC_203_DCTF_BYTES: [u8; 4] = [0xF4, 0x90, 0x83, 0x8B];
84const DC_203_UTF8E128_BYTES: [u8; 5] = [0xF8, 0x88, 0xA0, 0x83, 0x8B];
85const DCMM_TYPE_BINARY: u8 = 0;
86const DCMM_TYPE_LEGACY_TEXT: u8 = 1;
87const DCMM_TYPE_BINARY_METADATA: u8 = 2;
88const DCMM_TYPE_BINARY_SHA256: u8 = 3;
89const DCMM_TYPE_LEGACY_SHA256: u8 = 4;
90const BASE64_DIGIT_START: u32 = 127;
91const BASE64_DIGIT_END: u32 = 190;
92const BASE64_PADDING_DC: u32 = 195;
93
94/// `Dc 641` (`Global graph system block most recent node ID at time of document creation`).
95pub const DC_SYSTEM_BLOCK_MOST_RECENT_NODE_ID: DcShorthand =
96    DcShorthand::Short(641);
97
98/// Structured comment prefix recording a node's creation timestamp in signed nanoseconds
99/// since the Unix epoch inside `.ctbnodes` lines (`# @created_ns:<i128> ...`).
100pub const CREATED_NS_COMMENT_PREFIX: &str = "@created_ns:";
101
102/// Framing and relationship Document Characters used when encoding, decoding, and partitioning
103/// `.ctbnbdl` node definitions.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct CtbnbdlFramingDcs {
106    /// `BeginGraphNodeDefinition` (`Dc 617`).
107    pub begin_node: DcShorthand,
108    /// `EndGraphNodeDefinition` (`Dc 618`).
109    pub end_node: DcShorthand,
110    /// `BeginChecksummedSection` (`Dc 543`).
111    pub begin_checksummed_section: DcShorthand,
112    /// `EndChecksummedSection` (`Dc 544`).
113    pub end_checksummed_section: DcShorthand,
114    /// `SectionDigest` (`Dc 545`).
115    pub section_digest: DcShorthand,
116    /// `BeginTimeMoment` (`Dc 390`).
117    pub begin_time_moment: DcShorthand,
118    /// `EndTimeMoment` (`Dc 391`).
119    pub end_time_moment: DcShorthand,
120    /// `SectionTimestampNodeCreationTime` (`Dc 1941`), or `None` on historical prefixes prior to its introduction.
121    pub section_node_creation_time: Option<DcShorthand>,
122    /// `NsSinceEpoch` (`FormatId::NsSinceEpoch`, `f487`).
123    pub ns_since_epoch_format: DcShorthand,
124    /// `Sha256` (`FormatId::Sha256`, `f245`).
125    pub sha256_format: DcShorthand,
126    /// `Escape` (`Dc 255`, `Ignore following Dc`).
127    pub escape: DcShorthand,
128    /// `EvaluateValueAsAtom` (`Dc 616`).
129    pub evaluate_as_atom: DcShorthand,
130    /// `HasA` (`Dc 584`).
131    pub has_a: DcShorthand,
132    /// `HasValue` (`Dc 610`).
133    pub has_value: DcShorthand,
134    /// `Preferred` (`Dc 570`).
135    pub preferred: DcShorthand,
136    /// `Supersedes` (`Dc 591`).
137    pub supersedes: DcShorthand,
138    /// `Retracts` (`Dc 592`).
139    pub retracts: DcShorthand,
140    /// `EnclosingDocument` (`Dc 615`).
141    pub enclosing_document: DcShorthand,
142    /// `IsInstanceOf` (`Dc 586`).
143    pub is_instance_of: DcShorthand,
144    /// `IsSubtypeOf` (`Dc 587`).
145    pub is_subtype_of: DcShorthand,
146    /// `IsBasedOn` (`Dc 588`).
147    pub is_based_on: DcShorthand,
148    /// `IsDeprecated` (`Dc 589`).
149    pub is_deprecated: DcShorthand,
150    /// `IsClosingDelimiterFor` (`Dc 590`).
151    pub is_closing_delimiter_for: DcShorthand,
152    /// `IsAssociatedWith` (`Dc 598`).
153    pub is_associated_with: DcShorthand,
154}
155
156/// Sanitizes a `.ctbnodes` comment string by escaping carriage returns and newlines.
157#[must_use]
158pub fn sanitize_comment(raw: &str) -> String {
159    raw.replace('\r', "\\r").replace('\n', "\\n")
160}
161
162/// Returns the current system wall-clock timestamp in signed nanoseconds since the Unix epoch.
163#[must_use]
164pub fn current_unix_timestamp_ns() -> i128 {
165    match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
166        Ok(dur) => i128::try_from(dur.as_nanos()).unwrap_or(i128::MAX),
167        Err(err) => {
168            let before =
169                i128::try_from(err.duration().as_nanos()).unwrap_or(i128::MAX);
170            // Reason for fallback: saturating to i128::MIN if pre-epoch duration exceeds i128::MAX avoids overflow.
171            before.checked_neg().unwrap_or(i128::MIN)
172        }
173    }
174}
175
176/// Single node entry in the System-block `.ctbnodes` ledger.
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct LedgerNode {
179    /// Global node ID in `SYSTEM_REGION_START..=SYSTEM_REGION_END`.
180    pub id: u128,
181    /// Ordered token sequence defining this node.
182    pub tokens: Vec<DcShorthand>,
183    /// Human-readable comment rendered after `# `.
184    pub comment: String,
185    /// Optional creation timestamp in signed nanoseconds since the Unix epoch,
186    /// persisted in `.ctbnodes` via `# @created_ns:<i128>` and in `.ctbnbdl`
187    /// checksummed sections via `SectionTimestampNodeCreationTime`.
188    pub created_ns: Option<i128>,
189}
190
191impl LedgerNode {
192    /// Formats this node as a single `.ctbnodes` line (`l<id>: <tokens> # [@created_ns:<ts>] <comment>`).
193    #[must_use]
194    pub fn format_line(&self) -> String {
195        let token_strs: Vec<String> =
196            self.tokens.iter().map(ToString::to_string).collect();
197        let body = token_strs.join(" ");
198        let clean_comment = sanitize_comment(&self.comment);
199        let full_comment = match (self.created_ns, clean_comment.is_empty()) {
200            (Some(ts), true) => format!("{CREATED_NS_COMMENT_PREFIX}{ts}"),
201            (Some(ts), false) => {
202                format!("{CREATED_NS_COMMENT_PREFIX}{ts} {clean_comment}")
203            }
204            (None, _) => clean_comment,
205        };
206        match (body.is_empty(), full_comment.is_empty()) {
207            (true, true) => format!("l{}: #", self.id),
208            (true, false) => format!("l{}: # {full_comment}", self.id),
209            (false, true) => format!("l{}: {body}", self.id),
210            (false, false) => format!("l{}: {body} # {full_comment}", self.id),
211        }
212    }
213
214    /// Parses a single non-empty `.ctbnodes` line.
215    pub fn parse_line(
216        line: &str,
217        file_label: &str,
218        line_no: usize,
219    ) -> Result<Self> {
220        let trimmed = line.trim();
221        ensure!(
222            !trimmed.is_empty(),
223            "{file_label}:{line_no}: unexpected blank line in .ctbnodes file"
224        );
225        let (code_part, created_ns, comment) = match trimmed.split_once('#') {
226            Some((before, after)) => {
227                let raw_after = after.trim();
228                if let Some(rest) =
229                    raw_after.strip_prefix(CREATED_NS_COMMENT_PREFIX)
230                {
231                    let (ts_str, rem_comment) =
232                        match rest.find(char::is_whitespace) {
233                            Some(pos) => {
234                                // Reason for fallback: pos comes from rest.find(...) so ..pos and pos.. are valid UTF-8 boundaries.
235                                let head = rest.get(..pos).unwrap_or_default();
236                                // Reason for fallback: pos comes from rest.find(...) so pos.. is a valid UTF-8 boundary.
237                                let tail =
238                                    rest.get(pos..).unwrap_or_default().trim();
239                                (head, tail)
240                            }
241                            None => (rest, ""),
242                        };
243                    let ts = ts_str.parse::<i128>().with_context(|| {
244                        format!(
245                            "{file_label}:{line_no}: invalid @created_ns timestamp '{ts_str}'"
246                        )
247                    })?;
248                    (before.trim(), Some(ts), rem_comment.to_string())
249                } else {
250                    (before.trim(), None, raw_after.to_string())
251                }
252            }
253            None => (trimmed, None, String::new()),
254        };
255        let Some((lhs, rhs)) = code_part.split_once(':') else {
256            bail!(
257                "{file_label}:{line_no}: missing ':' separator in node declaration '{trimmed}'"
258            );
259        };
260        let lhs_shorthand =
261            DcShorthand::parse(lhs.trim()).with_context(|| {
262                format!(
263                    "{file_label}:{line_no}: invalid node ID shorthand '{lhs}'"
264                )
265            })?;
266        let DcShorthand::Long(id) = lhs_shorthand else {
267            bail!(
268                "{file_label}:{line_no}: System-block node ID must use 'l<digits>' syntax, found '{lhs}'"
269            );
270        };
271        ensure!(
272            (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&id),
273            "{file_label}:{line_no}: node ID l{id} is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
274        );
275        let mut tokens = Vec::new();
276        for raw_tok in rhs.split_whitespace() {
277            let tok = DcShorthand::parse(raw_tok).with_context(|| {
278                format!(
279                    "{file_label}:{line_no}: invalid token shorthand '{raw_tok}'"
280                )
281            })?;
282            tokens.push(tok);
283        }
284        Ok(Self {
285            id,
286            tokens,
287            comment,
288            created_ns,
289        })
290    }
291}
292
293fn format_grouped_id(first_id: u128) -> String {
294    let digits = first_id.to_string();
295    let len = digits.len();
296    let mut grouped = String::with_capacity(
297        len.saturating_add(len.checked_div(5).unwrap_or(0)),
298    );
299    for (idx, ch) in digits.chars().enumerate() {
300        let remaining = len.saturating_sub(idx);
301        if idx > 0 && remaining.is_multiple_of(5) {
302            grouped.push('_');
303        }
304        grouped.push(ch);
305    }
306    grouped
307}
308
309/// Formats a global node ID into a `.ctbnodes` chunk filename with `_` grouping
310/// every 5 digits from the right (e.g., `8589934592` -> `"85899_34592.ctbnodes"`).
311#[must_use]
312pub fn format_chunk_filename(first_id: u128) -> String {
313    format!("{}.ctbnodes", format_grouped_id(first_id))
314}
315
316/// Formats a global node ID into a `.ctbnbdl` chunk bundle filename with `_` grouping
317/// every 5 digits from the right (e.g., `8589934592` -> `"85899_34592.ctbnbdl"`).
318#[must_use]
319pub fn format_chunk_bundle_filename(first_id: u128) -> String {
320    format!("{}.ctbnbdl", format_grouped_id(first_id))
321}
322
323fn parse_grouped_stem_id(stem: &str) -> Option<u128> {
324    if stem.is_empty() || stem.starts_with('_') || stem.ends_with('_') {
325        return None;
326    }
327    let mut clean = String::with_capacity(stem.len());
328    for ch in stem.chars() {
329        if ch.is_ascii_digit() {
330            clean.push(ch);
331        } else if ch == '_' {
332            // separator
333        } else {
334            return None;
335        }
336    }
337    if clean.is_empty() {
338        return None;
339    }
340    clean.parse::<u128>().ok()
341}
342
343/// Parses a `.ctbnodes` chunk filename (e.g., `"85899_34592.ctbnodes"`) into its starting node ID.
344#[must_use]
345pub fn parse_chunk_filename_start_id(filename: &str) -> Option<u128> {
346    let stem = filename.strip_suffix(".ctbnodes")?;
347    parse_grouped_stem_id(stem)
348}
349
350/// Parses a `.ctbnbdl` chunk filename (e.g., `"85899_34592.ctbnbdl"`) into its starting node ID.
351#[must_use]
352pub fn parse_chunk_bundle_filename_start_id(filename: &str) -> Option<u128> {
353    let stem = filename.strip_suffix(".ctbnbdl")?;
354    parse_grouped_stem_id(stem)
355}
356
357/// Resolves the `.ctbnbdl` bundle directory associated with `graph_dir`:
358/// - `<parent>/graph-bundles` when `graph_dir` ends with `"graph"` (e.g. `assets/data/graph` -> `assets/data/graph-bundles`),
359/// - `<graph_dir>/graph-bundles` otherwise.
360#[must_use]
361pub fn bundles_dir_for_graph_dir(graph_dir: &Path) -> PathBuf {
362    if graph_dir.file_name().and_then(|s| s.to_str()) == Some("graph") {
363        graph_dir.with_file_name("graph-bundles")
364    } else {
365        graph_dir.join("graph-bundles")
366    }
367}
368
369/// Formats a `.ctbnodes` chunk's relative path inside `graph_dir`:
370/// - The first 999 `.ctbnodes` files (`chunk_idx` `0..999`, i.e. `85899_34592.ctbnodes` through
371///   `85900_34392.ctbnodes`) live directly in `graph_dir`.
372/// - Starting at the 1000th `.ctbnodes` file (`chunk_idx == 999`, `85900_34492.ctbnodes`), each
373///   block of 1000 `.ctbnodes` files lives in a subdirectory named after the grouped prefix of
374///   that block's starting chunk ID (`"85900/85900_34492.ctbnodes"`, ..., `"85901/85901_34492.ctbnodes"`).
375#[must_use]
376pub fn format_chunk_rel_path(first_id: u128) -> String {
377    let filename = format_chunk_filename(first_id);
378    let offset = first_id.saturating_sub(SYSTEM_REGION_START);
379    // Reason for fallback: MAX_NODES_PER_CHUNK is the compile-time constant 100.
380    let per_chunk = u128::try_from(MAX_NODES_PER_CHUNK).unwrap_or(100);
381    // Reason for fallback: per_chunk is non-zero (100).
382    let chunk_idx = offset.checked_div(per_chunk).unwrap_or(0);
383    // Reason for fallback: ROOT_CHUNKS_BEFORE_SUBFOLDER is the compile-time constant 999.
384    let root_limit = u128::try_from(ROOT_CHUNKS_BEFORE_SUBFOLDER).unwrap_or(999);
385    if chunk_idx < root_limit {
386        return filename;
387    }
388    // Reason for fallback: CHUNKS_PER_SUBFOLDER is the compile-time constant 1000.
389    let per_sub = u128::try_from(CHUNKS_PER_SUBFOLDER).unwrap_or(1000);
390    // Reason for fallback: per_sub is non-zero (1000).
391    let bucket_idx = chunk_idx
392        .saturating_sub(root_limit)
393        .checked_div(per_sub)
394        .unwrap_or(0);
395    let bucket_start_chunk =
396        root_limit.saturating_add(bucket_idx.saturating_mul(per_sub));
397    let bucket_first_id = SYSTEM_REGION_START
398        .saturating_add(bucket_start_chunk.saturating_mul(per_chunk));
399    let bucket_grouped = format_grouped_id(bucket_first_id);
400    // Reason for fallback: System-region IDs are >= 10 digits so format_grouped_id always contains '_'.
401    let prefix = bucket_grouped
402        .rsplit_once('_')
403        .map_or(bucket_grouped.as_str(), |(p, _)| p);
404    format!("{prefix}/{filename}")
405}
406
407/// Parses a `.ctbnodes` relative path (`"85899_34592.ctbnodes"` or `"85900/85900_34492.ctbnodes"`)
408/// into its starting node ID, validating any parent directory component.
409#[must_use]
410pub fn parse_chunk_rel_path_start_id(rel_path: &str) -> Option<u128> {
411    match rel_path.split_once('/') {
412        None => parse_chunk_filename_start_id(rel_path),
413        Some((subdir, fname)) => {
414            if fname.contains('/') || parse_grouped_stem_id(subdir).is_none() {
415                return None;
416            }
417            parse_chunk_filename_start_id(fname)
418        }
419    }
420}
421
422/// Returns `path` formatted relative to `graph_dir` using forward-slash separators.
423#[must_use]
424pub fn chunk_rel_path_from_graph_dir(
425    graph_dir: &Path,
426    path: &Path,
427) -> Option<String> {
428    let rel = path.strip_prefix(graph_dir).ok()?;
429    let mut parts: Vec<&str> = Vec::new();
430    for comp in rel.components() {
431        parts.push(comp.as_os_str().to_str()?);
432    }
433    if parts.is_empty() {
434        None
435    } else {
436        Some(parts.join("/"))
437    }
438}
439
440/// Returns `true` if `dir_name` is a valid numeric-prefix `.ctbnodes` shard subdirectory name
441/// (e.g. `"85900"`, `"85901"`, `"1_00000"`).
442#[must_use]
443pub fn is_chunk_prefix_subdir_name(dir_name: &str) -> bool {
444    parse_grouped_stem_id(dir_name).is_some()
445}
446
447/// Returns the sorted list of `.ctbnodes` chunk files in `graph_dir` (including 1000-file
448/// numeric-prefix subdirectories).
449pub fn list_chunk_files(graph_dir: &Path) -> Result<Vec<PathBuf>> {
450    if !graph_dir.exists() {
451        return Ok(Vec::new());
452    }
453    let mut keyed_files: Vec<(u128, PathBuf)> = Vec::new();
454    for entry in std::fs::read_dir(graph_dir).with_context(|| {
455        format!("Failed to read graph directory {}", graph_dir.display())
456    })? {
457        let entry = entry?;
458        let file_type = entry.file_type()?;
459        let path = entry.path();
460        let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
461            continue;
462        };
463        if file_type.is_file() {
464            if let Some(start_id) = parse_chunk_filename_start_id(name) {
465                if (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&start_id)
466                {
467                    keyed_files.push((start_id, path));
468                }
469            }
470        } else if file_type.is_dir() && is_chunk_prefix_subdir_name(name) {
471            for sub_entry in std::fs::read_dir(&path).with_context(|| {
472                format!(
473                    "Failed to read graph shard subdirectory {}",
474                    path.display()
475                )
476            })? {
477                let sub_entry = sub_entry?;
478                if !sub_entry.file_type()?.is_file() {
479                    continue;
480                }
481                let sub_path = sub_entry.path();
482                let Some(sub_name) =
483                    sub_path.file_name().and_then(|s| s.to_str())
484                else {
485                    continue;
486                };
487                if let Some(start_id) = parse_chunk_filename_start_id(sub_name)
488                {
489                    if (SYSTEM_REGION_START..=SYSTEM_REGION_END)
490                        .contains(&start_id)
491                    {
492                        keyed_files.push((start_id, sub_path));
493                    }
494                }
495            }
496        }
497    }
498    keyed_files.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
499    Ok(keyed_files.into_iter().map(|(_, p)| p).collect())
500}
501
502/// Loads all `LedgerNode` entries from a `.ctbnodes` text string.
503pub fn load_ledger_nodes_from_str(
504    content: &str,
505    file_label: &str,
506) -> Result<Vec<LedgerNode>> {
507    let mut nodes = Vec::new();
508    for (idx, line) in content.lines().enumerate() {
509        if line.trim().is_empty() {
510            continue;
511        }
512        let line_no = idx.saturating_add(1);
513        let node = LedgerNode::parse_line(line, file_label, line_no)?;
514        nodes.push(node);
515    }
516    Ok(nodes)
517}
518
519/// Loads all `LedgerNode` entries from a single `.ctbnodes` file.
520pub fn load_ledger_nodes_from_file(path: &Path) -> Result<Vec<LedgerNode>> {
521    // Reason for fallback: paths without a terminal filename component use the generic ".ctbnodes" diagnostic label
522    let file_label = path
523        .file_name()
524        .and_then(|s| s.to_str())
525        .unwrap_or(".ctbnodes");
526    let content = std::fs::read_to_string(path).with_context(|| {
527        format!("Failed to read .ctbnodes file {}", path.display())
528    })?;
529    load_ledger_nodes_from_str(&content, file_label)
530}
531
532fn load_ledger_nodes_from_dir_raw(graph_dir: &Path) -> Result<Vec<LedgerNode>> {
533    let files = list_chunk_files(graph_dir)?;
534    let mut nodes = Vec::new();
535    for (chunk_idx, path) in files.iter().enumerate() {
536        // Reason for fallback: chunk_idx * 100 easily fits in u128 on any 64-bit platform
537        let chunk_start_id = SYSTEM_REGION_START.saturating_add(
538            u128::try_from(chunk_idx.saturating_mul(MAX_NODES_PER_CHUNK))
539                .unwrap_or(0),
540        );
541        let expected_rel = format_chunk_rel_path(chunk_start_id);
542        // Reason for fallback: paths outside graph_dir or non-UTF-8 fail the equality check against expected_rel immediately below
543        let actual_rel = chunk_rel_path_from_graph_dir(graph_dir, path)
544            .unwrap_or_else(|| path.display().to_string());
545        ensure!(
546            actual_rel == expected_rel,
547            "Expected sequential chunk file '{expected_rel}', found '{actual_rel}'"
548        );
549        let file_nodes = load_ledger_nodes_from_file(path)?;
550        let chunk_count = file_nodes.len();
551        for (line_idx, node) in file_nodes.into_iter().enumerate() {
552            let line_no = line_idx.saturating_add(1);
553            // Reason for fallback: nodes.len() fits in u128 on any platform
554            let expected_id = SYSTEM_REGION_START
555                .saturating_add(u128::try_from(nodes.len()).unwrap_or(0));
556            ensure!(
557                node.id == expected_id,
558                "{actual_rel}:{line_no}: expected sequential node ID l{expected_id}, found l{}",
559                node.id
560            );
561            nodes.push(node);
562        }
563        ensure!(
564            chunk_count <= MAX_NODES_PER_CHUNK,
565            "{actual_rel}: chunk contains {chunk_count} nodes, exceeding maximum {MAX_NODES_PER_CHUNK}"
566        );
567        if chunk_idx.saturating_add(1) < files.len() {
568            ensure!(
569                chunk_count == MAX_NODES_PER_CHUNK,
570                "{actual_rel}: non-final chunk has {chunk_count} nodes, expected {MAX_NODES_PER_CHUNK}. \
571                 CRITICAL: This indicates {actual_rel} was truncated or reverted (e.g. via 'git checkout') \
572                 after later chunk files were created. NEVER delete or revert .ctbnodes files!"
573            );
574        }
575    }
576    Ok(nodes)
577}
578
579/// Verifies that `current_nodes` is a strict append-only extension of `baseline_nodes`
580/// (every node in `baseline_nodes` must appear at the same index in `current_nodes`
581/// with the exact same `id` and `tokens`).
582pub fn verify_nodes_append_only_against_baseline(
583    baseline_label: &str,
584    baseline_nodes: &[LedgerNode],
585    current_nodes: &[LedgerNode],
586) -> Result<()> {
587    // Reason for fallback: empty baseline has no last node ID
588    let last_base_id = baseline_nodes.last().map_or(0, |n| n.id);
589    ensure!(
590        current_nodes.len() >= baseline_nodes.len(),
591        "CRITICAL: Append-only graph ledger rollback detected against {baseline_label}! \
592         Working tree has {} nodes, but {baseline_label} has {} nodes (up to l{last_base_id}). \
593         Graph files in assets/data/graph/ are strictly append-only and must NEVER be reverted or deleted.",
594        current_nodes.len(),
595        baseline_nodes.len()
596    );
597    for (idx, base_node) in baseline_nodes.iter().enumerate() {
598        let Some(cur_node) = current_nodes.get(idx) else {
599            bail!(
600                "CRITICAL: Missing node at index {idx} (expected l{}) when verifying against {baseline_label}",
601                base_node.id
602            );
603        };
604        ensure!(
605            cur_node.id == base_node.id
606                && cur_node.tokens == base_node.tokens
607                && cur_node.created_ns == base_node.created_ns,
608            "CRITICAL: Append-only graph ledger mutation detected at node l{} against {baseline_label}! \
609             Existing node IDs, creation timestamps, and Dc statements are immutable (expected created_ns={:?} tokens {:?}, found created_ns={:?} tokens {:?}).",
610            base_node.id,
611            base_node.created_ns,
612            base_node.tokens,
613            cur_node.created_ns,
614            cur_node.tokens
615        );
616    }
617    Ok(())
618}
619
620fn find_repo_root_for_main_graph_dir(graph_dir: &Path) -> Option<PathBuf> {
621    let data_dir = graph_dir.parent()?;
622    if data_dir.file_name().and_then(|s| s.to_str()) != Some("data") {
623        return None;
624    }
625    let assets_dir = data_dir.parent()?;
626    if assets_dir.file_name().and_then(|s| s.to_str()) != Some("assets") {
627        return None;
628    }
629    let repo_root = assets_dir.parent()?;
630    if repo_root.file_name().and_then(|s| s.to_str()) == Some("built") {
631        return None;
632    }
633    if repo_root.join(".git").exists() {
634        Some(repo_root.to_path_buf())
635    } else {
636        None
637    }
638}
639
640/// Relative repository path to the reconstructible high-water ledger cache.
641pub const HIGHWATER_LEDGER_REL_PATH: &str = "built/graph-ledger/highwater";
642
643fn highwater_shadow_dirs(repo_root: &Path) -> Vec<(String, PathBuf)> {
644    vec![(
645        format!(
646            "reconstructible high-water ledger cache ({HIGHWATER_LEDGER_REL_PATH})"
647        ),
648        repo_root.join(HIGHWATER_LEDGER_REL_PATH),
649    )]
650}
651
652/// Verifies `current_nodes` against both high-water shadow ledgers and `git HEAD`
653/// (when `.git` and `git` are available).
654pub fn verify_repo_graph_append_only(
655    repo_root: &Path,
656    current_nodes: &[LedgerNode],
657) -> Result<()> {
658    for (label, shadow_dir) in highwater_shadow_dirs(repo_root) {
659        if shadow_dir.is_dir() {
660            let shadow_nodes = load_ledger_nodes_from_dir_raw(&shadow_dir)
661                .with_context(|| {
662                    format!(
663                        "Failed to load {label} from {}",
664                        shadow_dir.display()
665                    )
666                })?;
667            if !shadow_nodes.is_empty() {
668                verify_nodes_append_only_against_baseline(
669                    &label,
670                    &shadow_nodes,
671                    current_nodes,
672                )?;
673            }
674        }
675    }
676
677    if repo_root.join(".git").exists() {
678        if let Ok(ls_out) = std::process::Command::new("/usr/bin/git")
679            .arg("-C")
680            .arg(repo_root)
681            .args([
682                "ls-tree",
683                "-r",
684                "--name-only",
685                "HEAD",
686                "assets/data/graph/",
687            ])
688            .output()
689            && ls_out.status.success()
690        {
691            let stdout = String::from_utf8_lossy(&ls_out.stdout);
692            let mut keyed_paths: Vec<(u128, String)> = Vec::new();
693            for line in stdout.lines() {
694                let rel = line.trim();
695                let Some(fname) =
696                    Path::new(rel).file_name().and_then(|s| s.to_str())
697                else {
698                    continue;
699                };
700                if let Some(start_id) = parse_chunk_filename_start_id(fname) {
701                    keyed_paths.push((start_id, rel.to_string()));
702                }
703            }
704            keyed_paths
705                .sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
706            let mut head_nodes = Vec::new();
707            for (_, rel) in keyed_paths {
708                let show_out = std::process::Command::new("/usr/bin/git")
709                    .arg("-C")
710                    .arg(repo_root)
711                    .arg("show")
712                    .arg(format!("HEAD:{rel}"))
713                    .output()
714                    .with_context(|| {
715                        format!("Failed to read HEAD:{rel} from git")
716                    })?;
717                if show_out.status.success() {
718                    let text = String::from_utf8(show_out.stdout)
719                        .with_context(|| {
720                            format!("Invalid UTF-8 in HEAD:{rel}")
721                        })?;
722                    let chunk_nodes = load_ledger_nodes_from_str(&text, &rel)?;
723                    head_nodes.extend(chunk_nodes);
724                }
725            }
726            if !head_nodes.is_empty() {
727                verify_nodes_append_only_against_baseline(
728                    "git HEAD (assets/data/graph/*.ctbnodes)",
729                    &head_nodes,
730                    current_nodes,
731                )?;
732            }
733        }
734    }
735
736    Ok(())
737}
738
739/// Writes or appends a single `.ctbnodes` chunk file using strictly append-only semantics:
740/// - If `path` already exists and equals `content`, does not open the file for writing (`Ok(false)`).
741/// - If `path` already exists and is a strict byte prefix of `content`, opens `path` with
742///   `O_WRONLY | O_APPEND` (compatible with kernel `chattr +a`) and writes only the newly appended tail.
743/// - If `path` already exists and is NOT a strict byte prefix of `content`, fails loudly (`Err`).
744/// - If `path` does not exist yet, creates it with `O_WRONLY | O_CREAT | O_EXCL`.
745pub fn write_chunk_file_append_only(
746    path: &Path,
747    content: &str,
748) -> Result<bool> {
749    use std::io::Write;
750
751    if path.exists() {
752        let existing = std::fs::read(path).with_context(|| {
753            format!(
754                "Failed to read existing .ctbnodes chunk {}",
755                path.display()
756            )
757        })?;
758        if existing == content.as_bytes() {
759            return Ok(false);
760        }
761        ensure!(
762            content.as_bytes().starts_with(&existing),
763            "CRITICAL: Append-only invariant violated for {}: existing file content ({} bytes) \
764             is not a strict byte prefix of new content ({} bytes). Existing .ctbnodes entries must never be modified or truncated!",
765            path.display(),
766            existing.len(),
767            content.len()
768        );
769        let tail = content.as_bytes().get(existing.len()..).context(
770            "Existing chunk exceeds verified replacement byte length",
771        )?;
772        let mut file = std::fs::OpenOptions::new()
773            .append(true)
774            .open(path)
775            .with_context(|| {
776                format!("Failed to open {} in O_APPEND mode", path.display())
777            })?;
778        file.write_all(tail).with_context(|| {
779            format!(
780                "Failed to append {} bytes to {}",
781                tail.len(),
782                path.display()
783            )
784        })?;
785        return Ok(true);
786    }
787
788    if let Some(parent) = path.parent() {
789        std::fs::create_dir_all(parent).with_context(|| {
790            format!("Failed to create directory {}", parent.display())
791        })?;
792    }
793    let mut file = std::fs::OpenOptions::new()
794        .write(true)
795        .create_new(true)
796        .open(path)
797        .with_context(|| {
798            format!("Failed to create new .ctbnodes chunk {}", path.display())
799        })?;
800    file.write_all(content.as_bytes()).with_context(|| {
801        format!("Failed to write new .ctbnodes chunk {}", path.display())
802    })?;
803    Ok(true)
804}
805
806/// Writes `nodes` into 100-node chunk files (`85899_34592.ctbnodes`, ...) in `graph_dir`
807/// using strictly append-only file operations (`O_APPEND` on partial tail chunks, `O_CREAT | O_EXCL`
808/// on new chunks, and no-op on unchanged full chunks). Returns the number of files written.
809pub fn write_ledger_nodes_to_dir(
810    graph_dir: &Path,
811    nodes: &[LedgerNode],
812) -> Result<usize> {
813    std::fs::create_dir_all(graph_dir).with_context(|| {
814        format!("Failed to create graph directory {}", graph_dir.display())
815    })?;
816    let existing_files = list_chunk_files(graph_dir)?;
817    let expected_chunks = if nodes.is_empty() {
818        0
819    } else {
820        nodes
821            .len()
822            .saturating_add(MAX_NODES_PER_CHUNK.saturating_sub(1))
823            / MAX_NODES_PER_CHUNK
824    };
825    ensure!(
826        expected_chunks >= existing_files.len(),
827        "CRITICAL: Append-only invariant violated in {}: new node list has {} chunks, \
828         fewer than the {} existing chunk files on disk!",
829        graph_dir.display(),
830        expected_chunks,
831        existing_files.len()
832    );
833
834    let mut files_written = 0usize;
835    for chunk in nodes.chunks(MAX_NODES_PER_CHUNK) {
836        let Some(first_node) = chunk.first() else {
837            continue;
838        };
839        let file_path = graph_dir.join(format_chunk_rel_path(first_node.id));
840        let mut content = String::new();
841        for node in chunk {
842            content.push_str(&node.format_line());
843            content.push('\n');
844        }
845        if write_chunk_file_append_only(&file_path, &content)? {
846            files_written = files_written.saturating_add(1);
847        }
848    }
849    Ok(files_written)
850}
851
852/// Synchronizes the append-only high-water shadow ledgers with `nodes`.
853pub fn sync_highwater_shadow_ledgers(
854    repo_root: &Path,
855    nodes: &[LedgerNode],
856) -> Result<()> {
857    for (label, shadow_dir) in highwater_shadow_dirs(repo_root) {
858        std::fs::create_dir_all(&shadow_dir).with_context(|| {
859            format!("Failed to create {label} at {}", shadow_dir.display())
860        })?;
861        if let Ok(existing_files) = list_chunk_files(&shadow_dir) {
862            if let Some(last_file) = existing_files.last() {
863                #[cfg(unix)]
864                {
865                    use std::os::unix::fs::PermissionsExt;
866                    let _ = std::fs::set_permissions(
867                        last_file,
868                        std::fs::Permissions::from_mode(0o644),
869                    );
870                }
871            }
872        }
873        write_ledger_nodes_to_dir(&shadow_dir, nodes)
874            .with_context(|| format!("Failed to update {label}"))?;
875        if let Ok(updated_files) = list_chunk_files(&shadow_dir) {
876            #[cfg(unix)]
877            {
878                use std::os::unix::fs::PermissionsExt;
879                for file in updated_files {
880                    let _ = std::fs::set_permissions(
881                        &file,
882                        std::fs::Permissions::from_mode(0o444),
883                    );
884                }
885            }
886        }
887    }
888    Ok(())
889}
890
891/// Loads all existing `LedgerNode` entries from `.ctbnodes` chunk files in `graph_dir`.
892///
893/// When `graph_dir` is `<repo_root>/assets/data/graph`, this also automatically verifies
894/// that the loaded nodes have not been rolled back or mutated relative to the high-water
895/// shadow ledgers.
896pub fn load_ledger_nodes_from_dir(graph_dir: &Path) -> Result<Vec<LedgerNode>> {
897    if let Some(repo_root) = find_repo_root_for_main_graph_dir(graph_dir) {
898        let guard = LedgerReadGuard::acquire(&repo_root)?;
899        let (ledger_sha, nodes_arc) =
900            journal::ensure_ledger_journal_clean_and_load_committed(
901                &repo_root, &guard,
902            )?;
903        for (label, shadow_dir) in highwater_shadow_dirs(&repo_root) {
904            if shadow_dir.is_dir() {
905                let shadow_sha = journal::compute_ledger_dir_sha256(&shadow_dir)
906                    .with_context(|| {
907                        format!(
908                            "Failed to hash {label} at {}",
909                            shadow_dir.display()
910                        )
911                    })?;
912                if shadow_sha != ledger_sha {
913                    let shadow_nodes =
914                        load_ledger_nodes_from_dir_raw(&shadow_dir)
915                            .with_context(|| {
916                                format!(
917                                    "Failed to load {label} from {}",
918                                    shadow_dir.display()
919                                )
920                            })?;
921                    if !shadow_nodes.is_empty() {
922                        verify_nodes_append_only_against_baseline(
923                            &label,
924                            &shadow_nodes,
925                            &nodes_arc,
926                        )?;
927                    }
928                }
929            }
930        }
931        drop(guard);
932        return Ok(nodes_arc.as_ref().to_vec());
933    }
934    load_ledger_nodes_from_dir_raw(graph_dir)
935}
936
937/// Appends `tok` as an `[atom_dc]` token to `out`, escaping `Dc 203` (`Begin encapsulated binary data`),
938/// `escape` (`Dc 255`), and `evaluate_as_atom` (`Dc 616`) with a leading `escape` (`Dc 255`).
939pub fn push_atom_dc_with(
940    out: &mut Vec<DcShorthand>,
941    tok: DcShorthand,
942    framing: CtbnbdlFramingDcs,
943) {
944    if tok == DcShorthand::Short(203)
945        || tok == framing.escape
946        || tok == framing.evaluate_as_atom
947    {
948        out.push(framing.escape);
949    }
950    out.push(tok);
951}
952
953/// Consumes an `[atom_dc]` token at `*idx` from `tokens`, unescaping `255 203`, `255 255`, and `255 616`.
954#[must_use]
955pub fn consume_atom_dc_with(
956    tokens: &[DcShorthand],
957    idx: &mut usize,
958    framing: CtbnbdlFramingDcs,
959) -> Option<DcShorthand> {
960    let tok = *tokens.get(*idx)?;
961    *idx = idx.saturating_add(1);
962    if tok == framing.escape {
963        let escaped = *tokens.get(*idx)?;
964        if escaped == DcShorthand::Short(203)
965            || escaped == framing.escape
966            || escaped == framing.evaluate_as_atom
967        {
968            *idx = idx.saturating_add(1);
969            Some(escaped)
970        } else {
971            None
972        }
973    } else if tok == framing.evaluate_as_atom {
974        None
975    } else {
976        Some(tok)
977    }
978}
979
980/// Encodes a single `LedgerNode` (`id` + `tokens`) into its `Dc 617 .. Dc 618` token sequence:
981/// `617 [atom_dc: l<id>] <escaped body tokens...> 618`.
982#[must_use]
983pub fn encode_node_definition_tokens_with(
984    node: &LedgerNode,
985    framing: CtbnbdlFramingDcs,
986) -> Vec<DcShorthand> {
987    let mut out = Vec::with_capacity(node.tokens.len().saturating_add(4));
988    out.push(framing.begin_node);
989    push_atom_dc_with(&mut out, DcShorthand::from_global_id(node.id), framing);
990    for &tok in &node.tokens {
991        if tok == framing.escape || tok == framing.end_node {
992            out.push(framing.escape);
993        }
994        out.push(tok);
995    }
996    out.push(framing.end_node);
997    out
998}
999
1000fn push_dctf_token(out: &mut Vec<u8>, tok: DcShorthand) -> Result<()> {
1001    let mut char_buf = [0u8; 24];
1002    let gid = tok.to_global_id()?;
1003    let n = encode_dctf_buf(&mut char_buf, gid);
1004    if let Some(slice) = char_buf.get(..n) {
1005        out.extend_from_slice(slice);
1006    }
1007    Ok(())
1008}
1009
1010fn decode_dc_base64_payload(tokens: &[DcShorthand]) -> Result<Vec<u8>> {
1011    if tokens.is_empty() {
1012        return Ok(Vec::new());
1013    }
1014    let mut vals: Vec<u8> = Vec::with_capacity(tokens.len());
1015    let mut padding = 0usize;
1016    for &tok in tokens {
1017        match tok {
1018            DcShorthand::Short(n)
1019                if (BASE64_DIGIT_START..=BASE64_DIGIT_END).contains(&n) =>
1020            {
1021                ensure!(
1022                    padding == 0,
1023                    "Base64 digit {tok} after padding in Dc 203 encapsulation"
1024                );
1025                let digit = u8::try_from(n.saturating_sub(BASE64_DIGIT_START))?;
1026                vals.push(digit);
1027            }
1028            DcShorthand::Short(BASE64_PADDING_DC) => {
1029                padding = padding.saturating_add(1);
1030                ensure!(
1031                    padding <= 2,
1032                    "Too many base64 padding characters in Dc 203 encapsulation"
1033                );
1034            }
1035            _ => bail!(
1036                "Unexpected token {tok} inside base64 payload of Dc 203 encapsulation"
1037            ),
1038        }
1039    }
1040
1041    let total_chars = vals.len().saturating_add(padding);
1042    ensure!(
1043        total_chars.is_multiple_of(4) && !vals.is_empty(),
1044        "Invalid base64 length ({total_chars} chars) in Dc 203 encapsulation"
1045    );
1046
1047    let mut out = Vec::with_capacity(total_chars.saturating_div(4).saturating_mul(3));
1048    let mut idx = 0usize;
1049    while idx < vals.len() {
1050        let a = *vals.get(idx).context("Missing base64 char 0")?;
1051        let b = *vals.get(idx.saturating_add(1)).context("Missing base64 char 1")?;
1052        let c_opt = vals.get(idx.saturating_add(2)).copied();
1053        let d_opt = vals.get(idx.saturating_add(3)).copied();
1054
1055        let b0 = (a << 2) | (b >> 4);
1056        out.push(b0);
1057        if let Some(c) = c_opt {
1058            let b1 = ((b & 0x0F) << 4) | (c >> 2);
1059            out.push(b1);
1060            if let Some(d) = d_opt {
1061                let b2 = ((c & 0x03) << 6) | d;
1062                out.push(b2);
1063            }
1064        }
1065        idx = idx.saturating_add(4);
1066    }
1067    Ok(out)
1068}
1069
1070fn encode_dc_base64_u128(mut val: u128, out: &mut Vec<DcShorthand>) {
1071    if val == 0 {
1072        out.push(DcShorthand::Short(BASE64_DIGIT_START));
1073        return;
1074    }
1075    let mut digits = Vec::new();
1076    while val > 0 {
1077        let rem = u32::try_from(val & 0x3F).unwrap_or(0);
1078        digits.push(DcShorthand::Short(BASE64_DIGIT_START.saturating_add(rem)));
1079        val >>= 6;
1080    }
1081    for d in digits.into_iter().rev() {
1082        out.push(d);
1083    }
1084}
1085
1086fn encode_dc_base64_payload(bytes: &[u8], out: &mut Vec<DcShorthand>) {
1087    let mut idx = 0usize;
1088    while idx < bytes.len() {
1089        let b0 = *bytes.get(idx).unwrap_or(&0);
1090        let b1_opt = bytes.get(idx.saturating_add(1)).copied();
1091        let b2_opt = bytes.get(idx.saturating_add(2)).copied();
1092
1093        let c0 = u32::from(b0 >> 2);
1094        let c1 = u32::from(((b0 & 0x03) << 4) | (b1_opt.unwrap_or(0) >> 4));
1095        out.push(DcShorthand::Short(BASE64_DIGIT_START.saturating_add(c0)));
1096        out.push(DcShorthand::Short(BASE64_DIGIT_START.saturating_add(c1)));
1097
1098        if let Some(b1) = b1_opt {
1099            let c2 = u32::from(((b1 & 0x0F) << 2) | (b2_opt.unwrap_or(0) >> 6));
1100            out.push(DcShorthand::Short(BASE64_DIGIT_START.saturating_add(c2)));
1101            if let Some(b2) = b2_opt {
1102                let c3 = u32::from(b2 & 0x3F);
1103                out.push(DcShorthand::Short(
1104                    BASE64_DIGIT_START.saturating_add(c3),
1105                ));
1106            } else {
1107                out.push(DcShorthand::Short(BASE64_PADDING_DC));
1108            }
1109        } else {
1110            out.push(DcShorthand::Short(BASE64_PADDING_DC));
1111            out.push(DcShorthand::Short(BASE64_PADDING_DC));
1112        }
1113        idx = idx.saturating_add(3);
1114    }
1115}
1116
1117fn try_parse_textual_encapsulation(
1118    tokens: &[DcShorthand],
1119    start: usize,
1120) -> Result<Option<(Vec<u8>, usize)>> {
1121    if tokens.get(start) != Some(&DcShorthand::Short(203)) {
1122        return Ok(None);
1123    }
1124    let mut pos = start.saturating_add(1);
1125    let mut expected_len: Option<u128> = None;
1126
1127    match tokens.get(pos) {
1128        Some(&DcShorthand::Short(6)) => {
1129            pos = pos.saturating_add(1);
1130            if tokens.get(pos) == Some(&DcShorthand::Format(199)) {
1131                pos = pos.saturating_add(1);
1132            }
1133            let mut len_val = 0u128;
1134            let mut digit_count = 0usize;
1135            while let Some(&DcShorthand::Short(n)) = tokens.get(pos) {
1136                if (BASE64_DIGIT_START..=BASE64_DIGIT_END).contains(&n) {
1137                    let d = u128::from(n.saturating_sub(BASE64_DIGIT_START));
1138                    len_val = len_val
1139                        .checked_mul(64)
1140                        .and_then(|v| v.checked_add(d))
1141                        .context("Length overflow in Dc 203 encapsulation")?;
1142                    digit_count = digit_count.saturating_add(1);
1143                    pos = pos.saturating_add(1);
1144                } else {
1145                    break;
1146                }
1147            }
1148            ensure!(
1149                digit_count > 0 && tokens.get(pos) == Some(&DcShorthand::Short(7)),
1150                "Malformed length block in Dc 203 textual encapsulation"
1151            );
1152            pos = pos.saturating_add(1);
1153            expected_len = Some(len_val);
1154        }
1155        Some(&DcShorthand::Short(n))
1156            if (BASE64_DIGIT_START..=BASE64_DIGIT_END).contains(&n)
1157                || n == BASE64_PADDING_DC
1158                || n == 204 => {}
1159        _ => return Ok(None),
1160    }
1161
1162    let payload_start = pos;
1163    while let Some(&tok) = tokens.get(pos) {
1164        if tok == DcShorthand::Short(204) {
1165            let payload_slice = tokens
1166                .get(payload_start..pos)
1167                .context("Invalid textual encapsulation slice")?;
1168            let raw_bytes = decode_dc_base64_payload(payload_slice)?;
1169            if let Some(exp) = expected_len {
1170                ensure!(
1171                    u128::try_from(raw_bytes.len())? == exp,
1172                    "Dc 203 textual encapsulation declared length {exp} bytes, decoded {} bytes",
1173                    raw_bytes.len()
1174                );
1175            }
1176            return Ok(Some((raw_bytes, pos.saturating_add(1))));
1177        }
1178        pos = pos.saturating_add(1);
1179    }
1180
1181    bail!("Unterminated Dc 203 textual encapsulation (missing Dc 204)");
1182}
1183
1184/// Encodes a single `LedgerNode` into `DcMixed2` checksummed-section bytes:
1185/// `543 617 [atom_dc: l<id>] <escaped body tokens...> 618 [<SectionTimestampNodeCreationTime> 390 f487 6 f199 [11?] <base64> 7 391]? 544 545 <SHA-256 checksum>`.
1186pub fn encode_node_definition_dcmm2_bytes_with(
1187    node: &LedgerNode,
1188    framing: CtbnbdlFramingDcs,
1189) -> Result<Vec<u8>> {
1190    use crate::sha2::{Digest, Sha256};
1191
1192    let mut out = Vec::with_capacity(
1193        node.tokens
1194            .len()
1195            .saturating_add(16)
1196            .saturating_mul(4)
1197            .saturating_add(80),
1198    );
1199    push_dctf_token(&mut out, framing.begin_checksummed_section)?;
1200    let section_body_start = out.len();
1201
1202    push_dctf_token(&mut out, framing.begin_node)?;
1203
1204    let mut id_tokens = Vec::with_capacity(2);
1205    push_atom_dc_with(
1206        &mut id_tokens,
1207        DcShorthand::from_global_id(node.id),
1208        framing,
1209    );
1210    for tok in id_tokens {
1211        push_dctf_token(&mut out, tok)?;
1212    }
1213
1214    let mut i = 0usize;
1215    while let Some(&tok) = node.tokens.get(i) {
1216        if tok == framing.escape || tok == framing.end_node {
1217            push_dctf_token(&mut out, framing.escape)?;
1218            push_dctf_token(&mut out, tok)?;
1219            i = i.saturating_add(1);
1220        } else if tok == DcShorthand::Short(203)
1221            && let Some((raw_bytes, next_i)) =
1222                try_parse_textual_encapsulation(&node.tokens, i)?
1223        {
1224            out.extend_from_slice(&DC_203_DCTF_BYTES);
1225            out.push(DCMM_TYPE_BINARY_METADATA);
1226            let payload_len = u128::try_from(raw_bytes.len())?;
1227            out.extend_from_slice(&payload_len.to_be_bytes());
1228            out.extend_from_slice(&0u128.to_be_bytes());
1229            out.extend_from_slice(&raw_bytes);
1230            i = next_i;
1231        } else {
1232            push_dctf_token(&mut out, tok)?;
1233            i = i.saturating_add(1);
1234        }
1235    }
1236
1237    push_dctf_token(&mut out, framing.end_node)?;
1238
1239    if let Some(ts_ns) = node.created_ns {
1240        let ts_dc = framing.section_node_creation_time.context(
1241            "Cannot encode node creation timestamp in .ctbnbdl without SectionTimestampNodeCreationTime in framing Dcs",
1242        )?;
1243        push_dctf_token(&mut out, ts_dc)?;
1244        push_dctf_token(&mut out, framing.begin_time_moment)?;
1245        push_dctf_token(&mut out, framing.ns_since_epoch_format)?;
1246        push_dctf_token(&mut out, DcShorthand::Short(6))?;
1247        push_dctf_token(&mut out, DcShorthand::Format(199))?;
1248        if ts_ns < 0 {
1249            push_dctf_token(&mut out, DcShorthand::Short(11))?;
1250        }
1251        let mut digits = Vec::with_capacity(24);
1252        encode_dc_base64_u128(ts_ns.unsigned_abs(), &mut digits);
1253        for d in digits {
1254            push_dctf_token(&mut out, d)?;
1255        }
1256        push_dctf_token(&mut out, DcShorthand::Short(7))?;
1257        push_dctf_token(&mut out, framing.end_time_moment)?;
1258    }
1259
1260    let section_body_end = out.len();
1261    let section_body = out
1262        .get(section_body_start..section_body_end)
1263        .context("Invalid checksummed section body slice")?;
1264    let digest: [u8; 32] = Sha256::digest(section_body).into();
1265
1266    push_dctf_token(&mut out, framing.end_checksummed_section)?;
1267    push_dctf_token(&mut out, framing.section_digest)?;
1268
1269    let mut meta_bytes = Vec::with_capacity(8);
1270    push_dctf_token(&mut meta_bytes, framing.sha256_format)?;
1271    out.extend_from_slice(&DC_203_DCTF_BYTES);
1272    out.push(DCMM_TYPE_BINARY_METADATA);
1273    out.extend_from_slice(&32u128.to_be_bytes());
1274    out.extend_from_slice(&u128::try_from(meta_bytes.len())?.to_be_bytes());
1275    out.extend_from_slice(&meta_bytes);
1276    out.extend_from_slice(&digest);
1277
1278    Ok(out)
1279}
1280
1281fn encode_ctbnbdl_header_bytes(
1282    most_recent_node_id: Option<u128>,
1283    framing: CtbnbdlFramingDcs,
1284) -> Result<Vec<u8>> {
1285    let mut header = Vec::with_capacity(
1286        CTBNBDL_MAGIC
1287            .len()
1288            .saturating_add(DCMM_HEADER.len())
1289            .saturating_add(16),
1290    );
1291    header.extend_from_slice(&CTBNBDL_MAGIC);
1292    header.extend_from_slice(&DCMM_HEADER);
1293    if let Some(wm_id) = most_recent_node_id {
1294        ensure!(
1295            (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&wm_id),
1296            "System graph most_recent node ID l{wm_id} is outside the System block ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
1297        );
1298        let mut wm_tokens = Vec::with_capacity(3);
1299        wm_tokens.push(DC_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
1300        push_atom_dc_with(
1301            &mut wm_tokens,
1302            DcShorthand::from_global_id(wm_id),
1303            framing,
1304        );
1305        let mut char_buf = [0u8; 24];
1306        for tok in wm_tokens {
1307            let gid = tok.to_global_id()?;
1308            let n = encode_dctf_buf(&mut char_buf, gid);
1309            if let Some(slice) = char_buf.get(..n) {
1310                header.extend_from_slice(slice);
1311            }
1312        }
1313    }
1314    Ok(header)
1315}
1316
1317/// Compiles a slice of `LedgerNode` entries into a `.ctbnbdl` (`CtbNodeBundle2`) binary buffer:
1318/// 8-byte `CTBNBDL\x02` magic + 21-byte `DcMixed2` header + optional `641 l<max_node_id>` most_recent
1319/// + `DcTF` encoded `543 617 .. 618 [<ts>]? 544 545 <checksum>` checksummed node sections.
1320pub fn encode_nodes_to_ctbnbdl_bytes_with(
1321    nodes: &[LedgerNode],
1322    framing: CtbnbdlFramingDcs,
1323) -> Result<Vec<u8>> {
1324    let most_recent_node_id = nodes.iter().map(|n| n.id).max();
1325    let header_bytes = encode_ctbnbdl_header_bytes(most_recent_node_id, framing)?;
1326    let mut bytes = Vec::with_capacity(
1327        header_bytes
1328            .len()
1329            .saturating_add(nodes.len().saturating_mul(96)),
1330    );
1331    bytes.extend_from_slice(&header_bytes);
1332    for node in nodes {
1333        let node_bytes = encode_node_definition_dcmm2_bytes_with(node, framing)?;
1334        bytes.extend_from_slice(&node_bytes);
1335    }
1336    Ok(bytes)
1337}
1338
1339#[derive(Debug)]
1340enum StreamItem<'a> {
1341    Token(DcShorthand),
1342    Binary {
1343        meta_tokens: Vec<DcShorthand>,
1344        payload_len_u128: u128,
1345        bin_payload: &'a [u8],
1346    },
1347}
1348
1349fn read_stream_item<'a>(
1350    payload: &'a [u8],
1351    pos: usize,
1352    is_v2: bool,
1353    escaped: bool,
1354) -> Result<(StreamItem<'a>, usize)> {
1355    let rem = payload
1356        .get(pos..)
1357        .context("Stream cursor out of bounds in .ctbnbdl")?;
1358    let dc203_bytes: &[u8] = if is_v2 {
1359        &DC_203_DCTF_BYTES
1360    } else {
1361        &DC_203_UTF8E128_BYTES
1362    };
1363    if !escaped
1364        && let Some(after_dc203) = rem.strip_prefix(dc203_bytes)
1365        && let Some(&type_byte) = after_dc203.first()
1366        && matches!(
1367            type_byte,
1368            DCMM_TYPE_BINARY
1369                | DCMM_TYPE_LEGACY_TEXT
1370                | DCMM_TYPE_BINARY_METADATA
1371                | DCMM_TYPE_BINARY_SHA256
1372                | DCMM_TYPE_LEGACY_SHA256
1373        )
1374    {
1375        let size_bytes: [u8; 16] = after_dc203
1376            .get(1..17)
1377            .context("Truncated DcMixed encapsulation size in .ctbnbdl")?
1378            .try_into()?;
1379        let payload_len_u128 = u128::from_be_bytes(size_bytes);
1380        let payload_len = usize::try_from(payload_len_u128)
1381            .context("DcMixed encapsulation payload size overflow in .ctbnbdl")?;
1382
1383        let mut cursor = 17usize;
1384        let mut meta_bytes: &[u8] = &[];
1385        if type_byte == DCMM_TYPE_BINARY_METADATA {
1386            let meta_len_bytes: [u8; 16] = after_dc203
1387                .get(cursor..cursor.saturating_add(16))
1388                .context("Truncated DcMixed metadata length in .ctbnbdl")?
1389                .try_into()?;
1390            let meta_len =
1391                usize::try_from(u128::from_be_bytes(meta_len_bytes))
1392                    .context("DcMixed metadata length overflow in .ctbnbdl")?;
1393            cursor = cursor.saturating_add(16);
1394            let meta_end = cursor
1395                .checked_add(meta_len)
1396                .context("DcMixed metadata offset overflow in .ctbnbdl")?;
1397            meta_bytes = after_dc203
1398                .get(cursor..meta_end)
1399                .context("Truncated DcMixed metadata in .ctbnbdl")?;
1400            cursor = meta_end;
1401        } else if type_byte == DCMM_TYPE_BINARY_SHA256
1402            || type_byte == DCMM_TYPE_LEGACY_SHA256
1403        {
1404            let sha_end = cursor.saturating_add(32);
1405            ensure!(
1406                after_dc203.len() >= sha_end,
1407                "Truncated DcMixed SHA-256 checksum in .ctbnbdl"
1408            );
1409            cursor = sha_end;
1410        }
1411
1412        let payload_end = cursor
1413            .checked_add(payload_len)
1414            .context("DcMixed payload offset overflow in .ctbnbdl")?;
1415        let bin_payload = after_dc203
1416            .get(cursor..payload_end)
1417            .context("Truncated DcMixed binary payload in .ctbnbdl")?;
1418
1419        let mut meta_tokens = Vec::new();
1420        let mut meta_rem = meta_bytes;
1421        while !meta_rem.is_empty() {
1422            let decoded = if is_v2 {
1423                decode_dctf_buf(meta_rem)
1424            } else {
1425                decode_utf_8e_128_buf(meta_rem)
1426            };
1427            let Some((cp, consumed)) = decoded else {
1428                bail!(
1429                    "Invalid character sequence in .ctbnbdl encapsulation metadata"
1430                );
1431            };
1432            meta_tokens.push(DcShorthand::from_global_id(cp));
1433            // Reason for fallback: consumed <= meta_rem.len() is guaranteed by decode_dctf_buf / decode_utf_8e_128_buf.
1434            meta_rem = meta_rem.get(consumed..).unwrap_or_default();
1435        }
1436
1437        let next_pos = pos
1438            .checked_add(dc203_bytes.len())
1439            .and_then(|p| p.checked_add(payload_end))
1440            .context("Byte offset overflow in .ctbnbdl binary encapsulation")?;
1441        return Ok((
1442            StreamItem::Binary {
1443                meta_tokens,
1444                payload_len_u128,
1445                bin_payload,
1446            },
1447            next_pos,
1448        ));
1449    }
1450
1451    let decoded = if is_v2 {
1452        decode_dctf_buf(rem)
1453    } else {
1454        decode_utf_8e_128_buf(rem)
1455    };
1456    let Some((codepoint, consumed)) = decoded else {
1457        bail!("Invalid character sequence in .ctbnbdl stream at offset {pos}");
1458    };
1459    let next_pos = pos
1460        .checked_add(consumed)
1461        .context("Byte offset overflow in .ctbnbdl character stream")?;
1462    Ok((StreamItem::Token(DcShorthand::from_global_id(codepoint)), next_pos))
1463}
1464
1465fn push_binary_item_as_textual_tokens(
1466    meta_tokens: &[DcShorthand],
1467    payload_len_u128: u128,
1468    bin_payload: &[u8],
1469    out: &mut Vec<DcShorthand>,
1470) {
1471    out.push(DcShorthand::Short(203));
1472    out.extend_from_slice(meta_tokens);
1473    out.push(DcShorthand::Short(6));
1474    out.push(DcShorthand::Format(199));
1475    encode_dc_base64_u128(payload_len_u128, out);
1476    out.push(DcShorthand::Short(7));
1477    encode_dc_base64_payload(bin_payload, out);
1478    out.push(DcShorthand::Short(204));
1479}
1480
1481fn read_atom_dc_from_bytes(
1482    payload: &[u8],
1483    pos: &mut usize,
1484    is_v2: bool,
1485    framing: CtbnbdlFramingDcs,
1486) -> Result<DcShorthand> {
1487    let (item, next_pos) = read_stream_item(payload, *pos, is_v2, false)?;
1488    let StreamItem::Token(tok) = item else {
1489        bail!("Unexpected binary encapsulation in [atom_dc] position in .ctbnbdl");
1490    };
1491    *pos = next_pos;
1492    if tok == framing.escape {
1493        let (esc_item, after_esc) = read_stream_item(payload, *pos, is_v2, true)?;
1494        let StreamItem::Token(escaped) = esc_item else {
1495            bail!("Unexpected binary encapsulation after escape in [atom_dc]");
1496        };
1497        ensure!(
1498            escaped == DcShorthand::Short(203)
1499                || escaped == framing.escape
1500                || escaped == framing.evaluate_as_atom,
1501            "Invalid escaped [atom_dc] token {escaped} in .ctbnbdl"
1502        );
1503        *pos = after_esc;
1504        Ok(escaped)
1505    } else if tok == framing.evaluate_as_atom {
1506        bail!("Unexpected unescaped EvaluateValueAsAtom in .ctbnbdl [atom_dc]");
1507    } else {
1508        Ok(tok)
1509    }
1510}
1511
1512fn parse_bare_node_at(
1513    payload: &[u8],
1514    pos: &mut usize,
1515    is_v2: bool,
1516    framing: CtbnbdlFramingDcs,
1517) -> Result<(u128, Vec<DcShorthand>)> {
1518    let (open_item, after_open) = read_stream_item(payload, *pos, is_v2, false)?;
1519    let StreamItem::Token(open_tok) = open_item else {
1520        bail!(
1521            "Expected {} (Begin graph node definition), found binary encapsulation",
1522            framing.begin_node
1523        );
1524    };
1525    ensure!(
1526        open_tok == framing.begin_node,
1527        "Expected {} (Begin graph node definition), found {open_tok}",
1528        framing.begin_node
1529    );
1530    *pos = after_open;
1531    let id_sh = read_atom_dc_from_bytes(payload, pos, is_v2, framing)
1532        .context("Invalid or missing [atom_dc] node ID after BeginGraphNodeDefinition")?;
1533    let id = id_sh.to_global_id()?;
1534
1535    let mut body_tokens = Vec::new();
1536    let mut closed = false;
1537    while *pos < payload.len() {
1538        let (item, next_pos) = read_stream_item(payload, *pos, is_v2, false)?;
1539        *pos = next_pos;
1540        match item {
1541            StreamItem::Token(tok) => {
1542                if tok == framing.end_node {
1543                    closed = true;
1544                    break;
1545                }
1546                if tok == framing.escape {
1547                    let (esc_item, after_esc) =
1548                        read_stream_item(payload, *pos, is_v2, true).context(
1549                            "Trailing escape token at end of .ctbnbdl node body",
1550                        )?;
1551                    let StreamItem::Token(escaped) = esc_item else {
1552                        bail!("Unexpected binary chunk after escape in .ctbnbdl node body");
1553                    };
1554                    ensure!(
1555                        escaped == framing.escape || escaped == framing.end_node,
1556                        "Unexpected escaped token {escaped} after {} in .ctbnbdl node body",
1557                        framing.escape
1558                    );
1559                    *pos = after_esc;
1560                    body_tokens.push(escaped);
1561                } else {
1562                    body_tokens.push(tok);
1563                }
1564            }
1565            StreamItem::Binary {
1566                meta_tokens,
1567                payload_len_u128,
1568                bin_payload,
1569            } => {
1570                push_binary_item_as_textual_tokens(
1571                    &meta_tokens,
1572                    payload_len_u128,
1573                    bin_payload,
1574                    &mut body_tokens,
1575                );
1576            }
1577        }
1578    }
1579    ensure!(
1580        closed,
1581        "Unterminated node definition for l{id} (missing {})",
1582        framing.end_node
1583    );
1584    Ok((id, body_tokens))
1585}
1586
1587fn parse_signed_dc_i128_at(
1588    payload: &[u8],
1589    pos: &mut usize,
1590    is_v2: bool,
1591) -> Result<i128> {
1592    let (n_open, p1) = read_stream_item(payload, *pos, is_v2, false)?;
1593    ensure!(
1594        matches!(n_open, StreamItem::Token(DcShorthand::Short(6))),
1595        "Expected Dc 6 (Begin number) in node creation timestamp"
1596    );
1597    let (fmt_tok, p2) = read_stream_item(payload, p1, is_v2, false)?;
1598    ensure!(
1599        matches!(fmt_tok, StreamItem::Token(DcShorthand::Format(199))),
1600        "Expected f199 (Integer) in node creation timestamp"
1601    );
1602    *pos = p2;
1603
1604    let mut is_negative = false;
1605    let (peek_item, p_after_sign) = read_stream_item(payload, *pos, is_v2, false)?;
1606    if matches!(peek_item, StreamItem::Token(DcShorthand::Short(11))) {
1607        is_negative = true;
1608        *pos = p_after_sign;
1609    }
1610
1611    let mut mag: u128 = 0;
1612    let mut digit_count = 0usize;
1613    let mut closed = false;
1614    while *pos < payload.len() {
1615        let (item, next_pos) = read_stream_item(payload, *pos, is_v2, false)?;
1616        *pos = next_pos;
1617        match item {
1618            StreamItem::Token(DcShorthand::Short(7)) => {
1619                closed = true;
1620                break;
1621            }
1622            StreamItem::Token(DcShorthand::Short(n))
1623                if (BASE64_DIGIT_START..=BASE64_DIGIT_END).contains(&n) =>
1624            {
1625                let digit = u128::from(n.saturating_sub(BASE64_DIGIT_START));
1626                mag = mag
1627                    .checked_mul(64)
1628                    .and_then(|v| v.checked_add(digit))
1629                    .context("Integer magnitude overflow in node creation timestamp")?;
1630                digit_count = digit_count.saturating_add(1);
1631            }
1632            other => {
1633                bail!(
1634                    "Unexpected token {other:?} inside Dc 6..7 integer in node creation timestamp"
1635                );
1636            }
1637        }
1638    }
1639    ensure!(
1640        closed && digit_count > 0,
1641        "Malformed or unterminated Dc 6..7 integer in node creation timestamp"
1642    );
1643
1644    if is_negative {
1645        let min_abs = 1u128 << 127;
1646        if mag == min_abs {
1647            Ok(i128::MIN)
1648        } else {
1649            let signed = i128::try_from(mag)
1650                .context("Negative timestamp magnitude exceeds i128::MIN")?;
1651            signed
1652                .checked_neg()
1653                .context("Negation overflow in node creation timestamp")
1654        }
1655    } else {
1656        i128::try_from(mag)
1657            .context("Positive timestamp magnitude exceeds i128::MAX")
1658    }
1659}
1660
1661fn parse_node_record_at(
1662    payload: &[u8],
1663    pos: &mut usize,
1664    is_v2: bool,
1665    framing: CtbnbdlFramingDcs,
1666) -> Result<LedgerNode> {
1667    use crate::sha2::{Digest, Sha256};
1668
1669    let (first_item, after_first) = read_stream_item(payload, *pos, is_v2, false)?;
1670    let StreamItem::Token(first_tok) = first_item else {
1671        bail!("Expected section opener or node opener in .ctbnbdl, found binary encapsulation");
1672    };
1673
1674    if first_tok == framing.begin_node {
1675        let (id, tokens) = parse_bare_node_at(payload, pos, is_v2, framing)?;
1676        return Ok(LedgerNode {
1677            id,
1678            tokens,
1679            comment: String::new(),
1680            created_ns: None,
1681        });
1682    }
1683
1684    ensure!(
1685        first_tok == framing.begin_checksummed_section,
1686        "Expected {} (Begin checksummed section) or {} (Begin graph node definition), found {first_tok}",
1687        framing.begin_checksummed_section,
1688        framing.begin_node
1689    );
1690    let section_body_start = after_first;
1691    *pos = after_first;
1692
1693    let (id, tokens) = parse_bare_node_at(payload, pos, is_v2, framing)?;
1694
1695    let before_meta_or_end = *pos;
1696    let (after_node_item, after_meta_tok_pos) =
1697        read_stream_item(payload, before_meta_or_end, is_v2, false)
1698            .with_context(|| {
1699                format!(
1700                    "Truncated checksummed section after node l{id} (missing {})",
1701                    framing.end_checksummed_section
1702                )
1703            })?;
1704    let StreamItem::Token(after_node_tok) = after_node_item else {
1705        bail!("Unexpected binary chunk after node l{id} inside checksummed section");
1706    };
1707
1708    let (created_ns, section_body_end) =
1709        if after_node_tok == framing.end_checksummed_section {
1710            *pos = after_meta_tok_pos;
1711            (None, before_meta_or_end)
1712        } else {
1713            if let Some(expected_ts_dc) = framing.section_node_creation_time {
1714                ensure!(
1715                    after_node_tok == expected_ts_dc,
1716                    "Expected {} (SectionTimestampNodeCreationTime) or {} after node l{id}, found {after_node_tok}",
1717                    expected_ts_dc,
1718                    framing.end_checksummed_section
1719                );
1720            }
1721            *pos = after_meta_tok_pos;
1722            let (tm_open, after_tm_open) =
1723                read_stream_item(payload, *pos, is_v2, false)?;
1724            ensure!(
1725                matches!(tm_open, StreamItem::Token(t) if t == framing.begin_time_moment),
1726                "Expected {} (Begin time moment) after SectionTimestampNodeCreationTime for l{id}",
1727                framing.begin_time_moment
1728            );
1729            let (tm_fmt, after_tm_fmt) =
1730                read_stream_item(payload, after_tm_open, is_v2, false)?;
1731            ensure!(
1732                matches!(tm_fmt, StreamItem::Token(t) if t == framing.ns_since_epoch_format),
1733                "Expected {} (NsSinceEpoch) in creation timestamp for l{id}",
1734                framing.ns_since_epoch_format
1735            );
1736            *pos = after_tm_fmt;
1737            let ts_ns = parse_signed_dc_i128_at(payload, pos, is_v2)?;
1738            let (tm_close, after_tm_close) =
1739                read_stream_item(payload, *pos, is_v2, false)?;
1740            ensure!(
1741                matches!(tm_close, StreamItem::Token(t) if t == framing.end_time_moment),
1742                "Expected {} (End time moment) after creation timestamp integer for l{id}",
1743                framing.end_time_moment
1744            );
1745            let sec_end = after_tm_close;
1746            let (sec_close, after_sec_close) =
1747                read_stream_item(payload, sec_end, is_v2, false)?;
1748            ensure!(
1749                matches!(sec_close, StreamItem::Token(t) if t == framing.end_checksummed_section),
1750                "Expected {} (End checksummed section) after creation timestamp for l{id}",
1751                framing.end_checksummed_section
1752            );
1753            *pos = after_sec_close;
1754            (Some(ts_ns), sec_end)
1755        };
1756
1757    let (digest_tag_item, after_digest_tag) =
1758        read_stream_item(payload, *pos, is_v2, false).with_context(|| {
1759            format!(
1760                "Missing {} (Section digest) after checksummed section for l{id}",
1761                framing.section_digest
1762            )
1763        })?;
1764    ensure!(
1765        matches!(digest_tag_item, StreamItem::Token(t) if t == framing.section_digest),
1766        "Expected {} (Section digest) after {} for l{id}",
1767        framing.section_digest,
1768        framing.end_checksummed_section
1769    );
1770    *pos = after_digest_tag;
1771
1772    let (ck_item, after_ck) = read_stream_item(payload, *pos, is_v2, false)
1773        .with_context(|| {
1774            format!("Missing [checksum] payload after SectionDigest for l{id}")
1775        })?;
1776    *pos = after_ck;
1777
1778    let expected_digest_bytes: &[u8] = match ck_item {
1779        StreamItem::Binary {
1780            meta_tokens,
1781            bin_payload,
1782            ..
1783        } => {
1784            ensure!(
1785                meta_tokens.as_slice() == [framing.sha256_format]
1786                    && bin_payload.len() == 32,
1787                "Expected 32-byte {} checksum for node l{id}, found meta={meta_tokens:?} len={}",
1788                framing.sha256_format,
1789                bin_payload.len()
1790            );
1791            bin_payload
1792        }
1793        StreamItem::Token(DcShorthand::Short(203)) => {
1794            // Also accept textual Dc 203 [sha256_format] [6 f199 ... 7]? <base64> 204 checksums
1795            let mut ck_tokens = vec![DcShorthand::Short(203)];
1796            let mut closed_204 = false;
1797            while *pos < payload.len() {
1798                let (it, np) = read_stream_item(payload, *pos, is_v2, false)?;
1799                *pos = np;
1800                let StreamItem::Token(t) = it else {
1801                    bail!("Unexpected binary chunk inside textual checksum for l{id}");
1802                };
1803                ck_tokens.push(t);
1804                if t == DcShorthand::Short(204) {
1805                    closed_204 = true;
1806                    break;
1807                }
1808            }
1809            ensure!(closed_204, "Unterminated textual checksum for l{id}");
1810            ensure!(
1811                ck_tokens.get(1) == Some(&framing.sha256_format),
1812                "Unsupported textual checksum format for l{id}"
1813            );
1814            let mut synth = Vec::with_capacity(ck_tokens.len());
1815            synth.push(DcShorthand::Short(203));
1816            if let Some(rest) = ck_tokens.get(2..) {
1817                synth.extend_from_slice(rest);
1818            }
1819            let (decoded_ck, consumed_ck) =
1820                try_parse_textual_encapsulation(&synth, 0)?
1821                    .context("Malformed textual checksum encapsulation")?;
1822            ensure!(
1823                consumed_ck == synth.len() && decoded_ck.len() == 32,
1824                "Expected 32-byte textual SHA-256 digest for l{id}"
1825            );
1826            let section_slice = payload
1827                .get(section_body_start..section_body_end)
1828                .context("Invalid checksummed section byte span")?;
1829            let actual_digest: [u8; 32] = Sha256::digest(section_slice).into();
1830            ensure!(
1831                actual_digest.as_slice() == decoded_ck.as_slice(),
1832                "Checksum mismatch in .ctbnbdl section for node l{id}"
1833            );
1834            return Ok(LedgerNode {
1835                id,
1836                tokens,
1837                comment: String::new(),
1838                created_ns,
1839            });
1840        }
1841        StreamItem::Token(other) => {
1842            bail!(
1843                "Expected Dc 203 [checksum] after SectionDigest for l{id}, found {other}"
1844            );
1845        }
1846    };
1847
1848    let section_slice = payload
1849        .get(section_body_start..section_body_end)
1850        .context("Invalid checksummed section byte span")?;
1851    let actual_digest: [u8; 32] = Sha256::digest(section_slice).into();
1852    ensure!(
1853        actual_digest.as_slice() == expected_digest_bytes,
1854        "Checksum mismatch in .ctbnbdl section for node l{id}"
1855    );
1856
1857    Ok(LedgerNode {
1858        id,
1859        tokens,
1860        comment: String::new(),
1861        created_ns,
1862    })
1863}
1864
1865fn find_next_record_resync_offset(
1866    payload: &[u8],
1867    from_pos: usize,
1868    is_v2: bool,
1869    framing: CtbnbdlFramingDcs,
1870    checksummed_only: bool,
1871) -> usize {
1872    if !is_v2 || from_pos >= payload.len() {
1873        return payload.len();
1874    }
1875    let mut sec_marker = Vec::with_capacity(8);
1876    if push_dctf_token(&mut sec_marker, framing.begin_checksummed_section)
1877        .is_err()
1878        || sec_marker.is_empty()
1879    {
1880        return payload.len();
1881    }
1882    let mut node_marker = Vec::with_capacity(8);
1883    if !checksummed_only {
1884        let _ = push_dctf_token(&mut node_marker, framing.begin_node);
1885    }
1886
1887    let mut cur = from_pos;
1888    while cur < payload.len() {
1889        // Reason for fallback: cur < payload.len() guarantees cur.. is in-bounds.
1890        let tail = payload.get(cur..).unwrap_or_default();
1891        if tail.starts_with(&sec_marker)
1892            || (!node_marker.is_empty() && tail.starts_with(&node_marker))
1893        {
1894            return cur;
1895        }
1896        cur = cur.saturating_add(1);
1897    }
1898    payload.len()
1899}
1900
1901fn decode_ctbnbdl_bundle_inner(
1902    bytes: &[u8],
1903    framing: CtbnbdlFramingDcs,
1904    resilient: bool,
1905) -> Result<(Option<u128>, Vec<LedgerNode>, Vec<String>)> {
1906    let header_len = CTBNBDL_MAGIC.len().saturating_add(DCMM_HEADER.len());
1907    ensure!(
1908        bytes.len() >= header_len,
1909        ".ctbnbdl buffer is shorter than the {header_len}-byte header ({} bytes)",
1910        bytes.len()
1911    );
1912    // Reason for fallback: bytes.len() >= header_len was just verified above.
1913    let magic_part = bytes.get(..CTBNBDL_MAGIC.len()).unwrap_or_default();
1914    // Reason for fallback: bytes.len() >= header_len was just verified above.
1915    let dcmm_part = bytes
1916        .get(CTBNBDL_MAGIC.len()..header_len)
1917        .unwrap_or_default();
1918    let is_v2 = if magic_part == CTBNBDL_MAGIC {
1919        ensure!(
1920            dcmm_part == DCMM_HEADER,
1921            "Invalid DcMixed2 header in v2 .ctbnbdl buffer"
1922        );
1923        true
1924    } else if magic_part == CTBNBDL_MAGIC_V1 {
1925        ensure!(
1926            dcmm_part == DCMM_HEADER_V1,
1927            "Invalid DcMixed1 header in v1 .ctbnbdl buffer"
1928        );
1929        false
1930    } else {
1931        bail!(
1932            "Invalid .ctbnbdl magic bytes: expected {CTBNBDL_MAGIC:?} or {CTBNBDL_MAGIC_V1:?}, found {magic_part:?}"
1933        );
1934    };
1935
1936    // Reason for fallback: bytes.len() >= header_len was verified above.
1937    let payload = bytes.get(header_len..).unwrap_or_default();
1938    let mut pos = 0usize;
1939    let mut most_recent_node_id = None;
1940    let mut warnings = Vec::new();
1941
1942    if pos < payload.len() {
1943        if let Ok((StreamItem::Token(DC_SYSTEM_BLOCK_MOST_RECENT_NODE_ID), after_641)) =
1944            read_stream_item(payload, pos, is_v2, false)
1945        {
1946            let mut wm_pos = after_641;
1947            match read_atom_dc_from_bytes(payload, &mut wm_pos, is_v2, framing)
1948                .and_then(|wm_sh| wm_sh.to_global_id())
1949            {
1950                Ok(wm_id)
1951                    if (SYSTEM_REGION_START..=SYSTEM_REGION_END)
1952                        .contains(&wm_id) =>
1953                {
1954                    most_recent_node_id = Some(wm_id);
1955                    pos = wm_pos;
1956                }
1957                Ok(wm_id) => {
1958                    let msg = format!(
1959                        "System graph most_recent node ID l{wm_id} in .ctbnbdl is outside the System block ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
1960                    );
1961                    if !resilient {
1962                        bail!("{msg}");
1963                    }
1964                    warnings.push(msg);
1965                    pos = find_next_record_resync_offset(
1966                        payload,
1967                        after_641,
1968                        is_v2,
1969                        framing,
1970                        false,
1971                    );
1972                }
1973                Err(err) => {
1974                    if !resilient {
1975                        return Err(err.context(
1976                            "Invalid or missing [atom_dc] node ID after Dc 641 in .ctbnbdl",
1977                        ));
1978                    }
1979                    warnings.push(format!(
1980                        "Corrupted Dc 641 header pin at byte offset {}: {err:#}",
1981                        header_len.saturating_add(pos)
1982                    ));
1983                    pos = find_next_record_resync_offset(
1984                        payload,
1985                        after_641,
1986                        is_v2,
1987                        framing,
1988                        false,
1989                    );
1990                }
1991            }
1992        }
1993    }
1994
1995    let mut sec_marker = Vec::with_capacity(8);
1996    if is_v2 {
1997        let _ = push_dctf_token(
1998            &mut sec_marker,
1999            framing.begin_checksummed_section,
2000        );
2001    }
2002    let mut saw_checksummed_section = false;
2003    let mut nodes = Vec::new();
2004    while pos < payload.len() {
2005        let rec_start = pos;
2006        // Reason for fallback: rec_start < payload.len() guarantees rec_start.. is in-bounds.
2007        let starts_with_sec = !sec_marker.is_empty()
2008            && payload
2009                .get(rec_start..)
2010                .unwrap_or_default()
2011                .starts_with(&sec_marker);
2012        if starts_with_sec {
2013            saw_checksummed_section = true;
2014        }
2015        match parse_node_record_at(payload, &mut pos, is_v2, framing) {
2016            Ok(node) => nodes.push(node),
2017            Err(err) => {
2018                if !resilient {
2019                    return Err(err);
2020                }
2021                warnings.push(format!(
2022                    "Quarantined corrupted .ctbnbdl node section at byte offset {}: {err:#}",
2023                    header_len.saturating_add(rec_start)
2024                ));
2025                pos = find_next_record_resync_offset(
2026                    payload,
2027                    rec_start.saturating_add(1),
2028                    is_v2,
2029                    framing,
2030                    saw_checksummed_section,
2031                );
2032            }
2033        }
2034    }
2035
2036    Ok((most_recent_node_id, nodes, warnings))
2037}
2038
2039/// Decodes a `.ctbnbdl` (`CtbNodeBundle1` or `CtbNodeBundle2`) binary buffer into its optional
2040/// leading `Dc 641` system block most recent node ID and its list of `LedgerNode` entries,
2041/// strictly verifying every `Dc 543..544 545` section digest.
2042pub fn decode_ctbnbdl_bundle_with(
2043    bytes: &[u8],
2044    framing: CtbnbdlFramingDcs,
2045) -> Result<(Option<u128>, Vec<LedgerNode>)> {
2046    let (most_recent_node_id, nodes, _) =
2047        decode_ctbnbdl_bundle_inner(bytes, framing, false)?;
2048    Ok((most_recent_node_id, nodes))
2049}
2050
2051/// Resiliently decodes a `.ctbnbdl` (`CtbNodeBundle1` or `CtbNodeBundle2`) binary buffer,
2052/// quarantining any corrupted or checksum-mismatched node section while recovering all
2053/// remaining valid nodes and returning diagnostic warnings for every skipped section.
2054pub fn decode_ctbnbdl_bundle_resilient_with(
2055    bytes: &[u8],
2056    framing: CtbnbdlFramingDcs,
2057) -> Result<(Option<u128>, Vec<LedgerNode>, Vec<String>)> {
2058    decode_ctbnbdl_bundle_inner(bytes, framing, true)
2059}
2060
2061/// Decodes a `.ctbnbdl` (`CtbNodeBundle1` or `CtbNodeBundle2`) binary buffer back into a list of
2062/// `LedgerNode` entries (with empty comments, as `.ctbnbdl` stores only the semantic Dc stream).
2063pub fn decode_nodes_from_ctbnbdl_bytes_with(
2064    bytes: &[u8],
2065    framing: CtbnbdlFramingDcs,
2066) -> Result<Vec<LedgerNode>> {
2067    let (_most_recent, nodes) = decode_ctbnbdl_bundle_with(bytes, framing)?;
2068    Ok(nodes)
2069}
2070
2071/// Parses a `.ctbnodes` file on disk and compiles its node definitions into `.ctbnbdl` bytes.
2072pub fn compile_ctbnodes_file_to_ctbnbdl_bytes(
2073    path: &Path,
2074    framing: CtbnbdlFramingDcs,
2075) -> Result<Vec<u8>> {
2076    let nodes = load_ledger_nodes_from_file(path)?;
2077    encode_nodes_to_ctbnbdl_bytes_with(&nodes, framing)
2078}
2079
2080/// Splits a slice of `LedgerNode` entries into one or more `.ctbnbdl` bundle buffers,
2081/// each paired with its starting node ID (`(first_node_id, bundle_bytes)`), stamping each
2082/// bundle with the provided `most_recent_node_id` (`Dc 641 l<most_recent_node_id>`).
2083pub fn encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
2084    nodes: &[LedgerNode],
2085    framing: CtbnbdlFramingDcs,
2086    max_nodes_per_bundle: usize,
2087    max_bytes_per_bundle: usize,
2088    most_recent_node_id: Option<u128>,
2089) -> Result<Vec<(u128, Vec<u8>)>> {
2090    ensure!(
2091        max_nodes_per_bundle > 0,
2092        "max_nodes_per_bundle must be greater than 0"
2093    );
2094    let header_bytes = encode_ctbnbdl_header_bytes(most_recent_node_id, framing)?;
2095    let header_len = header_bytes.len();
2096    ensure!(
2097        max_bytes_per_bundle > header_len,
2098        "max_bytes_per_bundle ({max_bytes_per_bundle}) must exceed the {header_len}-byte .ctbnbdl header"
2099    );
2100    if nodes.is_empty() {
2101        return Ok(Vec::new());
2102    }
2103
2104    let max_nodes_u128 =
2105        u128::try_from(max_nodes_per_bundle).unwrap_or(1_000_000);
2106    let mut bundles: Vec<(u128, Vec<u8>)> = Vec::new();
2107    let mut current_first_id: Option<u128> = None;
2108    let mut current_bucket: u128 = 0;
2109    let mut current_bytes: Vec<u8> = Vec::new();
2110
2111    for node in nodes {
2112        let node_bytes = encode_node_definition_dcmm2_bytes_with(node, framing)?;
2113        ensure!(
2114            header_len.saturating_add(node_bytes.len()) <= max_bytes_per_bundle,
2115            "Single encoded node l{} ({} bytes + {header_len}-byte header) exceeds max_bytes_per_bundle ({max_bytes_per_bundle})",
2116            node.id,
2117            node_bytes.len()
2118        );
2119
2120        let bucket = node
2121            .id
2122            .saturating_sub(SYSTEM_REGION_START)
2123            .checked_div(max_nodes_u128)
2124            .unwrap_or(0);
2125
2126        if let Some(first_id) = current_first_id {
2127            let crosses_bucket = bucket != current_bucket;
2128            let exceeds_bytes =
2129                current_bytes.len().saturating_add(node_bytes.len())
2130                    > max_bytes_per_bundle;
2131            if crosses_bucket || exceeds_bytes {
2132                bundles.push((first_id, std::mem::take(&mut current_bytes)));
2133                current_first_id = None;
2134            }
2135        }
2136
2137        if current_first_id.is_none() {
2138            current_first_id = Some(node.id);
2139            current_bucket = bucket;
2140            current_bytes.extend_from_slice(&header_bytes);
2141        }
2142        current_bytes.extend_from_slice(&node_bytes);
2143    }
2144
2145    if let Some(first_id) = current_first_id {
2146        bundles.push((first_id, current_bytes));
2147    }
2148
2149    Ok(bundles)
2150}
2151
2152/// Splits a slice of `LedgerNode` entries into one or more `.ctbnbdl` bundle buffers,
2153/// each paired with its starting node ID (`(first_node_id, bundle_bytes)`).
2154///
2155/// Bundles group up to `max_nodes_per_bundle` nodes or `max_bytes_per_bundle` bytes
2156/// (whichever is reached first). If a bundle must split early due to the byte limit,
2157/// the subsequent bundle is shortened so that bundle boundaries still align at
2158/// multiples of `max_nodes_per_bundle` relative to `SYSTEM_REGION_START`.
2159pub fn encode_nodes_to_ctbnbdl_bundles_with_limits(
2160    nodes: &[LedgerNode],
2161    framing: CtbnbdlFramingDcs,
2162    max_nodes_per_bundle: usize,
2163    max_bytes_per_bundle: usize,
2164) -> Result<Vec<(u128, Vec<u8>)>> {
2165    encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
2166        nodes,
2167        framing,
2168        max_nodes_per_bundle,
2169        max_bytes_per_bundle,
2170        nodes.iter().map(|n| n.id).max(),
2171    )
2172}
2173
2174/// Returns `true` if `tok` is one of the canonical relationship verbs in `framing`.
2175#[must_use]
2176pub fn is_relationship_verb_with(
2177    tok: DcShorthand,
2178    framing: CtbnbdlFramingDcs,
2179) -> bool {
2180    tok == framing.has_a
2181        || tok == framing.is_instance_of
2182        || tok == framing.is_subtype_of
2183        || tok == framing.is_based_on
2184        || tok == framing.is_deprecated
2185        || tok == framing.is_closing_delimiter_for
2186        || tok == framing.supersedes
2187        || tok == framing.retracts
2188        || tok == framing.is_associated_with
2189        || tok == framing.has_value
2190        || tok == DcShorthand::Short(645)
2191        || tok == DcShorthand::Short(646)
2192}
2193
2194/// Parses a relationship statement `<verb> [atom_dc] [atom_dc]` back into `(verb, subj, obj)`.
2195#[must_use]
2196pub fn parse_statement_tokens_with(
2197    tokens: &[DcShorthand],
2198    framing: CtbnbdlFramingDcs,
2199) -> Option<(DcShorthand, DcShorthand, DcShorthand)> {
2200    let verb = *tokens.first()?;
2201    if !is_relationship_verb_with(verb, framing) {
2202        return None;
2203    }
2204    let mut idx = 1usize;
2205    let subj = consume_atom_dc_with(tokens, &mut idx, framing)?;
2206    let obj = consume_atom_dc_with(tokens, &mut idx, framing)?;
2207    if idx == tokens.len() {
2208        Some((verb, subj, obj))
2209    } else {
2210        None
2211    }
2212}
2213
2214/// Encodes a `Dc 638 "For each"` relationship statement over a typed list of `[atom_dc]` targets:
2215/// `638 <inner_verb> [atom_dc: <inner_subj>] [atom_dc: <inner_obj>] 310 <list_type> <t_1> [312 <t_2> ...] 311`.
2216#[must_use]
2217pub fn encode_for_each_statement_tokens_with(
2218    inner_verb: DcShorthand,
2219    inner_subj: DcShorthand,
2220    inner_obj: DcShorthand,
2221    list_type: DcShorthand,
2222    targets: &[DcShorthand],
2223    framing: CtbnbdlFramingDcs,
2224) -> Vec<DcShorthand> {
2225    let mut out =
2226        Vec::with_capacity(targets.len().saturating_mul(2).saturating_add(7));
2227    out.push(DcShorthand::Short(638));
2228    out.push(inner_verb);
2229    push_atom_dc_with(&mut out, inner_subj, framing);
2230    push_atom_dc_with(&mut out, inner_obj, framing);
2231    out.push(DcShorthand::Short(310));
2232    out.push(list_type);
2233    for (i, &target) in targets.iter().enumerate() {
2234        if i > 0 {
2235            out.push(DcShorthand::Short(312));
2236        }
2237        push_atom_dc_with(&mut out, target, framing);
2238    }
2239    out.push(DcShorthand::Short(311));
2240    out
2241}
2242
2243/// Parses a `Dc 638 "For each"` relationship statement node
2244/// (`638 <inner_verb> <inner_subj> <inner_obj> (310 <list_type> <elem_1> [312 <elem_2> ...] 311 | <atom_dc>)`)
2245/// into `(inner_verb, inner_subj, inner_obj, list_type, expanded_targets)`.
2246#[must_use]
2247pub fn parse_for_each_statement_tokens_with(
2248    tokens: &[DcShorthand],
2249    framing: CtbnbdlFramingDcs,
2250) -> Option<(
2251    DcShorthand,
2252    DcShorthand,
2253    DcShorthand,
2254    DcShorthand,
2255    Vec<DcShorthand>,
2256)> {
2257    if tokens.first() != Some(&DcShorthand::Short(638)) {
2258        return None;
2259    }
2260    let inner_verb = *tokens.get(1)?;
2261    if !is_relationship_verb_with(inner_verb, framing) {
2262        return None;
2263    }
2264    let mut idx = 2usize;
2265    let inner_subj = consume_atom_dc_with(tokens, &mut idx, framing)?;
2266    let inner_obj = consume_atom_dc_with(tokens, &mut idx, framing)?;
2267
2268    if tokens.get(idx) == Some(&DcShorthand::Short(310)) {
2269        idx = idx.saturating_add(1);
2270        let list_type = *tokens.get(idx)?;
2271        idx = idx.saturating_add(1);
2272        let end_idx = tokens.len().checked_sub(1)?;
2273        if idx >= end_idx
2274            || tokens.get(end_idx) != Some(&DcShorthand::Short(311))
2275        {
2276            return None;
2277        }
2278        let mut targets = Vec::new();
2279        while idx < end_idx {
2280            if tokens.get(idx) == Some(&DcShorthand::Short(4)) {
2281                idx = idx.saturating_add(1);
2282                let start_tok =
2283                    consume_atom_dc_with(tokens, &mut idx, framing)?;
2284                let end_tok = consume_atom_dc_with(tokens, &mut idx, framing)?;
2285                match (start_tok, end_tok) {
2286                    (DcShorthand::Long(s), DcShorthand::Long(e))
2287                        if s <= e && e.saturating_sub(s) <= 1_000_000 =>
2288                    {
2289                        for id in s..=e {
2290                            targets.push(DcShorthand::Long(id));
2291                        }
2292                    }
2293                    (DcShorthand::Short(s), DcShorthand::Short(e))
2294                        if s <= e =>
2295                    {
2296                        for id in s..=e {
2297                            targets.push(DcShorthand::Short(id));
2298                        }
2299                    }
2300                    _ => return None,
2301                }
2302            } else {
2303                let elem = consume_atom_dc_with(tokens, &mut idx, framing)?;
2304                targets.push(elem);
2305            }
2306            if idx > end_idx {
2307                return None;
2308            }
2309            if idx < end_idx {
2310                if tokens.get(idx) != Some(&DcShorthand::Short(312)) {
2311                    return None;
2312                }
2313                idx = idx.saturating_add(1);
2314                if idx >= end_idx {
2315                    return None;
2316                }
2317            }
2318        }
2319        if targets.is_empty() {
2320            None
2321        } else {
2322            Some((inner_verb, inner_subj, inner_obj, list_type, targets))
2323        }
2324    } else {
2325        let elem = consume_atom_dc_with(tokens, &mut idx, framing)?;
2326        if idx == tokens.len() {
2327            Some((
2328                inner_verb,
2329                inner_subj,
2330                inner_obj,
2331                DcShorthand::Short(640),
2332                vec![elem],
2333            ))
2334        } else {
2335            None
2336        }
2337    }
2338}
2339
2340/// Partitions an ordered slice of `LedgerNode` entries into `(active_nodes, inactive_nodes)`
2341/// preserving ascending node ID order in both output vectors.
2342///
2343/// Inactive nodes include:
2344/// 1. Any node targeted by an active `591 <new_id> l<old_id>` (`Supersedes`) or
2345///    `592 615 l<old_id>` (`Retracts`) statement.
2346/// 2. All `591` (`Supersedes`) and `592` (`Retracts`) revision/retraction statements themselves.
2347/// 3. Any `610 l<has_a_id> <val>` (`Has value`) or `584 l<has_a_id> 570` (`Has a Preferred`)
2348///    statement whose subject `has_a_id` is inactive, or any `584 <subj> <prop>` (`prop != 570`)
2349///    statement that has no active `610` value statement.
2350/// 4. Any non-statement value node that is transitively referenced by an inactive statement
2351///    and is not transitively referenced by any active statement.
2352#[must_use]
2353pub fn partition_active_and_inactive_nodes_with(
2354    nodes: &[LedgerNode],
2355    framing: CtbnbdlFramingDcs,
2356) -> (Vec<LedgerNode>, Vec<LedgerNode>) {
2357    use std::collections::{HashMap, HashSet};
2358
2359    let mut node_by_id: HashMap<u128, &LedgerNode> =
2360        HashMap::with_capacity(nodes.len());
2361    for node in nodes {
2362        node_by_id.insert(node.id, node);
2363    }
2364
2365    // Pass 1: Reverse chronological pass to identify superseded and retracted node IDs,
2366    // as well as all `591` (`Supersedes`) and `592` (`Retracts`) revision statement IDs.
2367    let mut superseded_or_retracted_ids: HashSet<u128> = HashSet::new();
2368    let mut revision_stmt_ids: HashSet<u128> = HashSet::new();
2369    for node in nodes.iter().rev() {
2370        let Some((verb, subj, obj)) =
2371            parse_statement_tokens_with(&node.tokens, framing)
2372        else {
2373            continue;
2374        };
2375        if verb == framing.supersedes {
2376            revision_stmt_ids.insert(node.id);
2377            if !superseded_or_retracted_ids.contains(&node.id) {
2378                if let DcShorthand::Long(old_id) = obj {
2379                    superseded_or_retracted_ids.insert(old_id);
2380                }
2381            }
2382        } else if verb == framing.retracts && subj == framing.enclosing_document
2383        {
2384            revision_stmt_ids.insert(node.id);
2385            if !superseded_or_retracted_ids.contains(&node.id) {
2386                if let DcShorthand::Long(old_id) = obj {
2387                    superseded_or_retracted_ids.insert(old_id);
2388                }
2389            }
2390        }
2391    }
2392
2393    // Pass 2: Identify active vs. inactive statement nodes.
2394    let mut has_a_with_active_value: HashSet<u128> = HashSet::new();
2395    for node in nodes {
2396        if superseded_or_retracted_ids.contains(&node.id)
2397            || revision_stmt_ids.contains(&node.id)
2398        {
2399            continue;
2400        }
2401        if let Some((verb, DcShorthand::Long(has_a_id), _val)) =
2402            parse_statement_tokens_with(&node.tokens, framing)
2403        {
2404            if verb == framing.has_value
2405                && !superseded_or_retracted_ids.contains(&has_a_id)
2406            {
2407                has_a_with_active_value.insert(has_a_id);
2408            }
2409        }
2410    }
2411
2412    let mut active_stmt_ids: HashSet<u128> = HashSet::new();
2413    let mut inactive_stmt_ids: HashSet<u128> = HashSet::new();
2414    let mut provenance_stmt_ids: HashSet<u128> = HashSet::new();
2415    let sh_data_source = DcShorthand::Short(635);
2416    for node in nodes {
2417        if let Some((inner_verb, _, inner_obj, _, _)) =
2418            parse_for_each_statement_tokens_with(&node.tokens, framing)
2419        {
2420            if inner_verb == framing.has_a && inner_obj == sh_data_source {
2421                provenance_stmt_ids.insert(node.id);
2422            }
2423            let is_active = if superseded_or_retracted_ids.contains(&node.id)
2424                || revision_stmt_ids.contains(&node.id)
2425            {
2426                false
2427            } else if inner_verb == framing.has_a
2428                && inner_obj != framing.preferred
2429            {
2430                has_a_with_active_value.contains(&node.id)
2431            } else {
2432                true
2433            };
2434            if is_active {
2435                active_stmt_ids.insert(node.id);
2436            } else {
2437                inactive_stmt_ids.insert(node.id);
2438            }
2439            continue;
2440        }
2441
2442        let Some((verb, subj, obj)) =
2443            parse_statement_tokens_with(&node.tokens, framing)
2444        else {
2445            continue;
2446        };
2447        if verb == framing.has_a && obj == sh_data_source {
2448            provenance_stmt_ids.insert(node.id);
2449        } else if verb == framing.has_value {
2450            if let DcShorthand::Long(target_id) = subj
2451                && provenance_stmt_ids.contains(&target_id)
2452            {
2453                provenance_stmt_ids.insert(node.id);
2454            }
2455        }
2456        let is_active = if superseded_or_retracted_ids.contains(&node.id)
2457            || revision_stmt_ids.contains(&node.id)
2458        {
2459            false
2460        } else if verb == framing.has_value {
2461            matches!(
2462                subj,
2463                DcShorthand::Long(has_a_id)
2464                    if !superseded_or_retracted_ids.contains(&has_a_id)
2465            )
2466        } else if verb == framing.has_a && obj == framing.preferred {
2467            matches!(
2468                subj,
2469                DcShorthand::Long(has_a_id)
2470                    if !superseded_or_retracted_ids.contains(&has_a_id)
2471                        && has_a_with_active_value.contains(&has_a_id)
2472            )
2473        } else if verb == framing.has_a {
2474            has_a_with_active_value.contains(&node.id)
2475        } else {
2476            true
2477        };
2478        if is_active {
2479            active_stmt_ids.insert(node.id);
2480        } else {
2481            inactive_stmt_ids.insert(node.id);
2482        }
2483    }
2484
2485    // Pass 3: Compute transitive reachability of `DcShorthand::Long(id)` value nodes from
2486    // active domain statements and from inactive domain statements.
2487    // Note: Provenance metadata statements (`638` / `584 _ 635` and their `610` values)
2488    // do not keep otherwise-unreferenced value nodes alive when their domain statement is retracted.
2489    let collect_reachable = |seed_stmt_ids: &HashSet<u128>| -> HashSet<u128> {
2490        let mut reachable: HashSet<u128> = HashSet::new();
2491        let mut worklist: Vec<u128> = Vec::new();
2492        for &stmt_id in seed_stmt_ids {
2493            if provenance_stmt_ids.contains(&stmt_id) {
2494                continue;
2495            }
2496            if let Some(stmt_node) = node_by_id.get(&stmt_id) {
2497                for &tok in &stmt_node.tokens {
2498                    if let DcShorthand::Long(ref_id) = tok {
2499                        worklist.push(ref_id);
2500                    }
2501                }
2502            }
2503        }
2504        while let Some(ref_id) = worklist.pop() {
2505            if active_stmt_ids.contains(&ref_id)
2506                || inactive_stmt_ids.contains(&ref_id)
2507                || superseded_or_retracted_ids.contains(&ref_id)
2508                || revision_stmt_ids.contains(&ref_id)
2509                || provenance_stmt_ids.contains(&ref_id)
2510            {
2511                continue;
2512            }
2513            if reachable.insert(ref_id) {
2514                if let Some(ref_node) = node_by_id.get(&ref_id) {
2515                    for &tok in &ref_node.tokens {
2516                        if let DcShorthand::Long(inner_id) = tok {
2517                            worklist.push(inner_id);
2518                        }
2519                    }
2520                }
2521            }
2522        }
2523        reachable
2524    };
2525
2526    let reachable_from_active = collect_reachable(&active_stmt_ids);
2527    let reachable_from_inactive = collect_reachable(&inactive_stmt_ids);
2528
2529    // Pass 4: Partition `nodes` in ascending ID order.
2530    let mut active_nodes = Vec::with_capacity(nodes.len());
2531    let mut inactive_nodes = Vec::new();
2532    for node in nodes {
2533        let is_active = if active_stmt_ids.contains(&node.id) {
2534            true
2535        } else if inactive_stmt_ids.contains(&node.id)
2536            || superseded_or_retracted_ids.contains(&node.id)
2537        {
2538            false
2539        } else if reachable_from_active.contains(&node.id) {
2540            true
2541        } else {
2542            !reachable_from_inactive.contains(&node.id)
2543        };
2544        if is_active {
2545            active_nodes.push(node.clone());
2546        } else {
2547            inactive_nodes.push(node.clone());
2548        }
2549    }
2550
2551    (active_nodes, inactive_nodes)
2552}
2553
2554fn write_bytes_if_changed(path: &Path, bytes: &[u8]) -> Result<bool> {
2555    use std::io::Write;
2556
2557    if path.is_file() {
2558        if let Ok(existing) = std::fs::read(path) {
2559            if existing == bytes {
2560                return Ok(false);
2561            }
2562            if let Some(tail) = bytes.strip_prefix(existing.as_slice()) {
2563                let mut file = std::fs::OpenOptions::new()
2564                    .append(true)
2565                    .open(path)
2566                    .with_context(|| {
2567                        format!(
2568                            "Failed to open {} in append mode",
2569                            path.display()
2570                        )
2571                    })?;
2572                file.write_all(tail).with_context(|| {
2573                    format!(
2574                        "Failed to append {} bytes to {}",
2575                        tail.len(),
2576                        path.display()
2577                    )
2578                })?;
2579                return Ok(true);
2580            }
2581        }
2582    }
2583    if let Some(parent) = path.parent() {
2584        std::fs::create_dir_all(parent).with_context(|| {
2585            format!("Failed to create directory {}", parent.display())
2586        })?;
2587    }
2588    std::fs::write(path, bytes).with_context(|| {
2589        format!("Failed to write .ctbnbdl file {}", path.display())
2590    })?;
2591    Ok(true)
2592}
2593
2594fn write_ctbnbdl_bundles_to_dir(
2595    dst_dir: &Path,
2596    bundles: &[(u128, Vec<u8>)],
2597    remove_stale_ctbnodes: bool,
2598) -> Result<usize> {
2599    std::fs::create_dir_all(dst_dir).with_context(|| {
2600        format!(
2601            "Failed to create destination directory {}",
2602            dst_dir.display()
2603        )
2604    })?;
2605
2606    let mut expected_bundle_names =
2607        std::collections::HashSet::with_capacity(bundles.len());
2608    let mut compiled_count = 0usize;
2609    for (first_id, bytes) in bundles {
2610        let filename = format_chunk_bundle_filename(*first_id);
2611        let dst_path = dst_dir.join(&filename);
2612        expected_bundle_names.insert(filename);
2613        if write_bytes_if_changed(&dst_path, bytes)? {
2614            compiled_count = compiled_count.saturating_add(1);
2615        }
2616    }
2617
2618    for entry in std::fs::read_dir(dst_dir).with_context(|| {
2619        format!("Failed to read destination directory {}", dst_dir.display())
2620    })? {
2621        let entry = entry?;
2622        let path = entry.path();
2623        if !path.is_file() {
2624            continue;
2625        }
2626        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
2627            continue;
2628        };
2629        let ext = path.extension().and_then(|e| e.to_str());
2630        if (remove_stale_ctbnodes && ext == Some("ctbnodes"))
2631            || (ext == Some("ctbnbdl") && !expected_bundle_names.contains(name))
2632        {
2633            std::fs::remove_file(&path).with_context(|| {
2634                format!("Failed to remove stale file {}", path.display())
2635            })?;
2636        }
2637    }
2638
2639    Ok(compiled_count)
2640}
2641
2642/// Compiles all `.ctbnodes` chunk files in `src_dir` into:
2643/// 1. Unsplit append-friendly `.ctbnbdl` bundle files directly in `bundles_dir`
2644///    (containing all `LedgerNode`s in ascending ID order without a `Dc 641` watermark header,
2645///    so newly appended nodes extend the tail of the bundle without rewriting invalidated entries),
2646/// 2. Live (active) `.ctbnbdl` bundle files in `bundles_dir/split/live/` (with `Dc 641` watermark), and
2647/// 3. Historical (inactive) `.ctbnbdl` bundle files in `bundles_dir/split/history/` (with `Dc 641` watermark).
2648///
2649/// Returns `(unsplit_written, live_written, history_written)`.
2650pub fn compile_graph_bundles_from_ctbnodes_dir_with_limits(
2651    src_dir: &Path,
2652    bundles_dir: &Path,
2653    framing: CtbnbdlFramingDcs,
2654    max_nodes_per_bundle: usize,
2655    max_bytes_per_bundle: usize,
2656) -> Result<(usize, usize, usize)> {
2657    if !src_dir.is_dir() {
2658        return Ok((0, 0, 0));
2659    }
2660    let nodes = load_ledger_nodes_from_dir(src_dir)?;
2661    let unsplit_bundles =
2662        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
2663            &nodes,
2664            framing,
2665            max_nodes_per_bundle,
2666            max_bytes_per_bundle,
2667            None,
2668        )?;
2669    let unsplit_written =
2670        write_ctbnbdl_bundles_to_dir(bundles_dir, &unsplit_bundles, true)?;
2671
2672    let most_recent_node_id = nodes.iter().map(|n| n.id).max();
2673    let (active_nodes, inactive_nodes) =
2674        partition_active_and_inactive_nodes_with(&nodes, framing);
2675    let active_bundles =
2676        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
2677            &active_nodes,
2678            framing,
2679            max_nodes_per_bundle,
2680            max_bytes_per_bundle,
2681            most_recent_node_id,
2682        )?;
2683    let inactive_bundles =
2684        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
2685            &inactive_nodes,
2686            framing,
2687            max_nodes_per_bundle,
2688            max_bytes_per_bundle,
2689            most_recent_node_id,
2690        )?;
2691
2692    let split_live_dir = bundles_dir.join(GRAPH_BUNDLES_SPLIT_LIVE_SUBDIR);
2693    let live_written =
2694        write_ctbnbdl_bundles_to_dir(&split_live_dir, &active_bundles, true)?;
2695    let split_history_dir =
2696        bundles_dir.join(GRAPH_BUNDLES_SPLIT_HISTORY_SUBDIR);
2697    let history_written = write_ctbnbdl_bundles_to_dir(
2698        &split_history_dir,
2699        &inactive_bundles,
2700        true,
2701    )?;
2702
2703    Ok((unsplit_written, live_written, history_written))
2704}
2705
2706/// Same as [`compile_graph_bundles_from_ctbnodes_dir_with_limits`] using default
2707/// `MAX_NODES_PER_BUNDLE` and `MAX_BYTES_PER_BUNDLE` limits.
2708pub fn compile_graph_bundles_from_ctbnodes_dir(
2709    src_dir: &Path,
2710    bundles_dir: &Path,
2711    framing: CtbnbdlFramingDcs,
2712) -> Result<(usize, usize, usize)> {
2713    compile_graph_bundles_from_ctbnodes_dir_with_limits(
2714        src_dir,
2715        bundles_dir,
2716        framing,
2717        MAX_NODES_PER_BUNDLE,
2718        MAX_BYTES_PER_BUNDLE,
2719    )
2720}
2721
2722/// Compiles all `.ctbnodes` chunk files in `src_dir` into grouped active `.ctbnbdl` bundle files
2723/// in `dst_dir` using custom node-count and byte-size limits, removing any stale `.ctbnodes`
2724/// or obsolete `.ctbnbdl` files in `dst_dir`.
2725///
2726/// When `src_dir == dst_dir` (e.g., `assets/data/graph`), this delegates to
2727/// [`compile_graph_bundles_from_ctbnodes_dir_with_limits`] targeting
2728/// `bundles_dir_for_graph_dir(src_dir)` (`assets/data/graph-bundles/` and `split/{live,history}/`).
2729///
2730/// Returns the number of primary `.ctbnbdl` files written or updated.
2731pub fn compile_ctbnodes_dir_to_ctbnbdl_with_limits(
2732    src_dir: &Path,
2733    dst_dir: &Path,
2734    framing: CtbnbdlFramingDcs,
2735    max_nodes_per_bundle: usize,
2736    max_bytes_per_bundle: usize,
2737) -> Result<usize> {
2738    if !src_dir.is_dir() {
2739        return Ok(0);
2740    }
2741
2742    let is_same_dir = if let (Ok(c_src), Ok(c_dst)) =
2743        (src_dir.canonicalize(), dst_dir.canonicalize())
2744    {
2745        c_src == c_dst
2746    } else {
2747        src_dir == dst_dir
2748    };
2749
2750    if is_same_dir {
2751        let bundles_dir = bundles_dir_for_graph_dir(src_dir);
2752        let (unsplit_written, _, _) =
2753            compile_graph_bundles_from_ctbnodes_dir_with_limits(
2754                src_dir,
2755                &bundles_dir,
2756                framing,
2757                max_nodes_per_bundle,
2758                max_bytes_per_bundle,
2759            )?;
2760        return Ok(unsplit_written);
2761    }
2762
2763    std::fs::create_dir_all(dst_dir).with_context(|| {
2764        format!(
2765            "Failed to create destination directory {}",
2766            dst_dir.display()
2767        )
2768    })?;
2769
2770    let nodes = load_ledger_nodes_from_dir(src_dir)?;
2771    let most_recent_node_id = nodes.iter().map(|n| n.id).max();
2772    let (active_nodes, _inactive_nodes) =
2773        partition_active_and_inactive_nodes_with(&nodes, framing);
2774
2775    let active_bundles =
2776        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
2777            &active_nodes,
2778            framing,
2779            max_nodes_per_bundle,
2780            max_bytes_per_bundle,
2781            most_recent_node_id,
2782        )?;
2783    write_ctbnbdl_bundles_to_dir(dst_dir, &active_bundles, true)
2784}
2785
2786/// Compiles all `.ctbnodes` chunk files in `src_dir` into grouped active `.ctbnbdl` bundle files
2787/// in `dst_dir` (up to `MAX_NODES_PER_BUNDLE` = 1,000,000 nodes or `MAX_BYTES_PER_BUNDLE` = 50 MB
2788/// per bundle), removing any stale `.ctbnodes` or obsolete `.ctbnbdl` files in `dst_dir`.
2789///
2790/// When `src_dir == dst_dir` (e.g., `assets/data/graph`), this also compiles all filtered-out
2791/// inactive (superseded/retracted) nodes into `dst_dir.join("system")`.
2792///
2793/// Returns the number of active `.ctbnbdl` files written or updated in `dst_dir`.
2794pub fn compile_ctbnodes_dir_to_ctbnbdl(
2795    src_dir: &Path,
2796    dst_dir: &Path,
2797    framing: CtbnbdlFramingDcs,
2798) -> Result<usize> {
2799    compile_ctbnodes_dir_to_ctbnbdl_with_limits(
2800        src_dir,
2801        dst_dir,
2802        framing,
2803        MAX_NODES_PER_BUNDLE,
2804        MAX_BYTES_PER_BUNDLE,
2805    )
2806}
2807
2808/// Compiles all filtered-out inactive (superseded/retracted) nodes from `.ctbnodes` chunk files
2809/// in `src_dir` into grouped `.ctbnbdl` bundle files in `history_dst_dir` using custom
2810/// node-count and byte-size limits.
2811///
2812/// Returns the number of `.ctbnbdl` files written or updated in `history_dst_dir`.
2813pub fn compile_inactive_ctbnodes_dir_to_ctbnbdl_with_limits(
2814    src_dir: &Path,
2815    history_dst_dir: &Path,
2816    framing: CtbnbdlFramingDcs,
2817    max_nodes_per_bundle: usize,
2818    max_bytes_per_bundle: usize,
2819) -> Result<usize> {
2820    if !src_dir.is_dir() {
2821        return Ok(0);
2822    }
2823    let nodes = load_ledger_nodes_from_dir(src_dir)?;
2824    let most_recent_node_id = nodes.iter().map(|n| n.id).max();
2825    let (_active_nodes, inactive_nodes) =
2826        partition_active_and_inactive_nodes_with(&nodes, framing);
2827    let inactive_bundles =
2828        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
2829            &inactive_nodes,
2830            framing,
2831            max_nodes_per_bundle,
2832            max_bytes_per_bundle,
2833            most_recent_node_id,
2834        )?;
2835    write_ctbnbdl_bundles_to_dir(history_dst_dir, &inactive_bundles, true)
2836}
2837
2838/// Compiles all filtered-out inactive (superseded/retracted) nodes from `.ctbnodes` chunk files
2839/// in `src_dir` into grouped `.ctbnbdl` bundle files in `history_dst_dir` (up to
2840/// `MAX_NODES_PER_BUNDLE` = 1,000,000 nodes or `MAX_BYTES_PER_BUNDLE` = 50 MB per bundle).
2841///
2842/// Returns the number of `.ctbnbdl` files written or updated in `history_dst_dir`.
2843pub fn compile_inactive_ctbnodes_dir_to_ctbnbdl(
2844    src_dir: &Path,
2845    history_dst_dir: &Path,
2846    framing: CtbnbdlFramingDcs,
2847) -> Result<usize> {
2848    compile_inactive_ctbnodes_dir_to_ctbnbdl_with_limits(
2849        src_dir,
2850        history_dst_dir,
2851        framing,
2852        MAX_NODES_PER_BUNDLE,
2853        MAX_BYTES_PER_BUNDLE,
2854    )
2855}
2856
2857#[cfg(test)]
2858#[allow(
2859    clippy::panic,
2860    clippy::expect_used,
2861    clippy::unwrap_used,
2862    clippy::unwrap_in_result,
2863    clippy::panic_in_result_fn,
2864    clippy::indexing_slicing,
2865    clippy::arithmetic_side_effects,
2866    reason = "Standard repository test boilerplate"
2867)]
2868mod tests {
2869    use super::*;
2870
2871    fn test_framing() -> CtbnbdlFramingDcs {
2872        CtbnbdlFramingDcs {
2873            begin_node: DcShorthand::Short(617),
2874            end_node: DcShorthand::Short(618),
2875            begin_checksummed_section: DcShorthand::Short(543),
2876            end_checksummed_section: DcShorthand::Short(544),
2877            section_digest: DcShorthand::Short(545),
2878            begin_time_moment: DcShorthand::Short(390),
2879            end_time_moment: DcShorthand::Short(391),
2880            section_node_creation_time: Some(DcShorthand::Short(1941)),
2881            ns_since_epoch_format: DcShorthand::Format(487),
2882            sha256_format: DcShorthand::Format(245),
2883            escape: DcShorthand::Short(255),
2884            evaluate_as_atom: DcShorthand::Short(616),
2885            has_a: DcShorthand::Short(584),
2886            has_value: DcShorthand::Short(610),
2887            preferred: DcShorthand::Short(570),
2888            supersedes: DcShorthand::Short(591),
2889            retracts: DcShorthand::Short(592),
2890            enclosing_document: DcShorthand::Short(615),
2891            is_instance_of: DcShorthand::Short(586),
2892            is_subtype_of: DcShorthand::Short(587),
2893            is_based_on: DcShorthand::Short(588),
2894            is_deprecated: DcShorthand::Short(589),
2895            is_closing_delimiter_for: DcShorthand::Short(590),
2896            is_associated_with: DcShorthand::Short(605),
2897        }
2898    }
2899
2900    #[test]
2901    fn test_ctbnbdl_roundtrips_standalone_and_encapsulated_dc203() -> Result<()> {
2902        let framing = test_framing();
2903        let node = LedgerNode {
2904            id: SYSTEM_REGION_START + 1,
2905            tokens: vec![
2906                // Standalone Dc 203 token
2907                DcShorthand::Short(584),
2908                DcShorthand::Short(203),
2909                DcShorthand::Short(572),
2910                // Textual base64 encapsulation: b"," (length 1)
2911                DcShorthand::Short(203),
2912                DcShorthand::Short(6),
2913                DcShorthand::Format(199),
2914                DcShorthand::Short(128),
2915                DcShorthand::Short(7),
2916                DcShorthand::Short(138),
2917                DcShorthand::Short(127),
2918                DcShorthand::Short(195),
2919                DcShorthand::Short(195),
2920                DcShorthand::Short(204),
2921                // Empty textual base64 encapsulation: b"" (length 0)
2922                DcShorthand::Short(203),
2923                DcShorthand::Short(6),
2924                DcShorthand::Format(199),
2925                DcShorthand::Short(127),
2926                DcShorthand::Short(7),
2927                DcShorthand::Short(204),
2928            ],
2929            comment: String::new(),
2930            created_ns: Some(1_795_314_000_123_456_789),
2931        };
2932
2933        let encoded = encode_nodes_to_ctbnbdl_bytes_with(&[node.clone()], framing)?;
2934        let (_, decoded) = decode_ctbnbdl_bundle_with(&encoded, framing)?;
2935        assert_eq!(decoded.len(), 1);
2936        assert_eq!(decoded[0].id, node.id);
2937        assert_eq!(decoded[0].tokens, node.tokens);
2938        assert_eq!(decoded[0].created_ns, node.created_ns);
2939        Ok(())
2940    }
2941
2942    #[test]
2943    fn test_ctbnbdl_checksum_and_resilient_section_recovery() -> Result<()> {
2944        let framing = test_framing();
2945        let n0 = LedgerNode {
2946            id: SYSTEM_REGION_START + 10,
2947            tokens: vec![
2948                DcShorthand::Short(584),
2949                DcShorthand::Short(544),
2950                DcShorthand::Short(572),
2951            ],
2952            comment: "legacy node without timestamp".to_string(),
2953            created_ns: None,
2954        };
2955        let n1 = LedgerNode {
2956            id: SYSTEM_REGION_START + 11,
2957            tokens: vec![
2958                DcShorthand::Unicode(72),
2959                DcShorthand::Unicode(105),
2960            ],
2961            comment: "timestamped node".to_string(),
2962            created_ns: Some(1_700_000_000_000_000_000),
2963        };
2964        let n2 = LedgerNode {
2965            id: SYSTEM_REGION_START + 12,
2966            tokens: vec![
2967                DcShorthand::Short(584),
2968                DcShorthand::Short(310),
2969                DcShorthand::Short(572),
2970            ],
2971            comment: "pre-epoch timestamped node".to_string(),
2972            created_ns: Some(-42_000_000_000),
2973        };
2974
2975        for orig in [&n0, &n1, &n2] {
2976            let line = orig.format_line();
2977            let reparsed = LedgerNode::parse_line(&line, "test.ctbnodes", 1)?;
2978            assert_eq!(&reparsed, orig);
2979        }
2980        assert_eq!(
2981            n0.format_line(),
2982            format!("l{}: 584 544 572 # legacy node without timestamp", n0.id)
2983        );
2984
2985        let bundle = encode_nodes_to_ctbnbdl_bytes_with(
2986            &[n0.clone(), n1.clone(), n2.clone()],
2987            framing,
2988        )?;
2989        let (wm, strict_decoded) = decode_ctbnbdl_bundle_with(&bundle, framing)?;
2990        assert_eq!(wm, Some(n2.id));
2991        assert_eq!(strict_decoded.len(), 3);
2992        assert_eq!(strict_decoded[0].created_ns, None);
2993        assert_eq!(strict_decoded[1].created_ns, n1.created_ns);
2994        assert_eq!(strict_decoded[2].created_ns, n2.created_ns);
2995
2996        // Corrupt a byte inside n1's checksummed section body!
2997        let header_bytes = encode_ctbnbdl_header_bytes(Some(n2.id), framing)?;
2998        let n0_bytes = encode_node_definition_dcmm2_bytes_with(&n0, framing)?;
2999        let corrupt_offset = header_bytes.len() + n0_bytes.len() + 10;
3000        let mut corrupted = bundle.clone();
3001        corrupted[corrupt_offset] ^= 0xFF;
3002
3003        // Strict decoder MUST fail on the corrupted section.
3004        assert!(decode_ctbnbdl_bundle_with(&corrupted, framing).is_err());
3005
3006        // Resilient decoder MUST quarantine n1 with a warning and recover n0 and n2 intact!
3007        let (res_wm, res_nodes, warnings) =
3008            decode_ctbnbdl_bundle_resilient_with(&corrupted, framing)?;
3009        assert_eq!(res_wm, Some(n2.id));
3010        assert!(!warnings.is_empty());
3011        assert_eq!(res_nodes.len(), 2);
3012        assert_eq!(res_nodes[0].id, n0.id);
3013        assert_eq!(res_nodes[0].tokens, n0.tokens);
3014        assert_eq!(res_nodes[0].created_ns, None);
3015        assert_eq!(res_nodes[1].id, n2.id);
3016        assert_eq!(res_nodes[1].tokens, n2.tokens);
3017        assert_eq!(res_nodes[1].created_ns, n2.created_ns);
3018        Ok(())
3019    }
3020}