ctb_formats_dcdata/
seed_graph.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//! Runtime Seed Graph Loader & Index (Phase 2).
21//!
22//! Loads compiled `.ctbnbdl` (`CtbNodeBundle2` / `CtbNodeBundle1`) system graph
23//! bundles from the runtime resource bundle (`data/graph/85899_34592.ctbnbdl`, etc.)
24//! and indexes active statements, supersessions (`Dc 591`), retractions (`Dc 592`),
25//! seed classification entities, value nodes, and `.Semantic:Pattern` rules at runtime.
26
27#[allow(
28    unused_imports,
29    clippy::wildcard_imports,
30    reason = "Standard workspace module prelude"
31)]
32use crate::utilities::*;
33
34use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
35use std::path::Path;
36use std::sync::{Arc, OnceLock};
37
38use ctb_storage_minimal::global_graph_layout::{
39    SYSTEM_REGION_END, SYSTEM_REGION_START,
40};
41use ctb_storage_minimal::shorthand::DcShorthand;
42use ctb_utilities::format_id::DC_COLLECTIVE_TOOLBOX;
43
44use crate::dc::{
45    DC_APPROXIMATE_DECOMPOSITION, DC_BEGIN_ASSOCIATIVITY_GROUP,
46    DC_BEGIN_BLOCK_COMMENT, DC_BEGIN_BLOCK_COMMENT_NEW_LINE,
47    DC_BEGIN_ENUM_DECL, DC_BEGIN_IDENTIFIER, DC_BEGIN_LIST, DC_BEGIN_LITERAL,
48    DC_BEGIN_MODULE, DC_BEGIN_NAMED_STRUCT_DECL,
49    DC_BEGIN_POSITIONAL_STRUCT_DECL, DC_BEGIN_ROUTINE, DC_BEGIN_ROUTINE_DECL,
50    DC_BEGIN_SINGLE_LINE_COMMENT, DC_BEGIN_SINGLE_LINE_COMMENT_NEW_LINE,
51    DC_BEGIN_STAGER_MODULE, DC_BEGIN_TEST_BLOCK, DC_BEGIN_TYPE_DEF,
52    DC_BEGIN_WASM_PROGRAM, DC_BIDIRECTIONAL_CLASS, DC_BOOLEAN_TRUE,
53    DC_CANONICAL_DECOMPOSITION, DC_CANONICAL_NAME,
54    DC_CHARACTER_GENERAL_CATEGORY, DC_CHARACTER_SCRIPT,
55    DC_COLLECTIVE_TOOLBOX_DC_CSV_SEED_DATABASE,
56    DC_COLLECTIVE_TOOLBOX_SEED_GRAPH_DATA_SOURCE, DC_DATA_FORMAT_DESCRIPTION,
57    DC_DC_DOCUMENT_EXECUTION_KERNEL, DC_DC_GENERAL_CATEGORY,
58    DC_DECLARE_BRAND_TYPE, DC_DECLARE_CONST, DC_DECLARE_PUB, DC_DECOMPOSITION,
59    DC_DESCRIPTION, DC_ENCLOSING_DOCUMENT, DC_END_ASSOCIATIVITY_GROUP,
60    DC_END_BLOCK_COMMENT, DC_END_IDENTIFIER, DC_END_LIST, DC_END_LITERAL,
61    DC_END_SINGLE_LINE_COMMENT, DC_END_TYPE_DEF, DC_END_WASM_PROGRAM,
62    DC_ENTITY_TYPE, DC_ESCAPE, DC_EVALUATE_VALUE_AS_ATOM,
63    DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID, DC_HAS_A, DC_HAS_VALUE,
64    DC_IN_CONTEXT_OF, DC_IS_ASSOCIATED_WITH, DC_IS_BASED_ON, DC_IS_INSTANCE_OF,
65    DC_IS_STABLE, DC_MANUAL_ENTRY, DC_PATTERN_REPLACEMENT, DC_PREFERRED,
66    DC_PROGRAMMATIC_IDENTIFIER, DC_QUOTE_FOLLOWING_DC_AS_ATOM, DC_REPLACEMENT,
67    DC_RETRACTS, DC_ROUTINE_TEST_SUITE, DC_SEMANTIC_DECOMPOSITION,
68    DC_SUPERSEDES, DC_SYNTAX_RULE, DC_THIS_ELEMENT, DC_TYPE_ANY,
69    DC_TYPE_ATOM_DC, DC_TYPE_CONVERSION, DC_TYPE_ROUTINE, DC_UNICODE_SCRIPT,
70    DcChar,
71};
72use crate::sha2::{Digest, Sha256};
73
74use crate::graph_ledger::{
75    LedgerNode, MAX_NODES_PER_CHUNK, SeedEntityKey, chunk_filename_for_node_id,
76    decode_ctbnbdl_bundle, decode_ctbnbdl_bundle_resilient,
77    decode_integer_value_tokens, decode_string_value_tokens,
78    find_closed_delimited_span, format_chunk_bundle_filename,
79    format_chunk_filename, parse_chunk_bundle_filename_start_id,
80    parse_for_each_statement_tokens, parse_statement_tokens,
81    single_valued_property_set,
82};
83pub use crate::support::seed_graph_reconstruct::ReconstructedNamedType;
84
85/// Default glob pattern matching bundled active system graph `.ctbnbdl` files inside `ctoolbox.rsrc`.
86pub const SEED_GRAPH_ASSET_GLOB: &str = "data/graph/*.ctbnbdl";
87
88/// Default glob pattern matching optional historical/inactive system graph `.ctbnbdl` files
89/// inside `system_graph_history.rsrc` (`assets/data/graph/system/*.ctbnbdl`).
90pub const SYSTEM_GRAPH_HISTORY_ASSET_GLOB: &str = "data/graph/system/*.ctbnbdl";
91
92/// Primary seed graph bundle asset key inside `ctoolbox.rsrc`.
93pub const PRIMARY_SEED_GRAPH_ASSET_KEY: &str = "data/graph/85899_34592.ctbnbdl";
94
95static SHARED_SEED_GRAPH: OnceLock<Result<Arc<SeedGraphIndex>, String>> =
96    OnceLock::new();
97
98#[must_use]
99fn sh(dc: DcChar) -> DcShorthand {
100    DcShorthand::from_global_id(dc.to_u128())
101}
102
103/// Active reified `Has a` (`Dc 584`) + `Has value` (`Dc 610`) property assignment.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct ActivePropertyValue {
106    /// Node ID of the `584 <subject> <property>` (`Has a`) statement.
107    pub has_a_id: u128,
108    /// Node ID of the active `610 l<has_a_id> <value>` (`Has value`) statement.
109    pub has_val_id: u128,
110    /// Value token assigned by `has_val_id`.
111    pub value: DcShorthand,
112    /// Optional node ID of an active `584 l<has_a_id> 570` (`Preferred`) statement qualifying `has_a_id`.
113    pub preferred_id: Option<u128>,
114}
115
116/// Executable implementation body attached to an active converter routine or
117/// `.Formats:transformation` Format Dc in a [`SeedGraphIndex`] snapshot.
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub enum ActiveConverterBody<'a> {
120    /// Stage 0 `.WASM` decomposition (`Dc 1927`..`Dc 1928` or `wasm_routine`).
121    Wasm(&'a [DcShorthand]),
122    /// Stage 1 / Stage 2 lossless StageL/StageR Token-Dc decomposition.
123    StageL(Vec<DcChar>),
124}
125
126/// Single active conversion edge (`[Dc 302 "Type conversion", src, dst]`) resolved from
127/// [`SeedGraphIndex`].
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct ActiveConverterStep<'a> {
130    /// Subject owning the converter (`DcShorthand::Format(_)` transformation or
131    /// `DcShorthand::Long(_)` standalone `Routine` entity).
132    pub subject: DcShorthand,
133    /// Input format or starter Dc shorthand (`src` in `Dc 302 src dst`).
134    pub src: DcShorthand,
135    /// Output format or starter Dc shorthand (`dst` in `Dc 302 src dst`).
136    pub dst: DcShorthand,
137    /// Whether this converter or its decomposition carries `Dc 570 "Preferred"`.
138    pub is_preferred: bool,
139    /// Executable `.WASM` or StageL Token-Dc body.
140    pub body: ActiveConverterBody<'a>,
141}
142
143/// Version tag mixed into offline native substitute bundle fingerprints whenever
144/// [`discover_graph_wasm_substitute_snapshots`] or
145/// [`SeedGraphIndex::discover_system_wasm_substitute_targets`] selection rules change.
146pub const SYSTEM_WASM_SUBSTITUTE_DISCOVERY_VERSION: u32 = 2;
147
148/// Classification of an auto-discovered runnable graph node or Dc eligible for
149/// Guix-style native safe-Rust substitute compilation.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub enum SystemWasmSubstituteTargetKind {
152    /// Trusted System execution kernel (`Dc 1936`), compiled via
153    /// [`SeedGraphIndex::resolve_trusted_system_supervisor_bootstrap_tokens`].
154    SupervisorKernel,
155    /// Standalone uncontextualized `.WASM` module decomposition on a subject Dc.
156    StandaloneWasm,
157    /// Standalone unowned `.WASM` value node (`Dc 1927..Dc 1928`) directly in `LedgerNode`.
158    StandaloneWasmValueNode {
159        /// Global node ID of the `.WASM` value node.
160        node_id: u128,
161    },
162    /// Active `[Dc 302 src dst]` converter implemented directly as `.WASM`.
163    WasmConverter {
164        /// Converter source format or starter Dc shorthand.
165        src: DcShorthand,
166        /// Converter destination format or starter Dc shorthand.
167        dst: DcShorthand,
168    },
169    /// Active `[Dc 302 src dst]` converter implemented in StageL 3 (`l/u8 -> l/u8`).
170    StageLConverter {
171        /// Converter source format or starter Dc shorthand.
172        src: DcShorthand,
173        /// Converter destination format or starter Dc shorthand.
174        dst: DcShorthand,
175    },
176    /// Active `[Dc 302 src dst]` converter implemented in StageR 3 (`l/u8 -> l/u8`).
177    StageRConverter {
178        /// Converter source format or starter Dc shorthand.
179        src: DcShorthand,
180        /// Converter destination format or starter Dc shorthand.
181        dst: DcShorthand,
182    },
183    /// Standalone StageL 3 `pub dc/<shorthand>` routine (`l/u8 -> l/u8`).
184    StageLRoutineBytes,
185    /// Standalone StageL 3 `pub dc/<shorthand>` routine (`dcs -> dcs`).
186    StageLRoutineDcs,
187    /// Standalone StageR 3 `pub dc/<shorthand>` routine (`l/u8 -> l/u8`).
188    StageRRoutineBytes,
189    /// Standalone StageR 3 `pub dc/<shorthand>` routine (`dcs -> dcs`).
190    StageRRoutineDcs,
191}
192
193/// Single auto-discovered graph target eligible for native safe-Rust
194/// WebAssembly substitute compilation at a given snapshot.
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct SystemWasmSubstituteTarget {
197    /// Canonical subject shorthand identifying this routine, converter, or value node.
198    pub subject: DcShorthand,
199    /// Resolved 128-bit global Document Character ID.
200    pub global_id: u128,
201    /// Defining graph value/statement node ID attributing this revision to a `.ctbnodes` chunk.
202    pub defining_node_id: u128,
203    /// Uniform `.ctbnodes` chunk stem (e.g. `"85899_75792"` -> `"85899_75792.generated.rs"`).
204    pub chunk_prefix: String,
205    /// How this target should be lowered to an uninstrumented `.wasm` module.
206    pub kind: SystemWasmSubstituteTargetKind,
207}
208
209/// Vantage-point-agnostic runnable WebAssembly snapshot discovered across all
210/// revisions present in an arbitrary [`LedgerNode`] slice.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub struct GraphWasmSubstituteSnapshot {
213    /// Discovered runnable target and its `.ctbnodes` chunk attribution.
214    pub target: SystemWasmSubstituteTarget,
215    /// Snapshot watermark node ID at which this exact revision closure is evaluated.
216    pub pin_node_id: u128,
217    /// Whether this exact revision closure is active at the final node of the input slice.
218    pub is_head: bool,
219    /// Deterministic SHA-256 hex digest of this target's semantic source + compiler closure.
220    pub revision_sha256_hex: String,
221}
222
223/// Returns the uniform `.ctbnodes` chunk stem (e.g. `"85899_75792"`) owning `node_id`.
224///
225/// System-block node IDs align to `SYSTEM_REGION_START` via [`chunk_filename_for_node_id`];
226/// node IDs in any other graph block align to `MAX_NODES_PER_CHUNK` boundaries via
227/// [`format_chunk_filename`].
228#[must_use]
229pub fn substitute_chunk_prefix_for_node_id(node_id: u128) -> String {
230    let filename = if (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&node_id)
231    {
232        chunk_filename_for_node_id(node_id)
233    } else {
234        // Reason for fallback: MAX_NODES_PER_CHUNK is a small usize constant (100) that always fits in u128.
235        let max_u128 = u128::try_from(MAX_NODES_PER_CHUNK).unwrap_or(100);
236        // Reason for fallback: max_u128 >= 1 so checked_div never divides by zero.
237        let chunk_start = node_id
238            .checked_div(max_u128)
239            .unwrap_or(0)
240            .saturating_mul(max_u128);
241        format_chunk_filename(chunk_start)
242    };
243    // Reason for fallback: format_chunk_filename always ends with ".ctbnodes".
244    filename
245        .strip_suffix(".ctbnodes")
246        .unwrap_or(&filename)
247        .to_owned()
248}
249
250/// Decoupled non-executable metadata attached to a StageL/StageR routine entity
251/// (`Dc 2240..2241` decomposition) in a [`SeedGraphIndex`] snapshot.
252#[derive(Debug, Clone, Default, PartialEq, Eq)]
253pub struct StagelRoutineGraphMeta {
254    /// Whether the routine is exported (`pub` or `pub dc/<shorthand>`) or a direct value node.
255    pub is_pub: bool,
256    /// Optional `Dc 574` `"Programmatic identifier"` string on the subject.
257    pub name: Option<String>,
258    /// Optional PSR-4 namespace segments (`Dc 646` context on `574` for `pub`, or `Dc 598` for private).
259    pub home_namespace: Option<Vec<String>>,
260    /// Optional `Dc 573` `"Description"` doc-comment text on `Long` routine entities.
261    pub description: Option<String>,
262    /// Optional expanded `Dc 2206..2207` inline test suite tokens (`Dc 1942` `"Routine test suite"`).
263    pub test_suite_tokens: Option<Vec<DcChar>>,
264}
265
266/// Runtime index over the System-block seed graph (`8589934592..=12884901887`).
267#[derive(Debug, Clone)]
268pub struct SeedGraphIndex {
269    /// Monotonic process-unique identifier for fast per-snapshot memoization keys.
270    pub(crate) instance_id: u64,
271    /// All loaded `LedgerNode`s in ascending ID order.
272    pub(crate) nodes: Vec<LedgerNode>,
273    /// Maps node ID (`u128`) to its index in `nodes`.
274    pub(crate) node_index_by_id: HashMap<u128, usize>,
275    /// Maps a superseded node ID (`old_id`) to the statement node ID (`new_id`)
276    /// that superseded it via an active `591 <new_id> l<old_id>` (`Supersedes`) statement.
277    pub(crate) superseded_by: HashMap<u128, u128>,
278    /// Maps a retracted node ID (`old_id`) to the statement node ID (`retract_id`)
279    /// that retracted it via an active `592 615 l<old_id>` (`Retracts`) statement.
280    pub(crate) retracted_by: HashMap<u128, u128>,
281    /// Set of all inactive node IDs (superseded or retracted).
282    pub(crate) inactive_ids: HashSet<u128>,
283    /// Decoded UTF-8 strings for string value nodes, keyed by `u128` node ID.
284    pub(crate) string_by_node_id: HashMap<u128, String>,
285    /// Decoded unsigned integers for `6 f199 .. 7` value nodes, keyed by `u128` node ID.
286    pub(crate) integer_by_node_id: HashMap<u128, u128>,
287    /// Maps a `SeedEntityKey` (`BidiClass`, `GeneralCategory`, `Script`, `NamedConstruct`)
288    /// to its allocated `u128` node ID.
289    pub(crate) seed_entity_ids: HashMap<SeedEntityKey, u128>,
290    /// Reverse lookup from allocated `u128` node ID to its `SeedEntityKey`.
291    pub(crate) seed_entity_by_id: HashMap<u128, SeedEntityKey>,
292    /// Active single-valued properties: `(subject, prop_token) -> (has_a_id, has_val_id, current_val_token)`.
293    pub(crate) active_single_props:
294        BTreeMap<(DcShorthand, DcShorthand), (u128, u128, DcShorthand)>,
295    /// All active single-valued property assignments per `(subject, prop_token)` in ascending `has_a_id` order.
296    pub(crate) single_props_by_subj_prop:
297        BTreeMap<(DcShorthand, DcShorthand), Vec<(u128, u128, DcShorthand)>>,
298    /// Active multi-valued properties: `(subject, prop_token, val_token) -> (has_a_id, has_val_id)`.
299    pub(crate) active_multi_props:
300        BTreeMap<(DcShorthand, DcShorthand, DcShorthand), (u128, u128)>,
301    /// Active `584 l<has_a_id> 570` (`Preferred`) qualifiers on multi-valued properties:
302    /// `(subject, prop_token, val_token) -> pref_qual_id`.
303    pub(crate) active_multi_preferred:
304        BTreeMap<(DcShorthand, DcShorthand, DcShorthand), u128>,
305    /// Active multi-valued properties grouped by `(subject, prop_token)` in ascending `has_a_id` order
306    /// (with `Preferred`-qualified entries placed first).
307    pub(crate) multi_props_by_subj_prop:
308        HashMap<(DcShorthand, DcShorthand), Vec<ActivePropertyValue>>,
309    /// Active `<prefer>` replacements: `(subject, val_token) -> (has_a_id, has_val_id, pref_qual_id)`.
310    pub(crate) active_preferred:
311        BTreeMap<(DcShorthand, DcShorthand), (u128, u128, u128)>,
312    /// All active `<prefer>` replacement triples per `(subject, val_token)` in ascending `has_a_id` order.
313    pub(crate) preferred_all_by_subj_val:
314        BTreeMap<(DcShorthand, DcShorthand), Vec<(u128, u128, u128)>>,
315    /// Active `<prefer>` replacement values grouped by `subject` in ascending `has_a_id` order.
316    pub(crate) preferred_by_subject: HashMap<DcShorthand, Vec<DcShorthand>>,
317    /// Active direct binary statements: `(verb, subject, object) -> stmt_id`.
318    pub(crate) active_direct_stmts:
319        BTreeMap<(DcShorthand, DcShorthand, DcShorthand), u128>,
320    /// All active direct binary statement node IDs per `(verb, subject, object)` in ascending `stmt_id` order.
321    pub(crate) direct_stmts_all:
322        BTreeMap<(DcShorthand, DcShorthand, DcShorthand), Vec<u128>>,
323    /// Active direct binary statement objects grouped by `(verb, subject)` in ascending `stmt_id` order.
324    pub(crate) direct_objects_by_verb_subj:
325        HashMap<(DcShorthand, DcShorthand), Vec<DcShorthand>>,
326    /// Active direct binary statement subjects grouped by `(verb, object)` in ascending `stmt_id` order.
327    pub(crate) direct_subjects_by_verb_obj:
328        HashMap<(DcShorthand, DcShorthand), Vec<DcShorthand>>,
329    /// Active statement node IDs that are structurally orphaned (e.g. an active `584` property
330    /// statement with no active `610` value). Multiple active statements for the same property or
331    /// on the same `584` node are NOT shadowed here; all remain active in the index.
332    pub(crate) orphaned_stmt_ids: Vec<u128>,
333    /// In-graph provenance (`Dc 635` `"Collective Toolbox seed graph data source"`) mapped from
334    /// target node ID (`u128`) to its declared data source token (e.g. `Dc 636` or `Dc 637`).
335    pub(crate) node_data_source: HashMap<u128, DcShorthand>,
336    /// Active statement node IDs (`Dc 638` `"For each"`, `Dc 584` `"Has a"`, and `Dc 610` `"Has value"`)
337    /// that assert `Dc 635` `"Collective Toolbox seed graph data source"`.
338    pub(crate) provenance_stmt_ids: HashSet<u128>,
339    /// Set of node IDs loaded from the host-authenticated bundled asset (`ctoolbox.rsrc` /
340    /// `system_graph_history.rsrc`), distinguishing bundled System authority from extra or
341    /// unbundled resources (such as Wikidata).
342    pub(crate) bundled_origin_node_ids: HashSet<u128>,
343    /// `true` when loaded from the runtime asset bundle (`ctoolbox.rsrc` /
344    /// `system_graph_history.rsrc`), rather than constructed from an in-memory
345    /// or synthetic `LedgerNode` slice.
346    pub(crate) from_asset_bundle: bool,
347    /// Maps a superseded node ID (`old_id`) to the statement node ID (`supersede_stmt_id`)
348    /// of the `Dc 591` `"Supersedes"` statement itself.
349    pub(crate) superseding_stmt_by_old_id: HashMap<u128, u128>,
350    /// All active `Dc 635` `"Collective Toolbox seed graph data source"` assertions targeting
351    /// a node ID (`target_node_id -> Vec<(has_a_stmt_id, has_val_stmt_id, data_source_tok)>`).
352    pub(crate) node_provenance_assertions:
353        HashMap<u128, Vec<(u128, u128, DcShorthand)>>,
354    /// All statement node IDs (active or inactive) whose subject is `subj`.
355    pub(crate) subject_all_stmt_ids: HashMap<DcShorthand, Vec<u128>>,
356    /// All `Dc 610` `"Has value"` statement nodes (`(has_val_id, val_tok)`, active or inactive)
357    /// targeting a `Dc 584` / `Dc 638` statement node ID (`has_a_id`).
358    pub(crate) has_val_stmt_ids_by_has_a:
359        HashMap<u128, Vec<(u128, DcShorthand)>>,
360    /// Highest allocated node ID in the System block at the time the graph bundle was created
361    /// (`Dc 641` `"Global graph system block most recent node ID at time of document creation"`).
362    pub(crate) system_block_most_recent_node_id: Option<u128>,
363    /// Active non-seed entity nodes (`Dc 586` `"Is an instance of"` `Dc 615` `"Enclosing document"` `<class_tok>`),
364    /// mapped from entity `u128` node ID to `<class_tok>`.
365    pub(crate) entity_class_by_id: HashMap<u128, DcShorthand>,
366    /// Exact verbatim token slice -> active node IDs in ascending `node.id` order (populated on first query).
367    pub(crate) active_nodes_by_exact_tokens:
368        std::sync::OnceLock<HashMap<Vec<DcShorthand>, Vec<u128>>>,
369    /// All active statement triples `(stmt_id, verb, subj, obj)` sorted deterministically.
370    pub(crate) all_active_triples:
371        Vec<(u128, DcShorthand, DcShorthand, DcShorthand)>,
372    /// Indices into `all_active_triples` grouped by `(verb, subj)`.
373    pub(crate) triple_idx_by_verb_subj:
374        HashMap<(DcShorthand, DcShorthand), Vec<usize>>,
375    /// Indices into `all_active_triples` grouped by `(verb, obj)`.
376    pub(crate) triple_idx_by_verb_obj:
377        HashMap<(DcShorthand, DcShorthand), Vec<usize>>,
378    /// Indices into `all_active_triples` grouped by `verb`.
379    pub(crate) triple_idx_by_verb: HashMap<DcShorthand, Vec<usize>>,
380    /// Indices into `all_active_triples` grouped by `subj`.
381    pub(crate) triple_idx_by_subj: HashMap<DcShorthand, Vec<usize>>,
382    /// Indices into `all_active_triples` grouped by `obj`.
383    pub(crate) triple_idx_by_obj: HashMap<DcShorthand, Vec<usize>>,
384}
385
386/// Verified resolution of an unpinned 1-Short-Dc System supervisor entry document
387/// against the application-bundled System-block seed graph (`ctoolbox.rsrc`).
388#[derive(Debug, Clone, PartialEq, Eq)]
389pub struct TrustedSystemSupervisorResolution {
390    /// Unpinned Short Dc entry character that was resolved.
391    pub entry_dc: DcChar,
392    /// Active System-block statement node ID (`Dc 584` `"Has a"` or `Dc 594` `"Syntax rule"`)
393    /// binding `entry_dc` to its active definition.
394    pub statement_node_id: u128,
395    /// Active `Dc 610` `"Has value"` statement node ID assigning the definition node to `statement_node_id`.
396    pub value_statement_node_id: u128,
397    /// Active System-block definition node ID (`Dc 1927` `"Begin WASM program"` or routine node)
398    /// representing the resolved supervisor revision.
399    pub supervisor_revision_node_id: u128,
400    /// Highest allocated System-block node ID (`HEAD` watermark) of the trusted graph.
401    pub system_head_node_id: u128,
402    /// Deterministically sorted list of all transitive System-block dependency node IDs
403    /// reachable from the supervisor definition (including `supervisor_revision_node_id`).
404    pub dependency_snapshot_node_ids: Vec<u128>,
405    /// Raw `.WASM` / supervisor definition tokens from `supervisor_revision_node_id`.
406    pub definition_tokens: Vec<DcShorthand>,
407}
408
409/// Parses a `Dc 348 "Ambiguous values"` list node (`348 310 275 l<cand_1> 312 l<cand_2> ... 311`)
410/// into its ordered candidate node IDs.
411#[must_use]
412pub fn parse_ambiguous_values_tokens(
413    tokens: &[DcShorthand],
414) -> Option<Vec<u128>> {
415    let sh_ambiguous = DcShorthand::Short(348);
416    let sh_begin_list = sh(DC_BEGIN_LIST);
417    let sh_end_list = sh(DC_END_LIST);
418    let sh_graph_node = DcShorthand::Short(275);
419    let sh_list_sep = DcShorthand::Short(312);
420    if tokens.len() < 4
421        || tokens.first() != Some(&sh_ambiguous)
422        || tokens.get(1) != Some(&sh_begin_list)
423        || tokens.last() != Some(&sh_end_list)
424    {
425        return None;
426    }
427    let middle = tokens.get(2..tokens.len().saturating_sub(1))?;
428    let mut candidates = Vec::new();
429    for &tok in middle {
430        match tok {
431            DcShorthand::Long(id) => candidates.push(id),
432            t if t == sh_graph_node || t == sh_list_sep => {}
433            _ => return None,
434        }
435    }
436    if candidates.len() >= 2 {
437        Some(candidates)
438    } else {
439        None
440    }
441}
442
443/// Computes the set of effectively inactive node IDs, along with `superseded_by` (`old_id -> new_id`)
444/// and `retracted_by` (`old_id -> retract_stmt_id`), across `nodes` in reverse chronological order.
445#[must_use]
446pub fn compute_effective_inactive_ids(
447    nodes: &[LedgerNode],
448) -> (HashSet<u128>, HashMap<u128, u128>, HashMap<u128, u128>) {
449    let sh_supersedes = sh(DC_SUPERSEDES);
450    let sh_retracts = sh(DC_RETRACTS);
451
452    let mut inactive_ids = HashSet::new();
453    let mut superseded_by = HashMap::new();
454    let mut retracted_by = HashMap::new();
455
456    for node in nodes.iter().rev() {
457        if inactive_ids.contains(&node.id) {
458            continue;
459        }
460        if let Some((verb, subj, obj)) = parse_statement_tokens(&node.tokens) {
461            if verb == sh_supersedes {
462                if let DcShorthand::Long(old_id) = obj {
463                    let new_id = match subj {
464                        DcShorthand::Long(n_id) => n_id,
465                        _ => node.id,
466                    };
467                    inactive_ids.insert(old_id);
468                    superseded_by.insert(old_id, new_id);
469                }
470            } else if verb == sh_retracts {
471                if let DcShorthand::Long(old_id) = obj {
472                    inactive_ids.insert(old_id);
473                    retracted_by.insert(old_id, node.id);
474                }
475            }
476        }
477    }
478
479    (inactive_ids, superseded_by, retracted_by)
480}
481
482/// Returns the highest allocated node ID in the System block from the shared runtime seed graph.
483pub fn current_system_block_most_recent_node_id() -> Result<u128> {
484    let index = SeedGraphIndex::shared()?;
485    index
486        .system_block_most_recent_node_id()
487        .context("System block seed graph has no allocated node IDs")
488}
489
490impl SeedGraphIndex {
491    /// Returns the process-unique identifier assigned to this `SeedGraphIndex` instance.
492    #[must_use]
493    pub const fn instance_id(&self) -> u64 {
494        self.instance_id
495    }
496
497    /// Returns the lazily loaded process-wide `SeedGraphIndex` from the runtime asset bundle.
498    pub fn shared() -> Result<&'static Arc<Self>> {
499        let res = SHARED_SEED_GRAPH.get_or_init(|| {
500            Self::load_from_asset_bundle()
501                .map(Arc::new)
502                .map_err(|err| format!("{err:#}"))
503        });
504        match res {
505            Ok(arc) => Ok(arc),
506            Err(msg) => bail!("{msg}"),
507        }
508    }
509
510    /// Loads all active `data/graph/*.ctbnbdl` bundle files (beginning with
511    /// `data/graph/85899_34592.ctbnbdl`) from the runtime asset bundle (`ctoolbox.rsrc`)
512    /// and indexes all active statements, seed entities, and value nodes.
513    ///
514    /// Errors strictly by default on any checksum, framing, ordering, or value-immutability
515    /// violation unless `--recover-graph` is enabled on the current invocation.
516    pub fn load_from_asset_bundle() -> Result<Self> {
517        let recover_graph =
518            ctb_utilities::invocation_settings::get_settings().recover_graph;
519        Self::load_from_asset_bundle_with_recovery(recover_graph)
520    }
521
522    /// Loads active `data/graph/*.ctbnbdl` bundles from the runtime asset bundle,
523    /// enforcing strict errors when `recover_graph` is `false` or quarantining and
524    /// warning on damaged sections/invariants when `recover_graph` is `true` (`--recover-graph`).
525    pub fn load_from_asset_bundle_with_recovery(
526        recover_graph: bool,
527    ) -> Result<Self> {
528        let (active_most_recent, active_nodes) = Self::load_nodes_from_asset_dir(
529            SEED_GRAPH_ASSET_GLOB,
530            "data/graph",
531            Some(PRIMARY_SEED_GRAPH_ASSET_KEY),
532            true,
533            recover_graph,
534        )?;
535        if let Some(first) = active_nodes.first()
536            && first.id != SYSTEM_REGION_START
537        {
538            if recover_graph {
539                warn_fmt!(
540                    "Expected first active system graph node to start at l{SYSTEM_REGION_START} ('{}'), first recovered valid node is l{}",
541                    format_chunk_bundle_filename(SYSTEM_REGION_START),
542                    first.id
543                );
544            } else {
545                bail!(
546                    "Expected first active system graph node to start at l{SYSTEM_REGION_START} ('{}'), found l{}",
547                    format_chunk_bundle_filename(SYSTEM_REGION_START),
548                    first.id
549                );
550            }
551        }
552        let mut index = Self::from_bundled_nodes(active_nodes);
553        index.from_asset_bundle = true;
554        if let Some(wm) = active_most_recent {
555            // Reason for fallback: when no prior watermark has been recorded, wm is the initial watermark.
556            index.system_block_most_recent_node_id = Some(
557                index
558                    .system_block_most_recent_node_id
559                    .map_or(wm, |cur| cur.max(wm)),
560            );
561        }
562        index.validate_or_warn_graph_invariants(recover_graph)?;
563        Ok(index)
564    }
565
566    /// Loads both active `data/graph/*.ctbnbdl` bundles (from `ctoolbox.rsrc`) and optional
567    /// historical/inactive `data/graph/system/*.ctbnbdl` bundles (from `system_graph_history.rsrc`
568    /// if installed, or `assets/data/graph/system/` in dev mode), merging them in ascending
569    /// node ID order and resolving all `Dc 591` (`Supersedes`) and `Dc 592` (`Retracts`) history.
570    pub fn load_with_history_from_asset_bundle() -> Result<Self> {
571        let recover_graph =
572            ctb_utilities::invocation_settings::get_settings().recover_graph;
573        let (bundle_most_recent, merged) =
574            Self::load_merged_nodes_with_history_and_recovery(recover_graph)?;
575        let mut index = Self::from_bundled_nodes(merged);
576        index.from_asset_bundle = true;
577        if let Some(wm) = bundle_most_recent {
578            // Reason for fallback: when no prior watermark has been recorded, wm is the initial watermark.
579            index.system_block_most_recent_node_id = Some(
580                index
581                    .system_block_most_recent_node_id
582                    .map_or(wm, |cur| cur.max(wm)),
583            );
584        }
585        index.validate_or_warn_graph_invariants(recover_graph)?;
586        Ok(index)
587    }
588
589    /// Loads a `SeedGraphIndex` pinned to the System-block state as of `most_recent_node_id`
590    /// (`Dc 641` `"Global graph system block most recent node ID at time of document creation"`).
591    ///
592    /// If `most_recent_node_id` matches the shared `HEAD` seed graph's
593    /// `system_block_most_recent_node_id()`, returns the shared `HEAD` index in $O(1)$.
594    /// If `most_recent_node_id` exceeds `HEAD`, returns an error rather than silently
595    /// substituting `HEAD`. Otherwise, loads active and historical `.ctbnbdl` bundles,
596    /// verifies that historical coverage is complete up to `most_recent_node_id`, and
597    /// reconstructs the graph state as of `most_recent_node_id`.
598    pub fn load_at_most_recent_from_asset_bundle(
599        most_recent_node_id: u128,
600    ) -> Result<Arc<Self>> {
601        if let Some(block_desc) = ctb_storage_minimal::global_graph_layout::unsupported_graph_block_description(most_recent_node_id) {
602            bail!(
603                "Document pin Dc 641 targets unsupported graph block ({block_desc}): l{most_recent_node_id} is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
604            );
605        }
606        ensure!(
607            (SYSTEM_REGION_START..=SYSTEM_REGION_END)
608                .contains(&most_recent_node_id),
609            "Most recent System block node ID l{most_recent_node_id} is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
610        );
611        let shared = Self::shared()?;
612        if let Some(head_id) = shared.system_block_most_recent_node_id() {
613            if most_recent_node_id == head_id {
614                return Ok(Arc::clone(shared));
615            }
616            if most_recent_node_id > head_id {
617                bail!(
618                    "Document pin Dc 641 requires a newer System graph snapshot than the local graph (l{most_recent_node_id} > l{head_id})"
619                );
620            }
621        }
622        let recover_graph =
623            ctb_utilities::invocation_settings::get_settings().recover_graph;
624        let (active_most_recent, active_nodes) = Self::load_nodes_from_asset_dir(
625            SEED_GRAPH_ASSET_GLOB,
626            "data/graph",
627            Some(PRIMARY_SEED_GRAPH_ASSET_KEY),
628            true,
629            recover_graph,
630        )?;
631        let (history_most_recent, history_nodes) =
632            Self::load_nodes_from_asset_dir(
633                SYSTEM_GRAPH_HISTORY_ASSET_GLOB,
634                "data/graph/system",
635                None,
636                false,
637                recover_graph,
638            )?;
639        let mut index =
640            Self::from_active_and_history_nodes_at_most_recent_with_recovery(
641                active_most_recent,
642                active_nodes,
643                history_most_recent,
644                history_nodes,
645                most_recent_node_id,
646                recover_graph,
647            )?;
648        index.from_asset_bundle = true;
649        index.validate_or_warn_graph_invariants(recover_graph)?;
650        Ok(Arc::new(index))
651    }
652
653    /// Reconstructs a `SeedGraphIndex` pinned to `most_recent_node_id` from separate
654    /// active (`data/graph/*.ctbnbdl`) and historical (`data/graph/system/*.ctbnbdl`)
655    /// node lists, enforcing snapshot bounds and historical bundle completeness.
656    pub fn from_active_and_history_nodes_at_most_recent(
657        active_most_recent: Option<u128>,
658        active_nodes: Vec<LedgerNode>,
659        history_most_recent: Option<u128>,
660        history_nodes: Vec<LedgerNode>,
661        most_recent_node_id: u128,
662    ) -> Result<Self> {
663        Self::from_active_and_history_nodes_at_most_recent_with_recovery(
664            active_most_recent,
665            active_nodes,
666            history_most_recent,
667            history_nodes,
668            most_recent_node_id,
669            false,
670        )
671    }
672
673    fn from_active_and_history_nodes_at_most_recent_with_recovery(
674        active_most_recent: Option<u128>,
675        active_nodes: Vec<LedgerNode>,
676        history_most_recent: Option<u128>,
677        history_nodes: Vec<LedgerNode>,
678        most_recent_node_id: u128,
679        recover_graph: bool,
680    ) -> Result<Self> {
681        if let Some(block_desc) = ctb_storage_minimal::global_graph_layout::unsupported_graph_block_description(most_recent_node_id) {
682            bail!(
683                "Document pin Dc 641 targets unsupported graph block ({block_desc}): l{most_recent_node_id} is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
684            );
685        }
686        ensure!(
687            (SYSTEM_REGION_START..=SYSTEM_REGION_END)
688                .contains(&most_recent_node_id),
689            "Most recent System block node ID l{most_recent_node_id} is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
690        );
691        let head_id = active_most_recent
692            .max(history_most_recent)
693            .max(
694                active_nodes
695                    .iter()
696                    .chain(&history_nodes)
697                    .map(|node| node.id)
698                    .max(),
699            )
700            .context("Cannot resolve Dc 641 pin against an empty System graph")?;
701        if most_recent_node_id > head_id {
702            bail!(
703                "Document pin Dc 641 requires a newer System graph snapshot than the local graph (l{most_recent_node_id} > l{head_id})"
704            );
705        }
706        let (_, merged) = Self::merge_active_and_history_nodes(
707            active_most_recent,
708            active_nodes,
709            history_most_recent,
710            history_nodes,
711        )?;
712        if most_recent_node_id < head_id {
713            let mut expected_id = SYSTEM_REGION_START;
714            for node in &merged {
715                if node.id > most_recent_node_id {
716                    break;
717                }
718                if node.id != expected_id {
719                    if recover_graph {
720                        warn_fmt!(
721                            "Historical graph bundle system_graph_history.rsrc (data/graph/system/*.ctbnbdl) is missing node(s) l{expected_id}..l{} while recovering historical pin l{most_recent_node_id}",
722                            node.id
723                        );
724                        expected_id = node.id.saturating_add(1);
725                        continue;
726                    }
727                    bail!(
728                        "Historical graph bundle system_graph_history.rsrc (data/graph/system/*.ctbnbdl) is incomplete: missing node l{expected_id} required for historical pin l{most_recent_node_id}"
729                    );
730                }
731                expected_id = expected_id.saturating_add(1);
732            }
733            if expected_id <= most_recent_node_id {
734                if recover_graph {
735                    warn_fmt!(
736                        "Historical graph bundle system_graph_history.rsrc (data/graph/system/*.ctbnbdl) is missing trailing node(s) l{expected_id}..=l{most_recent_node_id} while recovering historical pin l{most_recent_node_id}"
737                    );
738                } else {
739                    bail!(
740                        "Historical graph bundle system_graph_history.rsrc (data/graph/system/*.ctbnbdl) is incomplete: missing node l{expected_id}..=l{most_recent_node_id} for historical pin l{most_recent_node_id}"
741                    );
742                }
743            }
744        }
745        let mut index = Self::from_nodes_at_most_recent(
746            merged,
747            most_recent_node_id,
748        );
749        index.bundled_origin_node_ids =
750            index.nodes.iter().map(|node| node.id).collect();
751        Ok(index)
752    }
753
754    fn load_merged_nodes_with_history_and_recovery(
755        recover_graph: bool,
756    ) -> Result<(Option<u128>, Vec<LedgerNode>)> {
757        let (active_most_recent, active_nodes) = Self::load_nodes_from_asset_dir(
758            SEED_GRAPH_ASSET_GLOB,
759            "data/graph",
760            Some(PRIMARY_SEED_GRAPH_ASSET_KEY),
761            true,
762            recover_graph,
763        )?;
764        let (history_most_recent, history_nodes) =
765            Self::load_nodes_from_asset_dir(
766                SYSTEM_GRAPH_HISTORY_ASSET_GLOB,
767                "data/graph/system",
768                None,
769                false,
770                recover_graph,
771            )?;
772        Self::merge_active_and_history_nodes(
773            active_most_recent,
774            active_nodes,
775            history_most_recent,
776            history_nodes,
777        )
778    }
779
780    fn merge_active_and_history_nodes(
781        active_most_recent: Option<u128>,
782        active_nodes: Vec<LedgerNode>,
783        history_most_recent: Option<u128>,
784        history_nodes: Vec<LedgerNode>,
785    ) -> Result<(Option<u128>, Vec<LedgerNode>)> {
786        let bundle_most_recent = active_most_recent.max(history_most_recent);
787        if history_nodes.is_empty() {
788            return Ok((bundle_most_recent, active_nodes));
789        }
790
791        let mut merged = Vec::with_capacity(
792            active_nodes.len().saturating_add(history_nodes.len()),
793        );
794        let mut a_iter = active_nodes.into_iter().peekable();
795        let mut h_iter = history_nodes.into_iter().peekable();
796        while let (Some(a), Some(h)) = (a_iter.peek(), h_iter.peek()) {
797            ensure!(
798                a.id != h.id,
799                "Duplicate node ID l{} present in both active data/graph/ and historical data/graph/system/ bundles",
800                a.id
801            );
802            if a.id < h.id {
803                if let Some(node) = a_iter.next() {
804                    merged.push(node);
805                }
806            } else if let Some(node) = h_iter.next() {
807                merged.push(node);
808            }
809        }
810        merged.extend(a_iter);
811        merged.extend(h_iter);
812        Ok((bundle_most_recent, merged))
813    }
814
815    fn load_nodes_from_asset_dir(
816        glob_pattern: &str,
817        expected_parent_dir: &str,
818        fallback_key: Option<&str>,
819        require_non_empty: bool,
820        recover_graph: bool,
821    ) -> Result<(Option<u128>, Vec<LedgerNode>)> {
822        let raw_paths = ctb_storage_asset_bundle::find_assets(glob_pattern)
823            .with_context(|| {
824                format!(
825                    "Failed to query runtime asset bundle for '{glob_pattern}'"
826                )
827            })?;
828        let expected_parent = Path::new(expected_parent_dir);
829        let mut asset_paths: Vec<String> = raw_paths
830            .into_iter()
831            .filter(|p| Path::new(p).parent() == Some(expected_parent))
832            .collect();
833
834        if asset_paths.is_empty() {
835            if let Some(fallback) = fallback_key {
836                if ctb_storage_asset_bundle::get_asset(fallback).is_some() {
837                    asset_paths.push(fallback.to_string());
838                }
839            }
840        }
841        if asset_paths.is_empty() {
842            if require_non_empty {
843                bail!(
844                    "No system graph .ctbnbdl bundles found in runtime asset bundle matching '{glob_pattern}'"
845                );
846            }
847            return Ok((None, Vec::new()));
848        }
849
850        let mut keyed_paths: Vec<(u128, String)> =
851            Vec::with_capacity(asset_paths.len());
852        for asset_path in asset_paths {
853            let filename = Path::new(&asset_path)
854                .file_name()
855                .and_then(|s| s.to_str())
856                .with_context(|| {
857                    format!("Asset path '{asset_path}' has no valid filename")
858                })?;
859            let start_id = parse_chunk_bundle_filename_start_id(filename)
860                .with_context(|| {
861                    format!(
862                        "Invalid .ctbnbdl bundle filename '{filename}' in asset '{asset_path}'"
863                    )
864                })?;
865            ensure!(
866                (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&start_id),
867                "Bundle '{asset_path}' start ID l{start_id} is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
868            );
869            keyed_paths.push((start_id, asset_path));
870        }
871        keyed_paths.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
872
873        let mut all_nodes: Vec<LedgerNode> = Vec::new();
874        let mut max_most_recent: Option<u128> = None;
875        for (expected_first_id, asset_path) in keyed_paths {
876            let bytes = ctb_storage_asset_bundle::get_asset(&asset_path)
877                .with_context(|| {
878                    format!(
879                        "Failed to read asset '{asset_path}' from runtime asset bundle"
880                    )
881                })?;
882            let (bundle_most_recent, bundle_nodes, bundle_warnings) =
883                if recover_graph {
884                    decode_ctbnbdl_bundle_resilient(&bytes).with_context(|| {
885                        format!("Failed to decode .ctbnbdl bundle '{asset_path}'")
886                    })?
887                } else {
888                    let (wm, nodes) = decode_ctbnbdl_bundle(&bytes)
889                        .with_context(|| {
890                            format!(
891                                "Failed to decode .ctbnbdl bundle '{asset_path}'"
892                            )
893                        })?;
894                    (wm, nodes, Vec::new())
895                };
896            for warning in &bundle_warnings {
897                warn_fmt!(
898                    "Recovered from corrupted section in '{asset_path}': {warning}"
899                );
900            }
901            if let Some(wm) = bundle_most_recent {
902                // Reason for fallback: when no prior bundle watermark has been recorded, wm is the initial watermark.
903                max_most_recent =
904                    Some(max_most_recent.map_or(wm, |cur| cur.max(wm)));
905            }
906            let Some(first_node) = bundle_nodes.first() else {
907                if recover_graph {
908                    warn_fmt!(
909                        "Decoded .ctbnbdl bundle '{asset_path}' yielded 0 valid nodes after quarantining corrupted sections"
910                    );
911                    continue;
912                }
913                bail!(
914                    "Decoded .ctbnbdl bundle '{asset_path}' contains 0 nodes"
915                );
916            };
917            if first_node.id != expected_first_id {
918                if recover_graph {
919                    warn_fmt!(
920                        "Bundle '{asset_path}' declares start ID l{expected_first_id}, first recovered valid node is l{}",
921                        first_node.id
922                    );
923                } else {
924                    bail!(
925                        "Bundle '{asset_path}' filename declares start ID l{expected_first_id}, but first decoded node is l{}",
926                        first_node.id
927                    );
928                }
929            }
930            for (idx, node) in bundle_nodes.into_iter().enumerate() {
931                if !(SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&node.id) {
932                    if recover_graph {
933                        warn_fmt!(
934                            "{asset_path} (node index {idx}): skipping out-of-range node ID l{}",
935                            node.id
936                        );
937                        continue;
938                    }
939                    bail!(
940                        "{asset_path} (node index {idx}): node ID l{} is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})",
941                        node.id
942                    );
943                }
944                if let Some(prev) = all_nodes.last()
945                    && node.id <= prev.id
946                {
947                    if recover_graph {
948                        warn_fmt!(
949                            "{asset_path} (node index {idx}): skipping non-monotonic node ID l{} (previous l{})",
950                            node.id,
951                            prev.id
952                        );
953                        continue;
954                    }
955                    bail!(
956                        "{asset_path} (node index {idx}): expected strictly increasing node ID > l{}, found l{}",
957                        prev.id,
958                        node.id
959                    );
960                }
961                all_nodes.push(node);
962            }
963        }
964        if require_non_empty && all_nodes.is_empty() {
965            bail!(
966                "All system graph .ctbnbdl bundles matching '{glob_pattern}' yielded 0 recoverable nodes"
967            );
968        }
969
970        Ok((max_most_recent, all_nodes))
971    }
972
973    /// Decodes a single `.ctbnbdl` byte slice strictly and builds a `SeedGraphIndex`.
974    ///
975    /// Fails immediately on any checksum mismatch, malformed section, supersession cycle,
976    /// or pure-value `Dc 591` / `Dc 592` revision.
977    pub fn from_ctbnbdl_bytes(bytes: &[u8]) -> Result<Self> {
978        let (most_recent, nodes) = decode_ctbnbdl_bundle(bytes)?;
979        let mut index = Self::from_nodes(nodes);
980        if let Some(wm) = most_recent {
981            // Reason for fallback: when no prior watermark has been recorded, wm is the initial watermark.
982            index.system_block_most_recent_node_id = Some(
983                index
984                    .system_block_most_recent_node_id
985                    .map_or(wm, |cur| cur.max(wm)),
986            );
987        }
988        index.validate_or_warn_graph_invariants(false)?;
989        Ok(index)
990    }
991
992    /// Resiliently decodes a `.ctbnbdl` byte slice (for `--recover-graph`), logging and
993    /// returning any section-quarantine or graph-invariant warnings while building a
994    /// `SeedGraphIndex` from all recovered valid nodes.
995    pub fn from_ctbnbdl_bytes_resilient(
996        bytes: &[u8],
997    ) -> Result<(Self, Vec<String>)> {
998        let (most_recent, nodes, mut warnings) =
999            decode_ctbnbdl_bundle_resilient(bytes)?;
1000        for warning in &warnings {
1001            warn_fmt!("Recovered from corrupted .ctbnbdl section: {warning}");
1002        }
1003        let mut index = Self::from_nodes(nodes);
1004        if let Some(wm) = most_recent {
1005            // Reason for fallback: when no prior watermark has been recorded, wm is the initial watermark.
1006            index.system_block_most_recent_node_id = Some(
1007                index
1008                    .system_block_most_recent_node_id
1009                    .map_or(wm, |cur| cur.max(wm)),
1010            );
1011        }
1012        let anomaly_warnings = index.collect_graph_invariant_anomalies();
1013        for warning in &anomaly_warnings {
1014            warn_fmt!("{warning}");
1015        }
1016        warnings.extend(anomaly_warnings);
1017        Ok((index, warnings))
1018    }
1019
1020    /// Builds a `SeedGraphIndex` from an ordered list of `LedgerNode`s using the default
1021    /// single-valued property set.
1022    #[must_use]
1023    pub fn from_nodes(nodes: Vec<LedgerNode>) -> Self {
1024        let single_props = single_valued_property_set();
1025        Self::from_nodes_with_single_props(nodes, &single_props)
1026    }
1027
1028    /// Builds a `SeedGraphIndex` from an ordered list of host-authenticated bundled `LedgerNode`s
1029    /// (loaded from `ctoolbox.rsrc` / `system_graph_history.rsrc`), marking all supplied System-region
1030    /// nodes as having authenticated bundled origin.
1031    #[must_use]
1032    pub fn from_bundled_nodes(nodes: Vec<LedgerNode>) -> Self {
1033        let bundled_ids: HashSet<u128> = nodes
1034            .iter()
1035            .filter(|n| (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&n.id))
1036            .map(|n| n.id)
1037            .collect();
1038        let mut index = Self::from_nodes(nodes);
1039        index.bundled_origin_node_ids = bundled_ids;
1040        index
1041    }
1042
1043    /// Builds a `SeedGraphIndex` pinned to `most_recent_node_id` from an ordered list of
1044    /// host-authenticated bundled `LedgerNode`s without marking `from_asset_bundle`.
1045    #[must_use]
1046    pub fn from_bundled_nodes_at_most_recent(
1047        nodes: Vec<LedgerNode>,
1048        most_recent_node_id: u128,
1049    ) -> Self {
1050        let mut index = Self::from_nodes_at_most_recent(nodes, most_recent_node_id);
1051        index.bundled_origin_node_ids = index
1052            .nodes
1053            .iter()
1054            .filter(|n| (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&n.id))
1055            .map(|n| n.id)
1056            .collect();
1057        index
1058    }
1059
1060    /// Loads and merges all active (`<graph_dir>/*.ctbnbdl`) and historical
1061    /// (`<graph_dir>/system/*.ctbnbdl`) System-graph bundles directly from disk in
1062    /// strictly ascending node ID order.
1063    ///
1064    /// # Errors
1065    /// Returns an error if `<graph_dir>` contains no `.ctbnbdl` files, if any bundle
1066    /// fails decoding or ordering checks, or if duplicate node IDs exist across active
1067    /// and historical bundles.
1068    pub fn load_merged_nodes_from_disk_graph_dir(
1069        graph_dir: &Path,
1070    ) -> Result<Vec<LedgerNode>> {
1071        fn read_dir_bundles(
1072            dir: &Path,
1073            require_non_empty: bool,
1074            recover_graph: bool,
1075        ) -> Result<(Option<u128>, Vec<LedgerNode>)> {
1076            if !dir.exists() {
1077                if require_non_empty {
1078                    bail!(
1079                        "System graph bundle directory {} does not exist",
1080                        dir.display()
1081                    );
1082                }
1083                return Ok((None, Vec::new()));
1084            }
1085            let mut keyed: Vec<(u128, std::path::PathBuf)> = Vec::new();
1086            for entry_res in std::fs::read_dir(dir).with_context(|| {
1087                format!(
1088                    "Failed to read System graph bundle directory {}",
1089                    dir.display()
1090                )
1091            })? {
1092                let entry = entry_res?;
1093                if !entry.file_type()?.is_file() {
1094                    continue;
1095                }
1096                let path = entry.path();
1097                let Some(name) = path.file_name().and_then(|s| s.to_str())
1098                else {
1099                    continue;
1100                };
1101                if !name.ends_with(".ctbnbdl") {
1102                    continue;
1103                }
1104                let start_id = parse_chunk_bundle_filename_start_id(name)
1105                    .with_context(|| {
1106                        format!(
1107                            "Invalid .ctbnbdl bundle filename '{name}' in {}",
1108                            dir.display()
1109                        )
1110                    })?;
1111                keyed.push((start_id, path));
1112            }
1113            if keyed.is_empty() {
1114                if require_non_empty {
1115                    bail!(
1116                        "No .ctbnbdl bundles found in {}",
1117                        dir.display()
1118                    );
1119                }
1120                return Ok((None, Vec::new()));
1121            }
1122            keyed.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
1123            let mut all_nodes: Vec<LedgerNode> = Vec::new();
1124            let mut max_wm: Option<u128> = None;
1125            for (expected_first_id, path) in keyed {
1126                let bytes = std::fs::read(&path).with_context(|| {
1127                    format!("Failed to read bundle {}", path.display())
1128                })?;
1129                let (wm, bundle_nodes, warnings) = if recover_graph {
1130                    decode_ctbnbdl_bundle_resilient(&bytes).with_context(
1131                        || format!("Failed to decode bundle {}", path.display()),
1132                    )?
1133                } else {
1134                    let (w, ns) = decode_ctbnbdl_bundle(&bytes).with_context(
1135                        || format!("Failed to decode bundle {}", path.display()),
1136                    )?;
1137                    (w, ns, Vec::new())
1138                };
1139                for warning in &warnings {
1140                    warn_fmt!(
1141                        "Recovered from corrupted section in {}: {warning}",
1142                        path.display()
1143                    );
1144                }
1145                if let Some(w) = wm {
1146                    // Reason for fallback: w initializes max_wm on the first bundle with a watermark.
1147                    max_wm = Some(max_wm.map_or(w, |cur| cur.max(w)));
1148                }
1149                let Some(first_node) = bundle_nodes.first() else {
1150                    if recover_graph {
1151                        warn_fmt!(
1152                            "Decoded .ctbnbdl bundle {} yielded 0 valid nodes after quarantining corrupted sections",
1153                            path.display()
1154                        );
1155                        continue;
1156                    }
1157                    bail!(
1158                        "Decoded .ctbnbdl bundle {} contains 0 nodes",
1159                        path.display()
1160                    );
1161                };
1162                if first_node.id != expected_first_id {
1163                    if recover_graph {
1164                        warn_fmt!(
1165                            "Bundle {} declares start ID l{expected_first_id}, first recovered valid node is l{}",
1166                            path.display(),
1167                            first_node.id
1168                        );
1169                    } else {
1170                        bail!(
1171                            "Bundle {} filename declares start ID l{expected_first_id}, found l{}",
1172                            path.display(),
1173                            first_node.id
1174                        );
1175                    }
1176                }
1177                for node in bundle_nodes {
1178                    if let Some(prev) = all_nodes.last()
1179                        && node.id <= prev.id
1180                    {
1181                        if recover_graph {
1182                            warn_fmt!(
1183                                "Bundle {}: skipping non-monotonic node ID l{} (previous l{})",
1184                                path.display(),
1185                                node.id,
1186                                prev.id
1187                            );
1188                            continue;
1189                        }
1190                        bail!(
1191                            "Bundle {}: expected strictly increasing node ID > l{}, found l{}",
1192                            path.display(),
1193                            prev.id,
1194                            node.id
1195                        );
1196                    }
1197                    all_nodes.push(node);
1198                }
1199            }
1200            if require_non_empty && all_nodes.is_empty() {
1201                bail!(
1202                    "All .ctbnbdl bundles in {} yielded 0 recoverable nodes",
1203                    dir.display()
1204                );
1205            }
1206            Ok((max_wm, all_nodes))
1207        }
1208
1209        let recover_graph =
1210            ctb_utilities::invocation_settings::get_settings().recover_graph;
1211        let (active_wm, active_nodes) =
1212            read_dir_bundles(graph_dir, true, recover_graph)?;
1213        let (hist_wm, hist_nodes) = read_dir_bundles(
1214            &graph_dir.join("system"),
1215            false,
1216            recover_graph,
1217        )?;
1218        let (_, merged) = Self::merge_active_and_history_nodes(
1219            active_wm,
1220            active_nodes,
1221            hist_wm,
1222            hist_nodes,
1223        )?;
1224        Ok(merged)
1225    }
1226
1227    /// Builds a `SeedGraphIndex` combining host-authenticated bundled System nodes (`bundled_nodes`)
1228    /// with extra/unbundled nodes (`extra_nodes`, such as Wikidata or external resource bundles).
1229    ///
1230    /// Only nodes originating from `bundled_nodes` are recorded in `bundled_origin_node_ids`;
1231    /// `extra_nodes` cannot supply bootstrap authority even if their numeric node IDs or
1232    /// self-asserted `Dc 635` provenance claims mimic bundled System nodes.
1233    pub fn from_bundled_and_extra_nodes(
1234        bundled_nodes: Vec<LedgerNode>,
1235        extra_nodes: Vec<LedgerNode>,
1236    ) -> Result<Self> {
1237        let mut bundled_ids = HashSet::with_capacity(bundled_nodes.len());
1238        let bundled_most_recent = bundled_nodes.iter().map(|n| n.id).max();
1239        for node in &bundled_nodes {
1240            ensure!(
1241                (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&node.id),
1242                "Bundled System node l{} is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})",
1243                node.id
1244            );
1245            bundled_ids.insert(node.id);
1246        }
1247        for extra in &extra_nodes {
1248            ensure!(
1249                !bundled_ids.contains(&extra.id),
1250                "Extra unbundled node ID l{} collides with an existing bundled System node ID",
1251                extra.id
1252            );
1253        }
1254        let mut combined = Vec::with_capacity(
1255            bundled_nodes.len().saturating_add(extra_nodes.len()),
1256        );
1257        combined.extend(bundled_nodes);
1258        combined.extend(extra_nodes);
1259        combined.sort_by_key(|n| n.id);
1260        let mut index = Self::from_nodes(combined);
1261        index.bundled_origin_node_ids = bundled_ids;
1262        index.system_block_most_recent_node_id = bundled_most_recent;
1263        Ok(index)
1264    }
1265
1266    /// Builds a `SeedGraphIndex` reflecting the System-block graph state as of `most_recent_node_id`
1267    /// (`Dc 641` `"Global graph system block most recent node ID at time of document creation"`),
1268    /// ignoring any statements, supersessions (`Dc 591`), or retractions (`Dc 592`) allocated
1269    /// with `node.id > most_recent_node_id`.
1270    #[must_use]
1271    pub fn from_nodes_at_most_recent(
1272        nodes: Vec<LedgerNode>,
1273        most_recent_node_id: u128,
1274    ) -> Self {
1275        let filtered: Vec<LedgerNode> = nodes
1276            .into_iter()
1277            .filter(|node| node.id <= most_recent_node_id)
1278            .collect();
1279        let mut index = Self::from_nodes(filtered);
1280        index.system_block_most_recent_node_id = Some(most_recent_node_id);
1281        index
1282    }
1283
1284    /// Builds a `SeedGraphIndex` from `nodes` and a custom set of single-valued property Dcs.
1285    #[must_use]
1286    pub fn from_nodes_with_single_props(
1287        nodes: Vec<LedgerNode>,
1288        single_valued_props: &HashSet<DcShorthand>,
1289    ) -> Self {
1290        let sh_supersedes = sh(DC_SUPERSEDES);
1291        let sh_retracts = sh(DC_RETRACTS);
1292        let sh_has_value = sh(DC_HAS_VALUE);
1293        let sh_has_a = sh(DC_HAS_A);
1294        let sh_preferred = sh(DC_PREFERRED);
1295        let sh_replacement = sh(DC_REPLACEMENT);
1296        let sh_is_instance_of = sh(DC_IS_INSTANCE_OF);
1297        let sh_enclosing_doc = sh(DC_ENCLOSING_DOCUMENT);
1298        let sh_prog_ident = sh(DC_PROGRAMMATIC_IDENTIFIER);
1299        let sh_canon_name = sh(DC_CANONICAL_NAME);
1300        let sh_bidi_class = sh(DC_BIDIRECTIONAL_CLASS);
1301        let sh_char_gen_cat = sh(DC_CHARACTER_GENERAL_CATEGORY);
1302        let sh_dc_gen_cat = sh(DC_DC_GENERAL_CATEGORY);
1303        let sh_char_script = sh(DC_CHARACTER_SCRIPT);
1304        let sh_uni_script = sh(DC_UNICODE_SCRIPT);
1305        let sh_entity_type = sh(DC_ENTITY_TYPE);
1306        let sh_data_source = sh(DC_COLLECTIVE_TOOLBOX_SEED_GRAPH_DATA_SOURCE);
1307        let sh_this_element = sh(DC_THIS_ELEMENT);
1308
1309        enum ParsedNodeForm {
1310            Statement(DcShorthand, DcShorthand, DcShorthand),
1311            ForEach(
1312                DcShorthand,
1313                DcShorthand,
1314                DcShorthand,
1315                DcShorthand,
1316                Vec<DcShorthand>,
1317            ),
1318            Value,
1319        }
1320
1321        let mut node_index_by_id = HashMap::with_capacity(nodes.len());
1322        let mut parsed_forms = Vec::with_capacity(nodes.len());
1323        for (idx, node) in nodes.iter().enumerate() {
1324            node_index_by_id.insert(node.id, idx);
1325            let form = if let Some((verb, subj, obj)) =
1326                parse_statement_tokens(&node.tokens)
1327            {
1328                ParsedNodeForm::Statement(verb, subj, obj)
1329            } else if let Some((
1330                inner_verb,
1331                inner_subj,
1332                inner_obj,
1333                list_type,
1334                targets,
1335            )) = parse_for_each_statement_tokens(&node.tokens)
1336            {
1337                ParsedNodeForm::ForEach(
1338                    inner_verb, inner_subj, inner_obj, list_type, targets,
1339                )
1340            } else {
1341                ParsedNodeForm::Value
1342            };
1343            parsed_forms.push(form);
1344        }
1345
1346        let mut inactive_ids = HashSet::new();
1347        let mut superseded_by = HashMap::new();
1348        let mut retracted_by = HashMap::new();
1349        for (node, form) in nodes.iter().zip(&parsed_forms).rev() {
1350            if inactive_ids.contains(&node.id) {
1351                continue;
1352            }
1353            if let &ParsedNodeForm::Statement(verb, subj, obj) = form {
1354                if verb == sh_supersedes {
1355                    if let DcShorthand::Long(old_id) = obj {
1356                        let new_id = match subj {
1357                            DcShorthand::Long(n_id) => n_id,
1358                            _ => node.id,
1359                        };
1360                        inactive_ids.insert(old_id);
1361                        superseded_by.insert(old_id, new_id);
1362                    }
1363                } else if verb == sh_retracts
1364                    && let DcShorthand::Long(old_id) = obj
1365                {
1366                    inactive_ids.insert(old_id);
1367                    retracted_by.insert(old_id, node.id);
1368                }
1369            }
1370        }
1371
1372        let mut superseding_stmt_by_old_id: HashMap<u128, u128> =
1373            HashMap::new();
1374        let mut subject_all_stmt_ids: HashMap<DcShorthand, Vec<u128>> =
1375            HashMap::new();
1376        let mut has_val_stmt_ids_by_has_a: HashMap<
1377            u128,
1378            Vec<(u128, DcShorthand)>,
1379        > = HashMap::new();
1380        let mut node_provenance_assertions: HashMap<
1381            u128,
1382            Vec<(u128, u128, DcShorthand)>,
1383        > = HashMap::new();
1384
1385        for (node, form) in nodes.iter().zip(&parsed_forms) {
1386            match form {
1387                &ParsedNodeForm::Statement(verb, subj, obj) => {
1388                    if verb == sh_supersedes {
1389                        if let DcShorthand::Long(old_id) = obj
1390                            && !inactive_ids.contains(&node.id)
1391                        {
1392                            superseding_stmt_by_old_id.insert(old_id, node.id);
1393                        }
1394                    } else if verb == sh_has_value {
1395                        if let DcShorthand::Long(has_a_id) = subj {
1396                            has_val_stmt_ids_by_has_a
1397                                .entry(has_a_id)
1398                                .or_default()
1399                                .push((node.id, obj));
1400                        }
1401                    } else if verb != sh_retracts {
1402                        let eff_subj = if subj == sh_enclosing_doc {
1403                            DcShorthand::Long(node.id)
1404                        } else {
1405                            subj
1406                        };
1407                        subject_all_stmt_ids
1408                            .entry(eff_subj)
1409                            .or_default()
1410                            .push(node.id);
1411                    }
1412                }
1413                ParsedNodeForm::ForEach(
1414                    inner_verb,
1415                    inner_subj,
1416                    _inner_obj,
1417                    _list_type,
1418                    targets,
1419                ) if *inner_verb != sh_has_value
1420                    && *inner_verb != sh_supersedes
1421                    && *inner_verb != sh_retracts =>
1422                {
1423                    for &elem in targets {
1424                        let eff_subj = if *inner_subj == sh_this_element {
1425                            elem
1426                        } else if *inner_subj == sh_enclosing_doc {
1427                            DcShorthand::Long(node.id)
1428                        } else {
1429                            *inner_subj
1430                        };
1431                        subject_all_stmt_ids
1432                            .entry(eff_subj)
1433                            .or_default()
1434                            .push(node.id);
1435                    }
1436                }
1437                ParsedNodeForm::ForEach(..) | ParsedNodeForm::Value => {}
1438            }
1439        }
1440
1441        // First pass: decode literal value nodes and find active `610` (`Has value`) and `584 <s1> 570` (`Preferred`) nodes.
1442        let mut string_by_node_id: HashMap<u128, String> = HashMap::new();
1443        let mut integer_by_node_id: HashMap<u128, u128> = HashMap::new();
1444        let mut active_has_val_by_stmt: HashMap<
1445            u128,
1446            Vec<(u128, DcShorthand)>,
1447        > = HashMap::new();
1448        let mut active_pref_qual_by_stmt: HashMap<u128, Vec<u128>> =
1449            HashMap::new();
1450        let mut orphaned_stmt_ids: Vec<u128> = Vec::new();
1451        let mut node_data_source: HashMap<u128, DcShorthand> = HashMap::new();
1452        let mut provenance_stmt_ids: HashSet<u128> = HashSet::new();
1453
1454        for (node, form) in nodes.iter().zip(&parsed_forms) {
1455            if matches!(form, ParsedNodeForm::Value) {
1456                if let Some(decoded_str) =
1457                    decode_string_value_tokens(&node.tokens)
1458                {
1459                    string_by_node_id.insert(node.id, decoded_str);
1460                } else if let Some(decoded_int) =
1461                    decode_integer_value_tokens(&node.tokens)
1462                {
1463                    integer_by_node_id.insert(node.id, decoded_int);
1464                }
1465            }
1466            if inactive_ids.contains(&node.id) {
1467                continue;
1468            }
1469            if let &ParsedNodeForm::Statement(verb, subj, obj) = form {
1470                if verb == sh_has_value {
1471                    if let DcShorthand::Long(has_a_id) = subj {
1472                        if inactive_ids.contains(&has_a_id) {
1473                            inactive_ids.insert(node.id);
1474                        } else {
1475                            let is_prop_has_a = node_index_by_id
1476                                .get(&has_a_id)
1477                                .and_then(|&idx| parsed_forms.get(idx))
1478                                .is_some_and(|f| match f {
1479                                    ParsedNodeForm::Statement(v, _, _)
1480                                    | ParsedNodeForm::ForEach(v, ..) => {
1481                                        *v == sh_has_a
1482                                    }
1483                                    ParsedNodeForm::Value => false,
1484                                });
1485                            if is_prop_has_a {
1486                                active_has_val_by_stmt
1487                                    .entry(has_a_id)
1488                                    .or_default()
1489                                    .push((node.id, obj));
1490                            } else {
1491                                orphaned_stmt_ids.push(node.id);
1492                            }
1493                        }
1494                    } else {
1495                        orphaned_stmt_ids.push(node.id);
1496                    }
1497                } else if verb == sh_has_a && obj == sh_preferred {
1498                    if let DcShorthand::Long(has_a_id) = subj {
1499                        let targets_has_a = node_index_by_id
1500                            .get(&has_a_id)
1501                            .and_then(|&idx| parsed_forms.get(idx))
1502                            .is_some_and(|f| match f {
1503                                ParsedNodeForm::Statement(v, _, _)
1504                                | ParsedNodeForm::ForEach(v, ..) => {
1505                                    *v == sh_has_a
1506                                }
1507                                ParsedNodeForm::Value => false,
1508                            });
1509                        if targets_has_a {
1510                            if inactive_ids.contains(&has_a_id) {
1511                                inactive_ids.insert(node.id);
1512                            } else {
1513                                active_pref_qual_by_stmt
1514                                    .entry(has_a_id)
1515                                    .or_default()
1516                                    .push(node.id);
1517                            }
1518                        }
1519                    }
1520                }
1521            }
1522        }
1523
1524        // Second pass: reconstruct seed entities and active statements.
1525        let mut seed_candidate_class: HashMap<u128, DcShorthand> =
1526            HashMap::new();
1527        let mut entity_class_by_id: HashMap<u128, DcShorthand> = HashMap::new();
1528        let mut seed_entity_ids = HashMap::new();
1529        let mut seed_entity_by_id = HashMap::new();
1530        let mut active_single_props = BTreeMap::new();
1531        let mut single_props_by_subj_prop: BTreeMap<
1532            (DcShorthand, DcShorthand),
1533            Vec<(u128, u128, DcShorthand)>,
1534        > = BTreeMap::new();
1535        let mut active_multi_props = BTreeMap::new();
1536        let mut active_multi_preferred = BTreeMap::new();
1537        let mut multi_props_by_subj_prop: HashMap<
1538            (DcShorthand, DcShorthand),
1539            Vec<ActivePropertyValue>,
1540        > = HashMap::new();
1541        let mut active_preferred = BTreeMap::new();
1542        let mut preferred_all_by_subj_val: BTreeMap<
1543            (DcShorthand, DcShorthand),
1544            Vec<(u128, u128, u128)>,
1545        > = BTreeMap::new();
1546        let mut preferred_by_subject: HashMap<DcShorthand, Vec<DcShorthand>> =
1547            HashMap::new();
1548        let mut active_direct_stmts = BTreeMap::new();
1549        let mut direct_stmts_all: BTreeMap<
1550            (DcShorthand, DcShorthand, DcShorthand),
1551            Vec<u128>,
1552        > = BTreeMap::new();
1553        let mut direct_objects_by_verb_subj: HashMap<
1554            (DcShorthand, DcShorthand),
1555            Vec<DcShorthand>,
1556        > = HashMap::new();
1557        let mut direct_subjects_by_verb_obj: HashMap<
1558            (DcShorthand, DcShorthand),
1559            Vec<DcShorthand>,
1560        > = HashMap::new();
1561        let mut consumed_pref_qual_has_a_ids: HashSet<u128> = HashSet::new();
1562        let mut all_active_triples: Vec<(
1563            u128,
1564            DcShorthand,
1565            DcShorthand,
1566            DcShorthand,
1567        )> = Vec::new();
1568
1569        for (node, form) in nodes.iter().zip(&parsed_forms) {
1570            if inactive_ids.contains(&node.id) {
1571                continue;
1572            }
1573            if let ParsedNodeForm::ForEach(
1574                inner_verb,
1575                inner_subj,
1576                inner_obj,
1577                _list_type,
1578                targets,
1579            ) = form
1580            {
1581                let inner_verb = *inner_verb;
1582                let inner_subj = *inner_subj;
1583                let inner_obj = *inner_obj;
1584                let resolve_iter_tok =
1585                    |pat: DcShorthand, elem: DcShorthand| -> DcShorthand {
1586                        if pat == sh_this_element {
1587                            elem
1588                        } else if pat == sh_enclosing_doc {
1589                            DcShorthand::Long(node.id)
1590                        } else {
1591                            pat
1592                        }
1593                    };
1594                for &elem in targets {
1595                    all_active_triples.push((
1596                        node.id,
1597                        inner_verb,
1598                        resolve_iter_tok(inner_subj, elem),
1599                        resolve_iter_tok(inner_obj, elem),
1600                    ));
1601                }
1602                if inner_verb == sh_has_a {
1603                    if let Some(has_vals) = active_has_val_by_stmt.get(&node.id)
1604                        && !has_vals.is_empty()
1605                    {
1606                        if inner_obj == sh_data_source {
1607                            provenance_stmt_ids.insert(node.id);
1608                            for &(has_val_id, val_tok) in has_vals {
1609                                provenance_stmt_ids.insert(has_val_id);
1610                                for &elem in targets {
1611                                    let subj =
1612                                        resolve_iter_tok(inner_subj, elem);
1613                                    if let DcShorthand::Long(target_node_id) =
1614                                        subj
1615                                    {
1616                                        node_provenance_assertions
1617                                            .entry(target_node_id)
1618                                            .or_default()
1619                                            .push((
1620                                                node.id,
1621                                                has_val_id,
1622                                                val_tok,
1623                                            ));
1624                                        node_data_source
1625                                            .insert(target_node_id, val_tok);
1626                                    }
1627                                }
1628                            }
1629                        } else {
1630                            let pref_ids =
1631                                active_pref_qual_by_stmt.get(&node.id);
1632                            let preferred_id =
1633                                pref_ids.and_then(|ids| ids.last().copied());
1634                            if preferred_id.is_some() {
1635                                consumed_pref_qual_has_a_ids.insert(node.id);
1636                            }
1637                            for &(has_val_id, val_tok) in has_vals {
1638                                for &elem in targets {
1639                                    let subj =
1640                                        resolve_iter_tok(inner_subj, elem);
1641                                    let obj = resolve_iter_tok(inner_obj, elem);
1642                                    if single_valued_props.contains(&obj) {
1643                                        single_props_by_subj_prop
1644                                            .entry((subj, obj))
1645                                            .or_default()
1646                                            .push((
1647                                                node.id, has_val_id, val_tok,
1648                                            ));
1649                                        active_single_props.insert(
1650                                            (subj, obj),
1651                                            (node.id, has_val_id, val_tok),
1652                                        );
1653                                    } else {
1654                                        if let Some(pref_id) = preferred_id {
1655                                            active_multi_preferred.insert(
1656                                                (subj, obj, val_tok),
1657                                                pref_id,
1658                                            );
1659                                        }
1660                                        active_multi_props.insert(
1661                                            (subj, obj, val_tok),
1662                                            (node.id, has_val_id),
1663                                        );
1664                                        multi_props_by_subj_prop
1665                                            .entry((subj, obj))
1666                                            .or_default()
1667                                            .push(ActivePropertyValue {
1668                                                has_a_id: node.id,
1669                                                has_val_id,
1670                                                value: val_tok,
1671                                                preferred_id,
1672                                            });
1673                                    }
1674                                }
1675                            }
1676                        }
1677                    } else {
1678                        orphaned_stmt_ids.push(node.id);
1679                    }
1680                } else if inner_verb != sh_has_value
1681                    && inner_verb != sh_supersedes
1682                    && inner_verb != sh_retracts
1683                {
1684                    for &elem in targets {
1685                        let subj = resolve_iter_tok(inner_subj, elem);
1686                        let obj = resolve_iter_tok(inner_obj, elem);
1687                        direct_stmts_all
1688                            .entry((inner_verb, subj, obj))
1689                            .or_default()
1690                            .push(node.id);
1691                        if active_direct_stmts
1692                            .insert((inner_verb, subj, obj), node.id)
1693                            .is_none()
1694                        {
1695                            direct_objects_by_verb_subj
1696                                .entry((inner_verb, subj))
1697                                .or_default()
1698                                .push(obj);
1699                            direct_subjects_by_verb_obj
1700                                .entry((inner_verb, obj))
1701                                .or_default()
1702                                .push(subj);
1703                        }
1704                    }
1705                }
1706                continue;
1707            }
1708
1709            let &ParsedNodeForm::Statement(verb, subj, obj) = form else {
1710                continue;
1711            };
1712            all_active_triples.push((node.id, verb, subj, obj));
1713
1714            // Self-referential entity declaration: `586 615 <class_tok>`.
1715            // Note: `Dc 615` ("Enclosing document") itself also has CSV classification
1716            // statements `586 615 l<gen_cat_or_script_id>` whose `obj` is an already-defined
1717            // BidiClass/GeneralCategory/Script seed entity; those are direct statements
1718            // about `Dc 615`, whereas all other `586 615 <class_tok>` nodes declare entities.
1719            let is_dc_615_classification_stmt =
1720                matches!(obj, DcShorthand::Long(obj_id) if matches!(
1721                    seed_entity_by_id.get(&obj_id),
1722                    Some(
1723                        SeedEntityKey::BidiClass(_)
1724                            | SeedEntityKey::GeneralCategory(_)
1725                            | SeedEntityKey::Script(_)
1726                    )
1727                ));
1728            if verb == sh_is_instance_of
1729                && subj == sh_enclosing_doc
1730                && !is_dc_615_classification_stmt
1731            {
1732                if obj == sh_bidi_class
1733                    || obj == sh_char_gen_cat
1734                    || obj == sh_dc_gen_cat
1735                    || obj == sh_char_script
1736                    || obj == sh_uni_script
1737                    || obj == sh_entity_type
1738                {
1739                    seed_candidate_class.insert(node.id, obj);
1740                } else {
1741                    entity_class_by_id.insert(node.id, obj);
1742                }
1743                continue;
1744            }
1745
1746            if verb == sh_has_value
1747                || verb == sh_supersedes
1748                || verb == sh_retracts
1749            {
1750                continue;
1751            }
1752            if verb == sh_has_a && obj == sh_preferred {
1753                if let DcShorthand::Long(target_id) = subj {
1754                    if node_index_by_id
1755                        .get(&target_id)
1756                        .and_then(|&idx| parsed_forms.get(idx))
1757                        .is_some_and(|f| {
1758                            matches!(
1759                                f,
1760                                ParsedNodeForm::Statement(v, _, _)
1761                                    if *v == sh_has_a
1762                            )
1763                        })
1764                    {
1765                        continue;
1766                    }
1767                }
1768            }
1769
1770            if verb == sh_has_a {
1771                if let Some(has_vals) = active_has_val_by_stmt.get(&node.id)
1772                    && !has_vals.is_empty()
1773                {
1774                    if obj == sh_data_source {
1775                        if let DcShorthand::Long(target_node_id) = subj {
1776                            provenance_stmt_ids.insert(node.id);
1777                            for &(has_val_id, val_tok) in has_vals {
1778                                provenance_stmt_ids.insert(has_val_id);
1779                                node_provenance_assertions
1780                                    .entry(target_node_id)
1781                                    .or_default()
1782                                    .push((node.id, has_val_id, val_tok));
1783                                node_data_source
1784                                    .insert(target_node_id, val_tok);
1785                            }
1786                            continue;
1787                        }
1788                    }
1789                    let pref_ids = active_pref_qual_by_stmt.get(&node.id);
1790                    let first_pref_id =
1791                        pref_ids.and_then(|ids| ids.last().copied());
1792                    if let Some(ids) = pref_ids {
1793                        for &extra_pref_id in ids
1794                            .get(..ids.len().saturating_sub(1))
1795                            .into_iter()
1796                            .flatten()
1797                        {
1798                            orphaned_stmt_ids.push(extra_pref_id);
1799                        }
1800                    }
1801                    for &(has_val_id, val_tok) in has_vals {
1802                        // Check if this names a seed entity (`584 l<seed_id> 572/574` -> `610 ... l<str_id>`).
1803                        if let (
1804                            DcShorthand::Long(seed_id),
1805                            DcShorthand::Long(str_id),
1806                        ) = (subj, val_tok)
1807                        {
1808                            if let (Some(&class_sh), Some(label)) = (
1809                                seed_candidate_class.get(&seed_id),
1810                                string_by_node_id.get(&str_id),
1811                            ) {
1812                                let key_opt = if class_sh == sh_bidi_class
1813                                    && obj == sh_prog_ident
1814                                {
1815                                    Some(SeedEntityKey::BidiClass(
1816                                        label.clone(),
1817                                    ))
1818                                } else if (class_sh == sh_char_gen_cat
1819                                    || class_sh == sh_dc_gen_cat)
1820                                    && obj == sh_prog_ident
1821                                {
1822                                    Some(SeedEntityKey::GeneralCategory(
1823                                        label.clone(),
1824                                    ))
1825                                } else if (class_sh == sh_char_script
1826                                    || class_sh == sh_uni_script)
1827                                    && obj == sh_canon_name
1828                                {
1829                                    Some(SeedEntityKey::Script(label.clone()))
1830                                } else if class_sh == sh_entity_type
1831                                    && obj == sh_canon_name
1832                                {
1833                                    Some(SeedEntityKey::NamedConstruct(
1834                                        label.clone(),
1835                                    ))
1836                                } else {
1837                                    None
1838                                };
1839                                if let Some(seed_key) = key_opt {
1840                                    if let Some(&existing_seed_id) =
1841                                        seed_entity_ids.get(&seed_key)
1842                                    {
1843                                        if existing_seed_id != seed_id {
1844                                            orphaned_stmt_ids.push(has_val_id);
1845                                            orphaned_stmt_ids.push(node.id);
1846                                            orphaned_stmt_ids.push(seed_id);
1847                                            continue;
1848                                        }
1849                                    } else {
1850                                        seed_entity_by_id
1851                                            .insert(seed_id, seed_key.clone());
1852                                        seed_entity_ids
1853                                            .insert(seed_key, seed_id);
1854                                    }
1855                                }
1856                            }
1857                        }
1858
1859                        if obj == sh_replacement {
1860                            if let Some(pref_id) = first_pref_id {
1861                                consumed_pref_qual_has_a_ids.insert(node.id);
1862                                preferred_all_by_subj_val
1863                                    .entry((subj, val_tok))
1864                                    .or_default()
1865                                    .push((node.id, has_val_id, pref_id));
1866                                if let std::collections::btree_map::Entry::Vacant(e) = active_preferred.entry((subj, val_tok)) {
1867                                    e.insert((node.id, has_val_id, pref_id));
1868                                    preferred_by_subject
1869                                        .entry(subj)
1870                                        .or_default()
1871                                        .push(val_tok);
1872                                }
1873                                continue;
1874                            }
1875                        }
1876
1877                        if single_valued_props.contains(&obj) {
1878                            single_props_by_subj_prop
1879                                .entry((subj, obj))
1880                                .or_default()
1881                                .push((node.id, has_val_id, val_tok));
1882                            active_single_props.insert(
1883                                (subj, obj),
1884                                (node.id, has_val_id, val_tok),
1885                            );
1886                        } else {
1887                            let preferred_id = first_pref_id;
1888                            if let Some(pref_id) = preferred_id {
1889                                consumed_pref_qual_has_a_ids.insert(node.id);
1890                                active_multi_preferred
1891                                    .insert((subj, obj, val_tok), pref_id);
1892                            }
1893                            active_multi_props.insert(
1894                                (subj, obj, val_tok),
1895                                (node.id, has_val_id),
1896                            );
1897                            multi_props_by_subj_prop
1898                                .entry((subj, obj))
1899                                .or_default()
1900                                .push(ActivePropertyValue {
1901                                    has_a_id: node.id,
1902                                    has_val_id,
1903                                    value: val_tok,
1904                                    preferred_id,
1905                                });
1906                        }
1907                    }
1908                } else {
1909                    orphaned_stmt_ids.push(node.id);
1910                }
1911            } else {
1912                direct_stmts_all
1913                    .entry((verb, subj, obj))
1914                    .or_default()
1915                    .push(node.id);
1916                if active_direct_stmts
1917                    .insert((verb, subj, obj), node.id)
1918                    .is_none()
1919                {
1920                    direct_objects_by_verb_subj
1921                        .entry((verb, subj))
1922                        .or_default()
1923                        .push(obj);
1924                    direct_subjects_by_verb_obj
1925                        .entry((verb, obj))
1926                        .or_default()
1927                        .push(subj);
1928                }
1929            }
1930        }
1931
1932        for (&has_a_id, pref_ids) in &active_pref_qual_by_stmt {
1933            if !consumed_pref_qual_has_a_ids.contains(&has_a_id) {
1934                orphaned_stmt_ids.extend(pref_ids.iter().copied());
1935            }
1936        }
1937        for &seed_id in seed_candidate_class.keys() {
1938            if !seed_entity_by_id.contains_key(&seed_id) {
1939                orphaned_stmt_ids.push(seed_id);
1940            }
1941        }
1942        orphaned_stmt_ids.sort_unstable();
1943        orphaned_stmt_ids.dedup();
1944
1945        for list in multi_props_by_subj_prop.values_mut() {
1946            if list.iter().any(|e| e.preferred_id.is_some()) {
1947                list.sort_by_key(|e| e.preferred_id.is_none());
1948            }
1949        }
1950
1951        all_active_triples.sort_unstable();
1952        all_active_triples.dedup();
1953        let mut triple_idx_by_verb_subj: HashMap<
1954            (DcShorthand, DcShorthand),
1955            Vec<usize>,
1956        > = HashMap::new();
1957        let mut triple_idx_by_verb_obj: HashMap<
1958            (DcShorthand, DcShorthand),
1959            Vec<usize>,
1960        > = HashMap::new();
1961        let mut triple_idx_by_verb: HashMap<DcShorthand, Vec<usize>> =
1962            HashMap::new();
1963        let mut triple_idx_by_subj: HashMap<DcShorthand, Vec<usize>> =
1964            HashMap::new();
1965        let mut triple_idx_by_obj: HashMap<DcShorthand, Vec<usize>> =
1966            HashMap::new();
1967        for (idx, &(_, verb, subj, obj)) in
1968            all_active_triples.iter().enumerate()
1969        {
1970            triple_idx_by_verb_subj
1971                .entry((verb, subj))
1972                .or_default()
1973                .push(idx);
1974            triple_idx_by_verb_obj
1975                .entry((verb, obj))
1976                .or_default()
1977                .push(idx);
1978            triple_idx_by_verb.entry(verb).or_default().push(idx);
1979            triple_idx_by_subj.entry(subj).or_default().push(idx);
1980            triple_idx_by_obj.entry(obj).or_default().push(idx);
1981        }
1982
1983        let system_block_most_recent_node_id = nodes.iter().map(|n| n.id).max();
1984        static NEXT_SEED_GRAPH_INSTANCE_ID: std::sync::atomic::AtomicU64 =
1985            std::sync::atomic::AtomicU64::new(1);
1986        let instance_id = NEXT_SEED_GRAPH_INSTANCE_ID
1987            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1988
1989        Self {
1990            instance_id,
1991            nodes,
1992            node_index_by_id,
1993            superseded_by,
1994            retracted_by,
1995            inactive_ids,
1996            string_by_node_id,
1997            integer_by_node_id,
1998            seed_entity_ids,
1999            seed_entity_by_id,
2000            active_single_props,
2001            single_props_by_subj_prop,
2002            active_multi_props,
2003            active_multi_preferred,
2004            multi_props_by_subj_prop,
2005            active_preferred,
2006            preferred_all_by_subj_val,
2007            preferred_by_subject,
2008            active_direct_stmts,
2009            direct_stmts_all,
2010            direct_objects_by_verb_subj,
2011            direct_subjects_by_verb_obj,
2012            orphaned_stmt_ids,
2013            node_data_source,
2014            provenance_stmt_ids,
2015            bundled_origin_node_ids: HashSet::new(),
2016            from_asset_bundle: false,
2017            superseding_stmt_by_old_id,
2018            node_provenance_assertions,
2019            subject_all_stmt_ids,
2020            has_val_stmt_ids_by_has_a,
2021            system_block_most_recent_node_id,
2022            entity_class_by_id,
2023            active_nodes_by_exact_tokens: std::sync::OnceLock::new(),
2024            all_active_triples,
2025            triple_idx_by_verb_subj,
2026            triple_idx_by_verb_obj,
2027            triple_idx_by_verb,
2028            triple_idx_by_subj,
2029            triple_idx_by_obj,
2030        }
2031    }
2032
2033    /// Builds a canonical value-node token sequence -> first allocated `u128` node ID map
2034    /// across active pure value nodes in this snapshot.
2035    #[must_use]
2036    pub(crate) fn build_value_node_by_tokens(
2037        &self,
2038    ) -> HashMap<Vec<DcShorthand>, u128> {
2039        let mut map = HashMap::new();
2040        for node in &self.nodes {
2041            if self.inactive_ids.contains(&node.id) {
2042                continue;
2043            }
2044            if parse_statement_tokens(&node.tokens).is_none()
2045                && parse_for_each_statement_tokens(&node.tokens).is_none()
2046                && parse_ambiguous_values_tokens(&node.tokens).is_none()
2047            {
2048                map.entry(node.tokens.clone()).or_insert(node.id);
2049            }
2050        }
2051        map
2052    }
2053
2054    /// Collects semantic graph invariant anomalies (supersession cycles, or active
2055    /// `Dc 591` / `Dc 592` statements revising pure value nodes other than `Dc 348`
2056    /// disambiguation lists).
2057    #[must_use]
2058    pub fn collect_graph_invariant_anomalies(&self) -> Vec<String> {
2059        let sh_supersedes = sh(DC_SUPERSEDES);
2060        let sh_retracts = sh(DC_RETRACTS);
2061        let mut anomalies = Vec::new();
2062
2063        for (&start_id, &first_next) in &self.superseded_by {
2064            let mut cur = first_next;
2065            let mut visited = HashSet::new();
2066            visited.insert(start_id);
2067            while let Some(&next) = self.superseded_by.get(&cur) {
2068                if !visited.insert(cur) {
2069                    if cur == start_id {
2070                        anomalies.push(format!(
2071                            "Graph supersession cycle detected starting at node l{start_id}"
2072                        ));
2073                    }
2074                    break;
2075                }
2076                cur = next;
2077            }
2078        }
2079
2080        for node in &self.nodes {
2081            if self.inactive_ids.contains(&node.id) {
2082                continue;
2083            }
2084            let Some((verb, subj, obj)) = parse_statement_tokens(&node.tokens)
2085            else {
2086                continue;
2087            };
2088            if verb == sh_supersedes {
2089                let DcShorthand::Long(old_id) = obj else {
2090                    continue;
2091                };
2092                let is_ambiguous_disambiguation =
2093                    if let DcShorthand::Long(new_id) = subj
2094                        && let Some(new_node) = self.get_node(new_id)
2095                    {
2096                        parse_ambiguous_values_tokens(&new_node.tokens)
2097                            .is_some()
2098                    } else {
2099                        false
2100                    };
2101                if !is_ambiguous_disambiguation
2102                    && let Some(old_node) = self.get_node(old_id)
2103                    && parse_statement_tokens(&old_node.tokens).is_none()
2104                    && parse_for_each_statement_tokens(&old_node.tokens)
2105                        .is_none()
2106                    && parse_ambiguous_values_tokens(&old_node.tokens).is_none()
2107                {
2108                    anomalies.push(format!(
2109                        "Dc 591 (Supersedes) statement l{} targets pure value node l{old_id}",
2110                        node.id
2111                    ));
2112                }
2113            } else if verb == sh_retracts
2114                && let DcShorthand::Long(old_id) = obj
2115                && let Some(old_node) = self.get_node(old_id)
2116                && parse_statement_tokens(&old_node.tokens).is_none()
2117                && parse_for_each_statement_tokens(&old_node.tokens).is_none()
2118                && parse_ambiguous_values_tokens(&old_node.tokens).is_none()
2119            {
2120                anomalies.push(format!(
2121                    "Dc 592 (Retracts) statement l{} targets pure value node l{old_id}",
2122                    node.id
2123                ));
2124            }
2125        }
2126
2127        anomalies
2128    }
2129
2130    /// Validates semantic graph invariants: errors strictly when `recover_graph` is `false`
2131    /// (the default), or logs warnings and continues when `recover_graph` is `true` (`--recover-graph`).
2132    pub fn validate_or_warn_graph_invariants(
2133        &self,
2134        recover_graph: bool,
2135    ) -> Result<()> {
2136        let anomalies = self.collect_graph_invariant_anomalies();
2137        if anomalies.is_empty() {
2138            return Ok(());
2139        }
2140        if recover_graph {
2141            for anomaly in &anomalies {
2142                warn_fmt!(
2143                    "Graph recovery (--recover-graph) continuing past invariant violation: {anomaly}"
2144                );
2145            }
2146            return Ok(());
2147        }
2148        if let Some(first) = anomalies.first() {
2149            bail!(
2150                "Graph invariant violation ({} total; pass --recover-graph to warn and recover): {first}",
2151                anomalies.len()
2152            );
2153        }
2154        Ok(())
2155    }
2156
2157    /// Returns the highest allocated node ID in the System block at the time the graph bundle
2158    /// was created (`Dc 641` `"Global graph system block most recent node ID at time of document creation"`).
2159    #[must_use]
2160    pub fn system_block_most_recent_node_id(&self) -> Option<u128> {
2161        self.system_block_most_recent_node_id
2162    }
2163
2164    /// Returns `true` if this `SeedGraphIndex` was loaded from the runtime
2165    /// asset bundle (`ctoolbox.rsrc` / `system_graph_history.rsrc`), meaning
2166    /// historical `Dc 641` pins must be reconstructed via the asset bundle
2167    /// (merging `data/graph/` and `data/graph/system/`) rather than slicing
2168    /// active-only nodes in memory.
2169    #[must_use]
2170    pub const fn is_from_asset_bundle(&self) -> bool {
2171        self.from_asset_bundle
2172    }
2173
2174    /// Returns the declared `Dc 635` (`"Collective Toolbox seed graph data source"`) token
2175    /// for `node_id` in the seed graph, if present.
2176    #[must_use]
2177    pub fn node_data_source(&self, node_id: u128) -> Option<DcShorthand> {
2178        self.node_data_source.get(&node_id).copied()
2179    }
2180
2181    /// Returns `true` if the seed graph contains any `Dc 635` (`"Collective Toolbox seed graph data source"`)
2182    /// provenance declarations.
2183    #[must_use]
2184    pub fn has_in_graph_provenance(&self) -> bool {
2185        !self.node_data_source.is_empty()
2186    }
2187
2188    /// Returns the total number of nodes in the loaded seed graph.
2189    #[must_use]
2190    pub fn node_count(&self) -> usize {
2191        self.nodes.len()
2192    }
2193
2194    /// Returns a slice of all loaded `LedgerNode`s.
2195    #[must_use]
2196    pub fn nodes(&self) -> &[LedgerNode] {
2197        &self.nodes
2198    }
2199
2200    /// Looks up a `LedgerNode` by its global node ID (`u128`).
2201    #[must_use]
2202    pub fn get_node(&self, id: u128) -> Option<&LedgerNode> {
2203        let &idx = self.node_index_by_id.get(&id)?;
2204        self.nodes.get(idx)
2205    }
2206
2207    /// Returns `true` if `id` exists in the seed graph and has not been superseded or retracted.
2208    #[must_use]
2209    pub fn is_node_active(&self, id: u128) -> bool {
2210        self.node_index_by_id.contains_key(&id)
2211            && !self.inactive_ids.contains(&id)
2212    }
2213
2214    /// Returns the total number of inactive (superseded or retracted) nodes in the seed graph.
2215    #[must_use]
2216    pub fn inactive_count(&self) -> usize {
2217        self.inactive_ids.len()
2218    }
2219
2220    /// Returns the number of superseded nodes (`Dc 591`) in the seed graph.
2221    #[must_use]
2222    pub fn superseded_count(&self) -> usize {
2223        self.superseded_by.len()
2224    }
2225
2226    /// Returns the number of retracted nodes (`Dc 592`) in the seed graph.
2227    #[must_use]
2228    pub fn retracted_count(&self) -> usize {
2229        self.retracted_by.len()
2230    }
2231
2232    /// Follows any `Dc 591 "Supersedes"` chain from `id` to its terminal replacement node,
2233    /// and if that node (or `id` itself) is a `Dc 348 "Ambiguous values"` list (`348 310 ... 311`),
2234    /// returns the ordered candidate node IDs.
2235    #[must_use]
2236    pub fn get_ambiguous_candidates(&self, id: u128) -> Option<Vec<u128>> {
2237        let mut cur = id;
2238        let mut visited = HashSet::new();
2239        while let Some(&next) = self.superseded_by.get(&cur) {
2240            if !visited.insert(cur) {
2241                break;
2242            }
2243            cur = next;
2244        }
2245        let target_node = self.get_node(cur)?;
2246        parse_ambiguous_values_tokens(&target_node.tokens)
2247    }
2248
2249    /// Returns the node ID that directly superseded `id` via `Dc 591` (`Supersedes`), if any.
2250    #[must_use]
2251    pub fn superseded_by(&self, id: u128) -> Option<u128> {
2252        self.superseded_by.get(&id).copied()
2253    }
2254
2255    /// Returns the statement node ID that retracted `id` via `Dc 592` (`Retracts`), if any.
2256    #[must_use]
2257    pub fn retracted_by(&self, id: u128) -> Option<u128> {
2258        self.retracted_by.get(&id).copied()
2259    }
2260
2261    /// Follows any `Dc 591` (`Supersedes`) chain starting from `id` to its latest active node ID,
2262    /// returning `None` if `id` is unknown, if the terminal revision was retracted (`Dc 592`),
2263    /// or if a supersession cycle is encountered.
2264    #[must_use]
2265    pub fn resolve_latest_node_id(&self, id: u128) -> Option<u128> {
2266        if !self.node_index_by_id.contains_key(&id) {
2267            return None;
2268        }
2269        let mut current = id;
2270        let mut steps = 0usize;
2271        while let Some(&next) = self.superseded_by.get(&current) {
2272            current = next;
2273            steps = steps.saturating_add(1);
2274            if steps > self.nodes.len() {
2275                return None;
2276            }
2277        }
2278        if self.inactive_ids.contains(&current) {
2279            None
2280        } else {
2281            Some(current)
2282        }
2283    }
2284
2285    /// Resolves `id` through any active `Dc 591` (`Supersedes`) chain within this snapshot
2286    /// and returns the active terminal `LedgerNode`, or `None` if `id` is unknown, retracted
2287    /// (`Dc 592`), or outside the snapshot.
2288    #[must_use]
2289    pub fn get_active_node(&self, id: u128) -> Option<&LedgerNode> {
2290        let resolved_id = self.resolve_latest_node_id(id)?;
2291        self.get_node(resolved_id)
2292    }
2293
2294    /// Returns the exact verbatim Dc token slice inside an active node `id`
2295    /// without following supersession chains or expanding child references.
2296    #[must_use]
2297    pub fn query_active_node_verbatim(
2298        &self,
2299        id: u128,
2300    ) -> Option<&[DcShorthand]> {
2301        if self.inactive_ids.contains(&id) {
2302            return None;
2303        }
2304        if let Some(pin_id) = self.system_block_most_recent_node_id
2305            && id > pin_id
2306        {
2307            return None;
2308        }
2309        self.get_node(id).map(|n| n.tokens.as_slice())
2310    }
2311
2312    /// Returns all active node IDs (sorted ascending) in the snapshot whose
2313    /// verbatim token slice equals `tokens` exactly.
2314    #[must_use]
2315    pub fn query_active_nodes_by_exact_tokens(
2316        &self,
2317        tokens: &[DcShorthand],
2318    ) -> &[u128] {
2319        let index = self.active_nodes_by_exact_tokens.get_or_init(|| {
2320            let mut map: HashMap<Vec<DcShorthand>, Vec<u128>> = HashMap::new();
2321            for node in &self.nodes {
2322                if self.inactive_ids.contains(&node.id) {
2323                    continue;
2324                }
2325                map.entry(node.tokens.clone()).or_default().push(node.id);
2326            }
2327            for ids in map.values_mut() {
2328                ids.sort_unstable();
2329                ids.dedup();
2330            }
2331            map
2332        });
2333        let Some(ids) = index.get(tokens) else {
2334            return &[];
2335        };
2336        if let Some(pin_id) = self.system_block_most_recent_node_id {
2337            let cutoff = ids.partition_point(|&id| id <= pin_id);
2338            #[expect(
2339                clippy::expect_used,
2340                reason = "partition_point always returns an index within 0..=ids.len()"
2341            )]
2342            return ids.get(..cutoff).expect(
2343                "partition_point always returns an index within 0..=ids.len()",
2344            );
2345        }
2346        ids.as_slice()
2347    }
2348
2349    /// Queries all active relationship triples `(stmt_id, verb, subj, obj)`
2350    /// in the snapshot matching the supplied pattern (`None` = `Dc 600`
2351    /// wildcard). Includes both direct 3-token statements and `Dc 638`
2352    /// for-each distributions.
2353    #[must_use]
2354    pub fn query_active_relationship_triples(
2355        &self,
2356        verb: Option<DcShorthand>,
2357        subj: Option<DcShorthand>,
2358        obj: Option<DcShorthand>,
2359    ) -> Vec<(u128, DcShorthand, DcShorthand, DcShorthand)> {
2360        let pin = self.system_block_most_recent_node_id;
2361        let matches_pin_and_filter =
2362            |&(stmt_id, v, s, o): &(
2363                u128,
2364                DcShorthand,
2365                DcShorthand,
2366                DcShorthand,
2367            )| {
2368                pin.is_none_or(|p| stmt_id <= p)
2369                    && verb.is_none_or(|want_v| v == want_v)
2370                    && subj.is_none_or(|want_s| s == want_s)
2371                    && obj.is_none_or(|want_o| o == want_o)
2372            };
2373
2374        let indexed_lookup: Option<Option<&Vec<usize>>> =
2375            match (verb, subj, obj) {
2376                (Some(v), Some(s), _) => {
2377                    Some(self.triple_idx_by_verb_subj.get(&(v, s)))
2378                }
2379                (Some(v), None, Some(o)) => {
2380                    Some(self.triple_idx_by_verb_obj.get(&(v, o)))
2381                }
2382                (Some(v), None, None) => Some(self.triple_idx_by_verb.get(&v)),
2383                (None, Some(s), _) => Some(self.triple_idx_by_subj.get(&s)),
2384                (None, None, Some(o)) => Some(self.triple_idx_by_obj.get(&o)),
2385                (None, None, None) => None,
2386            };
2387
2388        let mut out = Vec::new();
2389        if let Some(opt_indices) = indexed_lookup {
2390            // Absent key in a secondary triple index means zero active triples
2391            // match the constrained term(s), so returning an empty result is exact.
2392            let Some(indices) = opt_indices else {
2393                return out;
2394            };
2395            for &idx in indices {
2396                if let Some(triple) = self.all_active_triples.get(idx)
2397                    && matches_pin_and_filter(triple)
2398                {
2399                    out.push(*triple);
2400                }
2401            }
2402        } else {
2403            for triple in &self.all_active_triples {
2404                if matches_pin_and_filter(triple) {
2405                    out.push(*triple);
2406                }
2407            }
2408        }
2409        out
2410    }
2411
2412    /// Resolves `tok` as a string value node (`DcShorthand::Long(id)`), returning its decoded UTF-8 string.
2413    #[must_use]
2414    pub fn get_string(&self, tok: DcShorthand) -> Option<&str> {
2415        let DcShorthand::Long(id) = tok else {
2416            return None;
2417        };
2418        let resolved_id = self.resolve_latest_node_id(id)?;
2419        self.string_by_node_id.get(&resolved_id).map(String::as_str)
2420    }
2421
2422    /// Resolves `tok` as an integer value node (`DcShorthand::Long(id)`), returning its decoded `u128`.
2423    #[must_use]
2424    pub fn get_integer(&self, tok: DcShorthand) -> Option<u128> {
2425        let DcShorthand::Long(id) = tok else {
2426            return None;
2427        };
2428        let resolved_id = self.resolve_latest_node_id(id)?;
2429        self.integer_by_node_id.get(&resolved_id).copied()
2430    }
2431
2432    /// Looks up the allocated `u128` node ID for a `SeedEntityKey`.
2433    #[must_use]
2434    pub fn get_seed_entity_id(&self, key: &SeedEntityKey) -> Option<u128> {
2435        self.seed_entity_ids.get(key).copied()
2436    }
2437
2438    /// Looks up the `SeedEntityKey` for a seed entity node ID (`u128`),
2439    /// resolving through any active `Dc 591` (`Supersedes`) chain in the snapshot.
2440    #[must_use]
2441    pub fn get_seed_entity(&self, id: u128) -> Option<&SeedEntityKey> {
2442        let resolved_id = self.resolve_latest_node_id(id)?;
2443        self.seed_entity_by_id.get(&resolved_id)
2444    }
2445
2446    /// Returns the active value token for a single-valued property `(subj, prop)`.
2447    #[must_use]
2448    pub fn get_single_property(
2449        &self,
2450        subj: DcShorthand,
2451        prop: DcShorthand,
2452    ) -> Option<DcShorthand> {
2453        self.active_single_props
2454            .get(&(subj, prop))
2455            .map(|&(_, _, val)| val)
2456    }
2457
2458    /// Returns the full `ActivePropertyValue` (`has_a_id`, `has_val_id`, `value`) for a
2459    /// single-valued property `(subj, prop)`.
2460    #[must_use]
2461    pub fn get_single_property_entry(
2462        &self,
2463        subj: DcShorthand,
2464        prop: DcShorthand,
2465    ) -> Option<ActivePropertyValue> {
2466        self.active_single_props.get(&(subj, prop)).map(
2467            |&(has_a_id, has_val_id, value)| ActivePropertyValue {
2468                has_a_id,
2469                has_val_id,
2470                value,
2471                preferred_id: None,
2472            },
2473        )
2474    }
2475
2476    /// Returns the decoded UTF-8 string of a single-valued string property `(subj, prop)`.
2477    #[must_use]
2478    pub fn get_single_property_string(
2479        &self,
2480        subj: DcShorthand,
2481        prop: DcShorthand,
2482    ) -> Option<&str> {
2483        let val_tok = self.get_single_property(subj, prop)?;
2484        self.get_string(val_tok)
2485    }
2486
2487    /// Returns the decoded `u128` integer of a single-valued integer property `(subj, prop)`.
2488    #[must_use]
2489    pub fn get_single_property_integer(
2490        &self,
2491        subj: DcShorthand,
2492        prop: DcShorthand,
2493    ) -> Option<u128> {
2494        let val_tok = self.get_single_property(subj, prop)?;
2495        self.get_integer(val_tok)
2496    }
2497
2498    /// Returns all active `ActivePropertyValue` entries for a multi-valued property `(subj, prop)`.
2499    #[must_use]
2500    pub fn get_multi_properties(
2501        &self,
2502        subj: DcShorthand,
2503        prop: DcShorthand,
2504    ) -> &[ActivePropertyValue] {
2505        // Reason for fallback: subjects without any active multi-valued property values return an empty slice.
2506        self.multi_props_by_subj_prop
2507            .get(&(subj, prop))
2508            .map_or(&[], Vec::as_slice)
2509    }
2510
2511    /// Returns all active preferred replacement target tokens (`<prefer>`) for `subj`.
2512    #[must_use]
2513    pub fn get_preferred_replacements(
2514        &self,
2515        subj: DcShorthand,
2516    ) -> &[DcShorthand] {
2517        // Reason for fallback: subjects without preferred replacements return an empty slice.
2518        self.preferred_by_subject
2519            .get(&subj)
2520            .map_or(&[], Vec::as_slice)
2521    }
2522
2523    /// Returns `true` if the direct binary statement `(verb, subj, obj)` is currently active.
2524    #[must_use]
2525    pub fn has_direct_statement(
2526        &self,
2527        verb: DcShorthand,
2528        subj: DcShorthand,
2529        obj: DcShorthand,
2530    ) -> bool {
2531        self.active_direct_stmts.contains_key(&(verb, subj, obj))
2532    }
2533
2534    /// Returns `true` if `subj`'s active `Dc 574 "Programmatic identifier"` (`Has a` statement node)
2535    /// has an active `Dc 645 "Is stable"` statement (`645 l<ident_has_a_id> 517`) that is
2536    /// `Dc 646 "In context of"` `f649` (`Collective Toolbox`).
2537    #[must_use]
2538    pub fn has_stable_programmatic_identifier(&self, subj: DcShorthand) -> bool {
2539        let Some(&(ident_has_a_id, _, _)) = self
2540            .active_single_props
2541            .get(&(subj, sh(DC_PROGRAMMATIC_IDENTIFIER)))
2542        else {
2543            return false;
2544        };
2545        let Some(&stable_stmt_id) = self.active_direct_stmts.get(&(
2546            sh(DC_IS_STABLE),
2547            DcShorthand::Long(ident_has_a_id),
2548            sh(DC_BOOLEAN_TRUE),
2549        )) else {
2550            return false;
2551        };
2552        self.active_direct_stmts.contains_key(&(
2553            sh(DC_IN_CONTEXT_OF),
2554            DcShorthand::Long(stable_stmt_id),
2555            sh(DC_COLLECTIVE_TOOLBOX),
2556        ))
2557    }
2558
2559    pub(crate) fn format_stable_or_shorthand_token(
2560        &self,
2561        tok: DcShorthand,
2562    ) -> String {
2563        if self.has_stable_programmatic_identifier(tok) {
2564            if let Some(ident) = self
2565                .get_single_property_string(tok, sh(DC_PROGRAMMATIC_IDENTIFIER))
2566            {
2567                return ident.to_string();
2568            }
2569        }
2570        // Fallback for historical graph snapshots prior to Dc 645 (Is stable) or synthetic unit tests
2571        if !self
2572            .active_direct_stmts
2573            .keys()
2574            .any(|&(v, _, _)| v == sh(DC_IS_STABLE))
2575        {
2576            match tok {
2577                DcShorthand::Format(199) => return "Integer".to_string(),
2578                DcShorthand::Format(200) => return "Natural0".to_string(),
2579                DcShorthand::Format(351) => return "Natural1".to_string(),
2580                _ => {}
2581            }
2582        }
2583        tok.to_string()
2584    }
2585
2586    /// Returns all active object tokens `obj` for direct binary statements `(verb, subj, obj)`.
2587    #[must_use]
2588    pub fn get_direct_objects(
2589        &self,
2590        verb: DcShorthand,
2591        subj: DcShorthand,
2592    ) -> &[DcShorthand] {
2593        // Reason for fallback: (verb, subj) pairs without active statements return an empty slice.
2594        self.direct_objects_by_verb_subj
2595            .get(&(verb, subj))
2596            .map_or(&[], Vec::as_slice)
2597    }
2598
2599    /// Returns all active subject tokens `subj` for direct binary statements `(verb, subj, obj)`.
2600    #[must_use]
2601    pub fn get_direct_subjects(
2602        &self,
2603        verb: DcShorthand,
2604        obj: DcShorthand,
2605    ) -> &[DcShorthand] {
2606        // Reason for fallback: (verb, obj) pairs without active statements return an empty slice.
2607        self.direct_subjects_by_verb_obj
2608            .get(&(verb, obj))
2609            .map_or(&[], Vec::as_slice)
2610    }
2611
2612    /// Returns a map of all indexed `SeedEntityKey` entries to their allocated `u128` node IDs.
2613    #[must_use]
2614    pub fn seed_entities(&self) -> &HashMap<SeedEntityKey, u128> {
2615        &self.seed_entity_ids
2616    }
2617
2618    /// Returns the map of all active single-valued properties `(subject, prop_token) -> (has_a_id, has_val_id, val_token)`.
2619    #[must_use]
2620    pub fn active_single_props(
2621        &self,
2622    ) -> &BTreeMap<(DcShorthand, DcShorthand), (u128, u128, DcShorthand)> {
2623        &self.active_single_props
2624    }
2625
2626    /// Returns the map of all active multi-valued properties `(subject, prop_token, val_token) -> (has_a_id, has_val_id)`.
2627    #[must_use]
2628    pub fn active_multi_props(
2629        &self,
2630    ) -> &BTreeMap<(DcShorthand, DcShorthand, DcShorthand), (u128, u128)> {
2631        &self.active_multi_props
2632    }
2633
2634    /// Returns the map of all active preferred replacements `(subject, val_token) -> (has_a_id, has_val_id, pref_qual_id)`.
2635    #[must_use]
2636    pub fn active_preferred(
2637        &self,
2638    ) -> &BTreeMap<(DcShorthand, DcShorthand), (u128, u128, u128)> {
2639        &self.active_preferred
2640    }
2641
2642    /// Returns the map of all active direct binary statements `(verb, subject, object) -> stmt_id`.
2643    #[must_use]
2644    pub fn active_direct_stmts(
2645        &self,
2646    ) -> &BTreeMap<(DcShorthand, DcShorthand, DcShorthand), u128> {
2647        &self.active_direct_stmts
2648    }
2649
2650    /// Returns the raw `.Semantic:Pattern` token slice for the active `Dc 594` (`Syntax rule`)
2651    /// property on `subj`, without allocating or decoding a Rust `SyntaxPattern` AST.
2652    #[must_use]
2653    pub fn get_syntax_rule_tokens(
2654        &self,
2655        subj: DcShorthand,
2656    ) -> Option<&[DcShorthand]> {
2657        let DcShorthand::Long(node_id) =
2658            self.get_single_property(subj, sh(DC_SYNTAX_RULE))?
2659        else {
2660            return None;
2661        };
2662        self.get_active_node(node_id).map(|n| n.tokens.as_slice())
2663    }
2664
2665    /// Returns the raw `.Semantic:Pattern` token slice for a named syntax construct
2666    /// (e.g. `"number"`, `"string"`, `"value"`), without allocating a Rust `SyntaxPattern` AST.
2667    #[must_use]
2668    pub fn get_named_construct_tokens(
2669        &self,
2670        name: &str,
2671    ) -> Option<&[DcShorthand]> {
2672        let key = SeedEntityKey::NamedConstruct(name.to_string());
2673        let seed_id = self.get_seed_entity_id(&key)?;
2674        self.get_syntax_rule_tokens(DcShorthand::Long(seed_id))
2675    }
2676
2677    /// Returns `true` if `tokens` begins with a Dc-WASM program (`Dc 1927 "Begin WASM program"`)
2678    /// or a `wasm_routine` literal (`Dc 260 "Begin literal value"`, `Dc 262 "Begin type definition"`,
2679    /// `Dc 280 "Built-in type identifier: Routine"`).
2680    #[must_use]
2681    pub fn tokens_start_wasm_definition(tokens: &[DcShorthand]) -> bool {
2682        let Some(&first) = tokens.first() else {
2683            return false;
2684        };
2685        if first == sh(DC_BEGIN_WASM_PROGRAM) {
2686            return true;
2687        }
2688        first == sh(DC_BEGIN_LITERAL)
2689            && tokens.get(1) == Some(&sh(DC_BEGIN_TYPE_DEF))
2690            && tokens.get(2) == Some(&sh(DC_TYPE_ROUTINE))
2691    }
2692
2693    /// Returns `true` if `tokens` represents a Dc-WASM program, `wasm_routine` literal,
2694    /// WASM instruction/member helper fragment, or transitive reference to one in this snapshot.
2695    #[must_use]
2696    pub fn tokens_are_wasm_helper_or_definition(
2697        &self,
2698        tokens: &[DcShorthand],
2699    ) -> bool {
2700        let mut visited_nodes = HashSet::new();
2701        let mut visited_shorthands = HashSet::new();
2702        self.tokens_are_wasm_helper_or_definition_inner(
2703            tokens,
2704            &mut visited_nodes,
2705            &mut visited_shorthands,
2706        )
2707    }
2708
2709    const fn is_document_syntax_or_framing_short_dc(short_id: u32) -> bool {
2710        matches!(
2711            short_id,
2712            256
2713                | 260
2714                | 268
2715                | 276
2716                | 279
2717                | 307
2718                | 540
2719                | 541
2720                | 584
2721                | 585
2722                | 610
2723                | 616
2724                | 638
2725                | 1936
2726                | 1937
2727        )
2728    }
2729
2730    fn tokens_are_wasm_helper_or_definition_inner(
2731        &self,
2732        tokens: &[DcShorthand],
2733        visited_nodes: &mut HashSet<u128>,
2734        visited_shorthands: &mut HashSet<DcShorthand>,
2735    ) -> bool {
2736        if Self::tokens_start_wasm_definition(tokens) {
2737            return true;
2738        }
2739        if tokens.first() == Some(&sh(DC_BEGIN_LITERAL)) {
2740            return false;
2741        }
2742        if self.tokens_are_stagel_item_or_module(tokens) {
2743            return false;
2744        }
2745        if tokens
2746            .iter()
2747            .any(|&tok| matches!(tok, DcShorthand::Short(647..=1928)))
2748        {
2749            return true;
2750        }
2751        for &tok in tokens {
2752            match tok {
2753                DcShorthand::Long(node_id) => {
2754                    if !visited_nodes.insert(node_id) {
2755                        continue;
2756                    }
2757                    if self.entity_class_by_id.contains_key(&node_id) {
2758                        for prop_dc in [
2759                            DC_CANONICAL_DECOMPOSITION,
2760                            DC_DECOMPOSITION,
2761                            DC_SEMANTIC_DECOMPOSITION,
2762                        ] {
2763                            for entry in
2764                                self.get_multi_properties(tok, sh(prop_dc))
2765                            {
2766                                if let DcShorthand::Long(val_id) = entry.value {
2767                                    if !visited_nodes.insert(val_id) {
2768                                        continue;
2769                                    }
2770                                    if let Some(val_node) = self
2771                                        .get_active_node(val_id)
2772                                        .or_else(|| self.get_node(val_id))
2773                                        && self
2774                                            .tokens_are_wasm_helper_or_definition_inner(
2775                                                &val_node.tokens,
2776                                                visited_nodes,
2777                                                visited_shorthands,
2778                                            )
2779                                    {
2780                                        return true;
2781                                    }
2782                                }
2783                            }
2784                        }
2785                        continue;
2786                    }
2787                    let node_opt = self
2788                        .get_active_node(node_id)
2789                        .or_else(|| self.get_node(node_id));
2790                    if let Some(node) = node_opt
2791                        && self.tokens_are_wasm_helper_or_definition_inner(
2792                            &node.tokens,
2793                            visited_nodes,
2794                            visited_shorthands,
2795                        )
2796                    {
2797                        return true;
2798                    }
2799                }
2800                DcShorthand::Short(short_id) => {
2801                    if Self::is_document_syntax_or_framing_short_dc(short_id) {
2802                        continue;
2803                    }
2804                    if !visited_shorthands.insert(tok) {
2805                        continue;
2806                    }
2807                    for prop_dc in [
2808                        DC_CANONICAL_DECOMPOSITION,
2809                        DC_DECOMPOSITION,
2810                        DC_SEMANTIC_DECOMPOSITION,
2811                    ] {
2812                        for entry in self.get_multi_properties(tok, sh(prop_dc))
2813                        {
2814                            if let DcShorthand::Long(node_id) = entry.value {
2815                                if !visited_nodes.insert(node_id) {
2816                                    continue;
2817                                }
2818                                let node_opt = self
2819                                    .get_active_node(node_id)
2820                                    .or_else(|| self.get_node(node_id));
2821                                if let Some(node) = node_opt
2822                                    && self
2823                                        .tokens_are_wasm_helper_or_definition_inner(
2824                                            &node.tokens,
2825                                            visited_nodes,
2826                                            visited_shorthands,
2827                                        )
2828                                {
2829                                    return true;
2830                                }
2831                            }
2832                        }
2833                    }
2834                }
2835                _ => {}
2836            }
2837        }
2838        false
2839    }
2840
2841    /// Resolves any active `.WASM` program (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`),
2842    /// `wasm_routine` definition, or transitive WASM helper attached to `subj` via
2843    /// `Dc 611 "Canonical decomposition"`, `Dc 571 "Decomposition"`,
2844    /// `Dc 614 "Semantic decomposition"`, or a trailing `Dc 607 "Pattern replacement"`
2845    /// action inside `subj`'s `Dc 594 "Syntax rule"`.
2846    #[must_use]
2847    pub fn get_wasm_definition_tokens(
2848        &self,
2849        subj: DcShorthand,
2850    ) -> Option<&[DcShorthand]> {
2851        let mut visited = HashSet::new();
2852        self.get_wasm_definition_tokens_inner(subj, &mut visited)
2853    }
2854
2855    /// Resolves any active context-scoped `.WASM` program (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`)
2856    /// or `wasm_routine` definition attached to `subj` whose `Dc 646 "In context of"` qualifier
2857    /// matches `context_tokens` (preferring an exact match over a trailing `Dc 275 "*"` wildcard prefix).
2858    #[must_use]
2859    pub fn get_wasm_definition_tokens_in_context(
2860        &self,
2861        subj: DcShorthand,
2862        context_tokens: &[DcShorthand],
2863    ) -> Option<&[DcShorthand]> {
2864        if context_tokens.is_empty() {
2865            return self.get_wasm_definition_tokens(subj);
2866        }
2867        let props = [
2868            DC_CANONICAL_DECOMPOSITION,
2869            DC_DECOMPOSITION,
2870            DC_SEMANTIC_DECOMPOSITION,
2871        ];
2872        // Pass 1: exact context match.
2873        for prop_dc in props {
2874            for entry in self.get_multi_properties(subj, sh(prop_dc)) {
2875                let DcShorthand::Long(node_id) = entry.value else {
2876                    continue;
2877                };
2878                let ctx_objs = self.get_direct_objects(
2879                    sh(DC_IN_CONTEXT_OF),
2880                    DcShorthand::Long(entry.has_a_id),
2881                );
2882                let exact_match = ctx_objs.iter().any(|&ctx_obj| {
2883                    self.context_object_exact_match(ctx_obj, context_tokens)
2884                });
2885                if exact_match
2886                    && let Some(node) = self.get_active_node(node_id)
2887                    && self.tokens_are_wasm_helper_or_definition(&node.tokens)
2888                {
2889                    return Some(node.tokens.as_slice());
2890                }
2891            }
2892        }
2893        // Pass 2: longest trailing `Dc 275 "*"` wildcard prefix match (e.g. `2576 275` or `2576 2576 275`).
2894        let mut best: Option<(usize, &[DcShorthand])> = None;
2895        for prop_dc in props {
2896            for entry in self.get_multi_properties(subj, sh(prop_dc)) {
2897                let DcShorthand::Long(node_id) = entry.value else {
2898                    continue;
2899                };
2900                let ctx_objs = self.get_direct_objects(
2901                    sh(DC_IN_CONTEXT_OF),
2902                    DcShorthand::Long(entry.has_a_id),
2903                );
2904                for &ctx_obj in ctx_objs {
2905                    if let Some(prefix_len) = self
2906                        .context_object_wildcard_prefix_len(
2907                            ctx_obj,
2908                            context_tokens,
2909                        )
2910                        && best.is_none_or(|(best_len, _)| prefix_len > best_len)
2911                        && let Some(node) = self.get_active_node(node_id)
2912                        && self.tokens_are_wasm_helper_or_definition(&node.tokens)
2913                    {
2914                        best = Some((prefix_len, node.tokens.as_slice()));
2915                    }
2916                }
2917            }
2918        }
2919        best.map(|(_, tokens)| tokens)
2920    }
2921
2922    /// Lists all active context-scoped `.WASM` (`Dc 1927`..`Dc 1928`) definitions attached to
2923    /// `subj` in this snapshot (`(context_tokens, expanded_wasm_tokens)`), expanding interned
2924    /// Unicode runs and wrapping standalone `Dc 260`..`Dc 261` routines in `Dc 1927`..`Dc 1928`.
2925    #[must_use]
2926    pub fn list_active_contextual_wasm_definitions(
2927        &self,
2928        subj: DcShorthand,
2929    ) -> Vec<(Vec<DcShorthand>, Vec<DcShorthand>)> {
2930        let mut out: Vec<(Vec<DcShorthand>, Vec<DcShorthand>)> = Vec::new();
2931        for prop_dc in [
2932            DC_CANONICAL_DECOMPOSITION,
2933            DC_DECOMPOSITION,
2934            DC_SEMANTIC_DECOMPOSITION,
2935        ] {
2936            for entry in self.get_multi_properties(subj, sh(prop_dc)) {
2937                let DcShorthand::Long(node_id) = entry.value else {
2938                    continue;
2939                };
2940                if let Some(pin_id) = self.system_block_most_recent_node_id
2941                    && node_id > pin_id
2942                {
2943                    continue;
2944                }
2945                let Some(node) = self.get_active_node(node_id) else {
2946                    continue;
2947                };
2948                if !self.tokens_are_wasm_helper_or_definition(&node.tokens) {
2949                    continue;
2950                }
2951                let ctx_objs = self.get_direct_objects(
2952                    sh(DC_IN_CONTEXT_OF),
2953                    DcShorthand::Long(entry.has_a_id),
2954                );
2955                if ctx_objs.is_empty() {
2956                    continue;
2957                }
2958                let mut expanded =
2959                    self.expand_interned_string_nodes(&node.tokens);
2960                if expanded.first() != Some(&sh(DC_BEGIN_WASM_PROGRAM)) {
2961                    let mut wrapped =
2962                        Vec::with_capacity(expanded.len().saturating_add(2));
2963                    wrapped.push(sh(DC_BEGIN_WASM_PROGRAM));
2964                    wrapped.extend(expanded);
2965                    wrapped.push(sh(DC_END_WASM_PROGRAM));
2966                    expanded = wrapped;
2967                }
2968                for &ctx_obj in ctx_objs {
2969                    let ctx_vec =
2970                        if let Some(slice) = self.context_object_tokens(ctx_obj)
2971                        {
2972                            slice.to_vec()
2973                        } else {
2974                            vec![ctx_obj]
2975                        };
2976                    if !out.iter().any(|(existing, _)| existing == &ctx_vec) {
2977                        out.push((ctx_vec, expanded.clone()));
2978                    }
2979                }
2980            }
2981        }
2982        out
2983    }
2984
2985    fn context_object_tokens(&self, ctx_obj: DcShorthand) -> Option<&[DcShorthand]> {
2986        match ctx_obj {
2987            DcShorthand::Long(ctx_id) => {
2988                self.get_active_node(ctx_id).map(|n| n.tokens.as_slice())
2989            }
2990            _ => None,
2991        }
2992    }
2993
2994    fn context_object_exact_match(
2995        &self,
2996        ctx_obj: DcShorthand,
2997        query: &[DcShorthand],
2998    ) -> bool {
2999        if let Some(slice) = self.context_object_tokens(ctx_obj) {
3000            slice == query
3001        } else {
3002            query.len() == 1 && query.first() == Some(&ctx_obj)
3003        }
3004    }
3005
3006    fn context_object_wildcard_prefix_len(
3007        &self,
3008        ctx_obj: DcShorthand,
3009        query: &[DcShorthand],
3010    ) -> Option<usize> {
3011        let slice = self.context_object_tokens(ctx_obj)?;
3012        if slice.last() != Some(&sh(DC_TYPE_ANY)) {
3013            return None;
3014        }
3015        let prefix = slice.get(..slice.len().saturating_sub(1))?;
3016        if !prefix.is_empty()
3017            && query.len() > prefix.len()
3018            && query.starts_with(prefix)
3019        {
3020            Some(prefix.len())
3021        } else {
3022            None
3023        }
3024    }
3025
3026    fn has_any_context_qualifier(&self, stmt_id: u128) -> bool {
3027        if !self
3028            .get_direct_objects(sh(DC_IN_CONTEXT_OF), DcShorthand::Long(stmt_id))
3029            .is_empty()
3030        {
3031            return true;
3032        }
3033        self.subject_all_stmt_ids
3034            .get(&DcShorthand::Long(stmt_id))
3035            .is_some_and(|ids| {
3036                ids.iter().any(|&qid| {
3037                    self.get_node(qid)
3038                        .and_then(|n| parse_statement_tokens(&n.tokens))
3039                        .is_some_and(|(v, _, _)| v == sh(DC_IN_CONTEXT_OF))
3040                })
3041            })
3042    }
3043
3044    fn get_wasm_definition_tokens_inner(
3045        &self,
3046        subj: DcShorthand,
3047        visited: &mut HashSet<DcShorthand>,
3048    ) -> Option<&[DcShorthand]> {
3049        if !visited.insert(subj) {
3050            return None;
3051        }
3052        for prop_dc in [
3053            DC_CANONICAL_DECOMPOSITION,
3054            DC_DECOMPOSITION,
3055            DC_SEMANTIC_DECOMPOSITION,
3056        ] {
3057            for entry in self.get_multi_properties(subj, sh(prop_dc)) {
3058                if !self
3059                    .get_direct_objects(
3060                        sh(DC_IN_CONTEXT_OF),
3061                        DcShorthand::Long(entry.has_a_id),
3062                    )
3063                    .is_empty()
3064                {
3065                    continue;
3066                }
3067                match entry.value {
3068                    DcShorthand::Long(node_id) => {
3069                        if let Some(node) = self.get_active_node(node_id)
3070                            && self.tokens_are_wasm_helper_or_definition(
3071                                &node.tokens,
3072                            )
3073                        {
3074                            return Some(node.tokens.as_slice());
3075                        }
3076                    }
3077                    DcShorthand::Short(_) | DcShorthand::Format(_) => {
3078                        if let Some(tokens) = self
3079                            .get_wasm_definition_tokens_inner(
3080                                entry.value,
3081                                visited,
3082                            )
3083                        {
3084                            return Some(tokens);
3085                        }
3086                    }
3087                    DcShorthand::Unicode(_) | DcShorthand::Local(_) => {}
3088                }
3089            }
3090        }
3091
3092        if let Some(rule_tokens) = self.get_syntax_rule_tokens(subj) {
3093            let sh_open = sh(DC_BEGIN_ASSOCIATIVITY_GROUP);
3094            let sh_close = sh(DC_END_ASSOCIATIVITY_GROUP);
3095            let sh_repl = sh(DC_PATTERN_REPLACEMENT);
3096            if rule_tokens.last() == Some(&sh_close) {
3097                let mut depth = 0usize;
3098                let mut open_idx = None;
3099                for (idx, &tok) in rule_tokens.iter().enumerate().rev() {
3100                    if tok == sh_close {
3101                        depth = depth.saturating_add(1);
3102                    } else if tok == sh_open {
3103                        depth = depth.saturating_sub(1);
3104                        if depth == 0 {
3105                            open_idx = Some(idx);
3106                            break;
3107                        }
3108                    }
3109                }
3110                if let Some(start) = open_idx
3111                    && let Some(group_slice) = rule_tokens.get(start..)
3112                    && group_slice.get(1) == Some(&sh_repl)
3113                    && let Some(inner) =
3114                        group_slice.get(2..group_slice.len().saturating_sub(1))
3115                    && self.tokens_are_wasm_helper_or_definition(inner)
3116                {
3117                    if inner.len() == 1
3118                        && let Some(&DcShorthand::Long(node_id)) = inner.first()
3119                        && let Some(node) = self.get_active_node(node_id)
3120                    {
3121                        return Some(node.tokens.as_slice());
3122                    }
3123                    return Some(inner);
3124                }
3125            }
3126        }
3127
3128        for &base_tok in self.get_direct_objects(sh(DC_IS_BASED_ON), subj) {
3129            if matches!(base_tok, DcShorthand::Short(_) | DcShorthand::Format(_))
3130                && let Some(tokens) =
3131                    self.get_wasm_definition_tokens_inner(base_tok, visited)
3132            {
3133                return Some(tokens);
3134            }
3135        }
3136        None
3137    }
3138
3139    /// Resolves `subj` (`DcShorthand::Short` or `DcShorthand::Format`) as a WASM helper or
3140    /// definition in this snapshot via `Dc 611 "Canonical decomposition"`,
3141    /// `Dc 571 "Decomposition"`, `Dc 614 "Semantic decomposition"`, or a trailing
3142    /// `Dc 607 "Pattern replacement"` action inside `subj`'s `Dc 594 "Syntax rule"`.
3143    ///
3144    /// # Errors
3145    /// Returns an error if `subj`'s WASM decomposition or target node was retracted in this
3146    /// snapshot, targets an unsupported graph block, or exceeds the pinned System graph snapshot.
3147    pub fn resolve_wasm_helper_shorthand(
3148        &self,
3149        subj: DcShorthand,
3150    ) -> Result<Option<(Option<u128>, &[DcShorthand])>> {
3151        for prop_dc in [
3152            DC_CANONICAL_DECOMPOSITION,
3153            DC_DECOMPOSITION,
3154            DC_SEMANTIC_DECOMPOSITION,
3155        ] {
3156            for entry in self.get_multi_properties(subj, sh(prop_dc)) {
3157                if !self
3158                    .get_direct_objects(
3159                        sh(DC_IN_CONTEXT_OF),
3160                        DcShorthand::Long(entry.has_a_id),
3161                    )
3162                    .is_empty()
3163                {
3164                    continue;
3165                }
3166                if let DcShorthand::Long(node_id) = entry.value {
3167                    if let Some(block_desc) =
3168                        ctb_storage_minimal::global_graph_layout::unsupported_graph_block_description(
3169                            node_id,
3170                        )
3171                    {
3172                        bail!(
3173                            "Graph WASM helper {subj} target l{node_id} references unsupported graph block ({block_desc})"
3174                        );
3175                    }
3176                    if let Some(pin_id) = self.system_block_most_recent_node_id
3177                        && node_id > pin_id
3178                    {
3179                        bail!(
3180                            "Graph WASM helper {subj} target l{node_id} exceeds pinned System graph snapshot l{pin_id}"
3181                        );
3182                    }
3183                    if let Some(node) = self.get_active_node(node_id) {
3184                        if let Some(pin_id) =
3185                            self.system_block_most_recent_node_id
3186                            && node.id > pin_id
3187                        {
3188                            bail!(
3189                                "Graph WASM helper {subj} target l{} exceeds pinned System graph snapshot l{pin_id}",
3190                                node.id
3191                            );
3192                        }
3193                        if self
3194                            .tokens_are_wasm_helper_or_definition(&node.tokens)
3195                        {
3196                            return Ok(Some((
3197                                Some(node.id),
3198                                node.tokens.as_slice(),
3199                            )));
3200                        }
3201                    } else if self.retracted_by(node_id).is_some() {
3202                        bail!(
3203                            "Graph WASM helper {subj} target node l{node_id} was retracted in the active System graph snapshot"
3204                        );
3205                    }
3206                }
3207            }
3208        }
3209
3210        if let Some(tokens) = self.get_wasm_definition_tokens(subj) {
3211            return Ok(Some((None, tokens)));
3212        }
3213
3214        if let Some(stmt_ids) = self.subject_all_stmt_ids.get(&subj) {
3215            for &stmt_id in stmt_ids {
3216                let Some(stmt_node) = self.get_node(stmt_id) else {
3217                    continue;
3218                };
3219                let Some((verb, _, obj)) =
3220                    parse_statement_tokens(&stmt_node.tokens)
3221                else {
3222                    continue;
3223                };
3224                if verb == sh(DC_HAS_A)
3225                    && (obj == sh(DC_CANONICAL_DECOMPOSITION)
3226                        || obj == sh(DC_DECOMPOSITION)
3227                        || obj == sh(DC_SEMANTIC_DECOMPOSITION))
3228                    && !self.has_any_context_qualifier(stmt_id)
3229                    && let Some(has_vals) =
3230                        self.has_val_stmt_ids_by_has_a.get(&stmt_id)
3231                {
3232                    for &(has_val_id, val_tok) in has_vals {
3233                        if let DcShorthand::Long(target_id) = val_tok {
3234                            let is_wasm_target = self
3235                                .get_node(target_id)
3236                                .is_some_and(|n| {
3237                                    self.tokens_are_wasm_helper_or_definition(
3238                                        &n.tokens,
3239                                    )
3240                                });
3241                            if is_wasm_target
3242                                && (self.retracted_by(stmt_id).is_some()
3243                                    || self.retracted_by(has_val_id).is_some()
3244                                    || self.retracted_by(target_id).is_some()
3245                                    || self.inactive_ids.contains(&stmt_id)
3246                                    || self.inactive_ids.contains(&has_val_id)
3247                                    || self.inactive_ids.contains(&target_id))
3248                            {
3249                                bail!(
3250                                    "Graph WASM helper {subj} (or target node l{target_id}) was retracted in the active System graph snapshot"
3251                                );
3252                            }
3253                        }
3254                    }
3255                }
3256            }
3257        }
3258
3259        Ok(None)
3260    }
3261
3262    /// Returns the `<class_tok>` of an active non-seed entity node (`586 615 <class_tok>`),
3263    /// if `entity_id` is an active entity in this snapshot.
3264    #[must_use]
3265    pub fn get_entity_class(&self, entity_id: u128) -> Option<DcShorthand> {
3266        self.entity_class_by_id.get(&entity_id).copied()
3267    }
3268
3269    /// Returns `true` if `subj` is a `DcShorthand::Format(_)` whose active script in this
3270    /// snapshot is `.Formats:transformation`.
3271    #[must_use]
3272    pub fn is_transformation_format_subject(&self, subj: DcShorthand) -> bool {
3273        if !matches!(subj, DcShorthand::Format(_)) {
3274            return false;
3275        }
3276        for &obj in self.get_direct_objects(sh(DC_IS_INSTANCE_OF), subj) {
3277            if let DcShorthand::Long(seed_id) = obj
3278                && let Some(SeedEntityKey::Script(script_name)) =
3279                    self.get_seed_entity(seed_id)
3280                && crate::syntax::is_transformation_format_category(script_name)
3281            {
3282                return true;
3283            }
3284        }
3285        false
3286    }
3287
3288    /// Lists all active single-step converters (`[Dc 302 "Type conversion", src, dst]`) in this
3289    /// snapshot across standalone `Routine` entities (`Dc 280`) and `.Formats:transformation`
3290    /// Format Dcs (`DcShorthand::Format(_)`), ordered with `Dc 570 "Preferred"` entries first and
3291    /// ties broken by ascending global Dc ID.
3292    ///
3293    /// # Errors
3294    /// Returns an error if an active converter's decomposition target node was retracted,
3295    /// references an unsupported graph block, or exceeds the pinned System graph snapshot.
3296    pub fn list_all_active_converter_steps(
3297        &self,
3298    ) -> Result<Vec<ActiveConverterStep<'_>>> {
3299        let mut candidate_subjects: Vec<DcShorthand> = Vec::new();
3300        for (&entity_id, &class_tok) in &self.entity_class_by_id {
3301            if class_tok != sh(DC_TYPE_ROUTINE) {
3302                continue;
3303            }
3304            if let Some(pin_id) = self.system_block_most_recent_node_id
3305                && entity_id > pin_id
3306            {
3307                continue;
3308            }
3309            candidate_subjects.push(DcShorthand::Long(entity_id));
3310        }
3311        for &(subj, prop) in self.active_single_props.keys() {
3312            if prop == sh(DC_DATA_FORMAT_DESCRIPTION)
3313                && self.is_transformation_format_subject(subj)
3314            {
3315                candidate_subjects.push(subj);
3316            }
3317        }
3318
3319        let mut steps: Vec<(bool, u128, ActiveConverterStep<'_>)> = Vec::new();
3320        for subj in candidate_subjects {
3321            let Some(&(has_a_id, has_val_id, DcShorthand::Long(fmt_node_id))) =
3322                self.active_single_props
3323                    .get(&(subj, sh(DC_DATA_FORMAT_DESCRIPTION)))
3324            else {
3325                continue;
3326            };
3327            if let Some(pin_id) = self.system_block_most_recent_node_id
3328                && (has_a_id > pin_id
3329                    || has_val_id > pin_id
3330                    || fmt_node_id > pin_id)
3331            {
3332                continue;
3333            }
3334            let Some(fmt_node) = self.get_active_node(fmt_node_id) else {
3335                continue;
3336            };
3337            let [conv_op, src, dst] = fmt_node.tokens.as_slice() else {
3338                continue;
3339            };
3340            if *conv_op != sh(DC_TYPE_CONVERSION) {
3341                continue;
3342            }
3343
3344            let body = if let Some((_, wasm_tokens)) =
3345                self.resolve_wasm_helper_shorthand(subj)?
3346            {
3347                ActiveConverterBody::Wasm(wasm_tokens)
3348            } else if let Some((_, stagel_chars)) =
3349                self.resolve_stagel_decomposition_tokens(subj)?
3350            {
3351                ActiveConverterBody::StageL(stagel_chars)
3352            } else {
3353                continue;
3354            };
3355
3356            let entity_pref = self.has_direct_statement(
3357                sh(DC_HAS_A),
3358                subj,
3359                sh(DC_PREFERRED),
3360            );
3361            let decomp_pref = [
3362                DC_CANONICAL_DECOMPOSITION,
3363                DC_DECOMPOSITION,
3364                DC_SEMANTIC_DECOMPOSITION,
3365            ]
3366            .into_iter()
3367            .any(|prop_dc| {
3368                self.get_multi_properties(subj, sh(prop_dc))
3369                    .iter()
3370                    .any(|e| e.preferred_id.is_some())
3371            });
3372            let is_preferred = entity_pref || decomp_pref;
3373            let gid = subj.to_global_id()?;
3374            steps.push((
3375                !is_preferred,
3376                gid,
3377                ActiveConverterStep {
3378                    subject: subj,
3379                    src: *src,
3380                    dst: *dst,
3381                    is_preferred,
3382                    body,
3383                },
3384            ));
3385        }
3386
3387        steps.sort_by_key(|&(not_pref, gid, _)| (not_pref, gid));
3388        Ok(steps.into_iter().map(|(_, _, step)| step).collect())
3389    }
3390
3391    /// Resolves the shortest active conversion path (`[Dc 302 src_0 dst_0]`, ...,
3392    /// `[Dc 302 src_k dst]`) from `src` to `dst` in this snapshot, preferring `Dc 570 "Preferred"`
3393    /// converters at each hop and breaking ties deterministically by ascending global Dc ID.
3394    ///
3395    /// # Errors
3396    /// Returns an error if any candidate converter's target node is invalid in this snapshot.
3397    pub fn resolve_active_converter_chain(
3398        &self,
3399        src: DcShorthand,
3400        dst: DcShorthand,
3401    ) -> Result<Option<Vec<ActiveConverterStep<'_>>>> {
3402        let all_steps = self.list_all_active_converter_steps()?;
3403        if all_steps.is_empty() {
3404            return Ok(None);
3405        }
3406
3407        let mut queue: std::collections::VecDeque<DcShorthand> =
3408            std::collections::VecDeque::new();
3409        let mut prev_step_idx: HashMap<DcShorthand, usize> = HashMap::new();
3410        let mut visited: HashSet<DcShorthand> = HashSet::new();
3411        visited.insert(src);
3412        queue.push_back(src);
3413
3414        while let Some(curr) = queue.pop_front() {
3415            for (idx, step) in all_steps.iter().enumerate() {
3416                if step.src != curr {
3417                    continue;
3418                }
3419                if step.dst == dst {
3420                    let mut rev_indices = vec![idx];
3421                    let mut back = curr;
3422                    while back != src {
3423                        let Some(&p_idx) = prev_step_idx.get(&back) else {
3424                            break;
3425                        };
3426                        rev_indices.push(p_idx);
3427                        let Some(p_step) = all_steps.get(p_idx) else {
3428                            break;
3429                        };
3430                        back = p_step.src;
3431                    }
3432                    rev_indices.reverse();
3433                    let mut chain = Vec::with_capacity(rev_indices.len());
3434                    for s_idx in rev_indices {
3435                        if let Some(s) = all_steps.get(s_idx) {
3436                            chain.push(s.clone());
3437                        }
3438                    }
3439                    return Ok(Some(chain));
3440                }
3441                if visited.insert(step.dst) {
3442                    prev_step_idx.insert(step.dst, idx);
3443                    queue.push_back(step.dst);
3444                }
3445            }
3446        }
3447        Ok(None)
3448    }
3449
3450    /// Resolves the highest-precedence direct `.WASM` converter (`[Dc 302 "Type conversion", src, dst]`)
3451    /// in this snapshot (either a `.Formats:transformation` Format Dc or a standalone `Routine`
3452    /// entity), returning `(subject_global_dc_id, wasm_tokens)`.
3453    ///
3454    /// # Errors
3455    /// Returns an error if a matching active converter's target node was retracted, references an
3456    /// unsupported graph block, or exceeds the pinned System graph snapshot.
3457    pub fn resolve_active_converter_routine(
3458        &self,
3459        src: DcShorthand,
3460        dst: DcShorthand,
3461    ) -> Result<Option<(u128, &[DcShorthand])>> {
3462        for step in self.list_all_active_converter_steps()? {
3463            if step.src == src
3464                && step.dst == dst
3465                && let ActiveConverterBody::Wasm(wasm_tokens) = step.body
3466            {
3467                return Ok(Some((step.subject.to_global_id()?, wasm_tokens)));
3468            }
3469        }
3470        Ok(None)
3471    }
3472
3473    pub(crate) fn is_closed_string_literal_node(tokens: &[DcShorthand]) -> bool {
3474        tokens.first() == Some(&sh(DC_BEGIN_LITERAL))
3475            && find_closed_delimited_span(
3476                tokens,
3477                0,
3478                sh(DC_END_LITERAL),
3479                sh(DC_ESCAPE),
3480            ) == Some(tokens.len().saturating_sub(1))
3481    }
3482
3483    /// Returns `true` when `tokens` is a single self-contained single-line or
3484    /// block comment frame (`246`/`247`..`248` or `249`/`250`..`251`).
3485    #[must_use]
3486    pub(crate) fn is_closed_comment_node(tokens: &[DcShorthand]) -> bool {
3487        if tokens.len() < 2 {
3488            return false;
3489        }
3490        let sh_escape = sh(DC_ESCAPE);
3491        let Some(&first) = tokens.first() else {
3492            return false;
3493        };
3494        let close = if first == sh(DC_BEGIN_SINGLE_LINE_COMMENT)
3495            || first == sh(DC_BEGIN_SINGLE_LINE_COMMENT_NEW_LINE)
3496        {
3497            sh(DC_END_SINGLE_LINE_COMMENT)
3498        } else if first == sh(DC_BEGIN_BLOCK_COMMENT)
3499            || first == sh(DC_BEGIN_BLOCK_COMMENT_NEW_LINE)
3500        {
3501            sh(DC_END_BLOCK_COMMENT)
3502        } else {
3503            return false;
3504        };
3505        find_closed_delimited_span(tokens, 0, close, sh_escape)
3506            == Some(tokens.len().saturating_sub(1))
3507    }
3508
3509    /// Returns `true` when `tokens` is a single self-contained identifier frame
3510    /// (`Dc 270 .. Dc 271`, length >= 3) without unescaped nested `270` openers.
3511    #[must_use]
3512    pub(crate) fn is_closed_identifier_node(tokens: &[DcShorthand]) -> bool {
3513        if tokens.len() < 3 {
3514            return false;
3515        }
3516        let sh_open = sh(DC_BEGIN_IDENTIFIER);
3517        let sh_close = sh(DC_END_IDENTIFIER);
3518        let sh_escape = sh(DC_ESCAPE);
3519        if tokens.first() != Some(&sh_open) {
3520            return false;
3521        }
3522        let end_pos = tokens.len().saturating_sub(1);
3523        if find_closed_delimited_span(tokens, 0, sh_close, sh_escape)
3524            != Some(end_pos)
3525        {
3526            return false;
3527        }
3528        let mut idx = 1usize;
3529        while idx < end_pos {
3530            let Some(&tok) = tokens.get(idx) else {
3531                break;
3532            };
3533            if tok == sh_escape {
3534                idx = idx.saturating_add(2);
3535                continue;
3536            }
3537            if tok == sh_open {
3538                return false;
3539            }
3540            idx = idx.saturating_add(1);
3541        }
3542        true
3543    }
3544
3545    pub(crate) fn is_legacy_unicode_run_node(tokens: &[DcShorthand]) -> bool {
3546        !tokens.is_empty()
3547            && tokens.iter().all(|t| matches!(t, DcShorthand::Unicode(_)))
3548    }
3549
3550    /// Returns `true` when `tokens` at `type_open_idx` starts with `Dc 262 "Begin type definition"`
3551    /// and finds its matching `Dc 263 "End type definition"` strictly before `limit_idx`.
3552    #[must_use]
3553    pub(crate) fn find_matching_type_def_end(
3554        tokens: &[DcShorthand],
3555        type_open_idx: usize,
3556        limit_idx: usize,
3557    ) -> Option<usize> {
3558        let sh_open = sh(DC_BEGIN_TYPE_DEF);
3559        let sh_close = sh(DC_END_TYPE_DEF);
3560        let sh_escape = sh(DC_ESCAPE);
3561        if tokens.get(type_open_idx) != Some(&sh_open) {
3562            return None;
3563        }
3564        let mut depth = 1usize;
3565        let mut cur = type_open_idx.saturating_add(1);
3566        while cur < limit_idx {
3567            let tok = *tokens.get(cur)?;
3568            if tok == sh_escape {
3569                cur = cur.saturating_add(2);
3570                continue;
3571            }
3572            if tok == sh_open {
3573                depth = depth.saturating_add(1);
3574            } else if tok == sh_close {
3575                depth = depth.saturating_sub(1);
3576                if depth == 0 {
3577                    return Some(cur);
3578                }
3579            }
3580            cur = cur.saturating_add(1);
3581        }
3582        None
3583    }
3584
3585    /// Returns `true` when the `Dc 260 "Begin literal value"` frame at `lit_open_idx`
3586    /// declares `Dc 640 "Built-in type identifier: Atom Dc (unevaluated Document Character reference)"`
3587    /// (or `[list:atom_dc]`), suppressing normalization across its payload.
3588    #[must_use]
3589    pub(crate) fn is_atom_dc_literal_header(
3590        tokens: &[DcShorthand],
3591        lit_open_idx: usize,
3592    ) -> bool {
3593        let sh_type_atom_dc = sh(DC_TYPE_ATOM_DC);
3594        let sh_type_open = sh(DC_BEGIN_TYPE_DEF);
3595        let sh_list_open = sh(DC_BEGIN_LIST);
3596        let nx1 = tokens.get(lit_open_idx.saturating_add(1));
3597        if nx1 == Some(&sh_type_atom_dc) {
3598            return true;
3599        }
3600        if nx1 == Some(&sh_type_open) {
3601            let nx2 = tokens.get(lit_open_idx.saturating_add(2));
3602            if nx2 == Some(&sh_type_atom_dc) {
3603                return true;
3604            }
3605            if nx2 == Some(&sh_list_open)
3606                && tokens.get(lit_open_idx.saturating_add(3))
3607                    == Some(&sh_type_atom_dc)
3608            {
3609                return true;
3610            }
3611        }
3612        false
3613    }
3614
3615    /// Returns `true` when `tokens` is a bare sequence value node (without outer
3616    /// string/comment/identifier framing, statements, or module/WASM headers)
3617    /// eligible to splice inline inside `[string]`, comment, and `[identifier]` frames.
3618    #[must_use]
3619    pub(crate) fn is_bare_payload_value_node(tokens: &[DcShorthand]) -> bool {
3620        let Some(&first) = tokens.first() else {
3621            return false;
3622        };
3623        if parse_statement_tokens(tokens).is_some()
3624            || parse_for_each_statement_tokens(tokens).is_some()
3625            || parse_ambiguous_values_tokens(tokens).is_some()
3626            || Self::tokens_start_wasm_definition(tokens)
3627            || Self::is_closed_string_literal_node(tokens)
3628            || Self::is_closed_comment_node(tokens)
3629            || Self::is_closed_identifier_node(tokens)
3630        {
3631            return false;
3632        }
3633        !matches!(
3634            first,
3635            t if t == sh(DC_BEGIN_MODULE)
3636                || t == sh(DC_BEGIN_STAGER_MODULE)
3637                || t == sh(DC_BEGIN_ROUTINE_DECL)
3638                || t == sh(DC_BEGIN_ROUTINE)
3639                || t == sh(DC_BEGIN_TEST_BLOCK)
3640                || t == sh(DC_DECLARE_CONST)
3641                || t == sh(DC_DECLARE_PUB)
3642                || t == sh(DC_BEGIN_POSITIONAL_STRUCT_DECL)
3643                || t == sh(DC_DECLARE_BRAND_TYPE)
3644                || t == sh(DC_BEGIN_NAMED_STRUCT_DECL)
3645                || t == sh(DC_BEGIN_ENUM_DECL)
3646        )
3647    }
3648
3649    fn expand_bare_payload_with_lookup_inner<'a, F>(
3650        tokens: &[DcShorthand],
3651        lookup: &F,
3652        visiting: &mut HashSet<u128>,
3653    ) -> Vec<DcShorthand>
3654    where
3655        F: Fn(u128) -> Option<&'a [DcShorthand]>,
3656    {
3657        let sh_escape = sh(DC_ESCAPE);
3658        let sh_quote_atom = sh(DC_QUOTE_FOLLOWING_DC_AS_ATOM);
3659        let mut out = Vec::with_capacity(tokens.len());
3660        let mut i = 0usize;
3661        while let Some(&tok) = tokens.get(i) {
3662            if tok == sh_escape || tok == sh_quote_atom {
3663                out.push(tok);
3664                if let Some(&next_tok) = tokens.get(i.saturating_add(1)) {
3665                    out.push(next_tok);
3666                    i = i.saturating_add(2);
3667                } else {
3668                    i = i.saturating_add(1);
3669                }
3670                continue;
3671            }
3672            if let DcShorthand::Long(child_id) = tok
3673                && !visiting.contains(&child_id)
3674                && let Some(child_tokens) = lookup(child_id)
3675                && Self::is_bare_payload_value_node(child_tokens)
3676            {
3677                visiting.insert(child_id);
3678                let expanded = Self::expand_bare_payload_with_lookup_inner(
3679                    child_tokens,
3680                    lookup,
3681                    visiting,
3682                );
3683                visiting.remove(&child_id);
3684                out.extend(expanded);
3685            } else {
3686                out.push(tok);
3687            }
3688            i = i.saturating_add(1);
3689        }
3690        out
3691    }
3692
3693    fn push_re_escaped_for_frame(
3694        out: &mut Vec<DcShorthand>,
3695        expanded_payload: &[DcShorthand],
3696        frame_closer: DcShorthand,
3697        escape_leading_type_or_format: bool,
3698    ) {
3699        let sh_escape = sh(DC_ESCAPE);
3700        let sh_quote_atom = sh(DC_QUOTE_FOLLOWING_DC_AS_ATOM);
3701        let sh_type_open = sh(DC_BEGIN_TYPE_DEF);
3702        let mut idx = 0usize;
3703        while let Some(&tok) = expanded_payload.get(idx) {
3704            if tok == sh_quote_atom {
3705                out.push(tok);
3706                if let Some(&next_tok) =
3707                    expanded_payload.get(idx.saturating_add(1))
3708                {
3709                    if next_tok == sh_escape
3710                        && let Some(&esc_tok) =
3711                            expanded_payload.get(idx.saturating_add(2))
3712                    {
3713                        out.push(sh_escape);
3714                        out.push(esc_tok);
3715                        idx = idx.saturating_add(3);
3716                        continue;
3717                    }
3718                    if next_tok == frame_closer {
3719                        out.push(sh_escape);
3720                    }
3721                    out.push(next_tok);
3722                    idx = idx.saturating_add(2);
3723                } else {
3724                    idx = idx.saturating_add(1);
3725                }
3726                continue;
3727            }
3728            if tok == sh_escape {
3729                out.push(tok);
3730                if let Some(&next_tok) = expanded_payload.get(idx.saturating_add(1))
3731                {
3732                    out.push(next_tok);
3733                    idx = idx.saturating_add(2);
3734                } else {
3735                    idx = idx.saturating_add(1);
3736                }
3737                continue;
3738            }
3739            let needs_escape = tok == frame_closer
3740                || (escape_leading_type_or_format
3741                    && idx == 0
3742                    && (matches!(tok, DcShorthand::Format(_))
3743                        || tok == sh_type_open));
3744            if needs_escape {
3745                out.push(sh_escape);
3746            }
3747            out.push(tok);
3748            idx = idx.saturating_add(1);
3749        }
3750    }
3751
3752    /// Expands interned bare sequence payloads inside `[string]`, comment, and
3753    /// `[identifier]` frames, as well as historical closed `[string]` (`260..261`),
3754    /// comment (`246/247..248`, `249/250..251`), identifier (`270..271`), and
3755    /// pure-Unicode run node references, honoring `Dc 2239` (`Quote following Dc as atom`)
3756    /// with cycle protection.
3757    #[must_use]
3758    pub(crate) fn expand_interned_nodes_with_lookup<'a, F>(
3759        tokens: &[DcShorthand],
3760        lookup: &F,
3761    ) -> Vec<DcShorthand>
3762    where
3763        F: Fn(u128) -> Option<&'a [DcShorthand]>,
3764    {
3765        let mut visiting = HashSet::new();
3766        Self::expand_interned_nodes_with_lookup_inner(
3767            tokens,
3768            lookup,
3769            &mut visiting,
3770        )
3771    }
3772
3773    fn expand_interned_nodes_with_lookup_inner<'a, F>(
3774        tokens: &[DcShorthand],
3775        lookup: &F,
3776        visiting: &mut HashSet<u128>,
3777    ) -> Vec<DcShorthand>
3778    where
3779        F: Fn(u128) -> Option<&'a [DcShorthand]>,
3780    {
3781        let sh_escape = sh(DC_ESCAPE);
3782        let sh_atom = sh(DC_EVALUATE_VALUE_AS_ATOM);
3783        let sh_quote_atom = sh(DC_QUOTE_FOLLOWING_DC_AS_ATOM);
3784        let sh_type_atom_dc = sh(DC_TYPE_ATOM_DC);
3785        let sh_lit_open = sh(DC_BEGIN_LITERAL);
3786        let sh_lit_close = sh(DC_END_LITERAL);
3787        let sh_ident_open = sh(DC_BEGIN_IDENTIFIER);
3788        let sh_ident_close = sh(DC_END_IDENTIFIER);
3789        let sh_cmt_inline = sh(DC_BEGIN_SINGLE_LINE_COMMENT);
3790        let sh_cmt_nl = sh(DC_BEGIN_SINGLE_LINE_COMMENT_NEW_LINE);
3791        let sh_cmt_close = sh(DC_END_SINGLE_LINE_COMMENT);
3792        let sh_blk_inline = sh(DC_BEGIN_BLOCK_COMMENT);
3793        let sh_blk_nl = sh(DC_BEGIN_BLOCK_COMMENT_NEW_LINE);
3794        let sh_blk_close = sh(DC_END_BLOCK_COMMENT);
3795
3796        let mut out = Vec::with_capacity(tokens.len());
3797        let mut in_lit = false;
3798        let mut lit_is_atom_dc = false;
3799        let mut in_ident = false;
3800        let mut ident_has_type = false;
3801        let mut ident_has_payload = false;
3802        let mut comment_close: Option<DcShorthand> = None;
3803        let mut i = 0usize;
3804        while let Some(&tok) = tokens.get(i) {
3805            if tok == sh_escape || tok == sh_quote_atom {
3806                out.push(tok);
3807                if let Some(&next_tok) = tokens.get(i.saturating_add(1)) {
3808                    out.push(next_tok);
3809                    i = i.saturating_add(2);
3810                } else {
3811                    i = i.saturating_add(1);
3812                }
3813                if in_ident {
3814                    ident_has_payload = true;
3815                }
3816                continue;
3817            }
3818            if let Some(close_tok) = comment_close {
3819                if tok == close_tok {
3820                    comment_close = None;
3821                    out.push(tok);
3822                } else if let DcShorthand::Long(child_id) = tok
3823                    && !visiting.contains(&child_id)
3824                    && let Some(child_tokens) = lookup(child_id)
3825                    && Self::is_bare_payload_value_node(child_tokens)
3826                {
3827                    visiting.insert(child_id);
3828                    let expanded_child =
3829                        Self::expand_bare_payload_with_lookup_inner(
3830                            child_tokens,
3831                            lookup,
3832                            visiting,
3833                        );
3834                    visiting.remove(&child_id);
3835                    Self::push_re_escaped_for_frame(
3836                        &mut out,
3837                        &expanded_child,
3838                        close_tok,
3839                        false,
3840                    );
3841                } else {
3842                    out.push(tok);
3843                }
3844                i = i.saturating_add(1);
3845                continue;
3846            }
3847            if in_ident {
3848                if tok == sh_ident_close {
3849                    in_ident = false;
3850                    ident_has_type = false;
3851                    ident_has_payload = false;
3852                    out.push(tok);
3853                } else if let DcShorthand::Long(child_id) = tok
3854                    && !visiting.contains(&child_id)
3855                    && let Some(child_tokens) = lookup(child_id)
3856                    && Self::is_bare_payload_value_node(child_tokens)
3857                {
3858                    visiting.insert(child_id);
3859                    let expanded_child =
3860                        Self::expand_bare_payload_with_lookup_inner(
3861                            child_tokens,
3862                            lookup,
3863                            visiting,
3864                        );
3865                    visiting.remove(&child_id);
3866                    Self::push_re_escaped_for_frame(
3867                        &mut out,
3868                        &expanded_child,
3869                        sh_ident_close,
3870                        !ident_has_type && !ident_has_payload,
3871                    );
3872                    ident_has_payload = true;
3873                } else {
3874                    out.push(tok);
3875                    ident_has_payload = true;
3876                }
3877                i = i.saturating_add(1);
3878                continue;
3879            }
3880            if in_lit {
3881                if tok == sh_lit_close {
3882                    in_lit = false;
3883                    lit_is_atom_dc = false;
3884                    out.push(tok);
3885                } else if !lit_is_atom_dc
3886                    && let DcShorthand::Long(child_id) = tok
3887                    && !matches!(
3888                        out.last().copied(),
3889                        Some(t) if t == sh_atom || t == sh_type_atom_dc
3890                    )
3891                    && !visiting.contains(&child_id)
3892                    && let Some(child_tokens) = lookup(child_id)
3893                    && Self::is_bare_payload_value_node(child_tokens)
3894                {
3895                    visiting.insert(child_id);
3896                    let expanded_child =
3897                        Self::expand_bare_payload_with_lookup_inner(
3898                            child_tokens,
3899                            lookup,
3900                            visiting,
3901                        );
3902                    visiting.remove(&child_id);
3903                    Self::push_re_escaped_for_frame(
3904                        &mut out,
3905                        &expanded_child,
3906                        sh_lit_close,
3907                        false,
3908                    );
3909                } else {
3910                    out.push(tok);
3911                }
3912                i = i.saturating_add(1);
3913                continue;
3914            }
3915
3916            if tok == sh_cmt_inline || tok == sh_cmt_nl {
3917                comment_close = Some(sh_cmt_close);
3918                out.push(tok);
3919            } else if tok == sh_blk_inline || tok == sh_blk_nl {
3920                comment_close = Some(sh_blk_close);
3921                out.push(tok);
3922            } else if tok == sh_ident_open {
3923                out.push(tok);
3924                in_ident = true;
3925                ident_has_type = false;
3926                ident_has_payload = false;
3927                if let Some(end_idx) = find_closed_delimited_span(
3928                    tokens,
3929                    i,
3930                    sh_ident_close,
3931                    sh_escape,
3932                ) {
3933                    if let Some(&fmt_tok) = tokens.get(i.saturating_add(1))
3934                        && matches!(fmt_tok, DcShorthand::Format(_))
3935                        && i.saturating_add(2) < end_idx
3936                    {
3937                        out.push(fmt_tok);
3938                        ident_has_type = true;
3939                        i = i.saturating_add(2);
3940                        continue;
3941                    } else if tokens.get(i.saturating_add(1))
3942                        == Some(&sh(DC_BEGIN_TYPE_DEF))
3943                        && let Some(type_end) = Self::find_matching_type_def_end(
3944                            tokens,
3945                            i.saturating_add(1),
3946                            end_idx,
3947                        )
3948                        && type_end.saturating_add(1) < end_idx
3949                        && let Some(type_slice) =
3950                            tokens.get(i.saturating_add(1)..=type_end)
3951                    {
3952                        out.extend_from_slice(type_slice);
3953                        ident_has_type = true;
3954                        i = type_end.saturating_add(1);
3955                        continue;
3956                    }
3957                }
3958            } else if tok == sh_lit_open {
3959                let is_routine_lit = tokens.get(i.saturating_add(1))
3960                    == Some(&sh(DC_BEGIN_TYPE_DEF))
3961                    && tokens.get(i.saturating_add(2))
3962                        == Some(&sh(DC_TYPE_ROUTINE));
3963                out.push(tok);
3964                if !is_routine_lit {
3965                    in_lit = true;
3966                    lit_is_atom_dc = Self::is_atom_dc_literal_header(tokens, i);
3967                    if !lit_is_atom_dc
3968                        && tokens.get(i.saturating_add(1))
3969                            == Some(&sh(DC_BEGIN_TYPE_DEF))
3970                        && let Some(end_idx) = find_closed_delimited_span(
3971                            tokens,
3972                            i,
3973                            sh_lit_close,
3974                            sh_escape,
3975                        )
3976                        && let Some(type_end) = Self::find_matching_type_def_end(
3977                            tokens,
3978                            i.saturating_add(1),
3979                            end_idx,
3980                        )
3981                        && let Some(type_slice) =
3982                            tokens.get(i.saturating_add(1)..=type_end)
3983                    {
3984                        out.extend_from_slice(type_slice);
3985                        i = type_end.saturating_add(1);
3986                        continue;
3987                    }
3988                }
3989            } else if let DcShorthand::Long(child_id) = tok
3990                && out.last().copied() != Some(sh_atom)
3991                && !visiting.contains(&child_id)
3992                && let Some(child_tokens) = lookup(child_id)
3993                && (Self::is_closed_string_literal_node(child_tokens)
3994                    || Self::is_closed_comment_node(child_tokens)
3995                    || Self::is_closed_identifier_node(child_tokens)
3996                    || Self::is_legacy_unicode_run_node(child_tokens))
3997            {
3998                visiting.insert(child_id);
3999                let expanded_child = Self::expand_interned_nodes_with_lookup_inner(
4000                    child_tokens,
4001                    lookup,
4002                    visiting,
4003                );
4004                visiting.remove(&child_id);
4005                out.extend(expanded_child);
4006            } else {
4007                out.push(tok);
4008            }
4009            i = i.saturating_add(1);
4010        }
4011        out
4012    }
4013
4014    /// Expands interned `[string]` (`Dc 260 .. Dc 261`), comment
4015    /// (`Dc 246/247..248`, `Dc 249/250..251`), identifier (`Dc 270..271`), and
4016    /// legacy pre-cleanup pure-Unicode run nodes back into inline Dc tokens.
4017    #[must_use]
4018    pub fn expand_interned_string_nodes(
4019        &self,
4020        tokens: &[DcShorthand],
4021    ) -> Vec<DcShorthand> {
4022        Self::expand_interned_nodes_with_lookup(tokens, &|child_id| {
4023            self.get_active_node(child_id).map(|n| n.tokens.as_slice())
4024        })
4025    }
4026
4027    /// Returns `true` if `raw_tokens` (after expanding interned `[string]`
4028    /// nodes and skipping leading single-line comment frames) begins with a
4029    /// StageL 3 module or top-level declaration Token Dc.
4030    #[must_use]
4031    pub fn tokens_are_stagel_item_or_module(
4032        &self,
4033        raw_tokens: &[DcShorthand],
4034    ) -> bool {
4035        let expanded = self.expand_interned_string_nodes(raw_tokens);
4036        let mut chars = Vec::with_capacity(expanded.len());
4037        for tok in expanded {
4038            let Ok(gid) = tok.to_global_id() else {
4039                return false;
4040            };
4041            chars.push(DcChar::from_u128(gid));
4042        }
4043        let stripped = crate::stagel3::dc_tokens::strip_comment_frames(&chars);
4044        let Some(first) = stripped.first().copied() else {
4045            return false;
4046        };
4047        let u = first.to_u128();
4048        self.token_fills_canonical_or_equiv_role(u, crate::syntax::DcRole::BeginModule)
4049            || self.token_fills_canonical_or_equiv_role(
4050                u,
4051                crate::syntax::DcRole::BeginStagerModule,
4052            )
4053            || self.token_fills_canonical_or_equiv_role(
4054                u,
4055                crate::syntax::DcRole::BeginRoutineDecl,
4056            )
4057            || self.token_fills_canonical_or_equiv_role(
4058                u,
4059                crate::syntax::DcRole::BeginRoutine,
4060            )
4061            || self.token_fills_canonical_or_equiv_role(
4062                u,
4063                crate::syntax::DcRole::BeginPositionalStructDecl,
4064            )
4065            || self.token_fills_canonical_or_equiv_role(
4066                u,
4067                crate::syntax::DcRole::DeclareBrandType,
4068            )
4069            || self.token_fills_canonical_or_equiv_role(
4070                u,
4071                crate::syntax::DcRole::BeginNamedStructDecl,
4072            )
4073            || self.token_fills_canonical_or_equiv_role(
4074                u,
4075                crate::syntax::DcRole::BeginEnumDecl,
4076            )
4077            || self.token_fills_canonical_or_equiv_role(u, crate::syntax::DcRole::DeclarePub)
4078            || self.token_fills_canonical_or_equiv_role(u, crate::syntax::DcRole::DeclareConst)
4079    }
4080
4081    pub(crate) fn token_fills_canonical_or_equiv_role(
4082        &self,
4083        token: u128,
4084        role: crate::syntax::DcRole,
4085    ) -> bool {
4086        if role.matches_canonical(token) {
4087            return true;
4088        }
4089        let eq_verb = sh(crate::dc::DC_IS_EQUAL_TO);
4090        let start = DcShorthand::from_global_id(token);
4091        let mut visited = HashSet::new();
4092        visited.insert(start);
4093        let mut stack = vec![start];
4094        while let Some(cur) = stack.pop() {
4095            if let Some(objs) =
4096                self.direct_objects_by_verb_subj.get(&(eq_verb, cur))
4097            {
4098                for &partner in objs {
4099                    if visited.insert(partner) {
4100                        if partner
4101                            .to_global_id()
4102                            .is_ok_and(|gid| role.matches_canonical(gid))
4103                        {
4104                            return true;
4105                        }
4106                        stack.push(partner);
4107                    }
4108                }
4109            }
4110            if let Some(subjs) =
4111                self.direct_subjects_by_verb_obj.get(&(eq_verb, cur))
4112            {
4113                for &partner in subjs {
4114                    if visited.insert(partner) {
4115                        if partner
4116                            .to_global_id()
4117                            .is_ok_and(|gid| role.matches_canonical(gid))
4118                        {
4119                            return true;
4120                        }
4121                        stack.push(partner);
4122                    }
4123                }
4124            }
4125        }
4126        false
4127    }
4128
4129    /// Resolves `subj` (`DcShorthand::Long`, `Short`, or `Format`) to its active StageL 3
4130    /// Token-Dc decomposition (`(value_node_id, expanded_dc_chars)`) in this snapshot via
4131    /// `Dc 611 "Canonical decomposition"`, `Dc 571 "Decomposition"`, or
4132    /// `Dc 614 "Semantic decomposition"`.
4133    ///
4134    /// # Errors
4135    /// Returns an error if `subj` or its StageL decomposition target node was retracted in this
4136    /// snapshot (`Dc 592 "Retracts"`), references an unsupported graph block, or exceeds the
4137    /// pinned System graph snapshot (`Dc 641`).
4138    pub fn resolve_stagel_decomposition_tokens(
4139        &self,
4140        subj: DcShorthand,
4141    ) -> Result<Option<(u128, Vec<DcChar>)>> {
4142        if let DcShorthand::Long(subj_id) = subj {
4143            if let Some(block_desc) =
4144                ctb_storage_minimal::global_graph_layout::unsupported_graph_block_description(
4145                    subj_id,
4146                )
4147            {
4148                bail!(
4149                    "Graph StageL entity {subj} references unsupported graph block ({block_desc})"
4150                );
4151            }
4152            if let Some(pin_id) = self.system_block_most_recent_node_id
4153                && subj_id > pin_id
4154            {
4155                bail!(
4156                    "Graph StageL entity {subj} exceeds pinned System graph snapshot l{pin_id}"
4157                );
4158            }
4159            if self.retracted_by(subj_id).is_some() {
4160                bail!(
4161                    "Graph StageL entity {subj} was retracted in the active System graph snapshot"
4162                );
4163            }
4164        }
4165
4166        for prop_dc in [
4167            DC_CANONICAL_DECOMPOSITION,
4168            DC_DECOMPOSITION,
4169            DC_SEMANTIC_DECOMPOSITION,
4170        ] {
4171            for entry in self.get_multi_properties(subj, sh(prop_dc)) {
4172                if !self
4173                    .get_direct_objects(
4174                        sh(DC_IN_CONTEXT_OF),
4175                        DcShorthand::Long(entry.has_a_id),
4176                    )
4177                    .is_empty()
4178                {
4179                    continue;
4180                }
4181                if let DcShorthand::Long(node_id) = entry.value {
4182                    if let Some(block_desc) =
4183                        ctb_storage_minimal::global_graph_layout::unsupported_graph_block_description(
4184                            node_id,
4185                        )
4186                    {
4187                        bail!(
4188                            "Graph StageL item {subj} target l{node_id} references unsupported graph block ({block_desc})"
4189                        );
4190                    }
4191                    if let Some(pin_id) = self.system_block_most_recent_node_id
4192                        && node_id > pin_id
4193                    {
4194                        bail!(
4195                            "Graph StageL item {subj} target l{node_id} exceeds pinned System graph snapshot l{pin_id}"
4196                        );
4197                    }
4198                    if let Some(node) = self.get_active_node(node_id) {
4199                        if let Some(pin_id) =
4200                            self.system_block_most_recent_node_id
4201                            && node.id > pin_id
4202                        {
4203                            bail!(
4204                                "Graph StageL item {subj} target l{} exceeds pinned System graph snapshot l{pin_id}",
4205                                node.id
4206                            );
4207                        }
4208                        if self.tokens_are_stagel_item_or_module(&node.tokens) {
4209                            let expanded =
4210                                self.expand_interned_string_nodes(&node.tokens);
4211                            let mut dc_chars =
4212                                Vec::with_capacity(expanded.len());
4213                            for tok in expanded {
4214                                let gid = tok.to_global_id().with_context(
4215                                    || {
4216                                        format!(
4217                                            "Invalid DcShorthand token {tok} inside StageL decomposition l{}",
4218                                            node.id
4219                                        )
4220                                    },
4221                                )?;
4222                                dc_chars.push(DcChar::from_u128(gid));
4223                            }
4224                            return Ok(Some((node.id, dc_chars)));
4225                        }
4226                    } else if self.retracted_by(node_id).is_some() {
4227                        bail!(
4228                            "Graph StageL item {subj} target node l{node_id} was retracted in the active System graph snapshot"
4229                        );
4230                    }
4231                }
4232            }
4233        }
4234
4235        if let DcShorthand::Long(subj_id) = subj
4236            && let Some(node) = self.get_active_node(subj_id)
4237            && self.tokens_are_stagel_item_or_module(&node.tokens)
4238        {
4239            let expanded = self.expand_interned_string_nodes(&node.tokens);
4240            let mut dc_chars = Vec::with_capacity(expanded.len());
4241            for tok in expanded {
4242                let gid = tok.to_global_id().with_context(|| {
4243                    format!(
4244                        "Invalid DcShorthand token {tok} inside StageL value node l{}",
4245                        node.id
4246                    )
4247                })?;
4248                dc_chars.push(DcChar::from_u128(gid));
4249            }
4250            return Ok(Some((node.id, dc_chars)));
4251        }
4252
4253        if let Some(stmt_ids) = self.subject_all_stmt_ids.get(&subj) {
4254            for &stmt_id in stmt_ids {
4255                let Some(stmt_node) = self.get_node(stmt_id) else {
4256                    continue;
4257                };
4258                let Some((verb, _, obj)) =
4259                    parse_statement_tokens(&stmt_node.tokens)
4260                else {
4261                    continue;
4262                };
4263                if verb == sh(DC_HAS_A)
4264                    && (obj == sh(DC_CANONICAL_DECOMPOSITION)
4265                        || obj == sh(DC_DECOMPOSITION)
4266                        || obj == sh(DC_SEMANTIC_DECOMPOSITION))
4267                    && !self.has_any_context_qualifier(stmt_id)
4268                    && let Some(has_vals) =
4269                        self.has_val_stmt_ids_by_has_a.get(&stmt_id)
4270                {
4271                    for &(has_val_id, val_tok) in has_vals {
4272                        if let DcShorthand::Long(target_id) = val_tok {
4273                            let is_stagel_target =
4274                                self.get_node(target_id).is_some_and(|n| {
4275                                    self.tokens_are_stagel_item_or_module(
4276                                        &n.tokens,
4277                                    )
4278                                });
4279                            if is_stagel_target
4280                                && (self.retracted_by(stmt_id).is_some()
4281                                    || self.retracted_by(has_val_id).is_some()
4282                                    || self.retracted_by(target_id).is_some()
4283                                    || self.inactive_ids.contains(&stmt_id)
4284                                    || self.inactive_ids.contains(&has_val_id)
4285                                    || self.inactive_ids.contains(&target_id))
4286                            {
4287                                bail!(
4288                                    "Graph StageL item {subj} (or target node l{target_id}) was retracted in the active System graph snapshot"
4289                                );
4290                            }
4291                        }
4292                    }
4293                }
4294            }
4295        }
4296
4297        Ok(None)
4298    }
4299
4300    /// Resolves all active `pub` StageL symbols exported in `ns_segments` (`f229` `"File path"`
4301    /// context on `Dc 574 "Programmatic identifier"`), returning a deterministic map of
4302    /// `export_name -> Vec<subject_dc_shorthand>` (supporting fixed-arity parameter-type
4303    /// routine overloads and typed constant overloads within the same namespace).
4304    pub fn resolve_stagel_namespace_exports(
4305        &self,
4306        ns_segments: &[String],
4307    ) -> Result<BTreeMap<String, Vec<DcShorthand>>> {
4308        let expected_fp_chars =
4309            crate::stagel3::dc_tokens::encode_filepath_dc_tokens(ns_segments)?;
4310        let expected_fp_shorthands: Vec<DcShorthand> = expected_fp_chars
4311            .iter()
4312            .map(|c| DcShorthand::from_global_id(c.to_u128()))
4313            .collect();
4314
4315        let sh_prog_ident = sh(DC_PROGRAMMATIC_IDENTIFIER);
4316        let sh_in_ctx = sh(DC_IN_CONTEXT_OF);
4317        let mut exports: BTreeMap<String, Vec<DcShorthand>> = BTreeMap::new();
4318
4319        for (&(subj, prop), &(has_a_id, _, val_tok)) in
4320            &self.active_single_props
4321        {
4322            if prop != sh_prog_ident {
4323                continue;
4324            }
4325            let ctx_objs = self
4326                .get_direct_objects(sh_in_ctx, DcShorthand::Long(has_a_id));
4327            let matches_ns = ctx_objs.iter().any(|&ctx_obj| {
4328                let DcShorthand::Long(ctx_id) = ctx_obj else {
4329                    return false;
4330                };
4331                self.get_active_node(ctx_id).is_some_and(|ctx_node| {
4332                    self.expand_interned_string_nodes(&ctx_node.tokens)
4333                        == expected_fp_shorthands
4334                })
4335            });
4336            if !matches_ns {
4337                continue;
4338            }
4339            if let DcShorthand::Long(subj_id) = subj {
4340                if let Some(block_desc) =
4341                    ctb_storage_minimal::global_graph_layout::unsupported_graph_block_description(
4342                        subj_id,
4343                    )
4344                {
4345                    bail!(
4346                        "StageL export subject {subj} in namespace '{}' references unsupported graph block ({block_desc})",
4347                        ns_segments.join("/")
4348                    );
4349                }
4350                if let Some(pin_id) = self.system_block_most_recent_node_id
4351                    && subj_id > pin_id
4352                {
4353                    bail!(
4354                        "StageL export subject {subj} in namespace '{}' exceeds pinned System graph snapshot l{pin_id}",
4355                        ns_segments.join("/")
4356                    );
4357                }
4358            }
4359            let DcShorthand::Long(str_id) = val_tok else {
4360                continue;
4361            };
4362            let Some(ident_name) = self.string_by_node_id.get(&str_id) else {
4363                continue;
4364            };
4365            let list = exports.entry(ident_name.clone()).or_default();
4366            if !list.contains(&subj) {
4367                list.push(subj);
4368            }
4369        }
4370
4371        for list in exports.values_mut() {
4372            list.sort();
4373        }
4374
4375        Ok(exports)
4376    }
4377
4378    /// Resolves the declared PSR-4 StageL/StageR namespace segments (`f229` `"File path"`
4379    /// context on `Dc 574 "Programmatic identifier"`) for an exported StageL/StageR entity
4380    /// `subj`, returning `Ok(None)` when `subj` has no `FilePath`-contextualized programmatic
4381    /// identifier in the active snapshot.
4382    pub fn resolve_stagel_entity_namespace(
4383        &self,
4384        subj: DcShorthand,
4385    ) -> Result<Option<Vec<String>>> {
4386        if let DcShorthand::Long(subj_id) = subj {
4387            if let Some(block_desc) =
4388                ctb_storage_minimal::global_graph_layout::unsupported_graph_block_description(
4389                    subj_id,
4390                )
4391            {
4392                bail!(
4393                    "Graph StageL entity {subj} references unsupported graph block ({block_desc})"
4394                );
4395            }
4396            if let Some(pin_id) = self.system_block_most_recent_node_id
4397                && subj_id > pin_id
4398            {
4399                bail!(
4400                    "Graph StageL entity {subj} exceeds pinned System graph snapshot l{pin_id}"
4401                );
4402            }
4403        }
4404        let sh_prog_ident = sh(DC_PROGRAMMATIC_IDENTIFIER);
4405        let sh_in_ctx = sh(DC_IN_CONTEXT_OF);
4406        let Some(&(has_a_id, _, _)) =
4407            self.active_single_props.get(&(subj, sh_prog_ident))
4408        else {
4409            return Ok(None);
4410        };
4411        let ctx_objs =
4412            self.get_direct_objects(sh_in_ctx, DcShorthand::Long(has_a_id));
4413        for &ctx_obj in ctx_objs {
4414            let DcShorthand::Long(ctx_id) = ctx_obj else {
4415                continue;
4416            };
4417            let Some(ctx_node) = self.get_active_node(ctx_id) else {
4418                continue;
4419            };
4420            let expanded = self.expand_interned_string_nodes(&ctx_node.tokens);
4421            let mut dc_chars = Vec::with_capacity(expanded.len());
4422            let mut all_valid = true;
4423            for tok in expanded {
4424                if let Ok(gid) = tok.to_global_id() {
4425                    dc_chars.push(DcChar::from_u128(gid));
4426                } else {
4427                    all_valid = false;
4428                    break;
4429                }
4430            }
4431            if all_valid
4432                && let Ok(segs) =
4433                    crate::stagel3::dc_tokens::decode_filepath_dc_tokens(
4434                        &dc_chars,
4435                    )
4436            {
4437                return Ok(Some(segs));
4438            }
4439        }
4440        Ok(None)
4441    }
4442
4443    /// Resolves decoupled non-executable metadata (`is_pub`, `Dc 574` name, home namespace
4444    /// via `Dc 646` or `Dc 598`, `Dc 573` description, and `Dc 1942` test suite tokens)
4445    /// attached to a StageL/StageR routine entity or direct `Dc 2240..2241` value node `subj`.
4446    pub fn resolve_stagel_routine_metadata(
4447        &self,
4448        subj: DcShorthand,
4449    ) -> Result<StagelRoutineGraphMeta> {
4450        let sh_prog_ident = sh(DC_PROGRAMMATIC_IDENTIFIER);
4451        let sh_desc = sh(DC_DESCRIPTION);
4452        let sh_assoc = sh(DC_IS_ASSOCIATED_WITH);
4453        let sh_suite = sh(DC_ROUTINE_TEST_SUITE);
4454        let sh_in_ctx = sh(DC_IN_CONTEXT_OF);
4455
4456        let exported_ns = self.resolve_stagel_entity_namespace(subj)?;
4457        let is_direct_value_node = match subj {
4458            DcShorthand::Long(id) => !self.entity_class_by_id.contains_key(&id),
4459            _ => false,
4460        };
4461        let is_pub = matches!(subj, DcShorthand::Short(_) | DcShorthand::Format(_))
4462            || exported_ns.is_some()
4463            || is_direct_value_node;
4464
4465        let name = self
4466            .active_single_props
4467            .get(&(subj, sh_prog_ident))
4468            .and_then(|&(_, _, val_tok)| match val_tok {
4469                DcShorthand::Long(str_id) => {
4470                    self.string_by_node_id.get(&str_id).cloned()
4471                }
4472                _ => None,
4473            });
4474
4475        let home_namespace = if let Some(ns) = exported_ns {
4476            Some(ns)
4477        } else {
4478            let mut found_ns = None;
4479            for &assoc_obj in self.get_direct_objects(sh_assoc, subj) {
4480                let DcShorthand::Long(ctx_id) = assoc_obj else {
4481                    continue;
4482                };
4483                let Some(ctx_node) = self.get_active_node(ctx_id) else {
4484                    continue;
4485                };
4486                let expanded =
4487                    self.expand_interned_string_nodes(&ctx_node.tokens);
4488                let mut dc_chars = Vec::with_capacity(expanded.len());
4489                let mut all_valid = true;
4490                for tok in expanded {
4491                    if let Ok(gid) = tok.to_global_id() {
4492                        dc_chars.push(DcChar::from_u128(gid));
4493                    } else {
4494                        all_valid = false;
4495                        break;
4496                    }
4497                }
4498                if all_valid
4499                    && let Ok(segs) =
4500                        crate::stagel3::dc_tokens::decode_filepath_dc_tokens(
4501                            &dc_chars,
4502                        )
4503                {
4504                    found_ns = Some(segs);
4505                    break;
4506                }
4507            }
4508            found_ns
4509        };
4510
4511        let description = if matches!(subj, DcShorthand::Long(_)) {
4512            self.active_single_props
4513                .get(&(subj, sh_desc))
4514                .and_then(|&(_, _, val_tok)| match val_tok {
4515                    DcShorthand::Long(str_id) => {
4516                        self.string_by_node_id.get(&str_id).cloned()
4517                    }
4518                    _ => None,
4519                })
4520        } else {
4521            None
4522        };
4523
4524        let mut test_suite_tokens = None;
4525        for entry in self.get_multi_properties(subj, sh_suite) {
4526            if !self
4527                .get_direct_objects(sh_in_ctx, DcShorthand::Long(entry.has_a_id))
4528                .is_empty()
4529            {
4530                continue;
4531            }
4532            if let DcShorthand::Long(node_id) = entry.value {
4533                if let Some(pin_id) = self.system_block_most_recent_node_id
4534                    && node_id > pin_id
4535                {
4536                    continue;
4537                }
4538                if let Some(node) = self.get_active_node(node_id) {
4539                    let expanded =
4540                        self.expand_interned_string_nodes(&node.tokens);
4541                    let mut dc_chars = Vec::with_capacity(expanded.len());
4542                    for tok in expanded {
4543                        let gid = tok.to_global_id().with_context(|| {
4544                            format!(
4545                                "Invalid DcShorthand token {tok} inside routine test suite l{}",
4546                                node.id
4547                            )
4548                        })?;
4549                        dc_chars.push(DcChar::from_u128(gid));
4550                    }
4551                    test_suite_tokens = Some(dc_chars);
4552                    break;
4553                }
4554            }
4555        }
4556
4557        Ok(StagelRoutineGraphMeta {
4558            is_pub,
4559            name,
4560            home_namespace,
4561            description,
4562            test_suite_tokens,
4563        })
4564    }
4565
4566    /// Returns `true` if `source` is a trusted Collective Toolbox seed graph provenance source:
4567    /// `Dc 636 "Collective Toolbox Dc CSV seed database"` or `Dc 637 "Manual entry"`.
4568    #[must_use]
4569    pub fn is_trusted_seed_graph_data_source(source: DcShorthand) -> bool {
4570        source == sh(DC_COLLECTIVE_TOOLBOX_DC_CSV_SEED_DATABASE)
4571            || source == sh(DC_MANUAL_ENTRY)
4572    }
4573
4574    /// Returns `true` if `node_id` originated from the host-authenticated bundled asset
4575    /// (`ctoolbox.rsrc` / `system_graph_history.rsrc`).
4576    #[must_use]
4577    pub fn is_bundled_origin_node(&self, node_id: u128) -> bool {
4578        self.bundled_origin_node_ids.contains(&node_id)
4579    }
4580
4581    /// Verifies that `node_id` resides in the System block (`8_589_934_592..=17_179_869_183`),
4582    /// originated from the host-authenticated bundled asset (`ctoolbox.rsrc` /
4583    /// `system_graph_history.rsrc`), and carries verified `Dc 635`
4584    /// (`"Collective Toolbox seed graph data source"`) provenance (`Dc 636` or `Dc 637`)
4585    /// asserted by bundled System-block provenance statements.
4586    ///
4587    /// # Errors
4588    /// Returns an error if `node_id` is outside the System block, missing from the index,
4589    /// from an extra/unbundled resource, missing `Dc 635` provenance, or associated with an
4590    /// untrusted or unbundled `Dc 635` provenance statement.
4591    pub fn verify_authenticated_bundled_system_provenance(
4592        &self,
4593        node_id: u128,
4594    ) -> Result<()> {
4595        ensure!(
4596            (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&node_id),
4597            "Node l{node_id} is outside the System block ({SYSTEM_REGION_START}..={SYSTEM_REGION_END}) and cannot supply bootstrap or supervisor authority"
4598        );
4599        ensure!(
4600            self.node_index_by_id.contains_key(&node_id),
4601            "System node l{node_id} is not present in the loaded seed graph"
4602        );
4603        ensure!(
4604            self.bundled_origin_node_ids.contains(&node_id),
4605            "Node l{node_id} did not originate from the authenticated bundled System asset (ctoolbox.rsrc); extra or unbundled resources cannot supply bootstrap authority"
4606        );
4607
4608        if self.provenance_stmt_ids.contains(&node_id) {
4609            if let Some(assertions) = self.node_provenance_assertions.get(&node_id)
4610            {
4611                for &(has_a_id, has_val_id, source_tok) in assertions {
4612                    ensure!(
4613                        (SYSTEM_REGION_START..=SYSTEM_REGION_END)
4614                            .contains(&has_a_id)
4615                            && (SYSTEM_REGION_START..=SYSTEM_REGION_END)
4616                                .contains(&has_val_id),
4617                        "Provenance statement for l{node_id} (l{has_a_id} / l{has_val_id}) is outside the System block"
4618                    );
4619                    ensure!(
4620                        self.bundled_origin_node_ids.contains(&has_a_id)
4621                            && self.bundled_origin_node_ids.contains(&has_val_id),
4622                        "Provenance statement for l{node_id} (l{has_a_id} / l{has_val_id}) did not originate from the authenticated bundled asset"
4623                    );
4624                    ensure!(
4625                        Self::is_trusted_seed_graph_data_source(source_tok),
4626                        "Provenance statement for l{node_id} declares untrusted data source {source_tok} (expected Dc 636 or Dc 637)"
4627                    );
4628                }
4629            }
4630            return Ok(());
4631        }
4632
4633        let Some(assertions) = self.node_provenance_assertions.get(&node_id)
4634        else {
4635            bail!(
4636                "System node l{node_id} has no active Dc 635 (Collective Toolbox seed graph data source) provenance assertion"
4637            );
4638        };
4639        ensure!(
4640            !assertions.is_empty(),
4641            "System node l{node_id} has no active Dc 635 (Collective Toolbox seed graph data source) provenance assertion"
4642        );
4643        for &(has_a_id, has_val_id, source_tok) in assertions {
4644            ensure!(
4645                (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&has_a_id)
4646                    && (SYSTEM_REGION_START..=SYSTEM_REGION_END)
4647                        .contains(&has_val_id),
4648                "Provenance statement for System node l{node_id} (l{has_a_id} / l{has_val_id}) is outside the System block"
4649            );
4650            ensure!(
4651                self.bundled_origin_node_ids.contains(&has_a_id)
4652                    && self.bundled_origin_node_ids.contains(&has_val_id),
4653                "Provenance statement for System node l{node_id} (l{has_a_id} / l{has_val_id}) did not originate from the authenticated bundled asset"
4654            );
4655            ensure!(
4656                Self::is_trusted_seed_graph_data_source(source_tok),
4657                "System node l{node_id} has untrusted Dc 635 data source {source_tok} (expected Dc 636 or Dc 637)"
4658            );
4659        }
4660        Ok(())
4661    }
4662
4663    /// Verifies that `node_id` and every `Dc 591 "Supersedes"` / `Dc 592 "Retracts"` statement
4664    /// along its revision chain satisfy [`Self::verify_authenticated_bundled_system_provenance`].
4665    pub fn verify_node_supersession_and_retraction_chain(
4666        &self,
4667        node_id: u128,
4668    ) -> Result<()> {
4669        let mut current = node_id;
4670        let mut visited = HashSet::new();
4671        loop {
4672            if !visited.insert(current) {
4673                bail!(
4674                    "Detected supersession cycle while verifying provenance chain starting at l{node_id}"
4675                );
4676            }
4677            self.verify_authenticated_bundled_system_provenance(current)?;
4678            if let Some(&retract_stmt_id) = self.retracted_by.get(&current) {
4679                self.verify_authenticated_bundled_system_provenance(
4680                    retract_stmt_id,
4681                )
4682                .with_context(|| {
4683                    format!(
4684                        "Untrusted or unbundled Dc 592 retraction statement l{retract_stmt_id} targeting l{current}"
4685                    )
4686                })?;
4687            }
4688            if let Some(&sup_stmt_id) =
4689                self.superseding_stmt_by_old_id.get(&current)
4690            {
4691                self.verify_authenticated_bundled_system_provenance(
4692                    sup_stmt_id,
4693                )
4694                .with_context(|| {
4695                    format!(
4696                        "Untrusted or unbundled Dc 591 supersession statement l{sup_stmt_id} targeting l{current}"
4697                    )
4698                })?;
4699            }
4700            if let Some(&next_id) = self.superseded_by.get(&current) {
4701                current = next_id;
4702            } else {
4703                break;
4704            }
4705        }
4706        Ok(())
4707    }
4708
4709    /// Verifies that every statement (active or historical) touching `subj`, together with all
4710    /// `Dc 610 "Has value"` value statements and `Dc 591 "Supersedes"` / `Dc 592 "Retracts"`
4711    /// statements on those chains, satisfies [`Self::verify_authenticated_bundled_system_provenance`].
4712    pub fn verify_subject_provenance_and_history(
4713        &self,
4714        subj: DcShorthand,
4715    ) -> Result<()> {
4716        if let Some(stmt_ids) = self.subject_all_stmt_ids.get(&subj) {
4717            for &stmt_id in stmt_ids {
4718                self.verify_node_supersession_and_retraction_chain(stmt_id)
4719                    .with_context(|| {
4720                        format!(
4721                            "Statement l{stmt_id} on subject {subj} failed bundled System provenance verification"
4722                        )
4723                    })?;
4724                if let Some(has_vals) =
4725                    self.has_val_stmt_ids_by_has_a.get(&stmt_id)
4726                {
4727                    for &(has_val_id, _) in has_vals {
4728                        self.verify_node_supersession_and_retraction_chain(
4729                            has_val_id,
4730                        )
4731                        .with_context(|| {
4732                            format!(
4733                                "Value statement l{has_val_id} on statement l{stmt_id} (subject {subj}) failed bundled System provenance verification"
4734                            )
4735                        })?;
4736                    }
4737                }
4738            }
4739        }
4740        Ok(())
4741    }
4742
4743    fn resolve_active_wasm_definition_entry(
4744        &self,
4745        subj: DcShorthand,
4746    ) -> Option<(u128, u128, u128, Vec<DcShorthand>)> {
4747        let mut visited = HashSet::new();
4748        self.resolve_active_wasm_definition_entry_inner(subj, &mut visited)
4749    }
4750
4751    fn resolve_active_wasm_definition_entry_inner(
4752        &self,
4753        subj: DcShorthand,
4754        visited: &mut HashSet<DcShorthand>,
4755    ) -> Option<(u128, u128, u128, Vec<DcShorthand>)> {
4756        if !visited.insert(subj) {
4757            return None;
4758        }
4759        for prop_dc in [
4760            DC_CANONICAL_DECOMPOSITION,
4761            DC_DECOMPOSITION,
4762            DC_SEMANTIC_DECOMPOSITION,
4763            DC_APPROXIMATE_DECOMPOSITION,
4764        ] {
4765            for entry in self.get_multi_properties(subj, sh(prop_dc)) {
4766                if let DcShorthand::Long(def_id) = entry.value
4767                    && let Some(resolved_def_id) =
4768                        self.resolve_latest_node_id(def_id)
4769                    && let Some(node) = self.get_node(resolved_def_id)
4770                    && self.tokens_are_wasm_helper_or_definition(&node.tokens)
4771                {
4772                    return Some((
4773                        entry.has_a_id,
4774                        entry.has_val_id,
4775                        resolved_def_id,
4776                        node.tokens.clone(),
4777                    ));
4778                }
4779            }
4780        }
4781
4782        if let Some(rule_entry) =
4783            self.get_single_property_entry(subj, sh(DC_SYNTAX_RULE))
4784            && let DcShorthand::Long(rule_node_id) = rule_entry.value
4785            && let Some(resolved_rule_node_id) =
4786                self.resolve_latest_node_id(rule_node_id)
4787            && let Some(rule_node) = self.get_node(resolved_rule_node_id)
4788        {
4789            let rule_tokens = rule_node.tokens.as_slice();
4790            let sh_open = sh(DC_BEGIN_ASSOCIATIVITY_GROUP);
4791            let sh_close = sh(DC_END_ASSOCIATIVITY_GROUP);
4792            let sh_repl = sh(DC_PATTERN_REPLACEMENT);
4793            if rule_tokens.last() == Some(&sh_close) {
4794                let mut depth = 0usize;
4795                let mut open_idx = None;
4796                for (idx, &tok) in rule_tokens.iter().enumerate().rev() {
4797                    if tok == sh_close {
4798                        depth = depth.saturating_add(1);
4799                    } else if tok == sh_open {
4800                        depth = depth.saturating_sub(1);
4801                        if depth == 0 {
4802                            open_idx = Some(idx);
4803                            break;
4804                        }
4805                    }
4806                }
4807                if let Some(start) = open_idx
4808                    && let Some(group_slice) = rule_tokens.get(start..)
4809                    && group_slice.get(1) == Some(&sh_repl)
4810                    && let Some(inner) =
4811                        group_slice.get(2..group_slice.len().saturating_sub(1))
4812                    && self.tokens_are_wasm_helper_or_definition(inner)
4813                {
4814                    if inner.len() == 1
4815                        && let Some(&DcShorthand::Long(target_id)) =
4816                            inner.first()
4817                        && let Some(resolved_target_id) =
4818                            self.resolve_latest_node_id(target_id)
4819                        && let Some(node) = self.get_node(resolved_target_id)
4820                    {
4821                        return Some((
4822                            rule_entry.has_a_id,
4823                            rule_entry.has_val_id,
4824                            resolved_target_id,
4825                            node.tokens.clone(),
4826                        ));
4827                    }
4828                    return Some((
4829                        rule_entry.has_a_id,
4830                        rule_entry.has_val_id,
4831                        resolved_rule_node_id,
4832                        inner.to_vec(),
4833                    ));
4834                }
4835            }
4836        }
4837
4838        for &base_tok in self.get_direct_objects(sh(DC_IS_BASED_ON), subj) {
4839            if matches!(base_tok, DcShorthand::Short(_) | DcShorthand::Format(_))
4840                && let Some(entry) = self
4841                    .resolve_active_wasm_definition_entry_inner(
4842                        base_tok, visited,
4843                    )
4844            {
4845                return Some(entry);
4846            }
4847        }
4848        None
4849    }
4850
4851    /// Resolves an unpinned 1-Short-Dc bootstrap entry document (`bootstrap_tokens`) to its
4852    /// latest trusted System-block definition from the application-bundled trusted base (`ctoolbox.rsrc`).
4853    ///
4854    /// # Errors
4855    /// Returns an error if `bootstrap_tokens` is empty, begins with a `Dc 641` pin, contains
4856    /// multiple tokens or a non-Short Dc, or if any statement, supersession/retraction chain,
4857    /// or transitive dependency fails authenticated bundled System provenance verification.
4858    pub fn resolve_trusted_system_supervisor_bootstrap_tokens(
4859        &self,
4860        bootstrap_tokens: &[DcShorthand],
4861    ) -> Result<TrustedSystemSupervisorResolution> {
4862        let Some(&first) = bootstrap_tokens.first() else {
4863            bail!(
4864                "System supervisor bootstrap entry document cannot be empty (expected 1 unpinned Short Dc)"
4865            );
4866        };
4867        if first
4868            == sh(DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID)
4869        {
4870            bail!(
4871                "System supervisor bootstrap entry document must be unpinned; Dc 641 (Global graph system block most recent node ID at time of document creation) pin is not permitted"
4872            );
4873        }
4874        ensure!(
4875            bootstrap_tokens.len() == 1,
4876            "System supervisor bootstrap entry document must consist of exactly 1 unpinned Short Dc, found {} tokens",
4877            bootstrap_tokens.len()
4878        );
4879        let DcShorthand::Short(short_id) = first else {
4880            bail!(
4881                "System supervisor bootstrap entry document must be a Short Dc, found {first}"
4882            );
4883        };
4884        self.resolve_trusted_system_supervisor_dc(DcChar::from_short(short_id))
4885    }
4886
4887    /// Resolves the unpinned Short Dc `entry_dc` to its latest active System-block supervisor
4888    /// definition, verifying authenticated bundled-origin statement provenance (`ctoolbox.rsrc` +
4889    /// trusted `Dc 635` = `Dc 636` or `Dc 637`) across the entry character's statements,
4890    /// supersession (`Dc 591`) and retraction (`Dc 592`) chains, and all transitive dependencies.
4891    pub fn resolve_trusted_system_supervisor_dc(
4892        &self,
4893        entry_dc: DcChar,
4894    ) -> Result<TrustedSystemSupervisorResolution> {
4895        ensure!(
4896            matches!(sh(entry_dc), DcShorthand::Short(_)),
4897            "System supervisor entry Dc must be a Short Dc, found {entry_dc}"
4898        );
4899        ensure!(
4900            entry_dc != DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID,
4901            "Dc 641 (Global graph system block most recent node ID at time of document creation) cannot be used as the System supervisor entry Dc"
4902        );
4903        let system_head_node_id = self
4904            .system_block_most_recent_node_id()
4905            .context("System seed graph has no allocated System-block HEAD node ID")?;
4906        ensure!(
4907            (SYSTEM_REGION_START..=SYSTEM_REGION_END)
4908                .contains(&system_head_node_id),
4909            "System seed graph HEAD l{system_head_node_id} is outside the System block"
4910        );
4911
4912        let subj = sh(entry_dc);
4913        let mut base_cur = subj;
4914        let mut base_visited = HashSet::new();
4915        while base_visited.insert(base_cur) {
4916            self.verify_subject_provenance_and_history(base_cur)?;
4917            if let Some(&next_base) =
4918                self.get_direct_objects(sh(DC_IS_BASED_ON), base_cur).first()
4919            {
4920                base_cur = next_base;
4921            } else {
4922                break;
4923            }
4924        }
4925
4926        let (
4927            statement_node_id,
4928            value_statement_node_id,
4929            supervisor_revision_node_id,
4930            definition_tokens,
4931        ) = self
4932            .resolve_active_wasm_definition_entry(subj)
4933            .with_context(|| {
4934                format!(
4935                    "No active System-block WASM supervisor definition found for {entry_dc}"
4936                )
4937            })?;
4938
4939        self.verify_node_supersession_and_retraction_chain(statement_node_id)?;
4940        self.verify_node_supersession_and_retraction_chain(
4941            value_statement_node_id,
4942        )?;
4943        self.verify_node_supersession_and_retraction_chain(
4944            supervisor_revision_node_id,
4945        )?;
4946
4947        // Traverse and verify all transitive dependencies reachable from the supervisor definition.
4948        let mut dependency_set = std::collections::BTreeSet::new();
4949        let mut queue = std::collections::VecDeque::new();
4950        let mut visited_subjects = HashSet::new();
4951        visited_subjects.insert(subj);
4952        queue.push_back(supervisor_revision_node_id);
4953
4954        while let Some(node_id) = queue.pop_front() {
4955            if !dependency_set.insert(node_id) {
4956                continue;
4957            }
4958            self.verify_node_supersession_and_retraction_chain(node_id)
4959                .with_context(|| {
4960                    format!(
4961                        "Transitive supervisor dependency node l{node_id} failed bundled System provenance verification"
4962                    )
4963                })?;
4964            let resolved_id = self
4965                .resolve_latest_node_id(node_id)
4966                .with_context(|| {
4967                    format!(
4968                        "Transitive supervisor dependency node l{node_id} is retracted or unresolvable"
4969                    )
4970                })?;
4971            if resolved_id != node_id && dependency_set.insert(resolved_id) {
4972                self.verify_node_supersession_and_retraction_chain(resolved_id)?;
4973            }
4974            let node = self.get_node(resolved_id).with_context(|| {
4975                format!(
4976                    "Transitive supervisor dependency node l{resolved_id} is missing from seed graph"
4977                )
4978            })?;
4979            for &tok in &node.tokens {
4980                if let DcShorthand::Long(dep_id) = tok {
4981                    ensure!(
4982                        (SYSTEM_REGION_START..=SYSTEM_REGION_END)
4983                            .contains(&dep_id),
4984                        "Supervisor definition node l{resolved_id} references non-System node l{dep_id}"
4985                    );
4986                    if !dependency_set.contains(&dep_id) {
4987                        queue.push_back(dep_id);
4988                    }
4989                }
4990                if visited_subjects.insert(tok)
4991                    && let Some((dep_stmt_id, dep_val_id, dep_def_id, _)) =
4992                        self.resolve_active_wasm_definition_entry(tok)
4993                {
4994                    self.verify_subject_provenance_and_history(tok)?;
4995                    self.verify_node_supersession_and_retraction_chain(
4996                        dep_stmt_id,
4997                    )?;
4998                    self.verify_node_supersession_and_retraction_chain(
4999                        dep_val_id,
5000                    )?;
5001                    if !dependency_set.contains(&dep_def_id) {
5002                        queue.push_back(dep_def_id);
5003                    }
5004                }
5005            }
5006        }
5007
5008        Ok(TrustedSystemSupervisorResolution {
5009            entry_dc,
5010            statement_node_id,
5011            value_statement_node_id,
5012            supervisor_revision_node_id,
5013            system_head_node_id,
5014            dependency_snapshot_node_ids: dependency_set.into_iter().collect(),
5015            definition_tokens,
5016        })
5017    }
5018
5019    fn resolve_active_decomposition_defining_node_id(
5020        &self,
5021        subj: DcShorthand,
5022    ) -> u128 {
5023        let mut max_id = 0u128;
5024        for prop_dc in [
5025            DC_CANONICAL_DECOMPOSITION,
5026            DC_DECOMPOSITION,
5027            DC_SEMANTIC_DECOMPOSITION,
5028            DC_APPROXIMATE_DECOMPOSITION,
5029        ] {
5030            for entry in self.get_multi_properties(subj, sh(prop_dc)) {
5031                if let DcShorthand::Long(val_id) = entry.value {
5032                    max_id = max_id.max(val_id);
5033                } else {
5034                    max_id = max_id.max(entry.has_val_id);
5035                }
5036            }
5037        }
5038        if max_id == 0
5039            && let Some((has_a_id, has_val_id, val_tok)) =
5040                self.active_single_props.get(&(subj, sh(DC_SYNTAX_RULE))).copied()
5041        {
5042            if let DcShorthand::Long(val_id) = val_tok {
5043                max_id = val_id.max(has_val_id).max(has_a_id);
5044            } else {
5045                max_id = has_val_id.max(has_a_id);
5046            }
5047        }
5048        if max_id == 0
5049            && let DcShorthand::Long(nid) = subj
5050        {
5051            max_id = nid;
5052        }
5053        if max_id == 0 {
5054            // Reason for fallback: Synthetic in-memory graphs with inline non-Long decompositions attribute to earliest graph node.
5055            max_id = self
5056                .nodes
5057                .first()
5058                .map_or(SYSTEM_REGION_START, |n| n.id);
5059        }
5060        max_id
5061    }
5062
5063    /// Auto-discovers all runnable graph Dcs and standalone `.WASM` value nodes active at
5064    /// this snapshot (`Dc 1936`, active `.WASM`/StageL/StageR `[Dc 302 src dst]` converters,
5065    /// standalone uncontextualized `.WASM` modules, standalone `pub dc/<shorthand>`
5066    /// StageL/StageR routines with `(l/u8 -> l/u8)` or `(dcs -> dcs)` signatures, and
5067    /// unowned standalone `Dc 1927..Dc 1928` value nodes), sorted deterministically by
5068    /// ascending `(global_id, defining_node_id)`.
5069    ///
5070    /// # Errors
5071    /// Returns an error if `strict` is `true` and any discovered target fails shorthand
5072    /// global-ID resolution or decomposition inspection.
5073    pub fn discover_system_wasm_substitute_targets(
5074        &self,
5075    ) -> Result<Vec<SystemWasmSubstituteTarget>> {
5076        self.discover_wasm_substitute_targets_inner(true)
5077    }
5078
5079    fn discover_wasm_substitute_targets_inner(
5080        &self,
5081        strict: bool,
5082    ) -> Result<Vec<SystemWasmSubstituteTarget>> {
5083        use crate::stagel3::ast::{StageDialect, StageLType};
5084
5085        fn is_bytes_list_ty(ty: &StageLType) -> bool {
5086            matches!(ty, StageLType::List(inner) if matches!(inner.as_ref(), StageLType::U8))
5087        }
5088
5089        let mut targets: Vec<SystemWasmSubstituteTarget> = Vec::new();
5090        let mut seen_subjects: BTreeSet<DcShorthand> = BTreeSet::new();
5091        let mut owned_value_node_ids: HashSet<u128> = HashSet::new();
5092        for vals in self.has_val_stmt_ids_by_has_a.values() {
5093            for &(_, val_tok) in vals {
5094                if let DcShorthand::Long(vid) = val_tok {
5095                    owned_value_node_ids.insert(vid);
5096                }
5097            }
5098        }
5099        for (&(_, _, val_tok), _) in &self.active_multi_props {
5100            if let DcShorthand::Long(vid) = val_tok {
5101                owned_value_node_ids.insert(vid);
5102            }
5103        }
5104        for &(_, _, val_tok) in self.active_single_props.values() {
5105            if let DcShorthand::Long(vid) = val_tok {
5106                owned_value_node_ids.insert(vid);
5107            }
5108        }
5109
5110        // 1. Active single-step converters (`list_all_active_converter_steps`).
5111        let converter_steps = match self.list_all_active_converter_steps() {
5112            Ok(steps) => steps,
5113            Err(err) if !strict => {
5114                warn_fmt!(
5115                    "Skipping converter discovery at historical snapshot {:?}: {err:#}",
5116                    self.system_block_most_recent_node_id
5117                );
5118                Vec::new()
5119            }
5120            Err(err) => return Err(err),
5121        };
5122        for step in converter_steps {
5123            if !seen_subjects.insert(step.subject) {
5124                continue;
5125            }
5126            let kind = match step.body {
5127                ActiveConverterBody::Wasm(_) => {
5128                    SystemWasmSubstituteTargetKind::WasmConverter {
5129                        src: step.src,
5130                        dst: step.dst,
5131                    }
5132                }
5133                ActiveConverterBody::StageL(tokens) => {
5134                    let stripped =
5135                        crate::stagel3::dc_tokens::strip_comment_frames(
5136                            &tokens,
5137                        );
5138                    let is_stager = stripped.first().copied().is_some_and(|t| {
5139                        self.token_fills_canonical_or_equiv_role(
5140                            t.to_u128(),
5141                            crate::syntax::DcRole::BeginStagerModule,
5142                        )
5143                    });
5144                    if is_stager {
5145                        SystemWasmSubstituteTargetKind::StageRConverter {
5146                            src: step.src,
5147                            dst: step.dst,
5148                        }
5149                    } else {
5150                        SystemWasmSubstituteTargetKind::StageLConverter {
5151                            src: step.src,
5152                            dst: step.dst,
5153                        }
5154                    }
5155                }
5156            };
5157            let defining_node_id =
5158                self.resolve_active_decomposition_defining_node_id(step.subject);
5159            targets.push(SystemWasmSubstituteTarget {
5160                subject: step.subject,
5161                global_id: step.subject.to_global_id()?,
5162                defining_node_id,
5163                chunk_prefix: substitute_chunk_prefix_for_node_id(
5164                    defining_node_id,
5165                ),
5166                kind,
5167            });
5168        }
5169
5170        // Collect all active subjects owning a canonical/decomposition/semantic decomposition.
5171        let mut decomp_subjects: BTreeSet<DcShorthand> = BTreeSet::new();
5172        for (&(subj, prop, _), &(has_a_id, has_val_id)) in
5173            &self.active_multi_props
5174        {
5175            if prop != sh(DC_CANONICAL_DECOMPOSITION)
5176                && prop != sh(DC_DECOMPOSITION)
5177                && prop != sh(DC_SEMANTIC_DECOMPOSITION)
5178            {
5179                continue;
5180            }
5181            if let Some(pin_id) = self.system_block_most_recent_node_id
5182                && (has_a_id > pin_id || has_val_id > pin_id)
5183            {
5184                continue;
5185            }
5186            if let DcShorthand::Long(nid) = subj
5187                && let Some(pin_id) = self.system_block_most_recent_node_id
5188                && nid > pin_id
5189            {
5190                continue;
5191            }
5192            decomp_subjects.insert(subj);
5193        }
5194
5195        let decomp_props = [
5196            sh(DC_CANONICAL_DECOMPOSITION),
5197            sh(DC_DECOMPOSITION),
5198            sh(DC_SEMANTIC_DECOMPOSITION),
5199        ];
5200
5201        // 2. Standalone uncontextualized `.WASM` modules on subjects.
5202        let kernel_sh = sh(DC_DC_DOCUMENT_EXECUTION_KERNEL);
5203        for &subj in &decomp_subjects {
5204            if seen_subjects.contains(&subj) {
5205                continue;
5206            }
5207            let has_active_wasm_decomp = decomp_props.iter().any(|&p_sh| {
5208                self.get_multi_properties(subj, p_sh).into_iter().any(|entry| {
5209                    self.get_direct_objects(
5210                        sh(DC_IN_CONTEXT_OF),
5211                        DcShorthand::Long(entry.has_a_id),
5212                    )
5213                    .is_empty()
5214                        && matches!(entry.value, DcShorthand::Long(nid) if self.get_active_node(nid).is_some_and(|n| Self::tokens_start_wasm_definition(&n.tokens)))
5215                })
5216            });
5217            if !has_active_wasm_decomp {
5218                continue;
5219            }
5220            let resolved_helper = match self.resolve_wasm_helper_shorthand(subj)
5221            {
5222                Ok(v) => v,
5223                Err(err) if !strict => {
5224                    warn_fmt!(
5225                        "Skipping historical WASM subject {subj} at {:?}: {err:#}",
5226                        self.system_block_most_recent_node_id
5227                    );
5228                    continue;
5229                }
5230                Err(err) => return Err(err),
5231            };
5232            let Some((direct_node_id, tokens)) = resolved_helper else {
5233                continue;
5234            };
5235            if direct_node_id.is_none() || !Self::tokens_start_wasm_definition(tokens)
5236            {
5237                continue;
5238            }
5239            if let DcShorthand::Long(nid) = subj
5240                && let Some(pin_id) = self.system_block_most_recent_node_id
5241                && nid > pin_id
5242            {
5243                continue;
5244            }
5245            seen_subjects.insert(subj);
5246            let use_supervisor_kernel = subj == kernel_sh
5247                && self
5248                    .resolve_trusted_system_supervisor_bootstrap_tokens(&[subj])
5249                    .is_ok();
5250            let kind = if use_supervisor_kernel {
5251                SystemWasmSubstituteTargetKind::SupervisorKernel
5252            } else {
5253                SystemWasmSubstituteTargetKind::StandaloneWasm
5254            };
5255            // Reason for fallback: direct_node_id is checked Some above, with decomposition lookup as secondary fallback.
5256            let defining_node_id = direct_node_id.unwrap_or_else(|| {
5257                self.resolve_active_decomposition_defining_node_id(subj)
5258            });
5259            targets.push(SystemWasmSubstituteTarget {
5260                subject: subj,
5261                global_id: subj.to_global_id()?,
5262                defining_node_id,
5263                chunk_prefix: substitute_chunk_prefix_for_node_id(
5264                    defining_node_id,
5265                ),
5266                kind,
5267            });
5268        }
5269
5270        // 3. Standalone Short / Format `pub dc/<shorthand>` StageL/StageR entrypoints.
5271        for &subj in &decomp_subjects {
5272            if seen_subjects.contains(&subj)
5273                || !matches!(subj, DcShorthand::Short(_) | DcShorthand::Format(_))
5274            {
5275                continue;
5276            }
5277            let has_active_stagel_decomp = decomp_props.iter().any(|&p_sh| {
5278                self.get_multi_properties(subj, p_sh).into_iter().any(|entry| {
5279                    self.get_direct_objects(
5280                        sh(DC_IN_CONTEXT_OF),
5281                        DcShorthand::Long(entry.has_a_id),
5282                    )
5283                    .is_empty()
5284                        && matches!(entry.value, DcShorthand::Long(nid) if self.get_active_node(nid).is_some_and(|n| self.tokens_are_stagel_item_or_module(&n.tokens)))
5285                })
5286            });
5287            if !has_active_stagel_decomp {
5288                continue;
5289            }
5290            let inspected = match crate::stagel3::seed_linker::inspect_standalone_graph_routine_signature(
5291                self, subj,
5292            ) {
5293                Ok(v) => v,
5294                Err(err) if !strict => {
5295                    warn_fmt!(
5296                        "Skipping historical StageL/StageR routine {subj} at {:?}: {err:#}",
5297                        self.system_block_most_recent_node_id
5298                    );
5299                    continue;
5300                }
5301                Err(err) => return Err(err),
5302            };
5303            let Some((dialect, routine)) = inspected else {
5304                continue;
5305            };
5306            let [param] = routine.params.as_slice() else {
5307                continue;
5308            };
5309            let kind = if is_bytes_list_ty(&param.ty)
5310                && is_bytes_list_ty(&routine.return_type)
5311            {
5312                match dialect {
5313                    StageDialect::StageL3 => {
5314                        SystemWasmSubstituteTargetKind::StageLRoutineBytes
5315                    }
5316                    StageDialect::StageR3 => {
5317                        SystemWasmSubstituteTargetKind::StageRRoutineBytes
5318                    }
5319                }
5320            } else if param.ty == StageLType::Dcs
5321                && routine.return_type == StageLType::Dcs
5322            {
5323                match dialect {
5324                    StageDialect::StageL3 => {
5325                        SystemWasmSubstituteTargetKind::StageLRoutineDcs
5326                    }
5327                    StageDialect::StageR3 => {
5328                        SystemWasmSubstituteTargetKind::StageRRoutineDcs
5329                    }
5330                }
5331            } else {
5332                continue;
5333            };
5334            seen_subjects.insert(subj);
5335            let defining_node_id =
5336                self.resolve_active_decomposition_defining_node_id(subj);
5337            targets.push(SystemWasmSubstituteTarget {
5338                subject: subj,
5339                global_id: subj.to_global_id()?,
5340                defining_node_id,
5341                chunk_prefix: substitute_chunk_prefix_for_node_id(
5342                    defining_node_id,
5343                ),
5344                kind,
5345            });
5346        }
5347
5348        // 4. Unowned standalone active `Dc 1927..Dc 1928` `.WASM` value nodes (for arbitrary node slices).
5349        for node in &self.nodes {
5350            if self.inactive_ids.contains(&node.id)
5351                || owned_value_node_ids.contains(&node.id)
5352            {
5353                continue;
5354            }
5355            if let Some(pin_id) = self.system_block_most_recent_node_id
5356                && node.id > pin_id
5357            {
5358                continue;
5359            }
5360            if node.tokens.first().copied() == Some(sh(DC_BEGIN_WASM_PROGRAM))
5361                && node.tokens.last().copied() == Some(sh(DC_END_WASM_PROGRAM))
5362            {
5363                let subj = DcShorthand::Long(node.id);
5364                if seen_subjects.insert(subj) {
5365                    targets.push(SystemWasmSubstituteTarget {
5366                        subject: subj,
5367                        global_id: subj.to_global_id()?,
5368                        defining_node_id: node.id,
5369                        chunk_prefix: substitute_chunk_prefix_for_node_id(
5370                            node.id,
5371                        ),
5372                        kind:
5373                            SystemWasmSubstituteTargetKind::StandaloneWasmValueNode {
5374                                node_id: node.id,
5375                            },
5376                    });
5377                }
5378            }
5379        }
5380
5381        targets.sort_by(|a, b| {
5382            a.global_id
5383                .cmp(&b.global_id)
5384                .then_with(|| a.defining_node_id.cmp(&b.defining_node_id))
5385        });
5386        Ok(targets)
5387    }
5388
5389    /// Computes the deterministic SHA-256 closure digest (`[u8; 32]`) of a
5390    /// [`SystemWasmSubstituteTarget`] across its active source and compiler dependencies
5391    /// in this [`SeedGraphIndex`] snapshot.
5392    ///
5393    /// # Errors
5394    /// Returns an error if `target`'s active decomposition or converter chain is missing.
5395    pub fn compute_substitute_target_revision_sha256(
5396        &self,
5397        target: &SystemWasmSubstituteTarget,
5398    ) -> Result<[u8; 32]> {
5399        fn push_sh_bytes(buf: &mut Vec<u8>, tok: DcShorthand) -> Result<()> {
5400            buf.extend_from_slice(&tok.to_global_id()?.to_le_bytes());
5401            Ok(())
5402        }
5403        fn push_dc_chars(buf: &mut Vec<u8>, chars: &[DcChar]) {
5404            let stripped = crate::stagel3::dc_tokens::strip_comment_frames(chars);
5405            // Reason for fallback: slice length in memory never exceeds u64::MAX on 32/64-bit targets.
5406            let len_u64 = u64::try_from(stripped.len()).unwrap_or(u64::MAX);
5407            buf.extend_from_slice(&len_u64.to_le_bytes());
5408            for ch in stripped {
5409                buf.extend_from_slice(&ch.to_u128().to_le_bytes());
5410            }
5411        }
5412        fn push_expanded_wasm_tokens(
5413            sg: &SeedGraphIndex,
5414            buf: &mut Vec<u8>,
5415            tokens: &[DcShorthand],
5416            visited: &mut HashSet<DcShorthand>,
5417        ) -> Result<()> {
5418            let expanded = sg.expand_interned_string_nodes(tokens);
5419            // Reason for fallback: slice length in memory never exceeds u64::MAX on 32/64-bit targets.
5420            let len_u64 = u64::try_from(expanded.len()).unwrap_or(u64::MAX);
5421            buf.extend_from_slice(&len_u64.to_le_bytes());
5422            for tok in expanded {
5423                push_sh_bytes(buf, tok)?;
5424                if visited.insert(tok)
5425                    && let Some((_, _, _, helper_toks)) =
5426                        sg.resolve_active_wasm_definition_entry(tok)
5427                {
5428                    buf.push(0xE1);
5429                    push_expanded_wasm_tokens(sg, buf, &helper_toks, visited)?;
5430                }
5431            }
5432            Ok(())
5433        }
5434
5435        let mut buf: Vec<u8> = Vec::with_capacity(512);
5436        buf.extend_from_slice(&target.global_id.to_le_bytes());
5437        let target_dc = DcChar::from_u128(target.global_id);
5438        match &target.kind {
5439            SystemWasmSubstituteTargetKind::SupervisorKernel => {
5440                buf.push(1);
5441                let resolved = self
5442                    .resolve_trusted_system_supervisor_bootstrap_tokens(&[
5443                        target.subject,
5444                    ])?;
5445                let mut visited = HashSet::new();
5446                push_expanded_wasm_tokens(
5447                    self,
5448                    &mut buf,
5449                    &resolved.definition_tokens,
5450                    &mut visited,
5451                )?;
5452            }
5453            SystemWasmSubstituteTargetKind::StandaloneWasm => {
5454                buf.push(2);
5455                let (_, tokens) = self
5456                    .resolve_wasm_helper_shorthand(target.subject)?
5457                    .with_context(|| {
5458                        format!(
5459                            "Target {} missing active standalone WASM decomposition",
5460                            target.subject
5461                        )
5462                    })?;
5463                let mut visited = HashSet::new();
5464                push_expanded_wasm_tokens(self, &mut buf, tokens, &mut visited)?;
5465            }
5466            SystemWasmSubstituteTargetKind::StandaloneWasmValueNode {
5467                node_id,
5468            } => {
5469                buf.push(3);
5470                let node = self.get_active_node(*node_id).with_context(|| {
5471                    format!(
5472                        "Standalone WASM value node l{node_id} missing from snapshot"
5473                    )
5474                })?;
5475                let mut visited = HashSet::new();
5476                push_expanded_wasm_tokens(
5477                    self,
5478                    &mut buf,
5479                    &node.tokens,
5480                    &mut visited,
5481                )?;
5482            }
5483            SystemWasmSubstituteTargetKind::WasmConverter { src, dst } => {
5484                buf.push(4);
5485                push_sh_bytes(&mut buf, *src)?;
5486                push_sh_bytes(&mut buf, *dst)?;
5487                let step = self
5488                    .list_all_active_converter_steps()?
5489                    .into_iter()
5490                    .find(|s| s.subject == target.subject)
5491                    .with_context(|| {
5492                        format!(
5493                            "WASM converter {} missing from snapshot",
5494                            target.subject
5495                        )
5496                    })?;
5497                let ActiveConverterBody::Wasm(tokens) = step.body else {
5498                    bail!("Converter {} is not .WASM", target.subject);
5499                };
5500                let mut visited = HashSet::new();
5501                push_expanded_wasm_tokens(self, &mut buf, tokens, &mut visited)?;
5502            }
5503            SystemWasmSubstituteTargetKind::StageLConverter { .. }
5504            | SystemWasmSubstituteTargetKind::StageLRoutineBytes => {
5505                buf.push(5);
5506                let entry_tokens =
5507                    crate::stagel3::seed_linker::build_entry_module_for_graph_routine_dc(
5508                        target_dc, self,
5509                    )?;
5510                let bundled =
5511                    crate::stagel3::seed_linker::bundle_dc_module_dependencies(
5512                        &entry_tokens,
5513                        self,
5514                    )?;
5515                push_dc_chars(&mut buf, &bundled);
5516                let (_, conv_toks) = self
5517                    .resolve_active_converter_routine(
5518                        sh(DC_BEGIN_MODULE),
5519                        sh(DC_BEGIN_WASM_PROGRAM),
5520                    )?
5521                    .context(
5522                        "Missing active StageL -> WASM converter routine in snapshot",
5523                    )?;
5524                let mut visited = HashSet::new();
5525                push_expanded_wasm_tokens(
5526                    self,
5527                    &mut buf,
5528                    conv_toks,
5529                    &mut visited,
5530                )?;
5531            }
5532            SystemWasmSubstituteTargetKind::StageRConverter { .. }
5533            | SystemWasmSubstituteTargetKind::StageRRoutineBytes
5534            | SystemWasmSubstituteTargetKind::StageLRoutineDcs
5535            | SystemWasmSubstituteTargetKind::StageRRoutineDcs => {
5536                let entry_tokens = if matches!(
5537                    target.kind,
5538                    SystemWasmSubstituteTargetKind::StageLRoutineDcs
5539                        | SystemWasmSubstituteTargetKind::StageRRoutineDcs
5540                ) {
5541                    buf.push(6);
5542                    crate::stagel3::seed_linker::build_stager_dcs_entry_module_for_graph_routine_dc(
5543                        target_dc, self,
5544                    )?
5545                } else {
5546                    buf.push(7);
5547                    crate::stagel3::seed_linker::build_stager_bytes_entry_module_for_graph_routine_dc(
5548                        target_dc, self,
5549                    )?
5550                };
5551                let bundled =
5552                    crate::stagel3::seed_linker::bundle_dc_module_dependencies(
5553                        &entry_tokens,
5554                        self,
5555                    )?;
5556                push_dc_chars(&mut buf, &bundled);
5557                let chain = self
5558                    .resolve_active_converter_chain(
5559                        sh(DC_BEGIN_STAGER_MODULE),
5560                        sh(DC_BEGIN_WASM_PROGRAM),
5561                    )?
5562                    .context(
5563                        "Missing active StageR -> WASM converter chain in snapshot",
5564                    )?;
5565                for step in &chain {
5566                    push_sh_bytes(&mut buf, step.subject)?;
5567                    match &step.body {
5568                        ActiveConverterBody::Wasm(toks) => {
5569                            let mut visited = HashSet::new();
5570                            push_expanded_wasm_tokens(
5571                                self,
5572                                &mut buf,
5573                                toks,
5574                                &mut visited,
5575                            )?;
5576                        }
5577                        ActiveConverterBody::StageL(chars) => {
5578                            push_dc_chars(&mut buf, chars);
5579                        }
5580                    }
5581                }
5582            }
5583        }
5584        Ok(Sha256::digest(&buf).into())
5585    }
5586
5587    fn compute_substitute_target_revision_hex(
5588        &self,
5589        target: &SystemWasmSubstituteTarget,
5590    ) -> Result<String> {
5591        let digest = self.compute_substitute_target_revision_sha256(target)?;
5592        let mut hex = String::with_capacity(64);
5593        for b in digest {
5594            use std::fmt::Write as _;
5595            let _ = write!(hex, "{b:02x}");
5596        }
5597        Ok(hex)
5598    }
5599}
5600
5601/// Discovers all runnable WebAssembly snapshots across an arbitrary slice of
5602/// [`LedgerNode`]s without privileging `HEAD` over historical `Dc 641` revisions.
5603///
5604/// Every revision closure present across code-touching batch watermarks in `nodes`
5605/// (including superseded or retracted historical implementations as well as raw
5606/// unowned `Dc 1927..Dc 1928` `.WASM` value nodes) is discovered once and attributed
5607/// via [`substitute_chunk_prefix_for_node_id`] to the `.ctbnodes` chunk of its
5608/// defining node ID.
5609///
5610/// # Errors
5611/// Returns an error if `nodes` contains duplicate node IDs or if any target active
5612/// at the final watermark of `nodes` fails inspection or closure hashing.
5613pub fn discover_graph_wasm_substitute_snapshots(
5614    nodes: &[LedgerNode],
5615) -> Result<Vec<GraphWasmSubstituteSnapshot>> {
5616    if nodes.is_empty() {
5617        return Ok(Vec::new());
5618    }
5619
5620    let mut ordered: Vec<LedgerNode> = nodes.to_vec();
5621    ordered.sort_by_key(|n| n.id);
5622    for pair in ordered.windows(2) {
5623        if let [a, b] = pair {
5624            ensure!(
5625                a.id < b.id,
5626                "Duplicate LedgerNode ID l{} in discover_graph_wasm_substitute_snapshots",
5627                a.id
5628            );
5629        }
5630    }
5631    let head_id = ordered
5632        .last()
5633        .map(|n| n.id)
5634        .context("Non-empty ordered slice missing last node")?;
5635
5636    // Identify code-bearing value nodes and code-touching batch watermarks in O(N).
5637    let sh_wasm_begin = sh(DC_BEGIN_WASM_PROGRAM);
5638    let sh_stagel_begin = sh(DC_BEGIN_MODULE);
5639    let sh_stager_begin = sh(DC_BEGIN_STAGER_MODULE);
5640    let sh_routine_begin = sh(DC_BEGIN_ROUTINE_DECL);
5641    let sh_anon_routine_begin = sh(DC_BEGIN_ROUTINE);
5642    let sh_has_a = sh(DC_HAS_A);
5643    let sh_has_val = sh(DC_HAS_VALUE);
5644    let sh_sup = sh(DC_SUPERSEDES);
5645    let sh_ret = sh(DC_RETRACTS);
5646    let sh_data_source = sh(DC_COLLECTIVE_TOOLBOX_SEED_GRAPH_DATA_SOURCE);
5647
5648    let mut code_val_ids: HashSet<u128> = HashSet::new();
5649    let mut raw_wasm_val_ids: BTreeSet<u128> = BTreeSet::new();
5650    for node in &ordered {
5651        if node.tokens.iter().any(|&t| {
5652            t == sh_wasm_begin
5653                || t == sh_stagel_begin
5654                || t == sh_stager_begin
5655                || t == sh_routine_begin
5656                || t == sh_anon_routine_begin
5657        }) {
5658            code_val_ids.insert(node.id);
5659        }
5660        if node.tokens.first().copied() == Some(sh_wasm_begin)
5661            && node.tokens.last().copied() == Some(sh(DC_END_WASM_PROGRAM))
5662        {
5663            raw_wasm_val_ids.insert(node.id);
5664        }
5665    }
5666
5667    let mut code_has_a_ids: HashSet<u128> = HashSet::new();
5668    let mut code_stmt_ids: BTreeSet<u128> = BTreeSet::new();
5669    let mut prov_has_a_targets: HashMap<u128, Vec<u128>> = HashMap::new();
5670    let mut covered_by_prov: HashSet<u128> = HashSet::new();
5671    let mut watermarks: BTreeSet<u128> = BTreeSet::new();
5672
5673    for node in &ordered {
5674        if let Some((verb, _inner_subj, obj, _list_type, targets_raw)) =
5675            parse_for_each_statement_tokens(&node.tokens)
5676        {
5677            if verb == sh_has_a && obj == sh_data_source {
5678                let targets: Vec<u128> = targets_raw
5679                    .into_iter()
5680                    .filter_map(|t| match t {
5681                        DcShorthand::Long(id) => Some(id),
5682                        _ => None,
5683                    })
5684                    .collect();
5685                prov_has_a_targets.insert(node.id, targets);
5686            }
5687            continue;
5688        }
5689        let Some((verb, subj, obj)) = parse_statement_tokens(&node.tokens)
5690        else {
5691            continue;
5692        };
5693        if verb == sh_has_a
5694            && obj == sh_data_source
5695            && let DcShorthand::Long(tid) = subj
5696        {
5697            prov_has_a_targets.insert(node.id, vec![tid]);
5698            continue;
5699        }
5700        if verb == sh_has_val
5701            && let DcShorthand::Long(ha_id) = subj
5702            && let Some(targets) = prov_has_a_targets.get(&ha_id)
5703        {
5704            let mut touches_code = false;
5705            for &tid in targets {
5706                covered_by_prov.insert(tid);
5707                if code_val_ids.contains(&tid) || code_stmt_ids.contains(&tid) {
5708                    touches_code = true;
5709                }
5710            }
5711            if touches_code {
5712                watermarks.insert(node.id);
5713            }
5714            continue;
5715        }
5716        if verb == sh_has_val
5717            && let DcShorthand::Long(ha_id) = subj
5718            && let DcShorthand::Long(val_id) = obj
5719        {
5720            raw_wasm_val_ids.remove(&val_id);
5721            if code_val_ids.contains(&val_id) || code_has_a_ids.contains(&ha_id)
5722            {
5723                code_has_a_ids.insert(ha_id);
5724                code_stmt_ids.insert(ha_id);
5725                code_stmt_ids.insert(node.id);
5726            }
5727        } else if verb == sh_sup
5728            && let DcShorthand::Long(new_id) = subj
5729            && let DcShorthand::Long(old_id) = obj
5730            && (code_stmt_ids.contains(&old_id)
5731                || code_stmt_ids.contains(&new_id))
5732        {
5733            if code_has_a_ids.contains(&old_id) {
5734                code_has_a_ids.insert(new_id);
5735            }
5736            code_stmt_ids.insert(new_id);
5737            code_stmt_ids.insert(node.id);
5738        } else if verb == sh_ret
5739            && let DcShorthand::Long(old_id) = obj
5740            && (code_stmt_ids.contains(&old_id)
5741                || code_val_ids.contains(&old_id))
5742        {
5743            code_stmt_ids.insert(node.id);
5744        }
5745    }
5746
5747    // Also capture un-provenanced code-touching statement runs (for arbitrary non-System or synthetic slices).
5748    for (idx, node) in ordered.iter().enumerate() {
5749        if code_stmt_ids.contains(&node.id) && !covered_by_prov.contains(&node.id)
5750        {
5751            let next_is_unprov_stmt = ordered
5752                .get(idx.saturating_add(1))
5753                .is_some_and(|next| {
5754                    parse_statement_tokens(&next.tokens).is_some()
5755                        && !covered_by_prov.contains(&next.id)
5756                });
5757            if !next_is_unprov_stmt {
5758                watermarks.insert(node.id);
5759            }
5760        }
5761    }
5762    for &raw_id in &raw_wasm_val_ids {
5763        watermarks.insert(raw_id);
5764    }
5765    watermarks.insert(head_id);
5766
5767    let single_props = single_valued_property_set();
5768    let mut by_revision_key: BTreeMap<
5769        (u128, String),
5770        GraphWasmSubstituteSnapshot,
5771    > = BTreeMap::new();
5772
5773    for wm_id in watermarks {
5774        let is_head = wm_id == head_id;
5775        let prefix_end = ordered.partition_point(|n| n.id <= wm_id);
5776        let prefix_nodes = ordered
5777            .get(..prefix_end)
5778            .context("Watermark partition_point out of bounds")?
5779            .to_vec();
5780        let bundled_ids: HashSet<u128> = prefix_nodes
5781            .iter()
5782            .filter(|n| (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&n.id))
5783            .map(|n| n.id)
5784            .collect();
5785        let mut sg = SeedGraphIndex::from_nodes_with_single_props(
5786            prefix_nodes,
5787            &single_props,
5788        );
5789        sg.bundled_origin_node_ids = bundled_ids;
5790        if (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&wm_id) {
5791            sg.system_block_most_recent_node_id = Some(wm_id);
5792        }
5793
5794        let targets = sg.discover_wasm_substitute_targets_inner(is_head)?;
5795        for target in targets {
5796            let rev_hex = match sg.compute_substitute_target_revision_hex(&target)
5797            {
5798                Ok(h) => h,
5799                Err(err) if !is_head => {
5800                    warn_fmt!(
5801                        "Skipping broken historical revision of {} at watermark l{wm_id}: {err:#}",
5802                        target.subject
5803                    );
5804                    continue;
5805                }
5806                Err(err) => return Err(err),
5807            };
5808            let key = (target.global_id, rev_hex.clone());
5809            if let Some(existing) = by_revision_key.get_mut(&key) {
5810                if is_head {
5811                    existing.is_head = true;
5812                }
5813            } else {
5814                by_revision_key.insert(
5815                    key,
5816                    GraphWasmSubstituteSnapshot {
5817                        target,
5818                        pin_node_id: wm_id,
5819                        is_head,
5820                        revision_sha256_hex: rev_hex,
5821                    },
5822                );
5823            }
5824        }
5825    }
5826
5827    let mut out: Vec<GraphWasmSubstituteSnapshot> =
5828        by_revision_key.into_values().collect();
5829    out.sort_by(|a, b| {
5830        a.target
5831            .defining_node_id
5832            .cmp(&b.target.defining_node_id)
5833            .then_with(|| a.target.global_id.cmp(&b.target.global_id))
5834            .then_with(|| a.pin_node_id.cmp(&b.pin_node_id))
5835    });
5836    Ok(out)
5837}
5838
5839#[cfg(test)]
5840#[allow(
5841    clippy::panic,
5842    clippy::expect_used,
5843    clippy::unwrap_used,
5844    clippy::unwrap_in_result,
5845    clippy::panic_in_result_fn,
5846    clippy::indexing_slicing,
5847    clippy::arithmetic_side_effects,
5848    reason = "Standard repository test boilerplate"
5849)]
5850mod tests {
5851    use super::*;
5852    use crate::dc::{
5853        DC_APPROXIMATE_DECOMPOSITION, DC_BEGIN_GRAPH_NODE_DEFINITION,
5854        DC_CANONICAL_COMBINING_CLASS, DC_CANONICAL_DECOMPOSITION,
5855        DC_CASE_MAPPING_PARTNER, DC_COMPATIBILITY_DECOMPOSITION,
5856        DC_DESCRIPTION, DC_END_GRAPH_NODE_DEFINITION, DC_INFORMAL_ALIAS,
5857        DC_IS_CLOSING_DELIMITER_FOR, DC_IS_DEPRECATED, DC_IS_SUBTYPE_OF,
5858        DC_RANGE, DC_SEMANTIC_DECOMPOSITION,
5859    };
5860    use crate::dc_def::{BidiClass, DcDefn, GeneralCategory};
5861    use crate::graph_ledger::{
5862        encode_integer_value_tokens, encode_nodes_to_ctbnbdl_bytes,
5863        encode_statement_tokens, encode_string_value_tokens,
5864        update_ledger_in_memory,
5865    };
5866    use crate::syntax::parse_dc_syntax;
5867    use ctb_utilities::format_id::DC_FILE_EXTENSION;
5868    use std::collections::BTreeSet;
5869
5870    fn make_test_defn(short_id: usize, name: &str, desc: &str) -> DcDefn {
5871        DcDefn {
5872            dc_id: 1_114_112 + u128::try_from(short_id).unwrap(),
5873            short_id: Some(short_id),
5874            ident: Some(format!("DC_TEST_{short_id}")),
5875            stable_ident: false,
5876            title: None,
5877            name: name.to_string(),
5878            category: "semantic".to_string(),
5879            combining_class: 0,
5880            bidi_class: BidiClass::BN,
5881            casing_partner: None,
5882            general_category: GeneralCategory::NonUnicodeControl,
5883            script: ".Semantic".to_string(),
5884            is_deprecated: false,
5885            decompositions: Vec::new(),
5886            aliases: vec!["alias-one".to_string()],
5887            formal_aliases: Vec::new(),
5888            cross_references: Vec::new(),
5889            annotations: Vec::new(),
5890            implies: vec!["571".to_string()],
5891            based_on: Vec::new(),
5892            os_associations: Vec::new(),
5893            magic_names: Vec::new(),
5894            syntax: Some(parse_dc_syntax(":~ [value]").unwrap()),
5895            closes: None,
5896            description: desc.to_string(),
5897            format: None,
5898            source_file: "test.csv".to_string(),
5899            line_number: 2,
5900        }
5901    }
5902
5903    #[crate::ctb_test]
5904    fn test_load_seed_graph_from_asset_bundle() -> Result<()> {
5905        let index = SeedGraphIndex::shared()?;
5906        assert!(
5907            index.node_count() >= 14_310,
5908            "Expected at least 14,310 nodes in bundled seed graph, found {}",
5909            index.node_count()
5910        );
5911        assert_eq!(
5912            index.superseded_count(),
5913            0,
5914            "Active-only bundled seed graph should have 0 superseded nodes, found {}",
5915            index.superseded_count()
5916        );
5917        let history_index =
5918            SeedGraphIndex::load_with_history_from_asset_bundle()?;
5919        assert!(
5920            history_index.superseded_count() >= 13,
5921            "Expected live supersessions in seed graph with history, found {}",
5922            history_index.superseded_count()
5923        );
5924
5925        // Verify Dc 617 (`Begin graph node definition`) has its superseded description and syntax rule
5926        let dc_617 = sh(DC_BEGIN_GRAPH_NODE_DEFINITION);
5927        assert_eq!(
5928            index.get_single_property_string(dc_617, sh(DC_CANONICAL_NAME)),
5929            Some("Begin graph node definition")
5930        );
5931        assert_eq!(
5932            index.get_single_property_string(
5933                dc_617,
5934                sh(DC_PROGRAMMATIC_IDENTIFIER)
5935            ),
5936            Some("BeginGraphNodeDefinition")
5937        );
5938        let rule_617 = index
5939            .decode_syntax_rule_for_subject(dc_617)?
5940            .expect("Expected syntax rule for Dc 617");
5941        let expected_617 = parse_dc_syntax(":~ [atom_dc] [^618]* 618")?;
5942        assert_eq!(rule_617.pattern, expected_617.pattern);
5943
5944        // Verify Dc 618 closes Dc 617 (`590 618 617`)
5945        let dc_618 = sh(DC_END_GRAPH_NODE_DEFINITION);
5946        assert!(index.has_direct_statement(
5947            sh(DC_IS_CLOSING_DELIMITER_FOR),
5948            dc_618,
5949            dc_617
5950        ));
5951        assert_eq!(
5952            index.get_direct_objects(sh(DC_IS_CLOSING_DELIMITER_FOR), dc_618),
5953            &[dc_617]
5954        );
5955
5956        // Verify f192 (`IaMetaXml`) has its superseded `~_meta\.xml$~` pattern extension
5957        // and f316 (`AppleDouble`) has both literal (`.ADF`, `.rsrc`) and regex pattern extensions
5958        let f192 = DcShorthand::Format(192);
5959        let exts_192 = index.get_multi_properties(f192, sh(DC_FILE_EXTENSION));
5960        assert_eq!(exts_192.len(), 1);
5961        let DcShorthand::Long(pat_node_id) = exts_192[0].value else {
5962            panic!("Expected Long node ID for f192 pattern extension");
5963        };
5964        let decoded_ext_rule = index.decode_pattern_node(pat_node_id)?;
5965        let expected_ext_rule =
5966            crate::syntax::parse_extension_regex("~_meta\\.xml$~")?;
5967        assert_eq!(decoded_ext_rule.pattern, expected_ext_rule.pattern);
5968
5969        let f316 = DcShorthand::Format(316);
5970        let exts_316 = index.get_multi_properties(f316, sh(DC_FILE_EXTENSION));
5971        assert_eq!(exts_316.len(), 7);
5972        assert!(
5973            exts_316
5974                .iter()
5975                .any(|e| index.get_string(e.value) == Some(".ADF"))
5976        );
5977        assert!(
5978            exts_316
5979                .iter()
5980                .any(|e| index.get_string(e.value) == Some(".rsrc"))
5981        );
5982
5983        Ok(())
5984    }
5985
5986    #[crate::ctb_test]
5987    fn test_supersession_chains_and_retractions_in_seed_graph_index()
5988    -> Result<()> {
5989        let mut defn = make_test_defn(900, "Name v1", "Desc v1");
5990        defn.combining_class = 230;
5991        defn.casing_partner = Some(901);
5992        defn.is_deprecated = true;
5993        defn.decompositions = vec![
5994            "<prefer> 310".to_string(),
5995            "<equiv> 311".to_string(),
5996            "<approx> 312".to_string(),
5997            "<semantic> 313".to_string(),
5998            "<compat> 314".to_string(),
5999        ];
6000        let scripts = BTreeSet::from([".Semantic".to_string()]);
6001
6002        // Revision 1
6003        let (nodes1, _) = update_ledger_in_memory(
6004            Vec::new(),
6005            &[defn.clone()],
6006            &[],
6007            &scripts,
6008            None,
6009        )?;
6010        let idx1 = SeedGraphIndex::from_nodes(nodes1.clone());
6011        let subj = DcShorthand::Short(900);
6012        let v1_name_entry = idx1
6013            .get_single_property_entry(subj, sh(DC_CANONICAL_NAME))
6014            .unwrap();
6015        assert_eq!(
6016            idx1.get_single_property_string(subj, sh(DC_CANONICAL_NAME)),
6017            Some("Name v1")
6018        );
6019        assert_eq!(
6020            idx1.get_single_property_integer(
6021                subj,
6022                sh(DC_CANONICAL_COMBINING_CLASS)
6023            ),
6024            Some(230)
6025        );
6026        assert_eq!(
6027            idx1.get_single_property(subj, sh(DC_CASE_MAPPING_PARTNER)),
6028            Some(DcShorthand::Short(901))
6029        );
6030        assert!(idx1.has_direct_statement(
6031            sh(DC_IS_DEPRECATED),
6032            subj,
6033            sh(crate::dc::DC_BOOLEAN_TRUE)
6034        ));
6035        assert_eq!(
6036            idx1.get_preferred_replacements(subj),
6037            &[DcShorthand::Short(310)]
6038        );
6039        assert_eq!(
6040            idx1.get_multi_properties(subj, sh(DC_CANONICAL_DECOMPOSITION))
6041                .len(),
6042            1
6043        );
6044        assert_eq!(
6045            idx1.get_multi_properties(subj, sh(DC_APPROXIMATE_DECOMPOSITION))
6046                .len(),
6047            1
6048        );
6049        assert_eq!(
6050            idx1.get_multi_properties(subj, sh(DC_SEMANTIC_DECOMPOSITION))
6051                .len(),
6052            1
6053        );
6054        assert_eq!(
6055            idx1.get_multi_properties(subj, sh(DC_COMPATIBILITY_DECOMPOSITION))
6056                .len(),
6057            1
6058        );
6059
6060        // Revision 2: update name to v2 (supersedes v1)
6061        defn.name = "Name v2".to_string();
6062        let (nodes2, _) = update_ledger_in_memory(
6063            nodes1,
6064            &[defn.clone()],
6065            &[],
6066            &scripts,
6067            None,
6068        )?;
6069        let idx2 = SeedGraphIndex::from_nodes(nodes2.clone());
6070        let v2_name_entry = idx2
6071            .get_single_property_entry(subj, sh(DC_CANONICAL_NAME))
6072            .unwrap();
6073        assert_eq!(v2_name_entry.has_a_id, v1_name_entry.has_a_id);
6074        assert_ne!(v2_name_entry.has_val_id, v1_name_entry.has_val_id);
6075
6076        // Revision 3: update name to v3 (chained supersession: v3 -> v2 -> v1) and retract alias, implies, deprecation, and <prefer>
6077        defn.name = "Name v3".to_string();
6078        defn.aliases.clear();
6079        defn.implies.clear();
6080        defn.is_deprecated = false;
6081        defn.decompositions.clear();
6082        let (nodes3, _) =
6083            update_ledger_in_memory(nodes2, &[defn], &[], &scripts, None)?;
6084
6085        // Roundtrip through `.ctbnbdl` binary encoding and load via `from_ctbnbdl_bytes`
6086        let bundle_bytes = encode_nodes_to_ctbnbdl_bytes(&nodes3)?;
6087        let idx3 = SeedGraphIndex::from_ctbnbdl_bytes(&bundle_bytes)?;
6088        let v3_name_entry = idx3
6089            .get_single_property_entry(subj, sh(DC_CANONICAL_NAME))
6090            .unwrap();
6091
6092        assert_eq!(
6093            idx3.get_single_property_string(subj, sh(DC_CANONICAL_NAME)),
6094            Some("Name v3")
6095        );
6096        assert!(!idx3.is_node_active(v1_name_entry.has_val_id));
6097        assert!(!idx3.is_node_active(v2_name_entry.has_val_id));
6098        assert!(idx3.is_node_active(v3_name_entry.has_val_id));
6099        assert_eq!(
6100            idx3.superseded_by(v1_name_entry.has_val_id),
6101            Some(v2_name_entry.has_val_id)
6102        );
6103        assert_eq!(
6104            idx3.superseded_by(v2_name_entry.has_val_id),
6105            Some(v3_name_entry.has_val_id)
6106        );
6107        assert_eq!(
6108            idx3.resolve_latest_node_id(v1_name_entry.has_val_id),
6109            Some(v3_name_entry.has_val_id)
6110        );
6111
6112        // Verify retractions removed the alias, subtype statement, deprecation, and preferred replacement
6113        assert!(
6114            idx3.get_multi_properties(subj, sh(DC_INFORMAL_ALIAS))
6115                .is_empty()
6116        );
6117        assert!(
6118            idx3.get_direct_objects(sh(DC_IS_SUBTYPE_OF), subj)
6119                .is_empty()
6120        );
6121        assert!(!idx3.has_direct_statement(
6122            sh(DC_IS_DEPRECATED),
6123            subj,
6124            sh(crate::dc::DC_BOOLEAN_TRUE)
6125        ));
6126        assert!(idx3.get_preferred_replacements(subj).is_empty());
6127        assert!(idx3.retracted_count() > 0);
6128
6129        Ok(())
6130    }
6131
6132    #[crate::ctb_test]
6133    fn test_retracted_retraction_restores_statement() {
6134        // Node 0: string "test"
6135        let id0 = SYSTEM_REGION_START;
6136        // Node 1: `587 900 571` (`Is a subtype of (900, 571)`)
6137        let id1 = SYSTEM_REGION_START + 1;
6138        // Node 2: `592 615 l<id1>` (retracts Node 1)
6139        let id2 = SYSTEM_REGION_START + 2;
6140        // Node 3: `592 615 l<id2>` (retracts the retraction in Node 2!)
6141        let id3 = SYSTEM_REGION_START + 3;
6142
6143        let nodes = vec![
6144            LedgerNode {
6145                id: id0,
6146                tokens: encode_string_value_tokens("test"),
6147                comment: String::new(),
6148                created_ns: None,
6149            },
6150            LedgerNode {
6151                id: id1,
6152                tokens: encode_statement_tokens(
6153                    sh(DC_IS_SUBTYPE_OF),
6154                    DcShorthand::Short(900),
6155                    DcShorthand::Short(571),
6156                ),
6157                comment: String::new(),
6158                created_ns: None,
6159            },
6160            LedgerNode {
6161                id: id2,
6162                tokens: encode_statement_tokens(
6163                    sh(DC_RETRACTS),
6164                    sh(DC_ENCLOSING_DOCUMENT),
6165                    DcShorthand::Long(id1),
6166                ),
6167                comment: String::new(),
6168                created_ns: None,
6169            },
6170            LedgerNode {
6171                id: id3,
6172                tokens: encode_statement_tokens(
6173                    sh(DC_RETRACTS),
6174                    sh(DC_ENCLOSING_DOCUMENT),
6175                    DcShorthand::Long(id2),
6176                ),
6177                comment: String::new(),
6178                created_ns: None,
6179            },
6180        ];
6181
6182        let index = SeedGraphIndex::from_nodes(nodes);
6183        assert!(!index.is_node_active(id2));
6184        assert!(index.is_node_active(id1));
6185        assert!(index.has_direct_statement(
6186            sh(DC_IS_SUBTYPE_OF),
6187            DcShorthand::Short(900),
6188            DcShorthand::Short(571)
6189        ));
6190    }
6191
6192    #[crate::ctb_test]
6193    fn test_all_live_syntax_rules_and_named_constructs_roundtrip_from_seed_graph()
6194    -> Result<()> {
6195        let index = SeedGraphIndex::shared()?;
6196
6197        // 1. Verify every named syntax construct in README-named-types.csv decodes identically
6198        let named_types_bytes =
6199            crate::get_dc_data_file("README-named-types.csv")
6200                .context("Missing embedded README-named-types.csv")?;
6201        let table = csv_tools::parse_csv_reader(
6202            &named_types_bytes,
6203            csv_tools::CsvParseOptions {
6204                has_header: true,
6205                flexible: true,
6206                ..Default::default()
6207            },
6208        )?;
6209        let reconstructed_named: HashMap<String, ReconstructedNamedType> = index
6210            .reconstruct_named_types()?
6211            .into_iter()
6212            .map(|r| (r.name.clone(), r))
6213            .collect();
6214        for row_idx in 0..table.row_count() {
6215            let Some(row) = table.row(row_idx) else {
6216                continue;
6217            };
6218            if row.iter().all(|c| c.trim().is_empty()) {
6219                continue;
6220            }
6221            let name = row[0].trim();
6222            let raw_syntax = row[1].trim();
6223            let expected_notes = row.get(2).map_or("", |s| s.trim());
6224            let expected = parse_dc_syntax(raw_syntax)?;
6225            let decoded_pat = index
6226                .decode_named_construct_pattern(name)?
6227                .with_context(|| {
6228                    format!(
6229                        "Named construct '{name}' missing from SeedGraphIndex"
6230                    )
6231                })?;
6232            assert_eq!(
6233                decoded_pat, expected.pattern,
6234                "Named construct '{name}' pattern mismatch after decoding from seed graph"
6235            );
6236            let rec = reconstructed_named.get(name).with_context(|| {
6237                format!(
6238                    "Named construct '{name}' missing from reconstruct_named_types()"
6239                )
6240            })?;
6241            assert_eq!(rec.syntax.pattern, expected.pattern);
6242            assert_eq!(
6243                rec.description, expected_notes,
6244                "Named construct '{name}' description (Dc 573) mismatch after decoding from seed graph"
6245            );
6246        }
6247
6248        // 2. Verify every Dc syntax rule and @stable_ident() declaration in the dataset decodes identically from the seed graph
6249        for defn in crate::lookup::get_all_dc_defns() {
6250            let subj = DcShorthand::from_global_id(defn.dc_id);
6251            assert_eq!(
6252                index.has_stable_programmatic_identifier(subj),
6253                defn.stable_ident,
6254                "@stable_ident() mismatch in SeedGraphIndex for {subj} ({})",
6255                defn.name
6256            );
6257            let Some(expected_rule) = &defn.syntax else {
6258                continue;
6259            };
6260            let decoded_rule = index
6261                .decode_syntax_rule_for_subject(subj)?
6262                .with_context(|| {
6263                    format!(
6264                        "Missing syntax rule in SeedGraphIndex for {subj} ({})",
6265                        defn.name
6266                    )
6267                })?;
6268            assert_eq!(
6269                decoded_rule.pattern, expected_rule.pattern,
6270                "Syntax pattern mismatch in SeedGraphIndex for {subj} ({})",
6271                defn.name
6272            );
6273            assert_eq!(
6274                decoded_rule.action, expected_rule.action,
6275                "Syntax action mismatch in SeedGraphIndex for {subj} ({})",
6276                defn.name
6277            );
6278        }
6279
6280        // Verify f199 (`Integer`), f200 (`Natural0`), and f351 (`Natural1`) reconstruct `stable_ident: true` in a vacuum
6281        assert!(index.has_stable_programmatic_identifier(DcShorthand::Format(199)));
6282        assert!(index.has_stable_programmatic_identifier(DcShorthand::Format(200)));
6283        assert!(index.has_stable_programmatic_identifier(DcShorthand::Format(351)));
6284        assert!(!index.has_stable_programmatic_identifier(DcShorthand::Format(207)));
6285        assert!(!index.has_stable_programmatic_identifier(DcShorthand::Format(84)));
6286        let reconstructed_formats = index.reconstruct_format_defns()?;
6287        for (fid, expected_ident) in [(199usize, "Integer"), (200, "Natural0"), (351, "Natural1")] {
6288            let rec_fmt = reconstructed_formats
6289                .iter()
6290                .find(|d| d.short_id == Some(fid))
6291                .expect("Expected format in reconstruct_format_defns()");
6292            assert!(
6293                rec_fmt.stable_ident,
6294                "Expected f{fid} ({expected_ident}) to reconstruct stable_ident == true from seed graph"
6295            );
6296            assert_eq!(rec_fmt.ident.as_deref(), Some(expected_ident));
6297        }
6298
6299        // 3. Verify integer value node decoding roundtrip
6300        for &val in &[0u128, 1, 2, 63, 64, 230, 1024, 1_000_000] {
6301            let tokens = encode_integer_value_tokens(val);
6302            assert_eq!(decode_integer_value_tokens(&tokens), Some(val));
6303        }
6304
6305        // 4. Verify that the active bundle (`SeedGraphIndex::shared()`) has all inactive/historical
6306        // nodes filtered out at build time, while `load_with_history_from_asset_bundle()` loads
6307        // both `data/graph/*.ctbnbdl` and `data/graph/system/*.ctbnbdl` (100% of `.ctbnodes`),
6308        // and both resolve identical active properties and statements.
6309        assert_eq!(
6310            index.inactive_count(),
6311            0,
6312            "Active-only SeedGraphIndex::shared() should contain 0 inactive nodes"
6313        );
6314        let full_index = SeedGraphIndex::load_with_history_from_asset_bundle()?;
6315        let repo_root = crate::updater::find_repository_root()?;
6316        let raw_ledger_nodes = crate::graph_ledger::load_ledger_nodes_from_dir(
6317            &repo_root.join("assets/data/graph"),
6318        )?;
6319        assert_eq!(
6320            full_index.node_count(),
6321            raw_ledger_nodes.len(),
6322            "Active + history .ctbnbdl bundles must account for 100% of nodes in assets/data/graph/*.ctbnodes"
6323        );
6324        assert!(
6325            full_index.inactive_count() > 0,
6326            "Full index with history should include superseded nodes from data/graph/system/*.ctbnbdl"
6327        );
6328        assert_eq!(index.active_single_props, full_index.active_single_props);
6329        assert_eq!(index.active_multi_props, full_index.active_multi_props);
6330        assert_eq!(index.active_preferred, full_index.active_preferred);
6331        assert_eq!(index.active_direct_stmts, full_index.active_direct_stmts);
6332        assert_eq!(index.seed_entity_ids, full_index.seed_entity_ids);
6333
6334        Ok(())
6335    }
6336
6337    #[crate::ctb_test]
6338    fn test_ambiguity_candidates_require_explicit_revisions() -> Result<()> {
6339        let original_id = 8_589_934_592_u128;
6340        let candidate_one = original_id.saturating_add(1);
6341        let candidate_two = original_id.saturating_add(2);
6342        let ambiguity_id = original_id.saturating_add(3);
6343        let supersession_id = original_id.saturating_add(4);
6344        let reference_id = original_id.saturating_add(5);
6345        let retraction_id = original_id.saturating_add(6);
6346        for (first, second) in [
6347            (candidate_one, candidate_two),
6348            (candidate_two, candidate_one),
6349        ] {
6350            let mut nodes = crate::graph_ledger::load_ledger_nodes_from_str(
6351                &format!(
6352                    "l{original_id}: u78\nl{candidate_one}: 587 900 901\nl{candidate_two}: 587 900 902\nl{ambiguity_id}: 348 310 275 l{first} 312 l{second} 311\nl{supersession_id}: 591 l{ambiguity_id} l{original_id}\nl{reference_id}: 588 900 l{candidate_one}\n"
6353                ),
6354                "ambiguity-test",
6355            )?;
6356            let index = SeedGraphIndex::from_nodes(nodes.clone());
6357            assert_eq!(
6358                index.get_ambiguous_candidates(original_id),
6359                Some(vec![first, second])
6360            );
6361            assert!(index.has_direct_statement(
6362                DcShorthand::Short(587),
6363                DcShorthand::Short(900),
6364                DcShorthand::Short(901)
6365            ));
6366            assert!(index.has_direct_statement(
6367                DcShorthand::Short(587),
6368                DcShorthand::Short(900),
6369                DcShorthand::Short(902)
6370            ));
6371            assert!(index.has_direct_statement(
6372                DcShorthand::Short(588),
6373                DcShorthand::Short(900),
6374                DcShorthand::Long(candidate_one)
6375            ));
6376
6377            nodes.extend(crate::graph_ledger::load_ledger_nodes_from_str(
6378                &format!("l{retraction_id}: 592 615 l{candidate_one}\n"),
6379                "ambiguity-test",
6380            )?);
6381            let revised = SeedGraphIndex::from_nodes(nodes);
6382            assert!(!revised.is_node_active(candidate_one));
6383            assert!(revised.is_node_active(candidate_two));
6384            assert!(!revised.has_direct_statement(
6385                DcShorthand::Short(587),
6386                DcShorthand::Short(900),
6387                DcShorthand::Short(901)
6388            ));
6389            assert!(revised.has_direct_statement(
6390                DcShorthand::Short(587),
6391                DcShorthand::Short(900),
6392                DcShorthand::Short(902)
6393            ));
6394            assert_eq!(
6395                revised.get_ambiguous_candidates(original_id),
6396                Some(vec![first, second])
6397            );
6398        }
6399        Ok(())
6400    }
6401
6402    #[crate::ctb_test]
6403    fn test_ambiguity_recovery_prefix_invariants() -> Result<()> {
6404        let full_index = SeedGraphIndex::load_with_history_from_asset_bundle()?;
6405        let full_index = SeedGraphIndex::from_nodes(
6406            full_index
6407                .nodes
6408                .into_iter()
6409                .filter(|node| node.id <= 8_589_958_343)
6410                .collect(),
6411        );
6412        let (active_nodes, _) =
6413            crate::ctbnbdl::partition_active_and_inactive_nodes_with(
6414                &full_index.nodes,
6415                crate::graph_ledger::default_ctbnbdl_framing_dcs(),
6416            );
6417        let active_index = SeedGraphIndex::from_nodes(active_nodes);
6418
6419        // 1. Exact node counts after Step 2a (2,465), Step 2b (2,838), and Step 3 (616 retractions):
6420        // Only the immutable recovery prefix is checked; later allocations and revisions are excluded.
6421        assert_eq!(active_index.node_count(), 17_147);
6422        assert_eq!(active_index.inactive_count(), 0);
6423        assert_eq!(full_index.node_count(), 23_752);
6424        assert_eq!(full_index.inactive_count(), 2_931);
6425
6426        // 2. Verify all 24 unambiguous overwritten IDs have no Dc 348 "Ambiguous values" candidates
6427        let unambiguous_ids: Vec<u128> = (8_589_951_799..=8_589_951_801)
6428            .chain(8_589_951_803..=8_589_951_812)
6429            .chain(8_589_951_814..=8_589_951_824)
6430            .collect();
6431        assert_eq!(unambiguous_ids.len(), 24);
6432        for &id in &unambiguous_ids {
6433            assert_eq!(
6434                full_index.get_ambiguous_candidates(id),
6435                None,
6436                "Unambiguous ID l{id} must not resolve to a Dc 348 'Ambiguous values' list"
6437            );
6438        }
6439
6440        // 3. Verify all 602 dependency-ambiguous overwritten IDs resolve to `[r1_eff(N), r2_eff(N)]`,
6441        // where `r2_eff(N)` is active for all 602 IDs and `r1_eff(N)` is retracted for all 559 statements
6442        // (and active for the 43 value nodes).
6443        let ambiguous_ids: Vec<u128> = std::iter::once(8_589_951_802)
6444            .chain(std::iter::once(8_589_951_813))
6445            .chain(8_589_951_825..=8_589_952_424)
6446            .collect();
6447        assert_eq!(ambiguous_ids.len(), 602);
6448        let mut r1_retracted_stmts = 0usize;
6449        let mut r1_active_values = 0usize;
6450        for &orig_id in &ambiguous_ids {
6451            assert!(
6452                !full_index.is_node_active(orig_id),
6453                "Overwritten ID l{orig_id} must be superseded"
6454            );
6455            let cands = full_index
6456                .get_ambiguous_candidates(orig_id)
6457                .with_context(|| {
6458                    format!(
6459                        "Ambiguous ID l{orig_id} is missing Dc 348 'Ambiguous values' candidates"
6460                    )
6461                })?;
6462            assert_eq!(
6463                cands.len(),
6464                2,
6465                "Expected 2 Dc 348 candidates for l{orig_id}"
6466            );
6467            let r1_eff = cands[0];
6468            let r2_eff = cands[1];
6469            assert!(
6470                full_index.is_node_active(r2_eff),
6471                "Run 2 candidate l{r2_eff} (for l{orig_id}) must be active"
6472            );
6473            assert!(
6474                active_index.get_node(r2_eff).is_some(),
6475                "Run 2 candidate l{r2_eff} must be present in active recovery prefix"
6476            );
6477            if full_index.is_node_active(r1_eff) {
6478                r1_active_values += 1;
6479            } else {
6480                r1_retracted_stmts += 1;
6481                assert!(
6482                    active_index.get_node(r1_eff).is_none(),
6483                    "Retracted Run 1 statement candidate l{r1_eff} must be excluded from active recovery prefix"
6484                );
6485            }
6486        }
6487        assert_eq!(r1_retracted_stmts, 559);
6488        assert_eq!(r1_active_values, 43);
6489
6490        // 4. Verify all 57 restored Run 1 tail nodes (`l8589952425`..`l8589952481`) are inactive in the
6491        // live index (54 superseded by `l8589957620`..`l8589957727` and retracted in Step 3, plus 3 directly retracted in Step 3).
6492        for tail_id in 8_589_952_425..=8_589_952_481 {
6493            assert!(
6494                full_index.get_node(tail_id).is_some(),
6495                "Restored Run 1 tail node l{tail_id} must exist in historical index"
6496            );
6497            assert!(
6498                !full_index.is_node_active(tail_id),
6499                "Restored Run 1 tail node l{tail_id} must be inactive after Step 3"
6500            );
6501            assert!(
6502                active_index.get_node(tail_id).is_none(),
6503                "Restored Run 1 tail node l{tail_id} must not be in active recovery prefix"
6504            );
6505        }
6506
6507        // 5. Verify committed journal provenance and allocated .ctbnode-incoming files across the repository.
6508        let repo_root = crate::updater::find_repository_root()?;
6509        let prov_map =
6510            crate::graph_ledger::inbox::verify_repo_committed_node_provenance(
6511                &repo_root,
6512            )?;
6513        for node_id in 8_589_952_425..=8_589_958_343 {
6514            assert_eq!(
6515                prov_map.owner(node_id),
6516                crate::graph_ledger::inbox::NodeProvenance::Csv,
6517                "Expected recovered/reconciled node l{node_id} to have Csv provenance"
6518            );
6519        }
6520
6521        Ok(())
6522    }
6523
6524    #[crate::ctb_test]
6525    fn test_seed_graph_and_syntax_resolver_at_most_recent() -> Result<()> {
6526        use crate::syntax::{CharTarget, SyntaxRuleResolver};
6527
6528        let scripts = BTreeSet::from([".Semantic".to_string()]);
6529        let subj = DcShorthand::Short(915);
6530
6531        // Revision 1: Dc 915 has syntax rule `:~ [atom_dc]`
6532        let mut defn = make_test_defn(915, "Test Op", "Test syntax rule op");
6533        defn.syntax = Some(parse_dc_syntax(":~ [atom_dc]")?);
6534        let (nodes1, _) = update_ledger_in_memory(
6535            Vec::new(),
6536            &[defn.clone()],
6537            &[],
6538            &scripts,
6539            None,
6540        )?;
6541        let t1 = nodes1.last().expect("Expected Revision 1 nodes").id;
6542
6543        // Revision 2: Dc 915 syntax rule superseded by `:~ [atom_dc] [atom_dc]`
6544        defn.syntax = Some(parse_dc_syntax(":~ [atom_dc] [atom_dc]")?);
6545        let (nodes2, _) = update_ledger_in_memory(
6546            nodes1,
6547            &[defn.clone()],
6548            &[],
6549            &scripts,
6550            None,
6551        )?;
6552        let t2 = nodes2.last().expect("Expected Revision 2 nodes").id;
6553        assert!(t2 > t1);
6554
6555        // Revision 3: Dc 915 syntax rule retracted
6556        defn.syntax = None;
6557        let (nodes3, _) =
6558            update_ledger_in_memory(nodes2, &[defn], &[], &scripts, None)?;
6559        let t3 = nodes3.last().expect("Expected Revision 3 nodes").id;
6560        assert!(t3 > t2);
6561
6562        // Verify SeedGraphIndex::from_nodes_at_most_recent & DatasetRuleResolver::from_seed_graph at t1, t2, t3
6563        let idx_t1 = SeedGraphIndex::from_nodes_at_most_recent(nodes3.clone(), t1);
6564        assert_eq!(idx_t1.system_block_most_recent_node_id(), Some(t1));
6565        let resolver_t1 = crate::syntax::DatasetRuleResolver::from_seed_graph(&idx_t1)?;
6566        let rule_t1 = resolver_t1
6567            .resolve_rule(&CharTarget::Dc(915))
6568            .expect("Expected syntax rule at t1");
6569        assert_eq!(rule_t1.pattern, parse_dc_syntax(":~ [atom_dc]")?.pattern);
6570
6571        let idx_t2 = SeedGraphIndex::from_nodes_at_most_recent(nodes3.clone(), t2);
6572        assert_eq!(idx_t2.system_block_most_recent_node_id(), Some(t2));
6573        let resolver_t2 = crate::syntax::DatasetRuleResolver::from_seed_graph(&idx_t2)?;
6574        let rule_t2 = resolver_t2
6575            .resolve_rule(&CharTarget::Dc(915))
6576            .expect("Expected syntax rule at t2");
6577        assert_eq!(
6578            rule_t2.pattern,
6579            parse_dc_syntax(":~ [atom_dc] [atom_dc]")?.pattern
6580        );
6581
6582        let idx_t3 = SeedGraphIndex::from_nodes_at_most_recent(nodes3, t3);
6583        assert_eq!(idx_t3.system_block_most_recent_node_id(), Some(t3));
6584        assert!(idx_t3.decode_syntax_rule_for_subject(subj)?.is_none());
6585        let resolver_t3 = crate::syntax::DatasetRuleResolver::from_seed_graph(&idx_t3)?;
6586        assert!(resolver_t3.resolve_rule(&CharTarget::Dc(915)).is_none());
6587
6588        // Verify historical asset bundle reconstruction on a real historical System-block node ID:
6589        // At `l8589958834` (before the `AddSystemGraphMostRecent` rename supersession at `l8589958838`..`l8589958845`),
6590        // `f655` had programmatic identifier `"AddSystemGraphWatermark"`, whereas at HEAD it is `"AddSystemGraphMostRecent"`.
6591        let f655 = DcShorthand::Format(655);
6592        let hist_idx =
6593            SeedGraphIndex::load_at_most_recent_from_asset_bundle(8_589_958_834)?;
6594        assert_eq!(
6595            hist_idx.system_block_most_recent_node_id(),
6596            Some(8_589_958_834)
6597        );
6598        assert_eq!(
6599            hist_idx.get_single_property_string(
6600                f655,
6601                sh(DC_PROGRAMMATIC_IDENTIFIER)
6602            ),
6603            Some("AddSystemGraphWatermark")
6604        );
6605
6606        let head_idx = SeedGraphIndex::shared()?;
6607        let head_id = head_idx
6608            .system_block_most_recent_node_id()
6609            .expect("Expected HEAD system_block_most_recent_node_id");
6610        let head_pinned =
6611            SeedGraphIndex::load_at_most_recent_from_asset_bundle(head_id)?;
6612        assert!(Arc::ptr_eq(head_idx, &head_pinned));
6613        assert_eq!(
6614            head_pinned.get_single_property_string(
6615                f655,
6616                sh(DC_PROGRAMMATIC_IDENTIFIER)
6617            ),
6618            Some("AddSystemGraphMostRecent")
6619        );
6620
6621        // Gate 1: Reject pins newer than the local graph (`most_recent_node_id > head_id`)
6622        // rather than silently substituting `HEAD`.
6623        let future_id = head_id.saturating_add(1);
6624        let future_err =
6625            SeedGraphIndex::load_at_most_recent_from_asset_bundle(future_id)
6626                .expect_err("Pin newer than HEAD must fail");
6627        assert!(
6628            future_err
6629                .to_string()
6630                .contains(&format!("l{future_id} > l{head_id}")),
6631            "Unexpected error for future pin: {future_err}"
6632        );
6633        let future_res_err =
6634            crate::syntax::syntax_resolver_at_most_recent(future_id)
6635                .expect_err("syntax_resolver_at_most_recent must reject pin newer than HEAD");
6636        assert!(
6637            future_res_err
6638                .to_string()
6639                .contains(&format!("l{future_id} > l{head_id}")),
6640            "Unexpected resolver error for future pin: {future_res_err}"
6641        );
6642
6643        // Gate 1: Reject unsupported graph blocks (Data block and blocks above System).
6644        for unsupported_id in [
6645            ctb_storage_minimal::global_graph_layout::DATA_REGION_START,
6646            ctb_storage_minimal::global_graph_layout::SYSTEM_REGION_END
6647                .saturating_add(1),
6648        ] {
6649            let err = SeedGraphIndex::load_at_most_recent_from_asset_bundle(
6650                unsupported_id,
6651            )
6652            .expect_err("Unsupported graph block pin must fail");
6653            assert!(
6654                err.to_string().contains("unsupported graph block"),
6655                "Expected unsupported graph block error for l{unsupported_id}, got: {err}"
6656            );
6657        }
6658
6659        // Gate 1: Require complete historical graph bundles when resolving historical pins.
6660        let prefix_id = SYSTEM_REGION_START;
6661        let prefix_nodes = vec![
6662            LedgerNode {
6663                id: prefix_id,
6664                tokens: Vec::new(),
6665                comment: String::new(),
6666                created_ns: None,
6667            },
6668            LedgerNode {
6669                id: prefix_id.saturating_add(2),
6670                tokens: Vec::new(),
6671                comment: String::new(),
6672                created_ns: None,
6673            },
6674        ];
6675        let prefix_index =
6676            SeedGraphIndex::from_active_and_history_nodes_at_most_recent(
6677                Some(prefix_id.saturating_add(2)),
6678                prefix_nodes,
6679                None,
6680                Vec::new(),
6681                prefix_id,
6682            )?;
6683        assert_eq!(
6684            prefix_index.system_block_most_recent_node_id(),
6685            Some(prefix_id),
6686        );
6687
6688        let full_hist = SeedGraphIndex::load_with_history_from_asset_bundle()?;
6689        let (part_active, part_history) =
6690            crate::ctbnbdl::partition_active_and_inactive_nodes_with(
6691                &full_hist.nodes,
6692                crate::graph_ledger::default_ctbnbdl_framing_dcs(),
6693            );
6694        let missing_hist_err =
6695            SeedGraphIndex::from_active_and_history_nodes_at_most_recent(
6696                Some(head_id),
6697                part_active.clone(),
6698                None,
6699                Vec::new(),
6700                8_589_958_834,
6701            )
6702            .expect_err("Historical pin without history bundle must fail");
6703        assert!(
6704            missing_hist_err
6705                .to_string()
6706                .contains("system_graph_history.rsrc"),
6707            "Expected system_graph_history.rsrc error when history is absent, got: {missing_hist_err}"
6708        );
6709
6710        let mut gapped_history = part_history;
6711        let removed_hist_node = gapped_history.remove(0);
6712        let incomplete_hist_err =
6713            SeedGraphIndex::from_active_and_history_nodes_at_most_recent(
6714                Some(head_id),
6715                part_active,
6716                Some(head_id),
6717                gapped_history,
6718                8_589_958_834,
6719            )
6720            .expect_err("Historical pin with gap in history bundle must fail");
6721        assert!(
6722            incomplete_hist_err.to_string().contains(&format!(
6723                "missing node l{}",
6724                removed_hist_node.id
6725            )),
6726            "Expected missing node error for incomplete history, got: {incomplete_hist_err}"
6727        );
6728
6729        // Verify that no active Dc 594 "Syntax rule" pattern node at HEAD uses deprecated Dc 4 "!Range (deprecated)"
6730        // or legacy Dc 584 "Has a" string subtype qualifiers, while pinning to `l8589958931` (before structured
6731        // range/subtype encoding) still decodes historical Dc 4 and Dc 584 pattern nodes cleanly.
6732        let sh_syntax_rule = sh(DC_SYNTAX_RULE);
6733        let sh_legacy_range = sh(DC_RANGE);
6734        let sh_has_a = sh(DC_HAS_A);
6735        for (&(subj, prop), &(_, _, val_tok)) in &head_idx.active_single_props {
6736            if prop == sh_syntax_rule
6737                && let DcShorthand::Long(pat_node_id) = val_tok
6738            {
6739                let pat_node = head_idx
6740                    .get_node(pat_node_id)
6741                    .expect("Active syntax rule node must exist");
6742                assert!(
6743                    !pat_node.tokens.contains(&sh_legacy_range),
6744                    "Active syntax rule node l{pat_node_id} on {subj} must not contain deprecated Dc 4 '!Range (deprecated)'"
6745                );
6746                assert!(
6747                    !pat_node.tokens.contains(&sh_has_a),
6748                    "Active syntax rule node l{pat_node_id} on {subj} must not contain legacy Dc 584 string subtype qualifier"
6749                );
6750            }
6751        }
6752
6753        let pre_range_idx =
6754            SeedGraphIndex::load_at_most_recent_from_asset_bundle(8_589_958_931)?;
6755        let pre_range_resolver =
6756            crate::syntax::DatasetRuleResolver::from_seed_graph(&pre_range_idx)?;
6757        assert!(
6758            pre_range_resolver
6759                .resolve_rule(&CharTarget::Dc(405))
6760                .is_some(),
6761            "Historical Dc 405 rule with legacy subtype encoding should decode at l8589958931"
6762        );
6763        assert!(
6764            pre_range_resolver
6765                .resolve_named_type("asciiprintable")
6766                .is_some(),
6767            "Historical asciiprintable construct with legacy Dc 4 range should decode at l8589958931"
6768        );
6769
6770        Ok(())
6771    }
6772
6773    #[crate::ctb_test]
6774    fn test_gate2_trusted_system_supervisor_resolution_and_bundled_provenance()
6775    -> Result<()> {
6776        let base_id = SYSTEM_REGION_START;
6777        let entry_dc = DcChar::from_short(527);
6778        let helper_dc = DcChar::from_short(528);
6779        let sh_entry = sh(entry_dc);
6780        let sh_helper = sh(helper_dc);
6781
6782        // Helper WASM routine node `l(base_id)`
6783        let helper_def_id = base_id;
6784        let helper_tokens = vec![
6785            sh(DC_BEGIN_WASM_PROGRAM),
6786            DcShorthand::Short(712),
6787            sh(crate::dc::DC_BEGIN_NUMBER),
6788            DcShorthand::Format(199),
6789            sh(crate::dc::DC_END_NUMBER),
6790            DcShorthand::Short(1928),
6791        ];
6792        // Helper statements `584 528 611` (`l(base_id + 1)`) and `610 l(base_id + 1) l(base_id)` (`l(base_id + 2)`)
6793        let helper_has_a_id = base_id + 1;
6794        let helper_has_val_id = base_id + 2;
6795
6796        // Supervisor revision 1 (`l(base_id + 3)`), superseded by revision 2 (`l(base_id + 6)`)
6797        let sup_v1_def_id = base_id + 3;
6798        let sup_v1_has_a_id = base_id + 4;
6799        let sup_v1_has_val_id = base_id + 5;
6800
6801        // Supervisor revision 2 (`l(base_id + 6)`) referencing `helper_dc` (`528`) and `l(helper_def_id)`
6802        let sup_v2_def_id = base_id + 6;
6803        let sup_v2_tokens = vec![
6804            sh(DC_BEGIN_WASM_PROGRAM),
6805            sh_helper,
6806            DcShorthand::Long(helper_def_id),
6807            DcShorthand::Short(1928),
6808        ];
6809        let sup_v2_has_a_id = base_id + 7;
6810        let sup_v2_has_val_id = base_id + 8;
6811        let sup_stmt_id = base_id + 9; // `591 l(sup_v2_has_a_id) l(sup_v1_has_a_id)`
6812
6813        // Bundled `Dc 635` provenance (`Dc 636`) covering all bundled nodes `base_id..=sup_stmt_id`
6814        let prov_has_a_id = base_id + 10;
6815        let prov_has_val_id = base_id + 11;
6816        let mut prov_for_each_tokens = vec![
6817            sh(crate::dc::DC_DISTRIBUTE_STATEMENT_OVER_EACH),
6818            sh(DC_HAS_A),
6819            sh(DC_THIS_ELEMENT),
6820            sh(DC_COLLECTIVE_TOOLBOX_SEED_GRAPH_DATA_SOURCE),
6821            sh(DC_BEGIN_LIST),
6822            sh(crate::dc::DC_TYPE_ATOM_DC),
6823        ];
6824        for id in base_id..=sup_stmt_id {
6825            if id > base_id {
6826                prov_for_each_tokens.push(DcShorthand::Short(312));
6827            }
6828            prov_for_each_tokens.push(DcShorthand::Long(id));
6829        }
6830        prov_for_each_tokens.push(sh(DC_END_LIST));
6831
6832        let bundled_nodes = vec![
6833            LedgerNode {
6834                id: helper_def_id,
6835                tokens: helper_tokens.clone(),
6836                comment: String::new(),
6837                created_ns: None,
6838            },
6839            LedgerNode {
6840                id: helper_has_a_id,
6841                tokens: encode_statement_tokens(
6842                    sh(DC_HAS_A),
6843                    sh_helper,
6844                    sh(DC_CANONICAL_DECOMPOSITION),
6845                ),
6846                comment: String::new(),
6847                created_ns: None,
6848            },
6849            LedgerNode {
6850                id: helper_has_val_id,
6851                tokens: encode_statement_tokens(
6852                    sh(DC_HAS_VALUE),
6853                    DcShorthand::Long(helper_has_a_id),
6854                    DcShorthand::Long(helper_def_id),
6855                ),
6856                comment: String::new(),
6857                created_ns: None,
6858            },
6859            LedgerNode {
6860                id: sup_v1_def_id,
6861                tokens: helper_tokens.clone(),
6862                comment: String::new(),
6863                created_ns: None,
6864            },
6865            LedgerNode {
6866                id: sup_v1_has_a_id,
6867                tokens: encode_statement_tokens(
6868                    sh(DC_HAS_A),
6869                    sh_entry,
6870                    sh(DC_CANONICAL_DECOMPOSITION),
6871                ),
6872                comment: String::new(),
6873                created_ns: None,
6874            },
6875            LedgerNode {
6876                id: sup_v1_has_val_id,
6877                tokens: encode_statement_tokens(
6878                    sh(DC_HAS_VALUE),
6879                    DcShorthand::Long(sup_v1_has_a_id),
6880                    DcShorthand::Long(sup_v1_def_id),
6881                ),
6882                comment: String::new(),
6883                created_ns: None,
6884            },
6885            LedgerNode {
6886                id: sup_v2_def_id,
6887                tokens: sup_v2_tokens.clone(),
6888                comment: String::new(),
6889                created_ns: None,
6890            },
6891            LedgerNode {
6892                id: sup_v2_has_a_id,
6893                tokens: encode_statement_tokens(
6894                    sh(DC_HAS_A),
6895                    sh_entry,
6896                    sh(DC_CANONICAL_DECOMPOSITION),
6897                ),
6898                comment: String::new(),
6899                created_ns: None,
6900            },
6901            LedgerNode {
6902                id: sup_v2_has_val_id,
6903                tokens: encode_statement_tokens(
6904                    sh(DC_HAS_VALUE),
6905                    DcShorthand::Long(sup_v2_has_a_id),
6906                    DcShorthand::Long(sup_v2_def_id),
6907                ),
6908                comment: String::new(),
6909                created_ns: None,
6910            },
6911            LedgerNode {
6912                id: sup_stmt_id,
6913                tokens: encode_statement_tokens(
6914                    sh(DC_SUPERSEDES),
6915                    DcShorthand::Long(sup_v2_has_a_id),
6916                    DcShorthand::Long(sup_v1_has_a_id),
6917                ),
6918                comment: String::new(),
6919                created_ns: None,
6920            },
6921            LedgerNode {
6922                id: prov_has_a_id,
6923                tokens: prov_for_each_tokens,
6924                comment: String::new(),
6925                created_ns: None,
6926            },
6927            LedgerNode {
6928                id: prov_has_val_id,
6929                tokens: encode_statement_tokens(
6930                    sh(DC_HAS_VALUE),
6931                    DcShorthand::Long(prov_has_a_id),
6932                    sh(DC_COLLECTIVE_TOOLBOX_DC_CSV_SEED_DATABASE),
6933                ),
6934                comment: String::new(),
6935                created_ns: None,
6936            },
6937        ];
6938
6939        let trusted_idx =
6940            SeedGraphIndex::from_bundled_nodes(bundled_nodes.clone());
6941        let resolved = trusted_idx
6942            .resolve_trusted_system_supervisor_bootstrap_tokens(&[sh_entry])?;
6943        assert_eq!(resolved.entry_dc, entry_dc);
6944        assert_eq!(resolved.statement_node_id, sup_v2_has_a_id);
6945        assert_eq!(resolved.value_statement_node_id, sup_v2_has_val_id);
6946        assert_eq!(resolved.supervisor_revision_node_id, sup_v2_def_id);
6947        assert_eq!(resolved.system_head_node_id, prov_has_val_id);
6948        assert_eq!(
6949            resolved.dependency_snapshot_node_ids,
6950            vec![helper_def_id, sup_v2_def_id]
6951        );
6952        assert_eq!(resolved.definition_tokens, sup_v2_tokens);
6953
6954        // 1. Reject `Dc 641` pinned or multi-token bootstrap documents.
6955        let pinned_err = trusted_idx
6956            .resolve_trusted_system_supervisor_bootstrap_tokens(&[
6957                sh(DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID),
6958                DcShorthand::Long(prov_has_val_id),
6959                sh_entry,
6960            ])
6961            .expect_err("Pinned bootstrap document must be rejected");
6962        assert!(pinned_err.to_string().contains("unpinned"));
6963        assert!(
6964            trusted_idx
6965                .resolve_trusted_system_supervisor_bootstrap_tokens(&[
6966                    sh_entry, sh_helper
6967                ])
6968                .is_err()
6969        );
6970        assert!(
6971            trusted_idx
6972                .resolve_trusted_system_supervisor_bootstrap_tokens(&[
6973                    DcShorthand::Long(sup_v2_def_id)
6974                ])
6975                .is_err()
6976        );
6977
6978        // 2. Reject unbundled nodes even if they have System-block IDs and forged `Dc 635 = Dc 636` claims.
6979        let unbundled_idx = SeedGraphIndex::from_nodes(bundled_nodes.clone());
6980        let unbundled_err = unbundled_idx
6981            .resolve_trusted_system_supervisor_dc(entry_dc)
6982            .expect_err("Unbundled nodes must not supply bootstrap authority");
6983        assert!(
6984            format!("{unbundled_err:#}")
6985                .contains("authenticated bundled System asset"),
6986            "Unexpected error: {unbundled_err:#}"
6987        );
6988
6989        // 3. Reject extra/unbundled nodes attempting to supersede (`Dc 591`) the bundled supervisor definition.
6990        let extra_def_id = base_id + 20;
6991        let extra_has_a_id = base_id + 21;
6992        let extra_has_val_id = base_id + 22;
6993        let extra_sup_id = base_id + 23;
6994        let extra_prov_a = base_id + 24;
6995        let extra_prov_v = base_id + 25;
6996        let extra_nodes = vec![
6997            LedgerNode {
6998                id: extra_def_id,
6999                tokens: helper_tokens.clone(),
7000                comment: String::new(),
7001                created_ns: None,
7002            },
7003            LedgerNode {
7004                id: extra_has_a_id,
7005                tokens: encode_statement_tokens(
7006                    sh(DC_HAS_A),
7007                    sh_entry,
7008                    sh(DC_CANONICAL_DECOMPOSITION),
7009                ),
7010                comment: String::new(),
7011                created_ns: None,
7012            },
7013            LedgerNode {
7014                id: extra_has_val_id,
7015                tokens: encode_statement_tokens(
7016                    sh(DC_HAS_VALUE),
7017                    DcShorthand::Long(extra_has_a_id),
7018                    DcShorthand::Long(extra_def_id),
7019                ),
7020                comment: String::new(),
7021                created_ns: None,
7022            },
7023            LedgerNode {
7024                id: extra_sup_id,
7025                tokens: encode_statement_tokens(
7026                    sh(DC_SUPERSEDES),
7027                    DcShorthand::Long(extra_has_a_id),
7028                    DcShorthand::Long(sup_v2_has_a_id),
7029                ),
7030                comment: String::new(),
7031                created_ns: None,
7032            },
7033            LedgerNode {
7034                id: extra_prov_a,
7035                tokens: encode_statement_tokens(
7036                    sh(DC_HAS_A),
7037                    DcShorthand::Long(extra_sup_id),
7038                    sh(DC_COLLECTIVE_TOOLBOX_SEED_GRAPH_DATA_SOURCE),
7039                ),
7040                comment: String::new(),
7041                created_ns: None,
7042            },
7043            LedgerNode {
7044                id: extra_prov_v,
7045                tokens: encode_statement_tokens(
7046                    sh(DC_HAS_VALUE),
7047                    DcShorthand::Long(extra_prov_a),
7048                    sh(DC_COLLECTIVE_TOOLBOX_DC_CSV_SEED_DATABASE),
7049                ),
7050                comment: String::new(),
7051                created_ns: None,
7052            },
7053        ];
7054        let mixed_idx = SeedGraphIndex::from_bundled_and_extra_nodes(
7055            bundled_nodes.clone(),
7056            extra_nodes,
7057        )?;
7058        let poison_err = mixed_idx
7059            .resolve_trusted_system_supervisor_dc(entry_dc)
7060            .expect_err("Extra unbundled supersession must fail provenance check");
7061        assert!(
7062            format!("{poison_err:#}")
7063                .contains("authenticated bundled System asset"),
7064            "Unexpected error: {poison_err:#}"
7065        );
7066
7067        // 4. Reject bundled nodes whose `Dc 635` provenance is an untrusted source (e.g. Wikidata / Format(999)).
7068        let mut untrusted_source_nodes = bundled_nodes;
7069        untrusted_source_nodes.last_mut().unwrap().tokens =
7070            encode_statement_tokens(
7071                sh(DC_HAS_VALUE),
7072                DcShorthand::Long(prov_has_a_id),
7073                DcShorthand::Format(999),
7074            );
7075        let untrusted_idx =
7076            SeedGraphIndex::from_bundled_nodes(untrusted_source_nodes);
7077        let untrusted_err = untrusted_idx
7078            .resolve_trusted_system_supervisor_dc(entry_dc)
7079            .expect_err("Untrusted Dc 635 data source must be rejected");
7080        assert!(
7081            format!("{untrusted_err:#}")
7082                .contains("untrusted Dc 635 data source"),
7083            "Unexpected error: {untrusted_err:#}"
7084        );
7085
7086        Ok(())
7087    }
7088
7089    #[crate::ctb_test]
7090    fn test_query_api_verbatim_reverse_triples_and_pins() -> Result<()> {
7091        let base = 8_589_990_000u128;
7092        let val_a = base;
7093        let has_a = base + 1;
7094        let has_val_old = base + 2;
7095        let val_b = base + 3;
7096        let has_val_new = base + 4;
7097        let sup_stmt = base + 5;
7098        let extra_stmt = base + 6;
7099        let ret_stmt = base + 7;
7100        let for_each_stmt = base + 8;
7101
7102        let tok_a = vec![
7103            DcShorthand::Short(260),
7104            DcShorthand::Unicode(0x41),
7105            DcShorthand::Short(261),
7106        ];
7107        let tok_b = vec![
7108            DcShorthand::Short(260),
7109            DcShorthand::Unicode(0x42),
7110            DcShorthand::Short(261),
7111        ];
7112        let subj = DcShorthand::Short(901);
7113        let subj2 = DcShorthand::Short(902);
7114
7115        let nodes = vec![
7116            LedgerNode {
7117                id: val_a,
7118                tokens: tok_a.clone(),
7119                comment: String::new(),
7120                created_ns: None,
7121            },
7122            LedgerNode {
7123                id: has_a,
7124                tokens: encode_statement_tokens(
7125                    sh(DC_HAS_A),
7126                    subj,
7127                    sh(DC_CANONICAL_NAME),
7128                ),
7129                comment: String::new(),
7130                created_ns: None,
7131            },
7132            LedgerNode {
7133                id: has_val_old,
7134                tokens: encode_statement_tokens(
7135                    sh(DC_HAS_VALUE),
7136                    DcShorthand::Long(has_a),
7137                    DcShorthand::Long(val_a),
7138                ),
7139                comment: String::new(),
7140                created_ns: None,
7141            },
7142            LedgerNode {
7143                id: val_b,
7144                tokens: tok_b.clone(),
7145                comment: String::new(),
7146                created_ns: None,
7147            },
7148            LedgerNode {
7149                id: has_val_new,
7150                tokens: encode_statement_tokens(
7151                    sh(DC_HAS_VALUE),
7152                    DcShorthand::Long(has_a),
7153                    DcShorthand::Long(val_b),
7154                ),
7155                comment: String::new(),
7156                created_ns: None,
7157            },
7158            LedgerNode {
7159                id: sup_stmt,
7160                tokens: encode_statement_tokens(
7161                    sh(DC_SUPERSEDES),
7162                    DcShorthand::Long(has_val_new),
7163                    DcShorthand::Long(has_val_old),
7164                ),
7165                comment: String::new(),
7166                created_ns: None,
7167            },
7168            LedgerNode {
7169                id: extra_stmt,
7170                tokens: encode_statement_tokens(
7171                    sh(DC_IS_BASED_ON),
7172                    subj,
7173                    subj2,
7174                ),
7175                comment: String::new(),
7176                created_ns: None,
7177            },
7178            LedgerNode {
7179                id: ret_stmt,
7180                tokens: encode_statement_tokens(
7181                    sh(DC_RETRACTS),
7182                    sh(DC_ENCLOSING_DOCUMENT),
7183                    DcShorthand::Long(extra_stmt),
7184                ),
7185                comment: String::new(),
7186                created_ns: None,
7187            },
7188            LedgerNode {
7189                id: for_each_stmt,
7190                tokens: crate::graph_ledger::encode_for_each_statement_tokens(
7191                    sh(DC_IS_STABLE),
7192                    sh(DC_THIS_ELEMENT),
7193                    sh(DC_BOOLEAN_TRUE),
7194                    sh(DC_TYPE_ATOM_DC),
7195                    &[subj, subj2],
7196                ),
7197                comment: String::new(),
7198                created_ns: None,
7199            },
7200        ];
7201
7202        // 1. Snapshot pinned at `has_val_old` sees `has_val_old` active and neither `has_val_new` nor `ret_stmt`/`for_each_stmt`.
7203        let pin_early =
7204            SeedGraphIndex::from_nodes_at_most_recent(nodes.clone(), has_val_old);
7205        assert_eq!(
7206            pin_early.query_active_node_verbatim(val_a),
7207            Some(tok_a.as_slice())
7208        );
7209        assert_eq!(pin_early.query_active_node_verbatim(val_b), None);
7210        assert_eq!(
7211            pin_early.query_active_nodes_by_exact_tokens(&tok_a),
7212            &[val_a]
7213        );
7214        assert_eq!(
7215            pin_early.query_active_relationship_triples(
7216                Some(sh(DC_HAS_VALUE)),
7217                Some(DcShorthand::Long(has_a)),
7218                None,
7219            ),
7220            vec![(
7221                has_val_old,
7222                sh(DC_HAS_VALUE),
7223                DcShorthand::Long(has_a),
7224                DcShorthand::Long(val_a),
7225            )]
7226        );
7227
7228        // 2. Full snapshot excludes superseded `has_val_old` and retracted `extra_stmt`, includes expanded `Dc 638`.
7229        let full = SeedGraphIndex::from_nodes(nodes);
7230        assert_eq!(full.query_active_node_verbatim(has_val_old), None);
7231        assert_eq!(full.query_active_node_verbatim(extra_stmt), None);
7232        assert!(full.query_active_node_verbatim(val_b).is_some());
7233        assert_eq!(
7234            full.query_active_relationship_triples(
7235                Some(sh(DC_HAS_VALUE)),
7236                Some(DcShorthand::Long(has_a)),
7237                None,
7238            ),
7239            vec![(
7240                has_val_new,
7241                sh(DC_HAS_VALUE),
7242                DcShorthand::Long(has_a),
7243                DcShorthand::Long(val_b),
7244            )]
7245        );
7246        assert_eq!(
7247            full.query_active_relationship_triples(
7248                Some(sh(DC_IS_BASED_ON)),
7249                None,
7250                None,
7251            ),
7252            vec![]
7253        );
7254        assert_eq!(
7255            full.query_active_relationship_triples(
7256                Some(sh(DC_IS_STABLE)),
7257                None,
7258                Some(sh(DC_BOOLEAN_TRUE)),
7259            ),
7260            vec![
7261                (
7262                    for_each_stmt,
7263                    sh(DC_IS_STABLE),
7264                    subj,
7265                    sh(DC_BOOLEAN_TRUE),
7266                ),
7267                (
7268                    for_each_stmt,
7269                    sh(DC_IS_STABLE),
7270                    subj2,
7271                    sh(DC_BOOLEAN_TRUE),
7272                ),
7273            ]
7274        );
7275
7276        Ok(())
7277    }
7278
7279    #[crate::ctb_test]
7280    fn test_discover_system_wasm_substitute_targets_on_default_seed_graph()
7281    -> Result<()> {
7282        let sg = SeedGraphIndex::shared()?;
7283        let targets = sg.discover_system_wasm_substitute_targets()?;
7284        let subjects: Vec<DcShorthand> =
7285            targets.iter().map(|t| t.subject).collect();
7286        assert_eq!(
7287            subjects,
7288            vec![
7289                DcShorthand::Short(1936),
7290                DcShorthand::Short(2608),
7291                DcShorthand::Format(19),
7292                DcShorthand::Format(1680),
7293                DcShorthand::Format(1681),
7294            ]
7295        );
7296        for target in &targets {
7297            assert_eq!(
7298                target.chunk_prefix,
7299                substitute_chunk_prefix_for_node_id(target.defining_node_id),
7300                "Expected chunk_prefix to match defining_node_id {}",
7301                target.defining_node_id
7302            );
7303            assert!(
7304                target.chunk_prefix.contains('_')
7305                    && target.chunk_prefix.len() == 11,
7306                "Expected NNNNN_NNNNN .ctbnodes chunk prefix, got {}",
7307                target.chunk_prefix
7308            );
7309            assert!(
7310                (SYSTEM_REGION_START..=SYSTEM_REGION_END)
7311                    .contains(&target.defining_node_id)
7312            );
7313        }
7314        assert_eq!(
7315            targets[0].kind,
7316            SystemWasmSubstituteTargetKind::SupervisorKernel
7317        );
7318        assert_eq!(
7319            targets[1].kind,
7320            SystemWasmSubstituteTargetKind::StageRRoutineDcs
7321        );
7322        assert_eq!(
7323            targets[2].kind,
7324            SystemWasmSubstituteTargetKind::StageRRoutineDcs
7325        );
7326        assert!(matches!(
7327            targets[3].kind,
7328            SystemWasmSubstituteTargetKind::WasmConverter { .. }
7329        ));
7330        assert!(matches!(
7331            targets[4].kind,
7332            SystemWasmSubstituteTargetKind::StageLConverter { .. }
7333        ));
7334
7335        // Verify arbitrary-node-slice discovery captures both superseded historical revisions and raw .WASM value nodes.
7336        let base = SYSTEM_REGION_START;
7337        let wasm_v1 = vec![
7338            sh(DC_BEGIN_WASM_PROGRAM),
7339            sh(DC_BEGIN_ROUTINE_DECL),
7340            DcShorthand::Unicode(0x41),
7341            sh(crate::dc::DC_END_ROUTINE_DECL),
7342            sh(DC_END_WASM_PROGRAM),
7343        ];
7344        let wasm_v2 = vec![
7345            sh(DC_BEGIN_WASM_PROGRAM),
7346            sh(DC_BEGIN_ROUTINE_DECL),
7347            DcShorthand::Unicode(0x42),
7348            sh(crate::dc::DC_END_ROUTINE_DECL),
7349            sh(DC_END_WASM_PROGRAM),
7350        ];
7351        let raw_wasm = vec![
7352            sh(DC_BEGIN_WASM_PROGRAM),
7353            sh(DC_BEGIN_ROUTINE_DECL),
7354            DcShorthand::Unicode(0x43),
7355            sh(crate::dc::DC_END_ROUTINE_DECL),
7356            sh(DC_END_WASM_PROGRAM),
7357        ];
7358        let subj = DcShorthand::Short(1999);
7359        let slice = vec![
7360            LedgerNode {
7361                id: base,
7362                tokens: wasm_v1,
7363                comment: String::new(),
7364                created_ns: None,
7365            },
7366            LedgerNode {
7367                id: base + 1,
7368                tokens: encode_statement_tokens(
7369                    sh(DC_HAS_A),
7370                    subj,
7371                    sh(DC_CANONICAL_DECOMPOSITION),
7372                ),
7373                comment: String::new(),
7374                created_ns: None,
7375            },
7376            LedgerNode {
7377                id: base + 2,
7378                tokens: encode_statement_tokens(
7379                    sh(DC_HAS_VALUE),
7380                    DcShorthand::Long(base + 1),
7381                    DcShorthand::Long(base),
7382                ),
7383                comment: String::new(),
7384                created_ns: None,
7385            },
7386            LedgerNode {
7387                id: base + 100,
7388                tokens: wasm_v2,
7389                comment: String::new(),
7390                created_ns: None,
7391            },
7392            LedgerNode {
7393                id: base + 101,
7394                tokens: encode_statement_tokens(
7395                    sh(DC_HAS_VALUE),
7396                    DcShorthand::Long(base + 1),
7397                    DcShorthand::Long(base + 100),
7398                ),
7399                comment: String::new(),
7400                created_ns: None,
7401            },
7402            LedgerNode {
7403                id: base + 102,
7404                tokens: encode_statement_tokens(
7405                    sh(DC_SUPERSEDES),
7406                    DcShorthand::Long(base + 101),
7407                    DcShorthand::Long(base + 2),
7408                ),
7409                comment: String::new(),
7410                created_ns: None,
7411            },
7412            LedgerNode {
7413                id: base + 205,
7414                tokens: raw_wasm,
7415                comment: String::new(),
7416                created_ns: None,
7417            },
7418        ];
7419        let snaps = discover_graph_wasm_substitute_snapshots(&slice)?;
7420        assert_eq!(snaps.len(), 3);
7421        assert_eq!(snaps[0].target.subject, subj);
7422        assert_eq!(snaps[0].target.chunk_prefix, "85899_34592");
7423        assert!(!snaps[0].is_head);
7424        assert_eq!(snaps[1].target.subject, subj);
7425        assert_eq!(snaps[1].target.chunk_prefix, "85899_34692");
7426        assert!(snaps[1].is_head);
7427        assert_eq!(snaps[2].target.subject, DcShorthand::Long(base + 205));
7428        assert_eq!(snaps[2].target.chunk_prefix, "85899_34792");
7429        assert!(snaps[2].is_head);
7430        Ok(())
7431    }
7432
7433    #[crate::ctb_test]
7434    fn test_expand_interned_nodes_expands_comments_identifiers_and_blocks_literals_atoms_cycles()
7435    -> Result<()> {
7436        let str_id = SYSTEM_REGION_START;
7437        let sl_cmt_id = SYSTEM_REGION_START + 1;
7438        let blk_cmt_id = SYSTEM_REGION_START + 2;
7439        let ident_id = SYSTEM_REGION_START + 3;
7440        let cyc_id = SYSTEM_REGION_START + 4;
7441
7442        let nodes = vec![
7443            LedgerNode {
7444                id: str_id,
7445                tokens: vec![
7446                    sh(DC_BEGIN_LITERAL),
7447                    DcShorthand::Unicode(0x61),
7448                    sh(DC_END_LITERAL),
7449                ],
7450                comment: "\"a\"".to_string(),
7451                created_ns: None,
7452            },
7453            LedgerNode {
7454                id: sl_cmt_id,
7455                tokens: vec![
7456                    sh(DC_BEGIN_SINGLE_LINE_COMMENT),
7457                    DcShorthand::Unicode(0x63),
7458                    sh(DC_END_SINGLE_LINE_COMMENT),
7459                ],
7460                comment: "// c".to_string(),
7461                created_ns: None,
7462            },
7463            LedgerNode {
7464                id: blk_cmt_id,
7465                tokens: vec![
7466                    sh(DC_BEGIN_BLOCK_COMMENT_NEW_LINE),
7467                    DcShorthand::Unicode(0x62),
7468                    sh(DC_END_BLOCK_COMMENT),
7469                ],
7470                comment: "/* b */".to_string(),
7471                created_ns: None,
7472            },
7473            LedgerNode {
7474                id: ident_id,
7475                tokens: vec![
7476                    sh(DC_BEGIN_IDENTIFIER),
7477                    DcShorthand::Unicode(0x78),
7478                    sh(DC_END_IDENTIFIER),
7479                ],
7480                comment: "x".to_string(),
7481                created_ns: None,
7482            },
7483            LedgerNode {
7484                id: cyc_id,
7485                tokens: vec![
7486                    sh(DC_BEGIN_IDENTIFIER),
7487                    DcShorthand::Long(cyc_id),
7488                    sh(DC_END_IDENTIFIER),
7489                ],
7490                comment: "cycle".to_string(),
7491                created_ns: None,
7492            },
7493        ];
7494
7495        let idx = SeedGraphIndex::from_nodes(nodes);
7496        let input = vec![
7497            DcShorthand::Long(sl_cmt_id),
7498            DcShorthand::Long(blk_cmt_id),
7499            DcShorthand::Long(ident_id),
7500            sh(DC_TYPE_ATOM_DC),
7501            DcShorthand::Long(ident_id),
7502            sh(DC_EVALUATE_VALUE_AS_ATOM),
7503            DcShorthand::Long(sl_cmt_id),
7504            sh(DC_ESCAPE),
7505            DcShorthand::Long(str_id),
7506            sh(DC_BEGIN_LITERAL),
7507            sh(DC_TYPE_ATOM_DC),
7508            DcShorthand::Long(ident_id),
7509            sh(DC_END_LITERAL),
7510            sh(DC_BEGIN_LITERAL),
7511            DcShorthand::Long(ident_id),
7512            DcShorthand::Long(sl_cmt_id),
7513            DcShorthand::Long(str_id),
7514            sh(DC_END_LITERAL),
7515            DcShorthand::Long(cyc_id),
7516        ];
7517
7518        let expected = vec![
7519            sh(DC_BEGIN_SINGLE_LINE_COMMENT),
7520            DcShorthand::Unicode(0x63),
7521            sh(DC_END_SINGLE_LINE_COMMENT),
7522            sh(DC_BEGIN_BLOCK_COMMENT_NEW_LINE),
7523            DcShorthand::Unicode(0x62),
7524            sh(DC_END_BLOCK_COMMENT),
7525            sh(DC_BEGIN_IDENTIFIER),
7526            DcShorthand::Unicode(0x78),
7527            sh(DC_END_IDENTIFIER),
7528            sh(DC_TYPE_ATOM_DC),
7529            sh(DC_BEGIN_IDENTIFIER),
7530            DcShorthand::Unicode(0x78),
7531            sh(DC_END_IDENTIFIER),
7532            sh(DC_EVALUATE_VALUE_AS_ATOM),
7533            DcShorthand::Long(sl_cmt_id),
7534            sh(DC_ESCAPE),
7535            DcShorthand::Long(str_id),
7536            sh(DC_BEGIN_LITERAL),
7537            sh(DC_TYPE_ATOM_DC),
7538            DcShorthand::Long(ident_id),
7539            sh(DC_END_LITERAL),
7540            sh(DC_BEGIN_LITERAL),
7541            DcShorthand::Long(ident_id),
7542            DcShorthand::Long(sl_cmt_id),
7543            DcShorthand::Long(str_id),
7544            sh(DC_END_LITERAL),
7545            sh(DC_BEGIN_IDENTIFIER),
7546            DcShorthand::Long(cyc_id),
7547            sh(DC_END_IDENTIFIER),
7548        ];
7549
7550        assert_eq!(idx.expand_interned_string_nodes(&input), expected);
7551
7552        // Bare payload nodes shared across `[string]`, comments, and `[identifier]`,
7553        // plus `Dc 2239 "Quote following Dc as atom"` suppression & idempotence.
7554        let bare_hello_id = SYSTEM_REGION_START + 10;
7555        let bare_delim_id = SYSTEM_REGION_START + 11;
7556        let nodes_bare = vec![
7557            LedgerNode {
7558                id: bare_hello_id,
7559                tokens: vec![
7560                    DcShorthand::Unicode(0x48),
7561                    DcShorthand::Unicode(0x69),
7562                ],
7563                comment: "\"Hi\"".to_string(),
7564                created_ns: None,
7565            },
7566            LedgerNode {
7567                id: bare_delim_id,
7568                tokens: vec![
7569                    DcShorthand::Unicode(0x61),
7570                    sh(DC_END_LITERAL),
7571                    sh(DC_END_IDENTIFIER),
7572                    DcShorthand::Unicode(0x62),
7573                ],
7574                comment: "delim".to_string(),
7575                created_ns: None,
7576            },
7577        ];
7578        let idx_bare = SeedGraphIndex::from_nodes(nodes_bare);
7579        let bare_input = vec![
7580            sh(DC_BEGIN_LITERAL),
7581            sh(DC_BEGIN_TYPE_DEF),
7582            DcShorthand::Short(264),
7583            sh(DC_END_TYPE_DEF),
7584            DcShorthand::Long(bare_hello_id),
7585            sh(DC_QUOTE_FOLLOWING_DC_AS_ATOM),
7586            DcShorthand::Long(bare_hello_id),
7587            DcShorthand::Long(bare_delim_id),
7588            sh(DC_END_LITERAL),
7589            sh(DC_BEGIN_IDENTIFIER),
7590            DcShorthand::Long(bare_delim_id),
7591            sh(DC_END_IDENTIFIER),
7592            sh(DC_BEGIN_SINGLE_LINE_COMMENT),
7593            DcShorthand::Long(bare_hello_id),
7594            sh(DC_END_SINGLE_LINE_COMMENT),
7595        ];
7596        let bare_expected = vec![
7597            sh(DC_BEGIN_LITERAL),
7598            sh(DC_BEGIN_TYPE_DEF),
7599            DcShorthand::Short(264),
7600            sh(DC_END_TYPE_DEF),
7601            DcShorthand::Unicode(0x48),
7602            DcShorthand::Unicode(0x69),
7603            sh(DC_QUOTE_FOLLOWING_DC_AS_ATOM),
7604            DcShorthand::Long(bare_hello_id),
7605            DcShorthand::Unicode(0x61),
7606            sh(DC_ESCAPE),
7607            sh(DC_END_LITERAL),
7608            sh(DC_END_IDENTIFIER),
7609            DcShorthand::Unicode(0x62),
7610            sh(DC_END_LITERAL),
7611            sh(DC_BEGIN_IDENTIFIER),
7612            DcShorthand::Unicode(0x61),
7613            sh(DC_END_LITERAL),
7614            sh(DC_ESCAPE),
7615            sh(DC_END_IDENTIFIER),
7616            DcShorthand::Unicode(0x62),
7617            sh(DC_END_IDENTIFIER),
7618            sh(DC_BEGIN_SINGLE_LINE_COMMENT),
7619            DcShorthand::Unicode(0x48),
7620            DcShorthand::Unicode(0x69),
7621            sh(DC_END_SINGLE_LINE_COMMENT),
7622        ];
7623        let once = idx_bare.expand_interned_string_nodes(&bare_input);
7624        assert_eq!(once, bare_expected);
7625        assert_eq!(idx_bare.expand_interned_string_nodes(&once), bare_expected);
7626        Ok(())
7627    }
7628
7629    #[crate::ctb_test]
7630    fn test_seed_graph_reader_recovers_from_corrupted_ctbnbdl_and_value_revisions()
7631    -> Result<()> {
7632        let framing = crate::graph_ledger::default_ctbnbdl_framing_dcs();
7633
7634        let id_old_val = SYSTEM_REGION_START;
7635        let id_corrupt = SYSTEM_REGION_START + 1;
7636        let id_new_val = SYSTEM_REGION_START + 2;
7637        let id_sup_val = SYSTEM_REGION_START + 3;
7638        let id_junk = SYSTEM_REGION_START + 4;
7639        let id_cyc_a = SYSTEM_REGION_START + 5;
7640        let id_cyc_b = SYSTEM_REGION_START + 6;
7641        let id_sup_ab = SYSTEM_REGION_START + 7;
7642        let id_sup_ba = SYSTEM_REGION_START + 8;
7643
7644        let nodes = vec![
7645            LedgerNode {
7646                id: id_old_val,
7647                tokens: encode_string_value_tokens("old_value"),
7648                comment: String::new(),
7649                created_ns: Some(1_700_000_000_000_000_000),
7650            },
7651            LedgerNode {
7652                id: id_corrupt,
7653                tokens: encode_string_value_tokens("corrupted_middle_section"),
7654                comment: String::new(),
7655                created_ns: Some(1_700_000_001_000_000_000),
7656            },
7657            LedgerNode {
7658                id: id_new_val,
7659                tokens: encode_string_value_tokens("new_value"),
7660                comment: String::new(),
7661                created_ns: Some(1_700_000_002_000_000_000),
7662            },
7663            // Reader must NOT assume pure-value immutability: even if a graph contains `591` on a value node,
7664            // it warns and resolves `id_old_val -> id_new_val` cleanly without crashing.
7665            LedgerNode {
7666                id: id_sup_val,
7667                tokens: encode_statement_tokens(
7668                    sh(DC_SUPERSEDES),
7669                    DcShorthand::Long(id_new_val),
7670                    DcShorthand::Long(id_old_val),
7671                ),
7672                comment: String::new(),
7673                created_ns: Some(1_700_000_003_000_000_000),
7674            },
7675            // Nonsense / mojibake / dangling references must not crash reader indexing.
7676            LedgerNode {
7677                id: id_junk,
7678                tokens: vec![
7679                    DcShorthand::Short(4095),
7680                    DcShorthand::Long(SYSTEM_REGION_END),
7681                    DcShorthand::Unicode(0xFFFD),
7682                ],
7683                comment: String::new(),
7684                created_ns: None,
7685            },
7686            // Even a 2-node supersession cycle must terminate cleanly (`None`) rather than looping.
7687            LedgerNode {
7688                id: id_cyc_a,
7689                tokens: encode_statement_tokens(
7690                    sh(DC_IS_BASED_ON),
7691                    DcShorthand::Short(901),
7692                    DcShorthand::Short(902),
7693                ),
7694                comment: String::new(),
7695                created_ns: None,
7696            },
7697            LedgerNode {
7698                id: id_cyc_b,
7699                tokens: encode_statement_tokens(
7700                    sh(DC_IS_BASED_ON),
7701                    DcShorthand::Short(901),
7702                    DcShorthand::Short(903),
7703                ),
7704                comment: String::new(),
7705                created_ns: None,
7706            },
7707            LedgerNode {
7708                id: id_sup_ab,
7709                tokens: encode_statement_tokens(
7710                    sh(DC_SUPERSEDES),
7711                    DcShorthand::Long(id_cyc_b),
7712                    DcShorthand::Long(id_cyc_a),
7713                ),
7714                comment: String::new(),
7715                created_ns: None,
7716            },
7717            LedgerNode {
7718                id: id_sup_ba,
7719                tokens: encode_statement_tokens(
7720                    sh(DC_SUPERSEDES),
7721                    DcShorthand::Long(id_cyc_a),
7722                    DcShorthand::Long(id_cyc_b),
7723                ),
7724                comment: String::new(),
7725                created_ns: None,
7726            },
7727        ];
7728
7729        // 1. Even with intact SHA-256 checksums, strict default (`from_ctbnbdl_bytes`, without
7730        //    `--recover-graph`) MUST error on pure-value supersession or supersession cycles so
7731        //    inconsistencies cannot go unnoticed.
7732        let uncorrupted_bundle =
7733            crate::graph_ledger::encode_nodes_to_ctbnbdl_bytes_with(
7734                &nodes, framing,
7735            )?;
7736        let strict_semantic_err =
7737            SeedGraphIndex::from_ctbnbdl_bytes(&uncorrupted_bundle)
7738                .unwrap_err();
7739        assert!(
7740            format!("{strict_semantic_err:#}").contains("--recover-graph"),
7741            "unexpected error: {strict_semantic_err:#}"
7742        );
7743
7744        // 2. Flipping bytes inside `id_corrupt`'s section body MUST fail strict default decoding,
7745        //    and MUST quarantine `id_corrupt` while recovering all valid nodes under `--recover-graph`.
7746        let mut bundle = uncorrupted_bundle;
7747        let header_and_n0 =
7748            crate::graph_ledger::encode_nodes_to_ctbnbdl_bytes_with(
7749                std::slice::from_ref(&nodes[0]),
7750                framing,
7751            )?;
7752        let corrupt_pos = header_and_n0.len().saturating_add(14);
7753        bundle[corrupt_pos] ^= 0xAA;
7754
7755        assert!(SeedGraphIndex::from_ctbnbdl_bytes(&bundle).is_err());
7756
7757        let (recovered_idx, warnings) =
7758            SeedGraphIndex::from_ctbnbdl_bytes_resilient(&bundle)?;
7759        assert!(warnings.len() >= 2);
7760        assert!(recovered_idx.get_node(id_corrupt).is_none());
7761        assert_eq!(
7762            recovered_idx.resolve_latest_node_id(id_old_val),
7763            Some(id_new_val)
7764        );
7765        assert_eq!(recovered_idx.resolve_latest_node_id(id_cyc_a), None);
7766        assert!(recovered_idx.get_node(id_junk).is_some());
7767        Ok(())
7768    }
7769}