ctb_formats_dcdata/build_support/ctbnbdl/
journal.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//! Unified durable append-only journal (`ledger-journal.jsonl`), single-inode reader/writer
21//! `flock` guards on the repository's permanent ledger lock, standalone pending-transaction
22//! recovery, and full `.ctbnbdl` bundle `(id, tokens)` verification.
23
24#[allow(
25    unused_imports,
26    clippy::wildcard_imports,
27    reason = "Standard workspace module prelude"
28)]
29use crate::utilities::*;
30
31use super::{
32    CtbnbdlFramingDcs, GRAPH_BUNDLES_SPLIT_HISTORY_SUBDIR,
33    GRAPH_BUNDLES_SPLIT_LIVE_SUBDIR, LedgerNode, MAX_BYTES_PER_BUNDLE,
34    MAX_NODES_PER_BUNDLE, MAX_NODES_PER_CHUNK, SYSTEM_REGION_START,
35    bundles_dir_for_graph_dir, chunk_rel_path_from_graph_dir,
36    decode_nodes_from_ctbnbdl_bytes_with,
37    encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent,
38    format_chunk_bundle_filename, format_chunk_rel_path, highwater_shadow_dirs,
39    list_chunk_files, load_ledger_nodes_from_dir_raw,
40    load_ledger_nodes_from_str, parse_chunk_rel_path_start_id,
41    partition_active_and_inactive_nodes_with,
42    verify_nodes_append_only_against_baseline, write_chunk_file_append_only,
43    write_ctbnbdl_bundles_to_dir,
44};
45use crate::fs2::FileExt;
46use crate::sha2::{Digest, Sha256};
47use crate::shorthand::DcShorthand;
48use serde::{Deserialize, Serialize};
49use std::collections::{BTreeMap, HashMap, HashSet};
50use std::fs::{self, File, OpenOptions};
51use std::io::Write;
52use std::path::{Path, PathBuf};
53
54/// Decodes a UTF-8 string value node from its token slice if all tokens are Unicode codepoints.
55#[must_use]
56pub fn decode_unicode_string_tokens(tokens: &[DcShorthand]) -> Option<String> {
57    if tokens.is_empty() {
58        return None;
59    }
60    let mut out = String::with_capacity(tokens.len());
61    for &tok in tokens {
62        let DcShorthand::Unicode(cp) = tok else {
63            return None;
64        };
65        let ch = char::from_u32(cp)?;
66        out.push(ch);
67    }
68    Some(out)
69}
70
71/// Resolves active `@ident(...)` short-Dc and format-Dc bindings from an in-memory slice of
72/// `.ctbnodes` [`LedgerNode`]s by bootstrapping from `"ProgrammaticIdentifier"`.
73#[allow(
74    clippy::type_complexity,
75    reason = "Private bootstrap tuple returns separate Short and Format identifier maps plus core revision Dcs"
76)]
77fn resolve_active_short_idents_from_nodes(
78    nodes: &[LedgerNode],
79) -> Result<(
80    HashMap<String, DcShorthand>,
81    HashMap<String, DcShorthand>,
82    DcShorthand,
83    DcShorthand,
84    DcShorthand,
85)> {
86    let mut strings_by_id: HashMap<u128, String> = HashMap::new();
87    let mut tokens_by_id: HashMap<u128, &[DcShorthand]> =
88        HashMap::with_capacity(nodes.len());
89
90    for node in nodes {
91        tokens_by_id.insert(node.id, node.tokens.as_slice());
92        if let Some(s) = decode_unicode_string_tokens(&node.tokens) {
93            strings_by_id.insert(node.id, s);
94        }
95    }
96
97    let prog_ident_str_ids: HashSet<u128> = strings_by_id
98        .iter()
99        .filter_map(|(&id, s)| {
100            if s == "ProgrammaticIdentifier" {
101                Some(id)
102            } else {
103                None
104            }
105        })
106        .collect();
107    ensure!(
108        !prog_ident_str_ids.is_empty(),
109        "System graph is missing the \"ProgrammaticIdentifier\" string value node"
110    );
111
112    let mut bootstrap_triple: Option<(DcShorthand, DcShorthand, DcShorthand)> =
113        None;
114    for node in nodes {
115        if let &[
116            has_value_dc,
117            DcShorthand::Long(claim_id),
118            DcShorthand::Long(val_id),
119        ] = node.tokens.as_slice()
120        {
121            if prog_ident_str_ids.contains(&val_id) {
122                if let Some(&&[has_a_dc, subj, prop]) =
123                    tokens_by_id.get(&claim_id)
124                {
125                    if subj == prop && matches!(subj, DcShorthand::Short(_)) {
126                        bootstrap_triple = Some((has_a_dc, has_value_dc, prop));
127                        break;
128                    }
129                }
130            }
131        }
132    }
133
134    let (has_a_dc, has_value_dc, prog_ident_dc) = bootstrap_triple.context(
135        "Failed to bootstrap HasA, HasValue, and ProgrammaticIdentifier from system graph",
136    )?;
137
138    let extract_prog_ident_subj =
139        |claim_tokens: &[DcShorthand]| -> Option<DcShorthand> {
140            match claim_tokens {
141                &[ha, subj, prop] | &[ha, _, subj, prop]
142                    if ha == has_a_dc
143                        && prop == prog_ident_dc
144                        && matches!(
145                            subj,
146                            DcShorthand::Short(_) | DcShorthand::Format(_)
147                        ) =>
148                {
149                    Some(subj)
150                }
151                _ => None,
152            }
153        };
154
155    let mut raw_ident_to_short: HashMap<&str, DcShorthand> = HashMap::new();
156    for node in nodes {
157        if let &[pred, DcShorthand::Long(claim_id), DcShorthand::Long(str_id)] =
158            node.tokens.as_slice()
159        {
160            if pred == has_value_dc {
161                if let Some(claim_tokens) = tokens_by_id.get(&claim_id) {
162                    if let Some(subj) = extract_prog_ident_subj(claim_tokens)
163                        && matches!(subj, DcShorthand::Short(_))
164                    {
165                        if let Some(ident_str) = strings_by_id.get(&str_id) {
166                            raw_ident_to_short.insert(ident_str.as_str(), subj);
167                        }
168                    }
169                }
170            }
171        }
172    }
173
174    let sh_supersedes = *raw_ident_to_short
175        .get("Supersedes")
176        .context("Missing @ident(\"Supersedes\") in system graph")?;
177    let sh_retracts = *raw_ident_to_short
178        .get("Retracts")
179        .context("Missing @ident(\"Retracts\") in system graph")?;
180    let sh_enclosing_doc = *raw_ident_to_short
181        .get("EnclosingDocument")
182        .context("Missing @ident(\"EnclosingDocument\") in system graph")?;
183
184    let mut inactive_ids: HashSet<u128> = HashSet::new();
185    for node in nodes.iter().rev() {
186        if inactive_ids.contains(&node.id) {
187            continue;
188        }
189        if let &[verb, _subj, DcShorthand::Long(old_id)] =
190            node.tokens.as_slice()
191        {
192            if verb == sh_supersedes || verb == sh_retracts {
193                inactive_ids.insert(old_id);
194            }
195        }
196    }
197
198    let mut active_ident_to_short: HashMap<String, DcShorthand> = HashMap::new();
199    let mut active_ident_to_format: HashMap<String, DcShorthand> =
200        HashMap::new();
201    for node in nodes {
202        if inactive_ids.contains(&node.id) {
203            continue;
204        }
205        if let &[pred, DcShorthand::Long(claim_id), DcShorthand::Long(str_id)] =
206            node.tokens.as_slice()
207        {
208            if pred == has_value_dc && !inactive_ids.contains(&claim_id) {
209                if let Some(claim_tokens) = tokens_by_id.get(&claim_id) {
210                    if let Some(subj) = extract_prog_ident_subj(claim_tokens) {
211                        if let Some(ident_str) = strings_by_id.get(&str_id) {
212                            match subj {
213                                DcShorthand::Short(_) => {
214                                    active_ident_to_short
215                                        .insert(ident_str.clone(), subj);
216                                }
217                                DcShorthand::Format(_) => {
218                                    active_ident_to_format
219                                        .insert(ident_str.clone(), subj);
220                                }
221                                _ => {}
222                            }
223                        }
224                    }
225                }
226            }
227        }
228    }
229
230    Ok((
231        active_ident_to_short,
232        active_ident_to_format,
233        sh_supersedes,
234        sh_retracts,
235        sh_enclosing_doc,
236    ))
237}
238
239/// Resolves the `CtbnbdlFramingDcs` from an in-memory slice of `.ctbnodes` [`LedgerNode`]s
240/// by bootstrapping from the `"ProgrammaticIdentifier"` string value node.
241///
242/// # Errors
243/// Returns an error if `"ProgrammaticIdentifier"` or any required framing Dc identifier
244/// cannot be resolved from `nodes`.
245pub fn resolve_ctbnbdl_framing_dcs_from_nodes(
246    nodes: &[LedgerNode],
247) -> Result<CtbnbdlFramingDcs> {
248    let (
249        active_ident_to_short,
250        active_ident_to_format,
251        sh_supersedes,
252        sh_retracts,
253        sh_enclosing_doc,
254    ) = resolve_active_short_idents_from_nodes(nodes)?;
255
256    let get_req = |ident: &str| -> Result<DcShorthand> {
257        active_ident_to_short.get(ident).copied().with_context(|| {
258            format!(
259                "Missing required @ident(\"{ident}\") in system graph for ctbnbdl framing"
260            )
261        })
262    };
263    let get_req_fmt = |ident: &str| -> Result<DcShorthand> {
264        active_ident_to_format.get(ident).copied().with_context(|| {
265            format!(
266                "Missing required format @ident(\"{ident}\") in system graph for ctbnbdl framing"
267            )
268        })
269    };
270
271    Ok(CtbnbdlFramingDcs {
272        begin_node: get_req("BeginGraphNodeDefinition")?,
273        end_node: get_req("EndGraphNodeDefinition")?,
274        begin_checksummed_section: get_req("BeginChecksummedSection")?,
275        end_checksummed_section: get_req("EndChecksummedSection")?,
276        section_digest: get_req("SectionDigest")?,
277        begin_time_moment: get_req("BeginTimeMoment")?,
278        end_time_moment: get_req("EndTimeMoment")?,
279        section_node_creation_time: active_ident_to_short
280            .get("SectionTimestampNodeCreationTime")
281            .copied(),
282        ns_since_epoch_format: get_req_fmt("NsSinceEpoch")?,
283        sha256_format: get_req_fmt("Sha256")?,
284        escape: get_req("Escape")?,
285        evaluate_as_atom: get_req("EvaluateValueAsAtom")?,
286        has_a: get_req("HasA")?,
287        has_value: get_req("HasValue")?,
288        preferred: get_req("Preferred")?,
289        supersedes: sh_supersedes,
290        retracts: sh_retracts,
291        enclosing_document: sh_enclosing_doc,
292        is_instance_of: get_req("IsInstanceOf")?,
293        is_subtype_of: get_req("IsSubtypeOf")?,
294        is_based_on: get_req("IsBasedOn")?,
295        is_deprecated: get_req("IsDeprecated")?,
296        is_closing_delimiter_for: get_req("IsClosingDelimiterFor")?,
297        is_associated_with: get_req("IsAssociatedWith")?,
298    })
299}
300
301/// Relative path from the repository root to the unified durable ledger journal.
302pub const LEDGER_JOURNAL_REL_PATH: &str =
303    "src/formats/dcdata/data-src/nodes/allocated/ledger-journal.jsonl";
304
305/// Relative path from the repository root to the local post-initialization marker.
306pub const JOURNAL_INITIALIZED_REL_PATH: &str =
307    "src/formats/dcdata/data-src/nodes/allocated/journal-initialized";
308
309/// Relative path from the repository root to the shared permanent lock canary file.
310pub const LOCK_CANARY_REL_PATH: &str =
311    "src/formats/dcdata/data-src/nodes/ledger.lock";
312
313/// Exclusive writer lock guard (`flock(LOCK_EX)`) on the permanent ledger lock.
314#[derive(Debug)]
315pub struct LedgerWriteGuard {
316    repo_root: PathBuf,
317    file: File,
318}
319
320/// Shared reader lock guard (`flock(LOCK_SH)`) on the permanent ledger lock.
321#[derive(Debug)]
322pub struct LedgerReadGuard {
323    repo_root: PathBuf,
324    file: File,
325}
326
327fn open_or_create_lock_canary(repo_root: &Path) -> Result<File> {
328    let canary_path = repo_root.join(LOCK_CANARY_REL_PATH);
329    if !canary_path.exists() {
330        if let Some(parent) = canary_path.parent() {
331            fs::create_dir_all(parent).with_context(|| {
332                format!("Failed to create {}", parent.display())
333            })?;
334        }
335        OpenOptions::new()
336            .write(true)
337            .create(true)
338            .truncate(false)
339            .open(&canary_path)
340            .with_context(|| {
341                format!(
342                    "Failed to create lock canary {}",
343                    canary_path.display()
344                )
345            })?;
346    }
347    OpenOptions::new()
348        .read(true)
349        .open(&canary_path)
350        .with_context(|| {
351            format!(
352                "Failed to open lock canary {} for flock",
353                canary_path.display()
354            )
355        })
356}
357
358impl LedgerWriteGuard {
359    /// Acquires an exclusive lock on the repository's permanent ledger lock.
360    pub fn acquire(repo_root: &Path) -> Result<Self> {
361        let file = open_or_create_lock_canary(repo_root)?;
362        file.lock_exclusive().with_context(|| {
363            format!(
364                "Failed to acquire exclusive flock(LOCK_EX) on {}",
365                repo_root.join(LOCK_CANARY_REL_PATH).display()
366            )
367        })?;
368        Ok(Self {
369            repo_root: repo_root.to_path_buf(),
370            file,
371        })
372    }
373
374    /// Returns the repository root protected by this write guard.
375    #[must_use]
376    pub fn repo_root(&self) -> &Path {
377        &self.repo_root
378    }
379}
380
381impl Drop for LedgerWriteGuard {
382    fn drop(&mut self) {
383        let _ = FileExt::unlock(&self.file);
384    }
385}
386
387impl LedgerReadGuard {
388    /// Acquires a shared lock on the repository's permanent ledger lock.
389    pub fn acquire(repo_root: &Path) -> Result<Self> {
390        let file = open_or_create_lock_canary(repo_root)?;
391        file.lock_shared().with_context(|| {
392            format!(
393                "Failed to acquire shared flock(LOCK_SH) on {}",
394                repo_root.join(LOCK_CANARY_REL_PATH).display()
395            )
396        })?;
397        Ok(Self {
398            repo_root: repo_root.to_path_buf(),
399            file,
400        })
401    }
402
403    /// Returns the repository root protected by this read guard.
404    #[must_use]
405    pub fn repo_root(&self) -> &Path {
406        &self.repo_root
407    }
408}
409
410impl Drop for LedgerReadGuard {
411    fn drop(&mut self) {
412        let _ = FileExt::unlock(&self.file);
413    }
414}
415
416/// Fault-injection hook for deterministic crash and recovery unit tests.
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418pub enum FaultInjectionPoint {
419    /// Write only `bytes_to_keep` bytes of the `BATCH_PENDING` line (without trailing `\n`) and abort.
420    TornPendingRecord {
421        /// Number of prefix bytes of the serialized JSON line to write before aborting.
422        bytes_to_keep: usize,
423    },
424    /// Abort during Phase 1 after appending `bytes_to_keep` bytes of `item_index`'s `.ctbnodes` line (without `\n`).
425    TornChunkLine {
426        /// Zero-based index of the item in `items` whose `.ctbnodes` line should be torn.
427        item_index: usize,
428        /// Number of prefix bytes of `raw_line` to write before aborting.
429        bytes_to_keep: usize,
430    },
431    /// Abort during Phase 1 after item `item_index` has been appended to `.ctbnodes` and moved to `nodes/allocated/`.
432    AfterItemAppendedAndMoved {
433        /// Zero-based index of the item after which to abort.
434        item_index: usize,
435    },
436    /// Abort after all items are written and moved, before invoking `fsync` on files and directories.
437    BeforeFsync,
438    /// Write only `bytes_to_keep` bytes of the `BATCH_COMMITTED` line (without trailing `\n`) and abort.
439    TornCommittedRecord {
440        /// Number of prefix bytes of the serialized JSON line to write before aborting.
441        bytes_to_keep: usize,
442    },
443}
444
445/// A single planned node append item in a durable ledger transaction and/or manifest.
446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
447pub struct PlannedLedgerItem {
448    /// Allocated global node ID (`l<node_id>`).
449    pub node_id: u128,
450    /// Complete formatted `.ctbnodes` line (without trailing `\n`).
451    pub raw_line: String,
452    /// Target `.ctbnodes` chunk filename (e.g. `"85899_52392.ctbnodes"`).
453    pub target_chunk: String,
454    /// Optional parsed token strings (present in precomputed manifests).
455    #[serde(default, skip_serializing_if = "Vec::is_empty")]
456    pub tokens: Vec<String>,
457    /// Optional comment string (present in precomputed manifests).
458    #[serde(default, skip_serializing_if = "String::is_empty")]
459    pub comment: String,
460    /// Provenance owner (`"csv"` or `"manual"`).
461    #[serde(default)]
462    pub provenance: String,
463    /// Optional human-readable rationale from `# @rationale:`.
464    #[serde(default, skip_serializing_if = "Option::is_none")]
465    pub rationale: Option<String>,
466    /// Authorized active duplicate node IDs from `# @allow-duplicate-of:`.
467    #[serde(default)]
468    pub allow_duplicate_of: Vec<u128>,
469    /// Source filename in `src/formats/dcdata/data-src/nodes/inbox/` (for `inbox_allocation`).
470    #[serde(default, skip_serializing_if = "Option::is_none")]
471    pub inbox_name: Option<String>,
472    /// Destination filename in `src/formats/dcdata/data-src/nodes/allocated/` (for `inbox_allocation`).
473    #[serde(default, skip_serializing_if = "Option::is_none")]
474    pub allocated_name: Option<String>,
475    /// Expected SHA-256 hex digest of the `.dcsh` source file (for `inbox_allocation`).
476    #[serde(default, skip_serializing_if = "Option::is_none")]
477    pub inbox_sha256: Option<String>,
478    /// Optional full `.dcsh` file contents (used in precomputed transaction manifests).
479    #[serde(default, skip_serializing_if = "Option::is_none")]
480    pub dcsh_content: Option<String>,
481}
482
483impl PlannedLedgerItem {
484    /// Returns a normalized copy without manifest-only staging fields (`tokens`, `comment`, `dcsh_content`)
485    /// so `BATCH_PENDING.items` and `manifest.planned_items` can be compared structurally.
486    #[must_use]
487    pub fn normalized_for_journal(&self) -> Self {
488        Self {
489            node_id: self.node_id,
490            raw_line: self.raw_line.clone(),
491            target_chunk: self.target_chunk.clone(),
492            tokens: Vec::new(),
493            comment: String::new(),
494            provenance: self.provenance.clone(),
495            rationale: self.rationale.clone(),
496            allow_duplicate_of: self.allow_duplicate_of.clone(),
497            inbox_name: self.inbox_name.clone(),
498            allocated_name: self.allocated_name.clone(),
499            inbox_sha256: self.inbox_sha256.clone(),
500            dcsh_content: None,
501        }
502    }
503}
504
505/// Precomputed deterministic transaction manifest used with `--require-manifest`.
506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
507pub struct TransactionManifest {
508    /// Human-readable manifest identifier.
509    pub manifest_id: String,
510    /// Transaction kind (`"inbox_allocation"` or `"csv_reconciliation"`).
511    pub kind: String,
512    /// Highest node ID in the baseline ledger prior to this transaction.
513    pub baseline_last_id: u128,
514    /// Total node count in the baseline ledger prior to this transaction.
515    pub baseline_node_count: usize,
516    /// Expected SHA-256 digest of the baseline `.ctbnodes` directory.
517    pub baseline_ledger_sha256: String,
518    /// Highest node ID in the ledger after this transaction completes.
519    pub final_last_id: u128,
520    /// Total node count in the ledger after this transaction completes.
521    pub final_node_count: usize,
522    /// Expected SHA-256 digest of the `.ctbnodes` directory after this transaction completes.
523    pub final_ledger_sha256: String,
524    /// Pinned SHA-256 digests of all input files (`nodes/inbox/*.dcsh` or CSV tables).
525    pub pinned_input_sha256s: BTreeMap<String, String>,
526    /// Ordered list of planned node allocations.
527    pub planned_items: Vec<PlannedLedgerItem>,
528}
529
530/// A single JSONL record (`BATCH_PENDING` or `BATCH_COMMITTED`) in `ledger-journal.jsonl`.
531#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
532pub struct JournalRecord {
533    /// Record state: `"BATCH_PENDING"` or `"BATCH_COMMITTED"`.
534    pub state: String,
535    /// Unique batch identifier matching `BATCH_PENDING` and `BATCH_COMMITTED`.
536    pub batch_id: String,
537    /// Transaction kind: `"bootstrap_checkpoint"`, `"inbox_allocation"`, or `"csv_reconciliation"`.
538    pub kind: String,
539    /// Highest node ID before this batch.
540    pub baseline_last_id: u128,
541    /// SHA-256 digest of `.ctbnodes` chunks before this batch.
542    pub baseline_ledger_sha256: String,
543    /// Highest node ID after this batch.
544    pub final_last_id: u128,
545    /// SHA-256 digest of `.ctbnodes` chunks after this batch.
546    pub final_ledger_sha256: String,
547    /// Optional SHA-256 digest of the required `TransactionManifest` bytes.
548    #[serde(default, skip_serializing_if = "Option::is_none")]
549    pub manifest_sha256: Option<String>,
550    /// Planned node items (recorded in `BATCH_PENDING`).
551    #[serde(default, skip_serializing_if = "Vec::is_empty")]
552    pub items: Vec<PlannedLedgerItem>,
553    /// SHA-256 digests of tracked unsplit `.ctbnbdl` bundles in `assets/data/graph-bundles/` (recorded in `BATCH_COMMITTED`).
554    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
555    pub unsplit_bundles_sha256: BTreeMap<String, String>,
556    /// SHA-256 digests of live `.ctbnbdl` bundles in `assets/data/graph-bundles/split/live/` (recorded in `BATCH_COMMITTED`).
557    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
558    pub active_bundles_sha256: BTreeMap<String, String>,
559    /// SHA-256 digests of historical `.ctbnbdl` bundles in `assets/data/graph-bundles/split/history/` (recorded in `BATCH_COMMITTED`).
560    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
561    pub history_bundles_sha256: BTreeMap<String, String>,
562    /// Lowercase hex SHA-256 checksum over the canonical JSON serialization of this record with `record_sha256: ""`.
563    pub record_sha256: String,
564}
565
566/// Recorded SHA-256 inventories for unsplit and split `.ctbnbdl` bundle directories.
567#[derive(Debug, Clone, Default, PartialEq, Eq)]
568pub struct CompiledBundleDigests {
569    /// SHA-256 digests of tracked unsplit `.ctbnbdl` files in `assets/data/graph-bundles/`.
570    pub unsplit_bundles_sha256: BTreeMap<String, String>,
571    /// SHA-256 digests of gitignored live `.ctbnbdl` files in `assets/data/graph-bundles/split/live/`.
572    pub active_bundles_sha256: BTreeMap<String, String>,
573    /// SHA-256 digests of gitignored historical `.ctbnbdl` files in `assets/data/graph-bundles/split/history/`.
574    pub history_bundles_sha256: BTreeMap<String, String>,
575}
576
577impl JournalRecord {
578    /// Computes the expected `record_sha256` over this record with `record_sha256` cleared.
579    pub fn compute_expected_sha256(&self) -> Result<String> {
580        let mut clone = self.clone();
581        clone.record_sha256.clear();
582        let json = serde_json::to_string(&clone)
583            .context("Failed to serialize JournalRecord for checksum")?;
584        Ok(sha256_bytes_hex(json.as_bytes()))
585    }
586
587    /// Populates `self.record_sha256` with the computed digest and returns `self`.
588    pub fn with_computed_sha256(mut self) -> Result<Self> {
589        self.record_sha256 = self.compute_expected_sha256()?;
590        Ok(self)
591    }
592
593    /// Verifies that `self.record_sha256` matches `compute_expected_sha256()`.
594    pub fn verify_sha256(&self) -> Result<()> {
595        ensure!(
596            !self.record_sha256.is_empty(),
597            "JournalRecord (batch_id={}, state={}) has empty record_sha256",
598            self.batch_id,
599            self.state
600        );
601        let expected = self.compute_expected_sha256()?;
602        ensure!(
603            self.record_sha256 == expected,
604            "CRITICAL: JournalRecord checksum mismatch for batch_id={} state={}: expected {}, found {}",
605            self.batch_id,
606            self.state,
607            expected,
608            self.record_sha256
609        );
610        Ok(())
611    }
612}
613
614/// Parsed state of `ledger-journal.jsonl`.
615#[derive(Debug, Clone)]
616pub struct ParsedJournal {
617    /// Byte length of the validated `\n`-terminated prefix of `ledger-journal.jsonl`.
618    pub valid_prefix_len: usize,
619    /// Unterminated trailing line fragment (not ending in `\n`), if a crash interrupted the last write.
620    pub torn_trailing_fragment: Option<Vec<u8>>,
621    /// All complete `\n`-terminated records, each verified with `verify_sha256()`.
622    pub records: Vec<JournalRecord>,
623    /// All completed `(BATCH_PENDING, BATCH_COMMITTED)` pairs in chronological order.
624    pub committed_pairs: Vec<(JournalRecord, JournalRecord)>,
625    /// Currently open `BATCH_PENDING` record at the end of the journal, if any.
626    pub open_pending: Option<JournalRecord>,
627    /// Most recent `BATCH_COMMITTED` record, if any.
628    pub last_committed: Option<JournalRecord>,
629}
630
631/// Computes the lowercase hex SHA-256 digest of `bytes`.
632#[must_use]
633pub fn sha256_bytes_hex(bytes: &[u8]) -> String {
634    let digest = Sha256::digest(bytes);
635    let mut out = String::with_capacity(64);
636    for b in digest {
637        use std::fmt::Write as _;
638        let _ = write!(&mut out, "{b:02x}");
639    }
640    out
641}
642
643/// Computes the lowercase hex SHA-256 digest of a file on disk.
644pub fn sha256_file_hex(path: &Path) -> Result<String> {
645    let bytes = fs::read(path).with_context(|| {
646        format!("Failed to read {} for SHA-256", path.display())
647    })?;
648    Ok(sha256_bytes_hex(&bytes))
649}
650
651/// Invokes `sync_all()` on a file path.
652pub fn fsync_file(path: &Path) -> Result<()> {
653    #[cfg(windows)]
654    let f = OpenOptions::new().write(true).open(path).with_context(|| {
655        format!("Failed to open {} for fsync", path.display())
656    })?;
657    #[cfg(not(windows))]
658    let f = File::open(path).with_context(|| {
659        format!("Failed to open {} for fsync", path.display())
660    })?;
661    f.sync_all()
662        .with_context(|| format!("Failed to fsync {}", path.display()))
663}
664
665/// Invokes `sync_all()` on a directory path on Unix platforms.
666///
667/// Windows `FlushFileBuffers` does not support directory handles
668/// (`ERROR_ACCESS_DENIED`); file and MFT entry durability on Windows is
669/// flushed via `fsync_file`.
670pub fn fsync_dir(dir: &Path) -> Result<()> {
671    if !dir.is_dir() {
672        return Ok(());
673    }
674    #[cfg(unix)]
675    {
676        let f = File::open(dir).with_context(|| {
677            format!("Failed to open directory {} for fsync", dir.display())
678        })?;
679        f.sync_all().with_context(|| {
680            format!("Failed to fsync directory {}", dir.display())
681        })?;
682    }
683    Ok(())
684}
685
686/// Returns the `.ctbnodes` chunk relative path (`"85899_34592.ctbnodes"`, ..., `"85900/85900_34492.ctbnodes"`)
687/// that owns `node_id`.
688#[must_use]
689pub fn chunk_filename_for_node_id(node_id: u128) -> String {
690    let offset = node_id.saturating_sub(SYSTEM_REGION_START);
691    // Reason for fallback: MAX_NODES_PER_CHUNK is the compile-time constant 100.
692    let max_u128 = u128::try_from(MAX_NODES_PER_CHUNK).unwrap_or(100);
693    // Reason for fallback: max_u128 is non-zero (100).
694    let chunk_start = SYSTEM_REGION_START.saturating_add(
695        offset
696            .checked_div(max_u128)
697            .unwrap_or(0)
698            .saturating_mul(max_u128),
699    );
700    format_chunk_rel_path(chunk_start)
701}
702
703/// Computes the canonical SHA-256 digest over all `.ctbnodes` chunk files in `graph_dir`,
704/// sorted by ascending chunk start ID (`rel_path\0content\0`).
705pub fn compute_ledger_dir_sha256(graph_dir: &Path) -> Result<String> {
706    let files = list_chunk_files(graph_dir)?;
707    let mut hasher = Sha256::new();
708    for path in files {
709        let Some(rel_name) = chunk_rel_path_from_graph_dir(graph_dir, &path)
710        else {
711            continue;
712        };
713        let bytes = fs::read(&path).with_context(|| {
714            format!("Failed to read chunk {}", path.display())
715        })?;
716        hasher.update(rel_name.as_bytes());
717        hasher.update(b"\0");
718        hasher.update(&bytes);
719        hasher.update(b"\0");
720    }
721    let digest = hasher.finalize();
722    let mut out = String::with_capacity(64);
723    for b in digest {
724        use std::fmt::Write as _;
725        let _ = write!(&mut out, "{b:02x}");
726    }
727    Ok(out)
728}
729
730/// Computes the canonical `.ctbnodes` directory SHA-256 digest from an in-memory slice of `LedgerNode`s.
731#[must_use]
732pub fn compute_nodes_slice_ledger_sha256(nodes: &[LedgerNode]) -> String {
733    let mut hasher = Sha256::new();
734    for chunk in nodes.chunks(MAX_NODES_PER_CHUNK) {
735        let Some(first) = chunk.first() else {
736            continue;
737        };
738        let rel_name = format_chunk_rel_path(first.id);
739        let mut content = String::new();
740        for node in chunk {
741            content.push_str(&node.format_line());
742            content.push('\n');
743        }
744        hasher.update(rel_name.as_bytes());
745        hasher.update(b"\0");
746        hasher.update(content.as_bytes());
747        hasher.update(b"\0");
748    }
749    let digest = hasher.finalize();
750    let mut out = String::with_capacity(64);
751    for b in digest {
752        use std::fmt::Write as _;
753        let _ = write!(&mut out, "{b:02x}");
754    }
755    out
756}
757
758/// Computes a sorted map of `<filename>.ctbnbdl -> sha256_hex` for all `.ctbnbdl` files directly in `dir`.
759pub fn compute_bundle_dir_sha256s(
760    dir: &Path,
761) -> Result<BTreeMap<String, String>> {
762    let mut map = BTreeMap::new();
763    if !dir.is_dir() {
764        return Ok(map);
765    }
766    for entry in fs::read_dir(dir)
767        .with_context(|| format!("Failed to read {}", dir.display()))?
768    {
769        let entry = entry?;
770        let path = entry.path();
771        if !path.is_file() {
772            continue;
773        }
774        if path.extension().and_then(|e| e.to_str()) != Some("ctbnbdl") {
775            continue;
776        }
777        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
778            continue;
779        };
780        map.insert(name.to_string(), sha256_file_hex(&path)?);
781    }
782    Ok(map)
783}
784
785fn decode_bundle_dir_nodes(
786    dir: &Path,
787    framing: CtbnbdlFramingDcs,
788) -> Result<Vec<LedgerNode>> {
789    if !dir.is_dir() {
790        return Ok(Vec::new());
791    }
792    let mut keyed_files: Vec<(u128, PathBuf)> = Vec::new();
793    for entry in fs::read_dir(dir)
794        .with_context(|| format!("Failed to read {}", dir.display()))?
795    {
796        let entry = entry?;
797        let path = entry.path();
798        if !path.is_file() {
799            continue;
800        }
801        if path.extension().and_then(|e| e.to_str()) != Some("ctbnbdl") {
802            continue;
803        }
804        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
805            continue;
806        };
807        let stem = name.strip_suffix(".ctbnbdl").unwrap_or(name);
808        let digits: String = stem.chars().filter(|&c| c != '_').collect();
809        let start_id: u128 = digits.parse().with_context(|| {
810            format!(
811                "Invalid .ctbnbdl bundle filename {} in {}",
812                name,
813                dir.display()
814            )
815        })?;
816        keyed_files.push((start_id, path));
817    }
818    keyed_files.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
819
820    let mut all_nodes = Vec::new();
821    let mut prev_id: Option<u128> = None;
822    for (_, path) in keyed_files {
823        let bytes = fs::read(&path).with_context(|| {
824            format!("Failed to read bundle {}", path.display())
825        })?;
826        let decoded = decode_nodes_from_ctbnbdl_bytes_with(&bytes, framing)
827            .with_context(|| {
828                format!("Failed to decode bundle {}", path.display())
829            })?;
830        for node in decoded {
831            if let Some(prev) = prev_id {
832                ensure!(
833                    node.id > prev,
834                    "Decoded .ctbnbdl node IDs in {} are not strictly ascending: l{} followed by l{}",
835                    path.display(),
836                    prev,
837                    node.id
838                );
839            }
840            prev_id = Some(node.id);
841            all_nodes.push(node);
842        }
843    }
844    Ok(all_nodes)
845}
846
847/// Verifies that the tracked unsplit bundles (`graph-bundles/*.ctbnbdl`) and, when present or required,
848/// the gitignored split live (`graph-bundles/split/live/*.ctbnbdl`) and historical
849/// (`graph-bundles/split/history/*.ctbnbdl`) bundles match `committed_nodes` in:
850/// 1. Exact bundle inventory and file SHA-256 digests (when `expected_digests` are provided),
851/// 2. Exact `(node.id, node.created_ns, &node.tokens)` sequence equality for unsplit bundles, and
852/// 3. Disjoint strictly ascending node IDs, union equality, and active/inactive partition equality
853///    for split bundles when `require_split` is `true` or `split/` exists on disk.
854pub fn verify_compiled_bundles_match_ledger(
855    graph_dir: &Path,
856    committed_nodes: &[LedgerNode],
857    framing: CtbnbdlFramingDcs,
858    expected_digests: Option<&CompiledBundleDigests>,
859    require_split: bool,
860) -> Result<()> {
861    fn project_node_id_tokens(
862        slice: &[LedgerNode],
863    ) -> Vec<(u128, Option<i128>, &[crate::shorthand::DcShorthand])> {
864        slice
865            .iter()
866            .map(|n| (n.id, n.created_ns, n.tokens.as_slice()))
867            .collect()
868    }
869
870    let bundles_dir = bundles_dir_for_graph_dir(graph_dir);
871    let actual_unsplit_sha256 = compute_bundle_dir_sha256s(&bundles_dir)?;
872    if let Some(expected) = expected_digests
873        && !expected.unsplit_bundles_sha256.is_empty()
874    {
875        ensure!(
876            actual_unsplit_sha256 == expected.unsplit_bundles_sha256,
877            "Unsplit .ctbnbdl bundle SHA-256 inventory in {} does not match BATCH_COMMITTED: expected {:?}, found {:?}",
878            bundles_dir.display(),
879            expected.unsplit_bundles_sha256,
880            actual_unsplit_sha256
881        );
882    }
883
884    let decoded_unsplit = decode_bundle_dir_nodes(&bundles_dir, framing)?;
885    let decoded_unsplit_pairs = project_node_id_tokens(&decoded_unsplit);
886    let committed_pairs = project_node_id_tokens(committed_nodes);
887    ensure!(
888        decoded_unsplit_pairs == committed_pairs,
889        "Decoded unsplit .ctbnbdl nodes ({} nodes) in {} do not match committed .ctbnodes ledger ({} nodes) by (id, created_ns, tokens)",
890        decoded_unsplit_pairs.len(),
891        bundles_dir.display(),
892        committed_pairs.len()
893    );
894
895    let live_dir = bundles_dir.join(GRAPH_BUNDLES_SPLIT_LIVE_SUBDIR);
896    let history_dir = bundles_dir.join(GRAPH_BUNDLES_SPLIT_HISTORY_SUBDIR);
897    let split_present =
898        require_split || live_dir.exists() || history_dir.exists();
899    if !split_present {
900        return Ok(());
901    }
902
903    let actual_active_sha256 = compute_bundle_dir_sha256s(&live_dir)?;
904    let actual_history_sha256 = compute_bundle_dir_sha256s(&history_dir)?;
905
906    if let Some(expected) = expected_digests {
907        ensure!(
908            actual_active_sha256 == expected.active_bundles_sha256,
909            "Active .ctbnbdl bundle SHA-256 inventory in {} does not match BATCH_COMMITTED: expected {:?}, found {:?}",
910            live_dir.display(),
911            expected.active_bundles_sha256,
912            actual_active_sha256
913        );
914        ensure!(
915            actual_history_sha256 == expected.history_bundles_sha256,
916            "Historical .ctbnbdl bundle SHA-256 inventory in {} does not match BATCH_COMMITTED: expected {:?}, found {:?}",
917            history_dir.display(),
918            expected.history_bundles_sha256,
919            actual_history_sha256
920        );
921    }
922
923    let decoded_active = decode_bundle_dir_nodes(&live_dir, framing)?;
924    let decoded_history = decode_bundle_dir_nodes(&history_dir, framing)?;
925
926    let active_ids: HashSet<u128> =
927        decoded_active.iter().map(|n| n.id).collect();
928    let history_ids: HashSet<u128> =
929        decoded_history.iter().map(|n| n.id).collect();
930    ensure!(
931        active_ids.is_disjoint(&history_ids),
932        "Active and historical .ctbnbdl bundles in {} are not disjoint!",
933        bundles_dir.display()
934    );
935
936    let (expected_active, expected_history) =
937        partition_active_and_inactive_nodes_with(committed_nodes, framing);
938
939    let decoded_active_pairs = project_node_id_tokens(&decoded_active);
940    let expected_active_pairs = project_node_id_tokens(&expected_active);
941    ensure!(
942        decoded_active_pairs == expected_active_pairs,
943        "Decoded active .ctbnbdl nodes ({} nodes) in {} do not match expected active partition ({} nodes) by (id, created_ns, tokens)",
944        decoded_active_pairs.len(),
945        live_dir.display(),
946        expected_active_pairs.len()
947    );
948
949    let decoded_history_pairs = project_node_id_tokens(&decoded_history);
950    let expected_history_pairs = project_node_id_tokens(&expected_history);
951    ensure!(
952        decoded_history_pairs == expected_history_pairs,
953        "Decoded historical .ctbnbdl nodes ({} nodes) in {} do not match expected inactive partition ({} nodes) by (id, created_ns, tokens)",
954        decoded_history_pairs.len(),
955        history_dir.display(),
956        expected_history_pairs.len()
957    );
958
959    let mut merged_decoded: Vec<(
960        u128,
961        Option<i128>,
962        &[crate::shorthand::DcShorthand],
963    )> = Vec::with_capacity(
964        decoded_active_pairs
965            .len()
966            .saturating_add(decoded_history_pairs.len()),
967    );
968    merged_decoded.extend(decoded_active_pairs);
969    merged_decoded.extend(decoded_history_pairs);
970    merged_decoded.sort_by_key(|(id, _, _)| *id);
971
972    ensure!(
973        merged_decoded == committed_pairs,
974        "Decoded active + history .ctbnbdl union ({} nodes) does not equal committed .ctbnodes ledger ({} nodes) by (id, created_ns, tokens)",
975        merged_decoded.len(),
976        committed_pairs.len()
977    );
978
979    Ok(())
980}
981
982/// Loads `.ctbnodes` directly under an already-held `LedgerWriteGuard` without opening a second lock fd
983/// or running external reader-gate checks while `BATCH_PENDING` is open.
984pub fn load_ledger_nodes_from_dir_with_write_guard(
985    _write_guard: &LedgerWriteGuard,
986    graph_dir: &Path,
987) -> Result<Vec<LedgerNode>> {
988    load_ledger_nodes_from_dir_raw(graph_dir)
989}
990
991/// Compiles `nodes` into tracked unsplit (`assets/data/graph-bundles/*.ctbnbdl`) and gitignored split
992/// (`assets/data/graph-bundles/split/{live,history}/*.ctbnbdl`) bundles under an already-held
993/// `LedgerWriteGuard` directly from the validated in-memory `nodes` slice, `fsync`s all bundle files
994/// and directories, updates `built/` staging directories if present, verifies the compiled bundles via
995/// `verify_compiled_bundles_match_ledger`, and returns [`CompiledBundleDigests`].
996pub fn compile_nodes_slice_to_ctbnbdl_with_write_guard(
997    write_guard: &LedgerWriteGuard,
998    nodes: &[LedgerNode],
999    graph_dir: &Path,
1000    framing: CtbnbdlFramingDcs,
1001) -> Result<CompiledBundleDigests> {
1002    let bundles_dir = bundles_dir_for_graph_dir(graph_dir);
1003    let unsplit_bundles =
1004        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
1005            nodes,
1006            framing,
1007            MAX_NODES_PER_BUNDLE,
1008            MAX_BYTES_PER_BUNDLE,
1009            None,
1010        )?;
1011    write_ctbnbdl_bundles_to_dir(&bundles_dir, &unsplit_bundles, true)?;
1012    for (first_id, _) in &unsplit_bundles {
1013        let filename = format_chunk_bundle_filename(*first_id);
1014        fsync_file(&bundles_dir.join(filename))?;
1015    }
1016    fsync_dir(&bundles_dir)?;
1017
1018    let most_recent_node_id = nodes.iter().map(|n| n.id).max();
1019    let (active_nodes, inactive_nodes) =
1020        partition_active_and_inactive_nodes_with(nodes, framing);
1021
1022    let active_bundles =
1023        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
1024            &active_nodes,
1025            framing,
1026            MAX_NODES_PER_BUNDLE,
1027            MAX_BYTES_PER_BUNDLE,
1028            most_recent_node_id,
1029        )?;
1030    let split_live_dir = bundles_dir.join(GRAPH_BUNDLES_SPLIT_LIVE_SUBDIR);
1031    write_ctbnbdl_bundles_to_dir(&split_live_dir, &active_bundles, true)?;
1032    for (first_id, _) in &active_bundles {
1033        let filename = format_chunk_bundle_filename(*first_id);
1034        fsync_file(&split_live_dir.join(filename))?;
1035    }
1036    fsync_dir(&split_live_dir)?;
1037
1038    let inactive_bundles =
1039        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
1040            &inactive_nodes,
1041            framing,
1042            MAX_NODES_PER_BUNDLE,
1043            MAX_BYTES_PER_BUNDLE,
1044            most_recent_node_id,
1045        )?;
1046    let split_history_dir =
1047        bundles_dir.join(GRAPH_BUNDLES_SPLIT_HISTORY_SUBDIR);
1048    write_ctbnbdl_bundles_to_dir(&split_history_dir, &inactive_bundles, true)?;
1049    for (first_id, _) in &inactive_bundles {
1050        let filename = format_chunk_bundle_filename(*first_id);
1051        fsync_file(&split_history_dir.join(filename))?;
1052    }
1053    fsync_dir(&split_history_dir)?;
1054    if let Some(split_root) = split_live_dir.parent() {
1055        fsync_dir(split_root)?;
1056    }
1057
1058    let runtime_graph_dir =
1059        write_guard.repo_root().join("built/assets/data/graph");
1060    if runtime_graph_dir.is_dir() {
1061        write_ctbnbdl_bundles_to_dir(
1062            &runtime_graph_dir,
1063            &active_bundles,
1064            true,
1065        )?;
1066    }
1067    let staged_history_dir = write_guard
1068        .repo_root()
1069        .join("built/system_graph_history_assets/data/graph/system");
1070    if staged_history_dir.is_dir() {
1071        write_ctbnbdl_bundles_to_dir(
1072            &staged_history_dir,
1073            &inactive_bundles,
1074            true,
1075        )?;
1076    }
1077
1078    let digests = CompiledBundleDigests {
1079        unsplit_bundles_sha256: compute_bundle_dir_sha256s(&bundles_dir)?,
1080        active_bundles_sha256: compute_bundle_dir_sha256s(&split_live_dir)?,
1081        history_bundles_sha256: compute_bundle_dir_sha256s(&split_history_dir)?,
1082    };
1083    verify_compiled_bundles_match_ledger(
1084        graph_dir,
1085        nodes,
1086        framing,
1087        Some(&digests),
1088        true,
1089    )?;
1090    Ok(digests)
1091}
1092
1093/// Parses and validates `ledger-journal.jsonl`:
1094/// - Any complete (`\n`-terminated) line that fails JSON parsing or `verify_sha256()` is rejected as hard corruption.
1095/// - Only an unterminated final line (not ending in `\n`) is reported in `torn_trailing_fragment`.
1096pub fn inspect_ledger_journal(journal_path: &Path) -> Result<ParsedJournal> {
1097    let raw = fs::read(journal_path).with_context(|| {
1098        format!("Failed to read ledger journal {}", journal_path.display())
1099    })?;
1100
1101    let mut valid_prefix_len = 0usize;
1102    let mut torn_trailing_fragment: Option<Vec<u8>> = None;
1103    let mut records: Vec<JournalRecord> = Vec::new();
1104
1105    for line_bytes in raw.split_inclusive(|&byte| byte == b'\n') {
1106        let offset = valid_prefix_len;
1107        if line_bytes.last() == Some(&b'\n') {
1108            let line_str = std::str::from_utf8(line_bytes)
1109                .with_context(|| {
1110                    format!(
1111                        "CRITICAL: Invalid UTF-8 in complete journal line in {} at byte offset {offset}",
1112                        journal_path.display()
1113                    )
1114                })?
1115                .trim_end_matches(['\r', '\n']);
1116            if !line_str.trim().is_empty() {
1117                let rec: JournalRecord = serde_json::from_str(line_str)
1118                    .with_context(|| {
1119                        format!(
1120                            "CRITICAL: Corrupted complete journal line in {} at byte offset {offset}",
1121                            journal_path.display()
1122                        )
1123                    })?;
1124                rec.verify_sha256().with_context(|| {
1125                    format!(
1126                        "CRITICAL: Checksum failure in complete journal record in {} at byte offset {offset}",
1127                        journal_path.display()
1128                    )
1129                })?;
1130                records.push(rec);
1131            }
1132            valid_prefix_len =
1133                valid_prefix_len.saturating_add(line_bytes.len());
1134        } else if !line_bytes.iter().all(u8::is_ascii_whitespace) {
1135            torn_trailing_fragment = Some(line_bytes.to_vec());
1136        }
1137    }
1138
1139    let mut committed_pairs: Vec<(JournalRecord, JournalRecord)> = Vec::new();
1140    let mut open_pending: Option<JournalRecord> = None;
1141    let mut last_committed: Option<JournalRecord> = None;
1142
1143    for (idx, rec) in records.iter().enumerate() {
1144        match rec.state.as_str() {
1145            "BATCH_PENDING" => {
1146                ensure!(
1147                    open_pending.is_none(),
1148                    "CRITICAL: Journal {} has consecutive BATCH_PENDING records without an intervening BATCH_COMMITTED (record index {idx}, batch_id={})",
1149                    journal_path.display(),
1150                    rec.batch_id
1151                );
1152                open_pending = Some(rec.clone());
1153            }
1154            "BATCH_COMMITTED" => {
1155                let Some(pending) = open_pending.take() else {
1156                    bail!(
1157                        "CRITICAL: Journal {} has orphan BATCH_COMMITTED at record index {idx} (batch_id={}) without matching BATCH_PENDING",
1158                        journal_path.display(),
1159                        rec.batch_id
1160                    );
1161                };
1162                ensure!(
1163                    pending.batch_id == rec.batch_id
1164                        && pending.kind == rec.kind
1165                        && pending.baseline_last_id == rec.baseline_last_id
1166                        && pending.baseline_ledger_sha256
1167                            == rec.baseline_ledger_sha256
1168                        && pending.final_last_id == rec.final_last_id
1169                        && pending.final_ledger_sha256
1170                            == rec.final_ledger_sha256
1171                        && pending.manifest_sha256 == rec.manifest_sha256,
1172                    "CRITICAL: BATCH_COMMITTED (batch_id={}) does not match preceding BATCH_PENDING (batch_id={}) in {}",
1173                    rec.batch_id,
1174                    pending.batch_id,
1175                    journal_path.display()
1176                );
1177                last_committed = Some(rec.clone());
1178                committed_pairs.push((pending, rec.clone()));
1179            }
1180            other => {
1181                bail!(
1182                    "CRITICAL: Unknown journal record state {:?} at index {idx} in {}",
1183                    other,
1184                    journal_path.display()
1185                );
1186            }
1187        }
1188    }
1189
1190    Ok(ParsedJournal {
1191        valid_prefix_len,
1192        torn_trailing_fragment,
1193        records,
1194        committed_pairs,
1195        open_pending,
1196        last_committed,
1197    })
1198}
1199
1200/// Truncates an unterminated trailing line from `journal_path` at `valid_prefix_len` and `fsync`s both file and parent directory.
1201pub fn repair_torn_journal_suffix(
1202    journal_path: &Path,
1203    valid_prefix_len: usize,
1204) -> Result<()> {
1205    let raw = fs::read(journal_path).with_context(|| {
1206        format!(
1207            "Failed to read {} for torn-suffix repair",
1208            journal_path.display()
1209        )
1210    })?;
1211    let prefix = raw.get(..valid_prefix_len).context(
1212        "valid_prefix_len exceeds journal file length during torn-suffix repair",
1213    )?;
1214    let tmp_path = journal_path.with_extension("jsonl.repair.tmp");
1215    {
1216        let mut f = OpenOptions::new()
1217            .create(true)
1218            .write(true)
1219            .truncate(true)
1220            .open(&tmp_path)
1221            .with_context(|| {
1222                format!("Failed to create {}", tmp_path.display())
1223            })?;
1224        f.write_all(prefix)?;
1225        f.sync_all()?;
1226    }
1227    fs::rename(&tmp_path, journal_path).with_context(|| {
1228        format!(
1229            "Failed to replace {} with repaired journal {}",
1230            journal_path.display(),
1231            tmp_path.display()
1232        )
1233    })?;
1234    fsync_file(journal_path)?;
1235    if let Some(parent) = journal_path.parent() {
1236        fsync_dir(parent)?;
1237    }
1238    Ok(())
1239}
1240
1241fn append_journal_record(
1242    journal_path: &Path,
1243    record: &JournalRecord,
1244    fault: Option<FaultInjectionPoint>,
1245) -> Result<()> {
1246    let record = record.clone().with_computed_sha256()?;
1247    let mut line = serde_json::to_string(&record)
1248        .context("Failed to serialize JournalRecord")?;
1249    line.push('\n');
1250
1251    if let Some(parent) = journal_path.parent() {
1252        fs::create_dir_all(parent).with_context(|| {
1253            format!("Failed to create {}", parent.display())
1254        })?;
1255    }
1256
1257    let torn_len = match (record.state.as_str(), fault) {
1258        (
1259            "BATCH_PENDING",
1260            Some(FaultInjectionPoint::TornPendingRecord { bytes_to_keep }),
1261        )
1262        | (
1263            "BATCH_COMMITTED",
1264            Some(FaultInjectionPoint::TornCommittedRecord { bytes_to_keep }),
1265        ) => Some(bytes_to_keep),
1266        _ => None,
1267    };
1268
1269    if let Some(keep) = torn_len {
1270        let clamped = keep.min(line.len().saturating_sub(1));
1271        let slice = line.as_bytes().get(..clamped).unwrap_or_default();
1272        let mut f = OpenOptions::new()
1273            .create(true)
1274            .append(true)
1275            .open(journal_path)
1276            .with_context(|| {
1277                format!("Failed to open {} for append", journal_path.display())
1278            })?;
1279        f.write_all(slice)?;
1280        f.sync_all()?;
1281        bail!(
1282            "Simulated fault injection: wrote torn {} record ({} bytes without newline)",
1283            record.state,
1284            slice.len()
1285        );
1286    }
1287
1288    let mut f = OpenOptions::new()
1289        .create(true)
1290        .append(true)
1291        .open(journal_path)
1292        .with_context(|| {
1293            format!("Failed to open {} for append", journal_path.display())
1294        })?;
1295    f.write_all(line.as_bytes())?;
1296    f.sync_all()?;
1297    if let Some(parent) = journal_path.parent() {
1298        fsync_dir(parent)?;
1299    }
1300    Ok(())
1301}
1302
1303fn stamp_journal_initialized_marker(repo_root: &Path) -> Result<()> {
1304    let marker_path = repo_root.join(JOURNAL_INITIALIZED_REL_PATH);
1305    if let Some(parent) = marker_path.parent() {
1306        fs::create_dir_all(parent).with_context(|| {
1307            format!("Failed to create {}", parent.display())
1308        })?;
1309    }
1310    if !marker_path.is_file() {
1311        let mut f = OpenOptions::new()
1312            .create(true)
1313            .write(true)
1314            .truncate(true)
1315            .open(&marker_path)
1316            .with_context(|| {
1317                format!("Failed to write {}", marker_path.display())
1318            })?;
1319        f.write_all(b"initialized\n")?;
1320        f.sync_all()?;
1321        if let Some(parent) = marker_path.parent() {
1322            fsync_dir(parent)?;
1323        }
1324    }
1325    Ok(())
1326}
1327
1328/// Loads all complete `.ctbnodes` nodes from `dir`, allowing at most a torn trailing line at the end
1329/// of the final chunk file when recovering an interrupted `BATCH_PENDING` transaction.
1330fn load_nodes_from_dir_allowing_torn_tail(
1331    dir: &Path,
1332) -> Result<(Vec<LedgerNode>, Option<(PathBuf, Vec<u8>)>)> {
1333    let files = list_chunk_files(dir)?;
1334    let mut all_nodes = Vec::new();
1335    let mut torn_tail: Option<(PathBuf, Vec<u8>)> = None;
1336    let total_files = files.len();
1337
1338    for (idx, path) in files.into_iter().enumerate() {
1339        let is_last_file = idx.saturating_add(1) == total_files;
1340        let raw = fs::read(&path).with_context(|| {
1341            format!("Failed to read .ctbnodes chunk {}", path.display())
1342        })?;
1343        let complete_len = if is_last_file
1344            && !raw.is_empty()
1345            && raw.last() != Some(&b'\n')
1346        {
1347            let complete_len = raw
1348                .iter()
1349                .rposition(|&byte| byte == b'\n')
1350                .map_or(0, |last_nl| last_nl.saturating_add(1));
1351            let tail = raw
1352                .get(complete_len..)
1353                .context("Invalid complete prefix length in .ctbnodes chunk")?;
1354            torn_tail = Some((path.clone(), tail.to_vec()));
1355            complete_len
1356        } else {
1357            ensure!(
1358                raw.is_empty() || raw.last() == Some(&b'\n'),
1359                "CRITICAL: Non-final .ctbnodes chunk {} has an unterminated line!",
1360                path.display()
1361            );
1362            raw.len()
1363        };
1364        let complete_bytes = raw
1365            .get(..complete_len)
1366            .context("Invalid complete prefix length in .ctbnodes chunk")?;
1367        let text_to_parse =
1368            std::str::from_utf8(complete_bytes).with_context(|| {
1369                format!(
1370                    "CRITICAL: Invalid UTF-8 in complete .ctbnodes lines in {}",
1371                    path.display()
1372                )
1373            })?;
1374
1375        let chunk_nodes = load_ledger_nodes_from_str(
1376            text_to_parse,
1377            &path.display().to_string(),
1378        )?;
1379        all_nodes.extend(chunk_nodes);
1380    }
1381
1382    Ok((all_nodes, torn_tail))
1383}
1384
1385fn verify_and_extract_baseline_for_pending(
1386    dir: &Path,
1387    label: &str,
1388    pending: &JournalRecord,
1389) -> Result<(Vec<LedgerNode>, usize)> {
1390    let (disk_nodes, torn_tail) = load_nodes_from_dir_allowing_torn_tail(dir)?;
1391    let baseline_count = disk_nodes
1392        .iter()
1393        .take_while(|n| n.id <= pending.baseline_last_id)
1394        .count();
1395    let baseline_nodes: Vec<LedgerNode> = disk_nodes
1396        .get(..baseline_count)
1397        .unwrap_or_default()
1398        .to_vec();
1399    let appended_nodes: &[LedgerNode] =
1400        disk_nodes.get(baseline_count..).unwrap_or_default();
1401
1402    let actual_baseline_sha =
1403        compute_nodes_slice_ledger_sha256(&baseline_nodes);
1404    ensure!(
1405        actual_baseline_sha == pending.baseline_ledger_sha256,
1406        "CRITICAL: {label} ({}) baseline prefix (<= l{}) SHA-256 {} does not match BATCH_PENDING.baseline_ledger_sha256 {}",
1407        dir.display(),
1408        pending.baseline_last_id,
1409        actual_baseline_sha,
1410        pending.baseline_ledger_sha256
1411    );
1412
1413    ensure!(
1414        appended_nodes.len() <= pending.items.len(),
1415        "CRITICAL: {label} ({}) has {} nodes beyond baseline l{}, exceeding BATCH_PENDING.items ({} items)",
1416        dir.display(),
1417        appended_nodes.len(),
1418        pending.baseline_last_id,
1419        pending.items.len()
1420    );
1421
1422    for (idx, node) in appended_nodes.iter().enumerate() {
1423        let Some(expected_item) = pending.items.get(idx) else {
1424            bail!("Unexpected appended node index {idx}");
1425        };
1426        let actual_line = node.format_line();
1427        ensure!(
1428            node.id == expected_item.node_id
1429                && actual_line == expected_item.raw_line,
1430            "CRITICAL: {label} ({}) appended node at offset {idx} (l{}: {:?}) does not match BATCH_PENDING item (l{}: {:?})",
1431            dir.display(),
1432            node.id,
1433            actual_line,
1434            expected_item.node_id,
1435            expected_item.raw_line
1436        );
1437    }
1438
1439    if let Some((torn_path, frag)) = torn_tail {
1440        let next_idx = appended_nodes.len();
1441        let Some(next_item) = pending.items.get(next_idx) else {
1442            bail!(
1443                "CRITICAL: {label} ({}) has trailing fragment {:?} after all {} BATCH_PENDING items!",
1444                torn_path.display(),
1445                frag,
1446                pending.items.len()
1447            );
1448        };
1449        let expected_full_line = format!("{}\n", next_item.raw_line);
1450        ensure!(
1451            expected_full_line.as_bytes().starts_with(&frag),
1452            "CRITICAL: {label} ({}) trailing fragment {:?} is not a strict byte prefix of expected item line {:?}",
1453            torn_path.display(),
1454            frag,
1455            expected_full_line
1456        );
1457    }
1458
1459    Ok((baseline_nodes, appended_nodes.len()))
1460}
1461
1462fn parse_planned_items_to_nodes(
1463    items: &[PlannedLedgerItem],
1464) -> Result<Vec<LedgerNode>> {
1465    let mut out = Vec::with_capacity(items.len());
1466    for item in items {
1467        let parsed = load_ledger_nodes_from_str(
1468            &format!("{}\n", item.raw_line),
1469            &item.target_chunk,
1470        )?;
1471        let Some(node) = parsed.into_iter().next() else {
1472            bail!(
1473                "Planned item for l{} produced no LedgerNode from raw_line {:?}",
1474                item.node_id,
1475                item.raw_line
1476            );
1477        };
1478        ensure!(
1479            node.id == item.node_id,
1480            "Planned item node_id l{} does not match parsed raw_line node l{}",
1481            item.node_id,
1482            node.id
1483        );
1484        out.push(node);
1485    }
1486    Ok(out)
1487}
1488
1489fn append_single_node_to_ledger_dir(
1490    dir: &Path,
1491    all_nodes_through_current: &[LedgerNode],
1492    torn_bytes_to_keep: Option<usize>,
1493) -> Result<PathBuf> {
1494    let Some(last_node) = all_nodes_through_current.last() else {
1495        bail!("append_single_node_to_ledger_dir called with empty node slice");
1496    };
1497    let chunk_rel = chunk_filename_for_node_id(last_node.id);
1498    let Some(chunk_start_id) = parse_chunk_rel_path_start_id(&chunk_rel) else {
1499        bail!("Invalid chunk relative path {chunk_rel}");
1500    };
1501    // Reason for fallback: MAX_NODES_PER_CHUNK is the compile-time constant 100.
1502    let chunk_end_id = chunk_start_id
1503        .saturating_add(u128::try_from(MAX_NODES_PER_CHUNK).unwrap_or(100));
1504
1505    let mut content = String::new();
1506    for node in all_nodes_through_current {
1507        if node.id >= chunk_start_id && node.id < chunk_end_id {
1508            if node.id == last_node.id
1509                && let Some(keep) = torn_bytes_to_keep
1510            {
1511                let line = node.format_line();
1512                let clamped = keep.min(line.len());
1513                content.push_str(line.get(..clamped).unwrap_or_default());
1514            } else {
1515                content.push_str(&node.format_line());
1516                content.push('\n');
1517            }
1518        }
1519    }
1520    let chunk_path = dir.join(&chunk_rel);
1521    write_chunk_file_append_only(&chunk_path, &content)?;
1522    Ok(chunk_path)
1523}
1524
1525fn unprotect_shadow_tail_for_append(shadow_dir: &Path, target_chunk: &str) {
1526    #[cfg(unix)]
1527    {
1528        use std::os::unix::fs::PermissionsExt;
1529        let chunk_path = shadow_dir.join(target_chunk);
1530        if chunk_path.exists() {
1531            let _ = fs::set_permissions(
1532                &chunk_path,
1533                fs::Permissions::from_mode(0o644),
1534            );
1535        }
1536    }
1537}
1538
1539fn reprotect_shadow_chunks(shadow_dir: &Path) {
1540    #[cfg(unix)]
1541    {
1542        use std::os::unix::fs::PermissionsExt;
1543        if let Ok(files) = list_chunk_files(shadow_dir) {
1544            for file in files {
1545                let _ = fs::set_permissions(
1546                    &file,
1547                    fs::Permissions::from_mode(0o444),
1548                );
1549            }
1550        }
1551    }
1552}
1553
1554/// When `ledger-journal.jsonl` has no open `BATCH_PENDING` record (for example, if
1555/// `ledger-journal.jsonl` was reverted while kernel append-only flags preserved
1556/// `assets/data/graph/*.ctbnodes` and `built/graph-ledger/highwater/*.ctbnodes`),
1557/// checks whether `.ctbnodes` has a strictly appended suffix beyond
1558/// `last_committed.final_last_id` and, if so, verifies all four recovery invariants
1559/// before synthesizing the missing `BATCH_PENDING` record:
1560/// 1. The `.ctbnodes` prefix `<= last_committed.final_last_id` matches both
1561///    `last_committed.final_last_id` and `last_committed.final_ledger_sha256`.
1562/// 2. The appended `.ctbnodes` suffix has no torn line and strictly contiguous IDs.
1563/// 3. At least one non-empty high-water shadow ledger (`built/graph-ledger/highwater`)
1564///    corroborates the exact full `.ctbnodes` sequence line-for-line.
1565/// 4. Every appended node ID is covered by an in-graph
1566///    `CollectiveToolboxDcCsvSeedDatabase` provenance pair within the appended suffix.
1567fn try_synthesize_pending_for_verified_csv_tail(
1568    repo_root: &Path,
1569    parsed: &ParsedJournal,
1570    required_manifest_present: bool,
1571) -> Result<Option<JournalRecord>> {
1572    if parsed.open_pending.is_some() || required_manifest_present {
1573        return Ok(None);
1574    }
1575    let Some(last_committed) = &parsed.last_committed else {
1576        return Ok(None);
1577    };
1578
1579    let graph_dir = repo_root.join("assets/data/graph");
1580    if !graph_dir.is_dir() {
1581        return Ok(None);
1582    }
1583
1584    let (disk_nodes, torn_tail) =
1585        load_nodes_from_dir_allowing_torn_tail(&graph_dir)?;
1586    let Some(last_disk_node) = disk_nodes.last() else {
1587        return Ok(None);
1588    };
1589    if last_disk_node.id <= last_committed.final_last_id {
1590        return Ok(None);
1591    }
1592
1593    ensure!(
1594        torn_tail.is_none(),
1595        "CRITICAL: {} has nodes beyond latest BATCH_COMMITTED (l{}) AND an unterminated trailing line, with no open BATCH_PENDING record in ledger-journal.jsonl",
1596        graph_dir.display(),
1597        last_committed.final_last_id
1598    );
1599
1600    let baseline_count = disk_nodes
1601        .iter()
1602        .take_while(|n| n.id <= last_committed.final_last_id)
1603        .count();
1604    let baseline_nodes = disk_nodes
1605        .get(..baseline_count)
1606        .context("Invalid baseline prefix slice during journal tail recovery")?;
1607    let appended_nodes = disk_nodes
1608        .get(baseline_count..)
1609        .context("Invalid appended suffix slice during journal tail recovery")?;
1610
1611    let actual_baseline_last_id = match baseline_nodes.last() {
1612        Some(node) => node.id,
1613        None => 0,
1614    };
1615    let actual_baseline_sha = compute_nodes_slice_ledger_sha256(baseline_nodes);
1616    ensure!(
1617        actual_baseline_last_id == last_committed.final_last_id
1618            && actual_baseline_sha == last_committed.final_ledger_sha256,
1619        "CRITICAL: {} prefix (<= l{}, sha256={}) does not match latest BATCH_COMMITTED ({}, final_last_id=l{}, sha256={}); refusing automatic journal recovery",
1620        graph_dir.display(),
1621        actual_baseline_last_id,
1622        actual_baseline_sha,
1623        last_committed.batch_id,
1624        last_committed.final_last_id,
1625        last_committed.final_ledger_sha256
1626    );
1627
1628    let mut expected_id = last_committed
1629        .final_last_id
1630        .checked_add(1)
1631        .context("Overflow computing expected appended node ID")?;
1632    for node in appended_nodes {
1633        ensure!(
1634            node.id == expected_id,
1635            "CRITICAL: Appended .ctbnodes tail in {} has non-contiguous node ID l{} (expected l{}); refusing automatic journal recovery",
1636            graph_dir.display(),
1637            node.id,
1638            expected_id
1639        );
1640        expected_id = expected_id
1641            .checked_add(1)
1642            .context("Overflow advancing expected appended node ID")?;
1643    }
1644
1645    let mut corroborated_by_shadow = false;
1646    for (label, shadow_dir) in highwater_shadow_dirs(repo_root) {
1647        if shadow_dir.is_dir() && !list_chunk_files(&shadow_dir)?.is_empty() {
1648            let shadow_nodes = load_ledger_nodes_from_dir_raw(&shadow_dir)
1649                .with_context(|| {
1650                    format!("Failed to load {label} from {}", shadow_dir.display())
1651                })?;
1652            verify_nodes_append_only_against_baseline(
1653                &label,
1654                &shadow_nodes,
1655                &disk_nodes,
1656            )?;
1657            if shadow_nodes.len() == disk_nodes.len() {
1658                corroborated_by_shadow = true;
1659            }
1660        }
1661    }
1662    ensure!(
1663        corroborated_by_shadow,
1664        "CRITICAL: {} has {} node(s) beyond latest BATCH_COMMITTED (l{}..=l{}), but high-water shadow ledger does not corroborate the appended tail; refusing automatic journal recovery",
1665        graph_dir.display(),
1666        appended_nodes.len(),
1667        last_committed.final_last_id.saturating_add(1),
1668        last_disk_node.id
1669    );
1670
1671    let (active_ident_to_short, _, _, _, _) =
1672        resolve_active_short_idents_from_nodes(&disk_nodes)?;
1673    let get_req = |ident: &str| -> Result<DcShorthand> {
1674        active_ident_to_short.get(ident).copied().with_context(|| {
1675            format!(
1676                "Missing required @ident(\"{ident}\") in system graph for CSV provenance recovery"
1677            )
1678        })
1679    };
1680    let sh_dist = get_req("DistributeStatementOverEach")?;
1681    let sh_has_a = get_req("HasA")?;
1682    let sh_this_elem = get_req("ThisElement")?;
1683    let sh_data_source = get_req("CollectiveToolboxSeedGraphDataSource")?;
1684    let sh_begin_list = get_req("BeginList")?;
1685    let sh_type_atom = get_req("TypeAtomDc")?;
1686    let sh_sep = get_req("ListElementSeparator")?;
1687    let sh_end_list = get_req("EndList")?;
1688    let sh_has_value = get_req("HasValue")?;
1689    let sh_csv_db = get_req("CollectiveToolboxDcCsvSeedDatabase")?;
1690
1691    let mut claim_targets_by_id: HashMap<u128, Vec<u128>> = HashMap::new();
1692    for node in appended_nodes {
1693        let toks = node.tokens.as_slice();
1694        if let &[ha, DcShorthand::Long(target_id), prop] = toks
1695            && ha == sh_has_a
1696            && prop == sh_data_source
1697        {
1698            claim_targets_by_id.insert(node.id, vec![target_id]);
1699            continue;
1700        }
1701        if let &[dist, ha, te, prop, DcShorthand::Long(target_id)] = toks
1702            && dist == sh_dist
1703            && ha == sh_has_a
1704            && te == sh_this_elem
1705            && prop == sh_data_source
1706        {
1707            claim_targets_by_id.insert(node.id, vec![target_id]);
1708            continue;
1709        }
1710        if toks.len() >= 8
1711            && toks.get(0) == Some(&sh_dist)
1712            && toks.get(1) == Some(&sh_has_a)
1713            && toks.get(2) == Some(&sh_this_elem)
1714            && toks.get(3) == Some(&sh_data_source)
1715            && toks.get(4) == Some(&sh_begin_list)
1716            && toks.get(5) == Some(&sh_type_atom)
1717            && toks.last() == Some(&sh_end_list)
1718        {
1719            let end_idx = toks.len().saturating_sub(1);
1720            let mut idx = 6usize;
1721            let mut targets: Vec<u128> = Vec::new();
1722            let mut valid = true;
1723            while idx < end_idx {
1724                let Some(&DcShorthand::Long(target_id)) = toks.get(idx) else {
1725                    valid = false;
1726                    break;
1727                };
1728                targets.push(target_id);
1729                idx = idx.saturating_add(1);
1730                if idx < end_idx {
1731                    if toks.get(idx) != Some(&sh_sep) {
1732                        valid = false;
1733                        break;
1734                    }
1735                    idx = idx.saturating_add(1);
1736                    if idx >= end_idx {
1737                        valid = false;
1738                        break;
1739                    }
1740                }
1741            }
1742            if valid && !targets.is_empty() {
1743                claim_targets_by_id.insert(node.id, targets);
1744            }
1745        }
1746    }
1747
1748    let mut csv_provenanced_ids: HashSet<u128> = HashSet::new();
1749    for node in appended_nodes {
1750        if let &[hv, DcShorthand::Long(claim_id), db] = node.tokens.as_slice()
1751            && hv == sh_has_value
1752            && db == sh_csv_db
1753            && let Some(targets) = claim_targets_by_id.get(&claim_id)
1754        {
1755            csv_provenanced_ids.insert(claim_id);
1756            csv_provenanced_ids.insert(node.id);
1757            for &target_id in targets {
1758                csv_provenanced_ids.insert(target_id);
1759            }
1760        }
1761    }
1762
1763    for node in appended_nodes {
1764        ensure!(
1765            csv_provenanced_ids.contains(&node.id),
1766            "CRITICAL: Appended node l{} in {} lacks verified in-graph CollectiveToolboxDcCsvSeedDatabase provenance; refusing automatic journal recovery",
1767            node.id,
1768            graph_dir.display()
1769        );
1770    }
1771
1772    let final_last_id = last_disk_node.id;
1773    let final_ledger_sha256 = compute_nodes_slice_ledger_sha256(&disk_nodes);
1774    let items: Vec<PlannedLedgerItem> = appended_nodes
1775        .iter()
1776        .map(|node| PlannedLedgerItem {
1777            node_id: node.id,
1778            raw_line: node.format_line(),
1779            target_chunk: chunk_filename_for_node_id(node.id),
1780            tokens: Vec::new(),
1781            comment: String::new(),
1782            provenance: "csv".to_string(),
1783            rationale: None,
1784            allow_duplicate_of: Vec::new(),
1785            inbox_name: None,
1786            allocated_name: None,
1787            inbox_sha256: None,
1788            dcsh_content: None,
1789        })
1790        .collect();
1791
1792    Ok(Some(JournalRecord {
1793        state: "BATCH_PENDING".to_string(),
1794        batch_id: format!(
1795            "csv-reconcile-recovered-{}-{final_last_id}",
1796            last_committed.final_last_id
1797        ),
1798        kind: "csv_reconciliation".to_string(),
1799        baseline_last_id: last_committed.final_last_id,
1800        baseline_ledger_sha256: last_committed.final_ledger_sha256.clone(),
1801        final_last_id,
1802        final_ledger_sha256,
1803        manifest_sha256: None,
1804        items,
1805        unsplit_bundles_sha256: BTreeMap::new(),
1806        active_bundles_sha256: BTreeMap::new(),
1807        history_bundles_sha256: BTreeMap::new(),
1808        record_sha256: String::new(),
1809    }))
1810}
1811
1812/// Synthesizes a zero-item `bundle_format_refresh` `BATCH_PENDING` record when `.ctbnodes`
1813/// matches `last_committed` (`final_last_id` and `final_ledger_sha256`), high-water shadow
1814/// ledgers corroborate `.ctbnodes`, and the canonical `.ctbnbdl` encoding or layout produced by
1815/// the current compiler differs from `last_committed`'s recorded bundle digests or on-disk
1816/// `assets/data/graph-bundles/` files.
1817fn try_synthesize_pending_for_bundle_format_refresh(
1818    repo_root: &Path,
1819    parsed: &ParsedJournal,
1820    required_manifest_present: bool,
1821) -> Result<Option<JournalRecord>> {
1822    if parsed.open_pending.is_some() || required_manifest_present {
1823        return Ok(None);
1824    }
1825    let Some(last_committed) = &parsed.last_committed else {
1826        return Ok(None);
1827    };
1828    let graph_dir = repo_root.join("assets/data/graph");
1829    if !graph_dir.is_dir() {
1830        return Ok(None);
1831    }
1832    let actual_ledger_sha = compute_ledger_dir_sha256(&graph_dir)?;
1833    if actual_ledger_sha != last_committed.final_ledger_sha256 {
1834        return Ok(None);
1835    }
1836    let disk_nodes = load_ledger_nodes_from_dir_raw(&graph_dir)?;
1837    // Reason for fallback: empty ledger has last_id == 0.
1838    let actual_last_id = disk_nodes.last().map_or(0, |n| n.id);
1839    if actual_last_id != last_committed.final_last_id {
1840        return Ok(None);
1841    }
1842
1843    for (label, shadow_dir) in highwater_shadow_dirs(repo_root) {
1844        if shadow_dir.is_dir() && !list_chunk_files(&shadow_dir)?.is_empty() {
1845            let shadow_nodes = load_ledger_nodes_from_dir_raw(&shadow_dir)?;
1846            verify_nodes_append_only_against_baseline(
1847                &label,
1848                &shadow_nodes,
1849                &disk_nodes,
1850            )?;
1851        }
1852    }
1853
1854    let framing = resolve_ctbnbdl_framing_dcs_from_nodes(&disk_nodes)?;
1855    let unsplit_bundles =
1856        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
1857            &disk_nodes,
1858            framing,
1859            MAX_NODES_PER_BUNDLE,
1860            MAX_BYTES_PER_BUNDLE,
1861            None,
1862        )?;
1863    let most_recent_node_id = disk_nodes.iter().map(|n| n.id).max();
1864    let (active_nodes, inactive_nodes) =
1865        partition_active_and_inactive_nodes_with(&disk_nodes, framing);
1866    let active_bundles =
1867        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
1868            &active_nodes,
1869            framing,
1870            MAX_NODES_PER_BUNDLE,
1871            MAX_BYTES_PER_BUNDLE,
1872            most_recent_node_id,
1873        )?;
1874    let inactive_bundles =
1875        encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
1876            &inactive_nodes,
1877            framing,
1878            MAX_NODES_PER_BUNDLE,
1879            MAX_BYTES_PER_BUNDLE,
1880            most_recent_node_id,
1881        )?;
1882
1883    let mut canonical_unsplit_sha = BTreeMap::new();
1884    for (first_id, bytes) in &unsplit_bundles {
1885        canonical_unsplit_sha.insert(
1886            format_chunk_bundle_filename(*first_id),
1887            sha256_bytes_hex(bytes),
1888        );
1889    }
1890    let mut canonical_active_sha = BTreeMap::new();
1891    for (first_id, bytes) in &active_bundles {
1892        canonical_active_sha.insert(
1893            format_chunk_bundle_filename(*first_id),
1894            sha256_bytes_hex(bytes),
1895        );
1896    }
1897    let mut canonical_history_sha = BTreeMap::new();
1898    for (first_id, bytes) in &inactive_bundles {
1899        canonical_history_sha.insert(
1900            format_chunk_bundle_filename(*first_id),
1901            sha256_bytes_hex(bytes),
1902        );
1903    }
1904
1905    let bundles_dir = bundles_dir_for_graph_dir(&graph_dir);
1906    let disk_unsplit_sha = compute_bundle_dir_sha256s(&bundles_dir)?;
1907
1908    if canonical_unsplit_sha == last_committed.unsplit_bundles_sha256
1909        && disk_unsplit_sha == canonical_unsplit_sha
1910        && canonical_active_sha == last_committed.active_bundles_sha256
1911        && canonical_history_sha == last_committed.history_bundles_sha256
1912    {
1913        return Ok(None);
1914    }
1915
1916    Ok(Some(JournalRecord {
1917        state: "BATCH_PENDING".to_string(),
1918        batch_id: format!(
1919            "bundle-format-refresh-{}-{}",
1920            parsed.records.len(),
1921            last_committed.final_last_id
1922        ),
1923        kind: "bundle_format_refresh".to_string(),
1924        baseline_last_id: last_committed.final_last_id,
1925        baseline_ledger_sha256: last_committed.final_ledger_sha256.clone(),
1926        final_last_id: last_committed.final_last_id,
1927        final_ledger_sha256: last_committed.final_ledger_sha256.clone(),
1928        manifest_sha256: None,
1929        items: Vec::new(),
1930        unsplit_bundles_sha256: BTreeMap::new(),
1931        active_bundles_sha256: BTreeMap::new(),
1932        history_bundles_sha256: BTreeMap::new(),
1933        record_sha256: String::new(),
1934    }))
1935}
1936
1937/// Executes standalone recovery of any open `BATCH_PENDING` record, torn journal line, or
1938/// verified CSV-provenanced `.ctbnodes` tail ahead of `ledger-journal.jsonl`.
1939///
1940/// This function lives in `ctb_build_support` so it can be built and invoked via
1941/// `ctb-lint recover-ledger-journal` even when `ctb-formats-dcdata/build.rs` is blocked by an
1942/// uncommitted `BATCH_PENDING` transaction.
1943pub fn recover_pending_ledger_journal(
1944    repo_root: &Path,
1945    required_manifest_path: Option<&Path>,
1946    dry_run: bool,
1947) -> Result<bool> {
1948    let write_guard = LedgerWriteGuard::acquire(repo_root)?;
1949    let loaded_manifest = if let Some(mpath) = required_manifest_path {
1950        let bytes = fs::read(mpath).with_context(|| {
1951            format!("Failed to read manifest {}", mpath.display())
1952        })?;
1953        let sha = sha256_bytes_hex(&bytes);
1954        let manifest: TransactionManifest = serde_json::from_slice(&bytes)
1955            .with_context(|| {
1956                format!("Failed to parse manifest {}", mpath.display())
1957            })?;
1958        Some((manifest, sha))
1959    } else {
1960        None
1961    };
1962    let manifest_ref = loaded_manifest.as_ref().map(|(m, s)| (m, s.as_str()));
1963    recover_pending_ledger_journal_with_guard(
1964        &write_guard,
1965        repo_root,
1966        manifest_ref,
1967        dry_run,
1968        None,
1969    )
1970}
1971
1972/// Internal recovery implementation operating under an already-held [`LedgerWriteGuard`].
1973pub fn recover_pending_ledger_journal_with_guard(
1974    write_guard: &LedgerWriteGuard,
1975    repo_root: &Path,
1976    required_manifest: Option<(&TransactionManifest, &str)>,
1977    dry_run: bool,
1978    fault: Option<FaultInjectionPoint>,
1979) -> Result<bool> {
1980    let journal_path = repo_root.join(LEDGER_JOURNAL_REL_PATH);
1981    if !journal_path.exists() {
1982        return Ok(false);
1983    }
1984
1985    let mut parsed = inspect_ledger_journal(&journal_path)?;
1986    if parsed.torn_trailing_fragment.is_some() {
1987        if dry_run {
1988            return Ok(true);
1989        }
1990        repair_torn_journal_suffix(&journal_path, parsed.valid_prefix_len)?;
1991        parsed = inspect_ledger_journal(&journal_path)?;
1992    }
1993
1994    if parsed.open_pending.is_none() {
1995        if let Some(synth_pending) = try_synthesize_pending_for_verified_csv_tail(
1996            repo_root,
1997            &parsed,
1998            required_manifest.is_some(),
1999        )? {
2000            if dry_run {
2001                return Ok(true);
2002            }
2003            append_journal_record(&journal_path, &synth_pending, fault)?;
2004            parsed = inspect_ledger_journal(&journal_path)?;
2005        } else if let Some(refresh_pending) =
2006            try_synthesize_pending_for_bundle_format_refresh(
2007                repo_root,
2008                &parsed,
2009                required_manifest.is_some(),
2010            )?
2011        {
2012            if dry_run {
2013                return Ok(true);
2014            }
2015            append_journal_record(&journal_path, &refresh_pending, fault)?;
2016            parsed = inspect_ledger_journal(&journal_path)?;
2017        }
2018    }
2019
2020    let Some(pending) = parsed.open_pending else {
2021        return Ok(false);
2022    };
2023
2024    if let Some((manifest, manifest_sha)) = required_manifest {
2025        ensure!(
2026            pending.manifest_sha256.as_deref() == Some(manifest_sha),
2027            "CRITICAL: Open BATCH_PENDING manifest_sha256 {:?} does not match required manifest SHA-256 {}",
2028            pending.manifest_sha256,
2029            manifest_sha
2030        );
2031        let pending_norm: Vec<PlannedLedgerItem> = pending
2032            .items
2033            .iter()
2034            .map(PlannedLedgerItem::normalized_for_journal)
2035            .collect();
2036        let manifest_norm: Vec<PlannedLedgerItem> = manifest
2037            .planned_items
2038            .iter()
2039            .map(PlannedLedgerItem::normalized_for_journal)
2040            .collect();
2041        ensure!(
2042            pending.kind == manifest.kind
2043                && pending.baseline_last_id == manifest.baseline_last_id
2044                && pending.baseline_ledger_sha256
2045                    == manifest.baseline_ledger_sha256
2046                && pending.final_last_id == manifest.final_last_id
2047                && pending.final_ledger_sha256 == manifest.final_ledger_sha256
2048                && pending_norm == manifest_norm,
2049            "CRITICAL: Open BATCH_PENDING contents do not match required manifest {}",
2050            manifest.manifest_id
2051        );
2052    }
2053
2054    let graph_dir = repo_root.join("assets/data/graph");
2055    let inbox_dir = repo_root.join("src/formats/dcdata/data-src/nodes/inbox");
2056    let allocated_dir =
2057        repo_root.join("src/formats/dcdata/data-src/nodes/allocated");
2058
2059    let (baseline_nodes, primary_appended_count) =
2060        verify_and_extract_baseline_for_pending(
2061            &graph_dir,
2062            "primary ledger",
2063            &pending,
2064        )?;
2065
2066    let mut shadow_appended_counts: BTreeMap<PathBuf, usize> = BTreeMap::new();
2067    for (label, shadow_dir) in highwater_shadow_dirs(repo_root) {
2068        if shadow_dir.is_dir() && !list_chunk_files(&shadow_dir)?.is_empty() {
2069            let (_, count) = verify_and_extract_baseline_for_pending(
2070                &shadow_dir,
2071                &label,
2072                &pending,
2073            )?;
2074            shadow_appended_counts.insert(shadow_dir, count);
2075        }
2076    }
2077
2078    // Validate all inbox/allocated source files for inbox_allocation items.
2079    for item in &pending.items {
2080        if let (Some(inbox_name), Some(alloc_name), Some(expected_sha)) = (
2081            item.inbox_name.as_deref(),
2082            item.allocated_name.as_deref(),
2083            item.inbox_sha256.as_deref(),
2084        ) {
2085            let inbox_path = inbox_dir.join(inbox_name);
2086            let alloc_path = allocated_dir.join(alloc_name);
2087            let in_inbox = inbox_path.is_file();
2088            let in_alloc = alloc_path.is_file();
2089            ensure!(
2090                in_inbox || in_alloc,
2091                "CRITICAL: Source .dcsh file for pending node l{} is missing from both {} and {}",
2092                item.node_id,
2093                inbox_path.display(),
2094                alloc_path.display()
2095            );
2096            if in_inbox {
2097                let actual_sha = sha256_file_hex(&inbox_path)?;
2098                ensure!(
2099                    actual_sha == expected_sha,
2100                    "CRITICAL: Inbox file {} SHA-256 {} does not match BATCH_PENDING inbox_sha256 {}",
2101                    inbox_path.display(),
2102                    actual_sha,
2103                    expected_sha
2104                );
2105            }
2106            if in_alloc {
2107                let actual_sha = sha256_file_hex(&alloc_path)?;
2108                ensure!(
2109                    actual_sha == expected_sha,
2110                    "CRITICAL: Allocated file {} SHA-256 {} does not match BATCH_PENDING inbox_sha256 {}",
2111                    alloc_path.display(),
2112                    actual_sha,
2113                    expected_sha
2114                );
2115            }
2116        }
2117    }
2118
2119    if dry_run {
2120        return Ok(true);
2121    }
2122
2123    let planned_nodes = parse_planned_items_to_nodes(&pending.items)?;
2124    let mut progressive_nodes = baseline_nodes;
2125    let shadow_dirs = highwater_shadow_dirs(repo_root);
2126    let mut touched_primary_chunks: BTreeMap<String, PathBuf> = BTreeMap::new();
2127    let mut touched_shadow_chunks: Vec<PathBuf> = Vec::new();
2128    let mut touched_allocated_files: Vec<PathBuf> = Vec::new();
2129
2130    for (idx, (item, node)) in pending
2131        .items
2132        .iter()
2133        .zip(planned_nodes.into_iter())
2134        .enumerate()
2135    {
2136        progressive_nodes.push(node);
2137
2138        let torn_keep = match fault {
2139            Some(FaultInjectionPoint::TornChunkLine {
2140                item_index,
2141                bytes_to_keep,
2142            }) if item_index == idx => Some(bytes_to_keep),
2143            _ => None,
2144        };
2145
2146        let primary_chunk = if idx >= primary_appended_count
2147            || torn_keep.is_some()
2148        {
2149            append_single_node_to_ledger_dir(
2150                &graph_dir,
2151                &progressive_nodes,
2152                torn_keep,
2153            )?
2154        } else {
2155            graph_dir.join(&item.target_chunk)
2156        };
2157        if torn_keep.is_some() {
2158            fsync_file(&primary_chunk)?;
2159            bail!(
2160                "Simulated fault injection: wrote torn .ctbnodes line for item {idx} (l{})",
2161                item.node_id
2162            );
2163        }
2164        touched_primary_chunks
2165            .insert(item.target_chunk.clone(), primary_chunk.clone());
2166
2167        for (label, shadow_dir) in &shadow_dirs {
2168            let shadow_count =
2169                shadow_appended_counts.get(shadow_dir).copied().unwrap_or(0);
2170            let shadow_chunk = if idx >= shadow_count {
2171                fs::create_dir_all(shadow_dir).with_context(|| {
2172                    format!(
2173                        "Failed to create {label} at {}",
2174                        shadow_dir.display()
2175                    )
2176                })?;
2177                unprotect_shadow_tail_for_append(
2178                    shadow_dir,
2179                    &item.target_chunk,
2180                );
2181                append_single_node_to_ledger_dir(
2182                    shadow_dir,
2183                    &progressive_nodes,
2184                    None,
2185                )?
2186            } else {
2187                shadow_dir.join(&item.target_chunk)
2188            };
2189            touched_shadow_chunks.push(shadow_chunk);
2190        }
2191
2192        if let (Some(inbox_name), Some(alloc_name)) =
2193            (item.inbox_name.as_deref(), item.allocated_name.as_deref())
2194        {
2195            fs::create_dir_all(&allocated_dir)?;
2196            let inbox_path = inbox_dir.join(inbox_name);
2197            let alloc_path = allocated_dir.join(alloc_name);
2198            if inbox_path.is_file() {
2199                fs::rename(&inbox_path, &alloc_path).with_context(|| {
2200                    format!(
2201                        "Failed to move {} to {}",
2202                        inbox_path.display(),
2203                        alloc_path.display()
2204                    )
2205                })?;
2206            }
2207            touched_allocated_files.push(alloc_path);
2208        }
2209
2210        if fault != Some(FaultInjectionPoint::BeforeFsync) {
2211            fsync_file(&primary_chunk)?;
2212            for (_, shadow_dir) in &shadow_dirs {
2213                let sc = shadow_dir.join(&item.target_chunk);
2214                if sc.is_file() {
2215                    fsync_file(&sc)?;
2216                }
2217            }
2218            if let Some(alloc_name) = item.allocated_name.as_deref() {
2219                let ap = allocated_dir.join(alloc_name);
2220                if ap.is_file() {
2221                    fsync_file(&ap)?;
2222                }
2223            }
2224        }
2225
2226        if fault
2227            == Some(FaultInjectionPoint::AfterItemAppendedAndMoved {
2228                item_index: idx,
2229            })
2230        {
2231            bail!(
2232                "Simulated fault injection: crash after item {idx} (l{}) appended and moved",
2233                item.node_id
2234            );
2235        }
2236    }
2237
2238    if fault == Some(FaultInjectionPoint::BeforeFsync) {
2239        bail!(
2240            "Simulated fault injection: crash after all writes/renames before fsync"
2241        );
2242    }
2243
2244    // Unconditionally fsync all touched primary chunks, shadow chunks, allocated files, and directories.
2245    for path in touched_primary_chunks.values() {
2246        fsync_file(path)?;
2247        if let Some(parent) = path.parent()
2248            && parent != graph_dir
2249        {
2250            fsync_dir(parent)?;
2251        }
2252    }
2253    fsync_dir(&graph_dir)?;
2254
2255    for path in &touched_shadow_chunks {
2256        if path.is_file() {
2257            fsync_file(path)?;
2258            if let Some(parent) = path.parent() {
2259                fsync_dir(parent)?;
2260            }
2261        }
2262    }
2263    for (_, shadow_dir) in &shadow_dirs {
2264        reprotect_shadow_chunks(shadow_dir);
2265        fsync_dir(shadow_dir)?;
2266    }
2267
2268    for path in &touched_allocated_files {
2269        if path.is_file() {
2270            fsync_file(path)?;
2271        }
2272    }
2273    fsync_dir(&inbox_dir)?;
2274    fsync_dir(&allocated_dir)?;
2275
2276    let actual_final_sha = compute_ledger_dir_sha256(&graph_dir)?;
2277    ensure!(
2278        actual_final_sha == pending.final_ledger_sha256,
2279        "CRITICAL: Final ledger SHA-256 {} after completing batch {} does not match expected {}",
2280        actual_final_sha,
2281        pending.batch_id,
2282        pending.final_ledger_sha256
2283    );
2284    let actual_last_id = progressive_nodes.last().map_or(0, |n| n.id);
2285    ensure!(
2286        actual_last_id == pending.final_last_id,
2287        "CRITICAL: Final node ID l{} after completing batch {} does not match expected l{}",
2288        actual_last_id,
2289        pending.batch_id,
2290        pending.final_last_id
2291    );
2292
2293    let framing = resolve_ctbnbdl_framing_dcs_from_nodes(&progressive_nodes)?;
2294    let bundle_digests = compile_nodes_slice_to_ctbnbdl_with_write_guard(
2295        write_guard,
2296        &progressive_nodes,
2297        &graph_dir,
2298        framing,
2299    )?;
2300
2301    let committed = JournalRecord {
2302        state: "BATCH_COMMITTED".to_string(),
2303        batch_id: pending.batch_id,
2304        kind: pending.kind,
2305        baseline_last_id: pending.baseline_last_id,
2306        baseline_ledger_sha256: pending.baseline_ledger_sha256,
2307        final_last_id: pending.final_last_id,
2308        final_ledger_sha256: pending.final_ledger_sha256,
2309        manifest_sha256: pending.manifest_sha256,
2310        items: Vec::new(),
2311        unsplit_bundles_sha256: bundle_digests.unsplit_bundles_sha256,
2312        active_bundles_sha256: bundle_digests.active_bundles_sha256,
2313        history_bundles_sha256: bundle_digests.history_bundles_sha256,
2314        record_sha256: String::new(),
2315    };
2316    append_journal_record(&journal_path, &committed, fault)?;
2317    stamp_journal_initialized_marker(repo_root)?;
2318    let _ = compact_closed_ledger_chunks_with_guard(write_guard, repo_root)?;
2319    Ok(true)
2320}
2321
2322/// Compacts `ledger-journal.jsonl` and removes closed-chunk `.ctbnode-incoming` (and legacy `.dcsh`)
2323/// files from `src/formats/dcdata/data-src/nodes/allocated/` for all `.ctbnodes` chunk files that
2324/// have reached `MAX_NODES_PER_CHUNK` (`100` nodes) and are therefore closed.
2325///
2326/// Any `Manual` provenance items (`provenance == "manual"`) in closed chunks are retained inside the
2327/// compacted `bootstrap_checkpoint` record's `items` list (with `inbox_name`, `allocated_name`, and
2328/// `inbox_sha256` cleared) so `Manual` node ownership is permanently preserved across compactions.
2329pub fn compact_closed_ledger_chunks(repo_root: &Path) -> Result<usize> {
2330    let write_guard = LedgerWriteGuard::acquire(repo_root)?;
2331    compact_closed_ledger_chunks_with_guard(&write_guard, repo_root)
2332}
2333
2334/// Internal closed-chunk compaction operating under an already-held [`LedgerWriteGuard`].
2335pub fn compact_closed_ledger_chunks_with_guard(
2336    write_guard: &LedgerWriteGuard,
2337    repo_root: &Path,
2338) -> Result<usize> {
2339    let journal_path = repo_root.join(LEDGER_JOURNAL_REL_PATH);
2340    if !journal_path.is_file() {
2341        return Ok(0);
2342    }
2343    let parsed = inspect_ledger_journal(&journal_path)?;
2344    if parsed.open_pending.is_some()
2345        || parsed.torn_trailing_fragment.is_some()
2346        || parsed.committed_pairs.is_empty()
2347    {
2348        return Ok(0);
2349    }
2350
2351    let graph_dir = repo_root.join("assets/data/graph");
2352    let nodes =
2353        load_ledger_nodes_from_dir_with_write_guard(write_guard, &graph_dir)?;
2354    let closed_node_count = nodes
2355        .len()
2356        .checked_div(MAX_NODES_PER_CHUNK)
2357        .unwrap_or(0)
2358        .saturating_mul(MAX_NODES_PER_CHUNK);
2359    if closed_node_count == 0 {
2360        return Ok(0);
2361    }
2362    let Some(closed_nodes) = nodes.get(..closed_node_count) else {
2363        return Ok(0);
2364    };
2365    let Some(last_closed_node) = closed_nodes.last() else {
2366        return Ok(0);
2367    };
2368    let closed_cutoff_id = last_closed_node.id;
2369
2370    let existing_bootstrap_last_id = parsed
2371        .committed_pairs
2372        .iter()
2373        .find(|(p, _)| p.kind == "bootstrap_checkpoint")
2374        .map_or(0, |(p, _)| p.final_last_id);
2375
2376    let allocated_dir =
2377        repo_root.join("src/formats/dcdata/data-src/nodes/allocated");
2378    let mut removable_files: Vec<PathBuf> = Vec::new();
2379    if allocated_dir.is_dir() {
2380        for entry in fs::read_dir(&allocated_dir)? {
2381            let entry = entry?;
2382            let path = entry.path();
2383            if !path.is_file() {
2384                continue;
2385            }
2386            let ext = path.extension().and_then(|e| e.to_str());
2387            if ext != Some("ctbnode-incoming") && ext != Some("dcsh") {
2388                continue;
2389            }
2390            let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
2391                continue;
2392            };
2393            if let Some((prefix, _)) = name.split_once('_')
2394                && let Ok(file_node_id) = prefix.parse::<u128>()
2395                && file_node_id <= closed_cutoff_id
2396            {
2397                removable_files.push(path);
2398            }
2399        }
2400    }
2401    removable_files.sort();
2402
2403    if closed_cutoff_id <= existing_bootstrap_last_id
2404        && removable_files.is_empty()
2405    {
2406        return Ok(0);
2407    }
2408
2409    if closed_cutoff_id > existing_bootstrap_last_id {
2410        let mut node_by_id: HashMap<u128, &LedgerNode> =
2411            HashMap::with_capacity(nodes.len());
2412        for node in &nodes {
2413            node_by_id.insert(node.id, node);
2414        }
2415
2416        let mut manual_items_by_id: BTreeMap<u128, PlannedLedgerItem> =
2417            BTreeMap::new();
2418        for (pending, committed) in &parsed.committed_pairs {
2419            for item in &pending.items {
2420                let Some(&ledger_node) = node_by_id.get(&item.node_id) else {
2421                    bail!(
2422                        "CRITICAL: Cannot compact journal {}: node l{} from {} is missing from .ctbnodes",
2423                        journal_path.display(),
2424                        item.node_id,
2425                        committed.batch_id
2426                    );
2427                };
2428                let actual_line = ledger_node.format_line();
2429                ensure!(
2430                    actual_line == item.raw_line,
2431                    "CRITICAL: Cannot compact journal {}: node l{} in .ctbnodes ({:?}) does not match {} ({:?})",
2432                    journal_path.display(),
2433                    item.node_id,
2434                    actual_line,
2435                    committed.batch_id,
2436                    item.raw_line
2437                );
2438                if item.node_id <= closed_cutoff_id
2439                    && item.provenance == "manual"
2440                {
2441                    let mut clean_item = item.normalized_for_journal();
2442                    clean_item.inbox_name = None;
2443                    clean_item.allocated_name = None;
2444                    clean_item.inbox_sha256 = None;
2445                    manual_items_by_id.insert(item.node_id, clean_item);
2446                }
2447            }
2448        }
2449
2450        let closed_ledger_sha256 =
2451            compute_nodes_slice_ledger_sha256(closed_nodes);
2452        let mut remaining_pairs: Vec<(JournalRecord, JournalRecord)> =
2453            Vec::new();
2454
2455        for (pending, committed) in &parsed.committed_pairs {
2456            if pending.kind == "bootstrap_checkpoint"
2457                || pending.final_last_id <= closed_cutoff_id
2458            {
2459                continue;
2460            }
2461            if pending.baseline_last_id < closed_cutoff_id {
2462                let mut trimmed_pending = pending.clone();
2463                trimmed_pending
2464                    .items
2465                    .retain(|item| item.node_id > closed_cutoff_id);
2466                trimmed_pending.baseline_last_id = closed_cutoff_id;
2467                trimmed_pending.baseline_ledger_sha256 =
2468                    closed_ledger_sha256.clone();
2469                trimmed_pending.manifest_sha256 = None;
2470                trimmed_pending = trimmed_pending.with_computed_sha256()?;
2471
2472                let mut trimmed_committed = committed.clone();
2473                trimmed_committed.baseline_last_id = closed_cutoff_id;
2474                trimmed_committed.baseline_ledger_sha256 =
2475                    closed_ledger_sha256.clone();
2476                trimmed_committed.manifest_sha256 = None;
2477                trimmed_committed = trimmed_committed.with_computed_sha256()?;
2478
2479                remaining_pairs.push((trimmed_pending, trimmed_committed));
2480            } else {
2481                remaining_pairs.push((pending.clone(), committed.clone()));
2482            }
2483        }
2484
2485        let compacted_manual_items: Vec<PlannedLedgerItem> =
2486            manual_items_by_id.into_values().collect();
2487        let batch_id = format!("bootstrap-compacted-{closed_cutoff_id}");
2488        let (
2489            manifest_sha256,
2490            unsplit_bundles_sha256,
2491            active_bundles_sha256,
2492            history_bundles_sha256,
2493        ) = if remaining_pairs.is_empty()
2494            && let Some(last_comm) = &parsed.last_committed
2495        {
2496            (
2497                last_comm.manifest_sha256.clone(),
2498                last_comm.unsplit_bundles_sha256.clone(),
2499                last_comm.active_bundles_sha256.clone(),
2500                last_comm.history_bundles_sha256.clone(),
2501            )
2502        } else {
2503            (None, BTreeMap::new(), BTreeMap::new(), BTreeMap::new())
2504        };
2505
2506        let ckpt_pending = JournalRecord {
2507            state: "BATCH_PENDING".to_string(),
2508            batch_id: batch_id.clone(),
2509            kind: "bootstrap_checkpoint".to_string(),
2510            baseline_last_id: closed_cutoff_id,
2511            baseline_ledger_sha256: closed_ledger_sha256.clone(),
2512            final_last_id: closed_cutoff_id,
2513            final_ledger_sha256: closed_ledger_sha256.clone(),
2514            manifest_sha256: manifest_sha256.clone(),
2515            items: compacted_manual_items,
2516            unsplit_bundles_sha256: BTreeMap::new(),
2517            active_bundles_sha256: BTreeMap::new(),
2518            history_bundles_sha256: BTreeMap::new(),
2519            record_sha256: String::new(),
2520        }
2521        .with_computed_sha256()?;
2522
2523        let ckpt_committed = JournalRecord {
2524            state: "BATCH_COMMITTED".to_string(),
2525            batch_id,
2526            kind: "bootstrap_checkpoint".to_string(),
2527            baseline_last_id: closed_cutoff_id,
2528            baseline_ledger_sha256: closed_ledger_sha256.clone(),
2529            final_last_id: closed_cutoff_id,
2530            final_ledger_sha256: closed_ledger_sha256,
2531            manifest_sha256,
2532            items: Vec::new(),
2533            unsplit_bundles_sha256,
2534            active_bundles_sha256,
2535            history_bundles_sha256,
2536            record_sha256: String::new(),
2537        }
2538        .with_computed_sha256()?;
2539
2540        let mut serialized = String::new();
2541        serialized.push_str(&serde_json::to_string(&ckpt_pending)?);
2542        serialized.push('\n');
2543        serialized.push_str(&serde_json::to_string(&ckpt_committed)?);
2544        serialized.push('\n');
2545        for (p, c) in &remaining_pairs {
2546            serialized.push_str(&serde_json::to_string(p)?);
2547            serialized.push('\n');
2548            serialized.push_str(&serde_json::to_string(c)?);
2549            serialized.push('\n');
2550        }
2551
2552        let tmp_path = journal_path.with_extension("jsonl.compact.tmp");
2553        {
2554            let mut f = OpenOptions::new()
2555                .create(true)
2556                .write(true)
2557                .truncate(true)
2558                .open(&tmp_path)
2559                .with_context(|| {
2560                    format!("Failed to create {}", tmp_path.display())
2561                })?;
2562            f.write_all(serialized.as_bytes())?;
2563            f.sync_all()?;
2564        }
2565        fs::rename(&tmp_path, &journal_path).with_context(|| {
2566            format!(
2567                "Failed to replace {} with compacted journal {}",
2568                journal_path.display(),
2569                tmp_path.display()
2570            )
2571        })?;
2572        fsync_file(&journal_path)?;
2573        if let Some(parent) = journal_path.parent() {
2574            fsync_dir(parent)?;
2575        }
2576    }
2577
2578    let removed_count = removable_files.len();
2579    for path in removable_files {
2580        fs::remove_file(&path).with_context(|| {
2581            format!(
2582                "Failed to remove closed-chunk allocated file {}",
2583                path.display()
2584            )
2585        })?;
2586    }
2587    if removed_count > 0 {
2588        fsync_dir(&allocated_dir)?;
2589    }
2590
2591    Ok(removed_count)
2592}
2593
2594/// External reader/packager gate: verifies under `LedgerReadGuard` (`LOCK_SH`) that:
2595/// 1. `ledger-journal.jsonl` exists on disk (never trusting a missing journal),
2596/// 2. `ledger-journal.jsonl` has no torn trailing line and no open `BATCH_PENDING` transaction,
2597/// 3. `ledger-journal.jsonl` ends with a verified `BATCH_COMMITTED` record whose `final_ledger_sha256`
2598///    and `final_last_id` match `assets/data/graph/*.ctbnodes`, and
2599/// 4. `assets/data/graph/*.ctbnbdl` and `assets/data/graph/system/*.ctbnbdl` match `BATCH_COMMITTED`'s
2600///    recorded bundle SHA-256 inventory and pass full `(node.id, &node.tokens)` union and partition verification.
2601#[derive(Clone, PartialEq, Eq)]
2602struct VerifiedCommittedLedgerCacheEntry {
2603    journal_sha256: String,
2604    ledger_sha256: String,
2605    unsplit_bundles_sha256: BTreeMap<String, String>,
2606    split_present: bool,
2607    active_bundles_sha256: BTreeMap<String, String>,
2608    history_bundles_sha256: BTreeMap<String, String>,
2609    nodes: std::sync::Arc<[LedgerNode]>,
2610}
2611
2612static VERIFIED_COMMITTED_LEDGER_CACHE: std::sync::LazyLock<
2613    std::sync::Mutex<Option<VerifiedCommittedLedgerCacheEntry>>,
2614> = std::sync::LazyLock::new(|| std::sync::Mutex::new(None));
2615
2616/// Verifies `ledger-journal.jsonl`, `assets/data/graph/*.ctbnodes`, and `.ctbnbdl` bundles under
2617/// `_read_guard`, returning `(final_ledger_sha256, committed_nodes)`.
2618///
2619/// Reuses the decoded node slice in-process only when the on-disk SHA-256 digests of
2620/// `ledger-journal.jsonl`, every `.ctbnodes` chunk file, and every `.ctbnbdl` bundle file match
2621/// a previously verified state byte-for-byte.
2622pub(super) fn ensure_ledger_journal_clean_and_load_committed(
2623    repo_root: &Path,
2624    _read_guard: &LedgerReadGuard,
2625) -> Result<(String, std::sync::Arc<[LedgerNode]>)> {
2626    let journal_path = repo_root.join(LEDGER_JOURNAL_REL_PATH);
2627    let init_marker = repo_root.join(JOURNAL_INITIALIZED_REL_PATH);
2628    ensure!(
2629        journal_path.is_file(),
2630        "CRITICAL: Ledger journal {} is missing (initialized_marker={})! Gated readers refuse to trust an uninitialized or deleted journal.",
2631        journal_path.display(),
2632        init_marker.exists()
2633    );
2634
2635    let journal_sha256 = sha256_file_hex(&journal_path)?;
2636    let graph_dir = repo_root.join("assets/data/graph");
2637    let actual_ledger_sha = compute_ledger_dir_sha256(&graph_dir)?;
2638
2639    let bundles_dir = bundles_dir_for_graph_dir(&graph_dir);
2640    let actual_unsplit_sha256 = compute_bundle_dir_sha256s(&bundles_dir)?;
2641    let live_dir = bundles_dir.join(GRAPH_BUNDLES_SPLIT_LIVE_SUBDIR);
2642    let history_dir = bundles_dir.join(GRAPH_BUNDLES_SPLIT_HISTORY_SUBDIR);
2643    let split_present = live_dir.exists() || history_dir.exists();
2644    let (actual_active_sha256, actual_history_sha256) = if split_present {
2645        (
2646            compute_bundle_dir_sha256s(&live_dir)?,
2647            compute_bundle_dir_sha256s(&history_dir)?,
2648        )
2649    } else {
2650        (BTreeMap::new(), BTreeMap::new())
2651    };
2652
2653    if let Ok(guard) = VERIFIED_COMMITTED_LEDGER_CACHE.lock()
2654        && let Some(ref cached) = *guard
2655        && cached.journal_sha256 == journal_sha256
2656        && cached.ledger_sha256 == actual_ledger_sha
2657        && cached.unsplit_bundles_sha256 == actual_unsplit_sha256
2658        && cached.split_present == split_present
2659        && cached.active_bundles_sha256 == actual_active_sha256
2660        && cached.history_bundles_sha256 == actual_history_sha256
2661    {
2662        return Ok((actual_ledger_sha, std::sync::Arc::clone(&cached.nodes)));
2663    }
2664
2665    let parsed = inspect_ledger_journal(&journal_path)?;
2666    ensure!(
2667        parsed.torn_trailing_fragment.is_none(),
2668        "CRITICAL: Ledger journal {} has an unterminated trailing line; run `ctb-lint recover-ledger-journal` before reading or building.",
2669        journal_path.display()
2670    );
2671    ensure!(
2672        parsed.open_pending.is_none(),
2673        "CRITICAL: Ledger journal {} has an uncommitted BATCH_PENDING transaction ({:?}); run `ctb-lint recover-ledger-journal` before reading or building.",
2674        journal_path.display(),
2675        parsed.open_pending.as_ref().map(|p| p.batch_id.as_str())
2676    );
2677    let Some(last_committed) = parsed.last_committed else {
2678        bail!(
2679            "CRITICAL: Ledger journal {} contains no BATCH_COMMITTED records!",
2680            journal_path.display()
2681        );
2682    };
2683
2684    ensure!(
2685        actual_ledger_sha == last_committed.final_ledger_sha256,
2686        "CRITICAL: On-disk .ctbnodes ledger SHA-256 {} in {} does not match latest BATCH_COMMITTED ({}) final_ledger_sha256 {}; if ledger-journal.jsonl fell behind an append-only CSV write, run `ctb-lint recover-ledger-journal`.",
2687        actual_ledger_sha,
2688        graph_dir.display(),
2689        last_committed.batch_id,
2690        last_committed.final_ledger_sha256
2691    );
2692
2693    let committed_nodes = load_ledger_nodes_from_dir_raw(&graph_dir)?;
2694    let actual_last_id = committed_nodes.last().map_or(0, |n| n.id);
2695    ensure!(
2696        actual_last_id == last_committed.final_last_id,
2697        "CRITICAL: On-disk .ctbnodes highest node ID l{} does not match latest BATCH_COMMITTED ({}) final_last_id l{}",
2698        actual_last_id,
2699        last_committed.batch_id,
2700        last_committed.final_last_id
2701    );
2702
2703    let framing = resolve_ctbnbdl_framing_dcs_from_nodes(&committed_nodes)?;
2704    let expected_digests = CompiledBundleDigests {
2705        unsplit_bundles_sha256: last_committed.unsplit_bundles_sha256.clone(),
2706        active_bundles_sha256: last_committed.active_bundles_sha256.clone(),
2707        history_bundles_sha256: last_committed.history_bundles_sha256.clone(),
2708    };
2709    verify_compiled_bundles_match_ledger(
2710        &graph_dir,
2711        &committed_nodes,
2712        framing,
2713        Some(&expected_digests),
2714        false,
2715    )?;
2716
2717    let nodes_arc: std::sync::Arc<[LedgerNode]> =
2718        std::sync::Arc::from(committed_nodes);
2719    if let Ok(mut guard) = VERIFIED_COMMITTED_LEDGER_CACHE.lock() {
2720        *guard = Some(VerifiedCommittedLedgerCacheEntry {
2721            journal_sha256,
2722            ledger_sha256: actual_ledger_sha.clone(),
2723            unsplit_bundles_sha256: actual_unsplit_sha256,
2724            split_present,
2725            active_bundles_sha256: actual_active_sha256,
2726            history_bundles_sha256: actual_history_sha256,
2727            nodes: std::sync::Arc::clone(&nodes_arc),
2728        });
2729    }
2730
2731    Ok((actual_ledger_sha, nodes_arc))
2732}
2733
2734pub fn ensure_ledger_journal_clean(
2735    repo_root: &Path,
2736    read_guard: &LedgerReadGuard,
2737) -> Result<()> {
2738    let _ = ensure_ledger_journal_clean_and_load_committed(repo_root, read_guard)?;
2739    Ok(())
2740}
2741
2742/// Output returned by [`execute_durable_ledger_transaction_with_planner`].
2743#[derive(Debug, Clone)]
2744pub struct DurableTransactionOutcome<T> {
2745    /// Whether an existing open `BATCH_PENDING` or already-committed manifest was resumed/reused.
2746    pub resumed_or_already_committed: bool,
2747    /// Number of `.ctbnodes` chunk files touched.
2748    pub files_written: usize,
2749    /// Number of nodes appended in the transaction.
2750    pub appended_count: usize,
2751    /// Final total node count in the ledger.
2752    pub total_nodes: usize,
2753    /// Custom planner payload (when the Fresh-Start planner ran).
2754    pub planner_payload: Option<T>,
2755}
2756
2757/// Shared durable transactional writer used by both `process_inbox_nodes` and `update_system_graph_ledger`.
2758///
2759/// Follows the strict recovery-first, manifest-enforced protocol under `LedgerWriteGuard` (`LOCK_EX`):
2760/// 1. Repairs any torn journal suffix and resumes any open `BATCH_PENDING` record **before** calling
2761///    committed-only provenance validation (`planner_fn`).
2762/// 2. If `--require-manifest` is supplied and the newly recovered (or already committed) `BATCH_COMMITTED`
2763///    record matches `manifest_sha256`, verifies the final ledger and `.ctbnbdl` state and returns idempotently.
2764/// 3. Otherwise (Fresh-Start path), verifies baseline ledger SHA-256 and pinned input SHA-256s, runs
2765///    `planner_fn` on the committed baseline nodes and `committed_pairs`, verifies byte-for-byte
2766///    agreement with `--require-manifest` (if supplied), writes `BATCH_PENDING` (when `!dry_run` and
2767///    either `!planned_items.is_empty()` or `required_manifest.is_some()`), and executes Phase 1 + Phase 2 +
2768///    `BATCH_COMMITTED` via `recover_pending_ledger_journal_with_guard`.
2769pub fn execute_durable_ledger_transaction_with_planner<T, F>(
2770    repo_root: &Path,
2771    kind: &str,
2772    batch_id_prefix: &str,
2773    required_manifest_path: Option<&Path>,
2774    dry_run: bool,
2775    fault: Option<FaultInjectionPoint>,
2776    planner_fn: F,
2777) -> Result<DurableTransactionOutcome<T>>
2778where
2779    F: FnOnce(
2780        &LedgerWriteGuard,
2781        &[LedgerNode],
2782        &[(JournalRecord, JournalRecord)],
2783    )
2784        -> Result<(Vec<PlannedLedgerItem>, BTreeMap<String, String>, T)>,
2785{
2786    let write_guard = LedgerWriteGuard::acquire(repo_root)?;
2787    let journal_path = repo_root.join(LEDGER_JOURNAL_REL_PATH);
2788    ensure!(
2789        journal_path.is_file(),
2790        "CRITICAL: Ledger journal {} is missing!",
2791        journal_path.display()
2792    );
2793
2794    let loaded_manifest = if let Some(mpath) = required_manifest_path {
2795        let bytes = fs::read(mpath).with_context(|| {
2796            format!("Failed to read required manifest {}", mpath.display())
2797        })?;
2798        let sha = sha256_bytes_hex(&bytes);
2799        let manifest: TransactionManifest = serde_json::from_slice(&bytes)
2800            .with_context(|| {
2801                format!("Failed to parse required manifest {}", mpath.display())
2802            })?;
2803        ensure!(
2804            manifest.kind == kind,
2805            "Required manifest {} has kind {:?}, expected {:?}",
2806            mpath.display(),
2807            manifest.kind,
2808            kind
2809        );
2810        Some((manifest, sha))
2811    } else {
2812        None
2813    };
2814    let manifest_ref = loaded_manifest.as_ref().map(|(m, s)| (m, s.as_str()));
2815
2816    // Step 1: Pending-first recovery BEFORE committed-only provenance validation!
2817    let recovered_pending = recover_pending_ledger_journal_with_guard(
2818        &write_guard,
2819        repo_root,
2820        manifest_ref,
2821        dry_run,
2822        fault,
2823    )?;
2824
2825    if !dry_run && manifest_ref.is_none() {
2826        let _ =
2827            compact_closed_ledger_chunks_with_guard(&write_guard, repo_root)?;
2828    }
2829
2830    let parsed = inspect_ledger_journal(&journal_path)?;
2831    if dry_run && recovered_pending {
2832        let pending_items =
2833            parsed.open_pending.as_ref().map_or(0, |p| p.items.len());
2834        return Ok(DurableTransactionOutcome {
2835            resumed_or_already_committed: true,
2836            files_written: 0,
2837            appended_count: pending_items,
2838            total_nodes: 0,
2839            planner_payload: None,
2840        });
2841    }
2842
2843    // Step 2: If a required manifest was supplied and the latest BATCH_COMMITTED already matches
2844    // `manifest_sha256` (either because step 1 just finished resuming it or because it was already
2845    // committed in an earlier invocation), verify final state and return idempotently.
2846    let graph_dir = repo_root.join("assets/data/graph");
2847    if let Some((manifest, manifest_sha)) = manifest_ref {
2848        if let Some(last_committed) = &parsed.last_committed {
2849            if last_committed.manifest_sha256.as_deref() == Some(manifest_sha) {
2850                let current_nodes =
2851                    load_ledger_nodes_from_dir_with_write_guard(
2852                        &write_guard,
2853                        &graph_dir,
2854                    )?;
2855                let actual_sha = compute_ledger_dir_sha256(&graph_dir)?;
2856                ensure!(
2857                    actual_sha == manifest.final_ledger_sha256
2858                        && current_nodes.len() == manifest.final_node_count
2859                        && current_nodes.last().map(|n| n.id)
2860                            == Some(manifest.final_last_id),
2861                    "CRITICAL: Committed manifest {} state on disk does not match manifest final state",
2862                    manifest.manifest_id
2863                );
2864                let framing =
2865                    resolve_ctbnbdl_framing_dcs_from_nodes(&current_nodes)?;
2866                let expected_digests = CompiledBundleDigests {
2867                    unsplit_bundles_sha256: last_committed
2868                        .unsplit_bundles_sha256
2869                        .clone(),
2870                    active_bundles_sha256: last_committed
2871                        .active_bundles_sha256
2872                        .clone(),
2873                    history_bundles_sha256: last_committed
2874                        .history_bundles_sha256
2875                        .clone(),
2876                };
2877                verify_compiled_bundles_match_ledger(
2878                    &graph_dir,
2879                    &current_nodes,
2880                    framing,
2881                    Some(&expected_digests),
2882                    false,
2883                )?;
2884                let touched_chunks: HashSet<&str> = manifest
2885                    .planned_items
2886                    .iter()
2887                    .map(|i| i.target_chunk.as_str())
2888                    .collect();
2889                return Ok(DurableTransactionOutcome {
2890                    resumed_or_already_committed: true,
2891                    files_written: touched_chunks.len(),
2892                    appended_count: manifest.planned_items.len(),
2893                    total_nodes: current_nodes.len(),
2894                    planner_payload: None,
2895                });
2896            }
2897        }
2898    }
2899
2900    // Step 3: Fresh-Start Path. Verify clean committed journal state.
2901    ensure!(
2902        parsed.open_pending.is_none()
2903            && parsed.torn_trailing_fragment.is_none(),
2904        "CRITICAL: Journal {} still has pending/torn state after recovery step",
2905        journal_path.display()
2906    );
2907    let Some(last_committed) = &parsed.last_committed else {
2908        bail!(
2909            "CRITICAL: Journal {} has no BATCH_COMMITTED baseline",
2910            journal_path.display()
2911        );
2912    };
2913
2914    let baseline_nodes =
2915        load_ledger_nodes_from_dir_with_write_guard(&write_guard, &graph_dir)?;
2916    for (label, shadow_dir) in highwater_shadow_dirs(repo_root) {
2917        if shadow_dir.is_dir() {
2918            let shadow_nodes = load_ledger_nodes_from_dir_raw(&shadow_dir)?;
2919            if !shadow_nodes.is_empty() {
2920                verify_nodes_append_only_against_baseline(
2921                    &label,
2922                    &shadow_nodes,
2923                    &baseline_nodes,
2924                )?;
2925            }
2926        }
2927    }
2928
2929    let baseline_last_id = baseline_nodes.last().map_or(0, |n| n.id);
2930    let baseline_ledger_sha256 = compute_ledger_dir_sha256(&graph_dir)?;
2931    ensure!(
2932        baseline_last_id == last_committed.final_last_id
2933            && baseline_ledger_sha256 == last_committed.final_ledger_sha256,
2934        "CRITICAL: Current ledger baseline (last_id=l{}, sha256={}) does not match latest BATCH_COMMITTED (last_id=l{}, sha256={})",
2935        baseline_last_id,
2936        baseline_ledger_sha256,
2937        last_committed.final_last_id,
2938        last_committed.final_ledger_sha256
2939    );
2940
2941    if let Some((manifest, _)) = manifest_ref {
2942        ensure!(
2943            baseline_last_id == manifest.baseline_last_id
2944                && baseline_nodes.len() == manifest.baseline_node_count
2945                && baseline_ledger_sha256 == manifest.baseline_ledger_sha256,
2946            "CRITICAL: Required manifest {} baseline mismatch: expected (last_id=l{}, count={}, sha256={}), found (last_id=l{}, count={}, sha256={})",
2947            manifest.manifest_id,
2948            manifest.baseline_last_id,
2949            manifest.baseline_node_count,
2950            manifest.baseline_ledger_sha256,
2951            baseline_last_id,
2952            baseline_nodes.len(),
2953            baseline_ledger_sha256
2954        );
2955    }
2956
2957    let (planned_items, actual_input_sha256s, payload) =
2958        planner_fn(&write_guard, &baseline_nodes, &parsed.committed_pairs)?;
2959
2960    let planned_nodes = parse_planned_items_to_nodes(&planned_items)?;
2961    let mut updated_nodes = baseline_nodes.clone();
2962    updated_nodes.extend(planned_nodes);
2963    verify_nodes_append_only_against_baseline(
2964        "existing working-tree ledger",
2965        &baseline_nodes,
2966        &updated_nodes,
2967    )?;
2968
2969    let final_last_id = updated_nodes.last().map_or(0, |n| n.id);
2970    let final_ledger_sha256 = compute_nodes_slice_ledger_sha256(&updated_nodes);
2971
2972    if let Some((manifest, _)) = manifest_ref {
2973        ensure!(
2974            actual_input_sha256s == manifest.pinned_input_sha256s,
2975            "CRITICAL: Pinned input SHA-256 mismatch for manifest {}: expected {:?}, found {:?}",
2976            manifest.manifest_id,
2977            manifest.pinned_input_sha256s,
2978            actual_input_sha256s
2979        );
2980        let planned_norm: Vec<PlannedLedgerItem> = planned_items
2981            .iter()
2982            .map(PlannedLedgerItem::normalized_for_journal)
2983            .collect();
2984        let manifest_norm: Vec<PlannedLedgerItem> = manifest
2985            .planned_items
2986            .iter()
2987            .map(PlannedLedgerItem::normalized_for_journal)
2988            .collect();
2989        ensure!(
2990            final_last_id == manifest.final_last_id
2991                && updated_nodes.len() == manifest.final_node_count
2992                && final_ledger_sha256 == manifest.final_ledger_sha256
2993                && planned_norm == manifest_norm,
2994            "CRITICAL: Planned transaction output (final_last_id=l{}, count={}, sha256={}, items={}) does not match required manifest {} (final_last_id=l{}, count={}, sha256={}, items={})",
2995            final_last_id,
2996            updated_nodes.len(),
2997            final_ledger_sha256,
2998            planned_norm.len(),
2999            manifest.manifest_id,
3000            manifest.final_last_id,
3001            manifest.final_node_count,
3002            manifest.final_ledger_sha256,
3003            manifest_norm.len()
3004        );
3005    }
3006
3007    let touched_chunks: HashSet<&str> = planned_items
3008        .iter()
3009        .map(|i| i.target_chunk.as_str())
3010        .collect();
3011    let files_written = touched_chunks.len();
3012    let appended_count = planned_items.len();
3013
3014    if dry_run || (planned_items.is_empty() && manifest_ref.is_none()) {
3015        return Ok(DurableTransactionOutcome {
3016            resumed_or_already_committed: false,
3017            files_written: 0,
3018            appended_count,
3019            total_nodes: updated_nodes.len(),
3020            planner_payload: Some(payload),
3021        });
3022    }
3023
3024    let batch_id = if let Some((manifest, _)) = manifest_ref {
3025        format!("{batch_id_prefix}-{}-{final_last_id}", manifest.manifest_id)
3026    } else {
3027        format!("{batch_id_prefix}-{baseline_last_id}-{final_last_id}")
3028    };
3029
3030    let journal_items: Vec<PlannedLedgerItem> = planned_items
3031        .iter()
3032        .map(PlannedLedgerItem::normalized_for_journal)
3033        .collect();
3034
3035    let pending = JournalRecord {
3036        state: "BATCH_PENDING".to_string(),
3037        batch_id,
3038        kind: kind.to_string(),
3039        baseline_last_id,
3040        baseline_ledger_sha256,
3041        final_last_id,
3042        final_ledger_sha256,
3043        manifest_sha256: manifest_ref.map(|(_, s)| s.to_string()),
3044        items: journal_items,
3045        unsplit_bundles_sha256: BTreeMap::new(),
3046        active_bundles_sha256: BTreeMap::new(),
3047        history_bundles_sha256: BTreeMap::new(),
3048        record_sha256: String::new(),
3049    };
3050    append_journal_record(&journal_path, &pending, fault)?;
3051
3052    recover_pending_ledger_journal_with_guard(
3053        &write_guard,
3054        repo_root,
3055        manifest_ref,
3056        false,
3057        fault,
3058    )?;
3059
3060    Ok(DurableTransactionOutcome {
3061        resumed_or_already_committed: false,
3062        files_written,
3063        appended_count,
3064        total_nodes: updated_nodes.len(),
3065        planner_payload: Some(payload),
3066    })
3067}
3068
3069#[cfg(test)]
3070#[allow(
3071    clippy::panic,
3072    clippy::expect_used,
3073    clippy::unwrap_used,
3074    clippy::unwrap_in_result,
3075    clippy::panic_in_result_fn,
3076    clippy::indexing_slicing,
3077    clippy::arithmetic_side_effects,
3078    reason = "Standard repository test boilerplate"
3079)]
3080mod tests {
3081    use super::super::encode_nodes_to_ctbnbdl_bundles_with_limits;
3082    use super::*;
3083    use crate::ctbnbdl::load_ledger_nodes_from_dir;
3084    use std::sync::atomic::{AtomicUsize, Ordering};
3085
3086    static NEXT_TEST_DIR_ID: AtomicUsize = AtomicUsize::new(1);
3087
3088    struct TempDir(PathBuf);
3089
3090    impl TempDir {
3091        fn new(prefix: &str) -> Self {
3092            let id = NEXT_TEST_DIR_ID.fetch_add(1, Ordering::Relaxed);
3093            let dir = std::env::temp_dir().join(format!(
3094                "ctb_journal_test_{}_{}_{}",
3095                prefix,
3096                std::process::id(),
3097                id
3098            ));
3099            if dir.exists() {
3100                let _ = fs::remove_dir_all(&dir);
3101            }
3102            fs::create_dir_all(&dir).unwrap();
3103            Self(dir)
3104        }
3105
3106        fn path(&self) -> &Path {
3107            &self.0
3108        }
3109    }
3110
3111    impl Drop for TempDir {
3112        fn drop(&mut self) {
3113            #[cfg(unix)]
3114            {
3115                use std::os::unix::fs::PermissionsExt;
3116                let shadow_dir = highwater_shadow_dirs(&self.0)
3117                    .into_iter()
3118                    .next()
3119                    .unwrap()
3120                    .1;
3121                if shadow_dir.is_dir() {
3122                    if let Ok(entries) = fs::read_dir(&shadow_dir) {
3123                        for entry in entries.flatten() {
3124                            let _ = fs::set_permissions(
3125                                entry.path(),
3126                                fs::Permissions::from_mode(0o644),
3127                            );
3128                        }
3129                    }
3130                }
3131            }
3132            let _ = fs::remove_dir_all(&self.0);
3133        }
3134    }
3135
3136    fn setup_checkout_fixture() -> TempDir {
3137        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
3138        let real_root = crate::find_repository_root_from(manifest_dir).unwrap();
3139        let tmp = TempDir::new("checkout");
3140        let root = tmp.path();
3141
3142        fs::create_dir_all(root.join(".git")).unwrap();
3143        fs::write(root.join(".ctoolbox_workspace_root"), b"").unwrap();
3144        fs::write(root.join("Cargo.toml"), b"[workspace]\n").unwrap();
3145        fs::create_dir_all(
3146            root.join("src/formats/dcdata/data-src/nodes/inbox"),
3147        )
3148        .unwrap();
3149        fs::create_dir_all(
3150            root.join("src/formats/dcdata/data-src/nodes/allocated"),
3151        )
3152        .unwrap();
3153
3154        let all_nodes = load_ledger_nodes_from_dir_raw(
3155            &real_root.join("assets/data/graph"),
3156        )
3157        .unwrap();
3158        let baseline_nodes: Vec<LedgerNode> =
3159            all_nodes.into_iter().take(17_833).collect();
3160        assert_eq!(baseline_nodes.len(), 17_833);
3161        assert_eq!(baseline_nodes.last().unwrap().id, 8_589_952_424);
3162
3163        let graph_dst = root.join("assets/data/graph");
3164        fs::create_dir_all(&graph_dst).unwrap();
3165        for chunk in baseline_nodes.chunks(100) {
3166            let chunk_rel = format_chunk_rel_path(chunk[0].id);
3167            let mut buf = String::new();
3168            for n in chunk {
3169                buf.push_str(&n.format_line());
3170                buf.push('\n');
3171            }
3172            let chunk_path = graph_dst.join(chunk_rel);
3173            if let Some(parent) = chunk_path.parent() {
3174                fs::create_dir_all(parent).unwrap();
3175            }
3176            fs::write(chunk_path, buf).unwrap();
3177        }
3178        {
3179            let write_guard = LedgerWriteGuard::acquire(root).unwrap();
3180            let framing =
3181                resolve_ctbnbdl_framing_dcs_from_nodes(&baseline_nodes)
3182                    .unwrap();
3183            compile_nodes_slice_to_ctbnbdl_with_write_guard(
3184                &write_guard,
3185                &baseline_nodes,
3186                &graph_dst,
3187                framing,
3188            )
3189            .unwrap();
3190        }
3191        tmp
3192    }
3193
3194    fn write_initial_checkpoint_for_test(
3195        repo_root: &Path,
3196        commit_record: bool,
3197    ) -> Result<()> {
3198        let write_guard = LedgerWriteGuard::acquire(repo_root)?;
3199        let journal_path = repo_root.join(LEDGER_JOURNAL_REL_PATH);
3200        let init_marker = repo_root.join(JOURNAL_INITIALIZED_REL_PATH);
3201        ensure!(
3202            !init_marker.exists(),
3203            "CRITICAL: Ledger journal {} is missing after initialization marker {} was already created!",
3204            journal_path.display(),
3205            init_marker.display()
3206        );
3207        let graph_dir = repo_root.join("assets/data/graph");
3208        let bundles_dir = bundles_dir_for_graph_dir(&graph_dir);
3209        let nodes = load_ledger_nodes_from_dir_with_write_guard(
3210            &write_guard,
3211            &graph_dir,
3212        )?;
3213        let last_id = nodes.last().map(|n| n.id).unwrap_or(0);
3214        let actual_ledger_sha256 = compute_ledger_dir_sha256(&graph_dir)?;
3215        let framing = resolve_ctbnbdl_framing_dcs_from_nodes(&nodes)?;
3216        let digests = CompiledBundleDigests {
3217            unsplit_bundles_sha256: compute_bundle_dir_sha256s(&bundles_dir)?,
3218            active_bundles_sha256: compute_bundle_dir_sha256s(
3219                &bundles_dir.join(GRAPH_BUNDLES_SPLIT_LIVE_SUBDIR),
3220            )?,
3221            history_bundles_sha256: compute_bundle_dir_sha256s(
3222                &bundles_dir.join(GRAPH_BUNDLES_SPLIT_HISTORY_SUBDIR),
3223            )?,
3224        };
3225        verify_compiled_bundles_match_ledger(
3226            &graph_dir,
3227            &nodes,
3228            framing,
3229            Some(&digests),
3230            true,
3231        )?;
3232
3233        let pending = JournalRecord {
3234            state: "BATCH_PENDING".to_string(),
3235            batch_id: "bootstrap-a90464028".to_string(),
3236            kind: "bootstrap_checkpoint".to_string(),
3237            baseline_last_id: last_id,
3238            baseline_ledger_sha256: actual_ledger_sha256.clone(),
3239            final_last_id: last_id,
3240            final_ledger_sha256: actual_ledger_sha256.clone(),
3241            manifest_sha256: None,
3242            items: Vec::new(),
3243            unsplit_bundles_sha256: BTreeMap::new(),
3244            active_bundles_sha256: BTreeMap::new(),
3245            history_bundles_sha256: BTreeMap::new(),
3246            record_sha256: String::new(),
3247        };
3248        append_journal_record(&journal_path, &pending, None)?;
3249        if !commit_record {
3250            bail!(
3251                "Simulated fault injection: crash after BATCH_PENDING before BATCH_COMMITTED"
3252            );
3253        }
3254        let committed = JournalRecord {
3255            state: "BATCH_COMMITTED".to_string(),
3256            batch_id: "bootstrap-a90464028".to_string(),
3257            kind: "bootstrap_checkpoint".to_string(),
3258            baseline_last_id: last_id,
3259            baseline_ledger_sha256: actual_ledger_sha256.clone(),
3260            final_last_id: last_id,
3261            final_ledger_sha256: actual_ledger_sha256,
3262            manifest_sha256: None,
3263            items: Vec::new(),
3264            unsplit_bundles_sha256: digests.unsplit_bundles_sha256,
3265            active_bundles_sha256: digests.active_bundles_sha256,
3266            history_bundles_sha256: digests.history_bundles_sha256,
3267            record_sha256: String::new(),
3268        };
3269        append_journal_record(&journal_path, &committed, None)?;
3270        stamp_journal_initialized_marker(repo_root)?;
3271        Ok(())
3272    }
3273
3274    #[test]
3275    fn test_journal_initialization_and_missing_journal_rejection() {
3276        let tmp = setup_checkout_fixture();
3277        let root = tmp.path();
3278        let graph_dir = root.join("assets/data/graph");
3279        let journal_path = root.join(LEDGER_JOURNAL_REL_PATH);
3280        let init_marker = root.join(JOURNAL_INITIALIZED_REL_PATH);
3281
3282        // Before journal exists, gated readers must reject the uninitialized checkout (never trusting a missing journal).
3283        let err = load_ledger_nodes_from_dir(&graph_dir).unwrap_err();
3284        assert!(
3285            err.to_string().contains("is missing"),
3286            "Expected missing journal error before initialization, got: {err}"
3287        );
3288
3289        // Write initial journal checkpoint under LOCK_EX.
3290        write_initial_checkpoint_for_test(root, true).unwrap();
3291        assert!(journal_path.is_file());
3292        assert!(init_marker.is_file());
3293
3294        // Verify journal has BATCH_PENDING + BATCH_COMMITTED with items: [] and 17,833 nodes untouched.
3295        let parsed = inspect_ledger_journal(&journal_path).unwrap();
3296        assert!(parsed.torn_trailing_fragment.is_none());
3297        assert!(parsed.open_pending.is_none());
3298        assert_eq!(parsed.records.len(), 2);
3299        assert_eq!(parsed.committed_pairs.len(), 1);
3300        assert_eq!(
3301            parsed.last_committed.as_ref().unwrap().batch_id,
3302            "bootstrap-a90464028"
3303        );
3304
3305        // Now gated readers and dc_codegen succeed!
3306        let nodes = load_ledger_nodes_from_dir(&graph_dir).unwrap();
3307        assert_eq!(nodes.len(), 17_833);
3308        let dc_code = crate::dc_codegen::generate_dc_code(&graph_dir).unwrap();
3309        assert!(dc_code.contains("pub const DC_RANGE"));
3310
3311        // Delete ledger-journal.jsonl after initialization and verify gated readers reject!
3312        fs::remove_file(&journal_path).unwrap();
3313        let err_reader = load_ledger_nodes_from_dir(&graph_dir).unwrap_err();
3314        assert!(
3315            err_reader.to_string().contains("initialized_marker=true"),
3316            "Expected post-initialization missing journal error, got: {err_reader}"
3317        );
3318    }
3319
3320    #[test]
3321    fn test_pending_journal_crash_recovery_via_standalone_build_support() {
3322        let tmp = setup_checkout_fixture();
3323        let root = tmp.path();
3324        let graph_dir = root.join("assets/data/graph");
3325
3326        // 1. Crash after writing BATCH_PENDING before BATCH_COMMITTED.
3327        let crash_err =
3328            write_initial_checkpoint_for_test(root, false).unwrap_err();
3329        assert!(crash_err.to_string().contains("Simulated fault injection"));
3330
3331        // Verify dc_codegen / gated readers are blocked while BATCH_PENDING is open.
3332        let blocked_err =
3333            crate::dc_codegen::generate_dc_code(&graph_dir).unwrap_err();
3334        assert!(
3335            blocked_err
3336                .to_string()
3337                .contains("uncommitted BATCH_PENDING transaction"),
3338            "Expected dc_codegen to be blocked while BATCH_PENDING is open, got: {blocked_err}"
3339        );
3340
3341        // Recover using standalone ctb_build_support::recover_pending_ledger_journal (no validate_data_tables needed).
3342        let recovered =
3343            recover_pending_ledger_journal(root, None, false).unwrap();
3344        assert!(recovered);
3345
3346        // Now dc_codegen succeeds!
3347        let dc_code = crate::dc_codegen::generate_dc_code(&graph_dir).unwrap();
3348        assert!(dc_code.contains("pub const DC_RANGE"));
3349    }
3350
3351    #[test]
3352    fn test_reject_tampered_ledger_against_journal() {
3353        let temp_dir = setup_checkout_fixture();
3354        let root = temp_dir.path();
3355        write_initial_checkpoint_for_test(root, true).unwrap();
3356
3357        // Tamper with a .ctbnodes chunk after journal commit and verify gated reader rejects it.
3358        let tail_chunk = root.join("assets/data/graph/85899_52392.ctbnodes");
3359        let mut content = fs::read_to_string(&tail_chunk).unwrap();
3360        content.push_str("l8589952425: 65 # tampered\n");
3361        fs::write(&tail_chunk, content).unwrap();
3362        let read_guard = LedgerReadGuard::acquire(root).unwrap();
3363        let err_tampered =
3364            ensure_ledger_journal_clean(root, &read_guard).unwrap_err();
3365        assert!(
3366            err_tampered
3367                .to_string()
3368                .contains("does not match latest BATCH_COMMITTED")
3369        );
3370    }
3371
3372    #[test]
3373    fn test_bundle_verification_catches_token_and_partition_corruption_at_same_max_id()
3374     {
3375        let tmp = setup_checkout_fixture();
3376        let root = tmp.path();
3377        let graph_dir = root.join("assets/data/graph");
3378        write_initial_checkpoint_for_test(root, true).unwrap();
3379
3380        let nodes = load_ledger_nodes_from_dir_raw(&graph_dir).unwrap();
3381        let framing = resolve_ctbnbdl_framing_dcs_from_nodes(&nodes).unwrap();
3382
3383        // Corrupt a single token on an interior node (keeping the highest node ID l8589952424 unchanged!)
3384        // and re-encode the split live bundle.
3385        let bundles_dir = bundles_dir_for_graph_dir(&graph_dir);
3386        let split_live_dir = bundles_dir.join(GRAPH_BUNDLES_SPLIT_LIVE_SUBDIR);
3387        let (mut active_nodes, _inactive_nodes) =
3388            partition_active_and_inactive_nodes_with(&nodes, framing);
3389        active_nodes[10].tokens =
3390            vec![crate::shorthand::DcShorthand::Unicode(999)];
3391        let corrupted_bundles =
3392            encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
3393                &active_nodes,
3394                framing,
3395                MAX_NODES_PER_BUNDLE,
3396                MAX_BYTES_PER_BUNDLE,
3397                nodes.iter().map(|n| n.id).max(),
3398            )
3399            .unwrap();
3400        write_ctbnbdl_bundles_to_dir(&split_live_dir, &corrupted_bundles, true)
3401            .unwrap();
3402
3403        // Verify that both verify_compiled_bundles_match_ledger (even without expected SHA-256 map)
3404        // and ensure_ledger_journal_clean reject the corrupted bundle!
3405        let err_verify = verify_compiled_bundles_match_ledger(
3406            &graph_dir, &nodes, framing, None, true,
3407        )
3408        .unwrap_err();
3409        assert!(
3410            err_verify
3411                .to_string()
3412                .contains("do not match expected active partition")
3413        );
3414
3415        let read_guard = LedgerReadGuard::acquire(root).unwrap();
3416        let err_gate =
3417            ensure_ledger_journal_clean(root, &read_guard).unwrap_err();
3418        assert!(
3419            err_gate.to_string().contains("bundle SHA-256 inventory")
3420                || err_gate
3421                    .to_string()
3422                    .contains("do not match expected active partition")
3423        );
3424
3425        // Also verify that on a fresh clone where gitignored `split/` is absent,
3426        // `ensure_ledger_journal_clean` still passes by verifying tracked unsplit `graph-bundles/*.ctbnbdl`
3427        // AND catches corruption of the unsplit bundle!
3428        fs::remove_dir_all(bundles_dir.join("split")).unwrap();
3429        ensure_ledger_journal_clean(root, &read_guard).unwrap();
3430
3431        let mut tampered_unsplit = nodes.clone();
3432        tampered_unsplit[5].tokens =
3433            vec![crate::shorthand::DcShorthand::Unicode(888)];
3434        let bad_unsplit =
3435            encode_nodes_to_ctbnbdl_bundles_with_limits_and_most_recent(
3436                &tampered_unsplit,
3437                framing,
3438                MAX_NODES_PER_BUNDLE,
3439                MAX_BYTES_PER_BUNDLE,
3440                None,
3441            )
3442            .unwrap();
3443        write_ctbnbdl_bundles_to_dir(&bundles_dir, &bad_unsplit, true).unwrap();
3444        let err_unsplit =
3445            ensure_ledger_journal_clean(root, &read_guard).unwrap_err();
3446        assert!(
3447            err_unsplit.to_string().contains("Unsplit .ctbnbdl bundle")
3448                || err_unsplit
3449                    .to_string()
3450                    .contains("Decoded unsplit .ctbnbdl nodes")
3451        );
3452    }
3453
3454    #[test]
3455    fn test_recover_journal_from_verified_csv_tail_and_reject_unprovenanced_tail()
3456     {
3457        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
3458        let real_root = crate::find_repository_root_from(manifest_dir).unwrap();
3459        let tmp = TempDir::new("csv_tail_recovery");
3460        let root = tmp.path();
3461
3462        fs::create_dir_all(root.join(".git")).unwrap();
3463        fs::write(root.join(".ctoolbox_workspace_root"), b"").unwrap();
3464        fs::write(root.join("Cargo.toml"), b"[workspace]\n").unwrap();
3465        fs::create_dir_all(
3466            root.join("src/formats/dcdata/data-src/nodes/inbox"),
3467        )
3468        .unwrap();
3469        fs::create_dir_all(
3470            root.join("src/formats/dcdata/data-src/nodes/allocated"),
3471        )
3472        .unwrap();
3473
3474        let all_nodes = load_ledger_nodes_from_dir_raw(
3475            &real_root.join("assets/data/graph"),
3476        )
3477        .unwrap();
3478        // Take first 42_100 nodes so all CSV provenance Dcs (including 638 DistributeStatementOverEach) are defined.
3479        let baseline_nodes: Vec<LedgerNode> =
3480            all_nodes.into_iter().take(42_100).collect();
3481        let last_base_id = baseline_nodes.last().unwrap().id;
3482
3483        let graph_dst = root.join("assets/data/graph");
3484        let shadow_dst = root.join(crate::ctbnbdl::HIGHWATER_LEDGER_REL_PATH);
3485        fs::create_dir_all(&graph_dst).unwrap();
3486        fs::create_dir_all(&shadow_dst).unwrap();
3487        for chunk in baseline_nodes.chunks(100) {
3488            let chunk_rel = format_chunk_rel_path(chunk[0].id);
3489            let mut buf = String::new();
3490            for n in chunk {
3491                buf.push_str(&n.format_line());
3492                buf.push('\n');
3493            }
3494            fs::write(graph_dst.join(&chunk_rel), &buf).unwrap();
3495            fs::write(shadow_dst.join(&chunk_rel), &buf).unwrap();
3496        }
3497        {
3498            let write_guard = LedgerWriteGuard::acquire(root).unwrap();
3499            let framing =
3500                resolve_ctbnbdl_framing_dcs_from_nodes(&baseline_nodes)
3501                    .unwrap();
3502            compile_nodes_slice_to_ctbnbdl_with_write_guard(
3503                &write_guard,
3504                &baseline_nodes,
3505                &graph_dst,
3506                framing,
3507            )
3508            .unwrap();
3509        }
3510        write_initial_checkpoint_for_test(root, true).unwrap();
3511
3512        // Snapshot journal + bundles before appending a verified CSV batch to .ctbnodes + highwater.
3513        let journal_path = root.join(LEDGER_JOURNAL_REL_PATH);
3514        let saved_journal = fs::read(&journal_path).unwrap();
3515
3516        let (idents, _, _, _, sh_enclosing_doc) =
3517            resolve_active_short_idents_from_nodes(&baseline_nodes).unwrap();
3518        let n1 = last_base_id + 1;
3519        let n2 = last_base_id + 2;
3520        let n3 = last_base_id + 3;
3521        let mut extended_nodes = baseline_nodes.clone();
3522        extended_nodes.push(LedgerNode {
3523            id: n1,
3524            tokens: vec![
3525                idents["IsInstanceOf"],
3526                sh_enclosing_doc,
3527                idents["TypeRoutine"],
3528            ],
3529            comment: "test routine entity".to_string(),
3530            created_ns: None,
3531        });
3532        extended_nodes.push(LedgerNode {
3533            id: n2,
3534            tokens: vec![
3535                idents["DistributeStatementOverEach"],
3536                idents["HasA"],
3537                idents["ThisElement"],
3538                idents["CollectiveToolboxSeedGraphDataSource"],
3539                idents["BeginList"],
3540                idents["TypeAtomDc"],
3541                DcShorthand::Long(n1),
3542                idents["EndList"],
3543            ],
3544            comment: "for each provenance".to_string(),
3545            created_ns: None,
3546        });
3547        extended_nodes.push(LedgerNode {
3548            id: n3,
3549            tokens: vec![
3550                idents["HasValue"],
3551                DcShorthand::Long(n2),
3552                idents["CollectiveToolboxDcCsvSeedDatabase"],
3553            ],
3554            comment: "has value csv seed db".to_string(),
3555            created_ns: None,
3556        });
3557
3558        for dir in [&graph_dst, &shadow_dst] {
3559            for chunk in extended_nodes.chunks(100) {
3560                if chunk.last().unwrap().id <= last_base_id {
3561                    continue;
3562                }
3563                let chunk_rel = format_chunk_rel_path(chunk[0].id);
3564                let mut buf = String::new();
3565                for n in chunk {
3566                    buf.push_str(&n.format_line());
3567                    buf.push('\n');
3568                }
3569                fs::write(dir.join(chunk_rel), buf).unwrap();
3570            }
3571        }
3572        // Keep stale journal at `last_base_id`: gated reader must block, dry_run must detect, and recovery must succeed.
3573        fs::write(&journal_path, &saved_journal).unwrap();
3574        {
3575            let rg = LedgerReadGuard::acquire(root).unwrap();
3576            assert!(ensure_ledger_journal_clean(root, &rg).is_err());
3577        }
3578        assert!(recover_pending_ledger_journal(root, None, true).unwrap());
3579        assert!(recover_pending_ledger_journal(root, None, false).unwrap());
3580        {
3581            let rg = LedgerReadGuard::acquire(root).unwrap();
3582            ensure_ledger_journal_clean(root, &rg).unwrap();
3583        }
3584
3585        // Now append an unprovenanced node `n4` (even with matching highwater!) and verify recovery refuses!
3586        let saved_journal_after_n3 = fs::read(&journal_path).unwrap();
3587        let n4 = n3 + 1;
3588        extended_nodes.push(LedgerNode {
3589            id: n4,
3590            tokens: vec![DcShorthand::Unicode(65)],
3591            comment: "unprovenanced".to_string(),
3592            created_ns: None,
3593        });
3594        for dir in [&graph_dst, &shadow_dst] {
3595            let last_chunk = extended_nodes.chunks(100).last().unwrap();
3596            let chunk_rel = format_chunk_rel_path(last_chunk[0].id);
3597            let mut buf = String::new();
3598            for n in last_chunk {
3599                buf.push_str(&n.format_line());
3600                buf.push('\n');
3601            }
3602            #[cfg(unix)]
3603            {
3604                use std::os::unix::fs::PermissionsExt;
3605                let p = dir.join(&chunk_rel);
3606                if p.exists() {
3607                    let _ =
3608                        fs::set_permissions(&p, fs::Permissions::from_mode(0o644));
3609                }
3610            }
3611            fs::write(dir.join(chunk_rel), buf).unwrap();
3612        }
3613        fs::write(&journal_path, &saved_journal_after_n3).unwrap();
3614        let err_unprov =
3615            recover_pending_ledger_journal(root, None, false).unwrap_err();
3616        assert!(
3617            err_unprov
3618                .to_string()
3619                .contains("lacks verified in-graph CollectiveToolboxDcCsvSeedDatabase provenance"),
3620            "Unexpected error: {err_unprov}"
3621        );
3622    }
3623
3624    #[test]
3625    fn test_ctbnodes_subfolder_sharding_after_999_chunks_and_unsplit_bundle_append()
3626     {
3627        assert_eq!(
3628            format_chunk_rel_path(SYSTEM_REGION_START),
3629            "85899_34592.ctbnodes"
3630        );
3631        // 999th chunk (0-based 998): stays in root
3632        let id_999th = SYSTEM_REGION_START + 998 * 100;
3633        assert_eq!(format_chunk_rel_path(id_999th), "85900_34392.ctbnodes");
3634        // 1000th chunk (0-based 999): first chunk in subfolder `85900/`
3635        let id_1000th = SYSTEM_REGION_START + 999 * 100;
3636        assert_eq!(
3637            format_chunk_rel_path(id_1000th),
3638            "85900/85900_34492.ctbnodes"
3639        );
3640        // 1999th chunk (0-based 1998): last chunk in subfolder `85900/`
3641        let id_1999th = SYSTEM_REGION_START + 1998 * 100;
3642        assert_eq!(
3643            format_chunk_rel_path(id_1999th),
3644            "85900/85901_34392.ctbnodes"
3645        );
3646        // 2000th chunk (0-based 1999): first chunk in subfolder `85901/`
3647        let id_2000th = SYSTEM_REGION_START + 1999 * 100;
3648        assert_eq!(
3649            format_chunk_rel_path(id_2000th),
3650            "85901/85901_34492.ctbnodes"
3651        );
3652
3653        let tmp = TempDir::new("subfolder_sharding_and_unsplit_append");
3654        let graph_dir = tmp.path().join("assets/data/graph");
3655        let total_nodes = 1000usize * 100 + 5; // 1001 chunks -> crosses 999 root chunks into `85900/`
3656        let nodes: Vec<LedgerNode> = (0..total_nodes)
3657            .map(|i| LedgerNode {
3658                id: SYSTEM_REGION_START + u128::try_from(i).unwrap(),
3659                tokens: vec![DcShorthand::Unicode(65)],
3660                comment: String::new(),
3661                created_ns: None,
3662            })
3663            .collect();
3664        let written =
3665            crate::ctbnbdl::write_ledger_nodes_to_dir(&graph_dir, &nodes)
3666                .unwrap();
3667        assert_eq!(written, 1001);
3668        assert!(graph_dir.join("85900_34392.ctbnodes").is_file());
3669        assert!(graph_dir.join("85900/85900_34492.ctbnodes").is_file());
3670        assert!(graph_dir.join("85900/85900_34592.ctbnodes").is_file());
3671
3672        let loaded = load_ledger_nodes_from_dir_raw(&graph_dir).unwrap();
3673        assert_eq!(loaded.len(), nodes.len());
3674        assert_eq!(
3675            compute_ledger_dir_sha256(&graph_dir).unwrap(),
3676            compute_nodes_slice_ledger_sha256(&nodes)
3677        );
3678
3679        // Verify unsplit bundle strictly appends bytes even when an earlier statement is retracted!
3680        let small_tmp = TempDir::new("unsplit_append_on_retract");
3681        let small_graph = small_tmp.path().join("assets/data/graph");
3682        let bundles_dir = bundles_dir_for_graph_dir(&small_graph);
3683        let real_nodes = load_ledger_nodes_from_dir_raw(
3684            &crate::find_repository_root_from(Path::new(env!(
3685                "CARGO_MANIFEST_DIR"
3686            )))
3687            .unwrap()
3688            .join("assets/data/graph"),
3689        )
3690        .unwrap();
3691        let framing =
3692            resolve_ctbnbdl_framing_dcs_from_nodes(&real_nodes).unwrap();
3693        let initial_small = vec![
3694            LedgerNode {
3695                id: SYSTEM_REGION_START,
3696                tokens: vec![
3697                    framing.is_instance_of,
3698                    framing.enclosing_document,
3699                    DcShorthand::Short(572),
3700                ],
3701                comment: String::new(),
3702                created_ns: Some(1_700_000_000_000_000_000),
3703            },
3704            LedgerNode {
3705                id: SYSTEM_REGION_START + 1,
3706                tokens: vec![
3707                    framing.has_a,
3708                    DcShorthand::Long(SYSTEM_REGION_START),
3709                    DcShorthand::Short(572),
3710                ],
3711                comment: String::new(),
3712                created_ns: Some(1_700_000_000_000_000_001),
3713            },
3714        ];
3715        crate::ctbnbdl::write_ledger_nodes_to_dir(&small_graph, &initial_small)
3716            .unwrap();
3717        crate::ctbnbdl::compile_graph_bundles_from_ctbnodes_dir(
3718            &small_graph,
3719            &bundles_dir,
3720            framing,
3721        )
3722        .unwrap();
3723        let unsplit_path = bundles_dir
3724            .join(format_chunk_bundle_filename(SYSTEM_REGION_START));
3725        let before_bytes = fs::read(&unsplit_path).unwrap();
3726
3727        // Now retract node `SYSTEM_REGION_START + 1`!
3728        let mut after_retract = initial_small.clone();
3729        after_retract.push(LedgerNode {
3730            id: SYSTEM_REGION_START + 2,
3731            tokens: vec![
3732                framing.retracts,
3733                framing.enclosing_document,
3734                DcShorthand::Long(SYSTEM_REGION_START + 1),
3735            ],
3736            comment: String::new(),
3737            created_ns: Some(1_700_000_000_000_000_002),
3738        });
3739        crate::ctbnbdl::write_ledger_nodes_to_dir(&small_graph, &after_retract)
3740            .unwrap();
3741        crate::ctbnbdl::compile_graph_bundles_from_ctbnodes_dir(
3742            &small_graph,
3743            &bundles_dir,
3744            framing,
3745        )
3746        .unwrap();
3747        let after_bytes = fs::read(&unsplit_path).unwrap();
3748        assert!(
3749            after_bytes.len() > before_bytes.len()
3750                && after_bytes.starts_with(&before_bytes),
3751            "Unsplit in-repo .ctbnbdl must remain a strict byte prefix even when an earlier statement is invalidated!"
3752        );
3753    }
3754}