ctb_runtime/
runtime.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//! Subprocess runtime, job supervisor, and execution environment manager.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29#[allow(
30    unused_imports,
31    clippy::wildcard_imports,
32    reason = "Standard workspace prelude"
33)]
34pub use ctb_utilities::ipc::service_prelude::*;
35
36pub mod cli;
37
38use ctb_utilities::ipc::service_traits::{
39    ChildIpcContext, renderer::RenderSettings,
40};
41use serde::{Deserialize, Serialize};
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
44struct Document {
45    data: Vec<u8>,
46}
47
48const NETWORK_SERVICE_NAME: &str = "network";
49const NETWORK_METHOD_ECHO: &str = "echo";
50
51/// Start a document runtime with the provided document data.
52///
53/// This initializes the runtime environment for document processing,
54/// setting up the event loop and IPC orchestration infrastructure.
55#[ipc_method]
56pub fn start(#[ipc(shm)] document: Vec<u8>) -> i32 {
57    let doc = Document { data: document };
58    log_fmt!("runtime started with {} bytes", doc.data.len());
59    0
60}
61
62/// Post a rendered frame to the workspace.
63///
64/// The workspace can attribute the frame to a subprocess via the sender
65/// context included in the IPC message envelope.
66pub async fn post_frame_to_workspace(
67    ipc: &dyn ChildIpcContext,
68    bytes: Vec<u8>,
69    content_type: &str,
70) -> Result<()> {
71    ipc.send_data_plane_message(bytes, content_type).await
72}
73
74/// Test function demonstrating nested document runtime spawning via
75/// dependency-injected IPC.
76///
77/// In real use, the document runtime would send a request to the workspace to
78/// spawn a sub-document process and pass the workspace the node ID to render
79/// in a single `start_document()` (or something like that) call. The workspace
80/// would then handle most interaction with the subprocess (including the final
81/// render of multiple documents composed together), because the runtime for one
82/// document shouldn't have access to the runtimes for nested documents data or
83/// state beyond the initial node ID or passed through secure message passing.
84///
85/// # Arguments
86///
87/// * `document` - The document content to process
88/// * `ipc` - The IPC context for communicating with the workspace
89///
90/// # Returns
91///
92/// A formatted string combining the original document with the subprocess
93/// response.
94#[ipc_method]
95pub async fn test_simple_nested_document(
96    #[ipc(shm)] document: String,
97    settings: RenderSettings,
98) -> Result<i32> {
99    let ipc = ipc!();
100    let renderer = ipc.request_spawn_renderer(None).await?;
101    let response_str = renderer
102        .render_from_string(document.as_str(), settings)
103        .await?;
104    let subruntime = ipc.request_spawn_runtime(None).await?;
105    let subruntime_response = subruntime
106        .test_prepend(
107            response_str.clone(),
108            "Prepend example 12345: ".to_string(),
109        )
110        .await?;
111
112    // First, send a rendered frame back to the workspace.
113    let frame = format!(
114        "Runtime input document: {document}. Rendered: {response_str}. With subdocument: {subruntime_response}."
115    );
116    post_frame_to_workspace(ipc, frame.into_bytes(), "text/plain").await?;
117
118    // Denial test: attempt an unauthorized direct call to the network service.
119    // The workspace capability router should reject this and log an ERROR.
120    let denial_args = postcard_helpers::encode(
121        &b"unauthorized network request".to_vec(),
122        "network echo request",
123    )?;
124
125    // Best-effort: we expect this to fail due to runtime capabilities.
126    let _ = ipc
127        .call_raw(NETWORK_SERVICE_NAME, NETWORK_METHOD_ECHO, denial_args)
128        .await;
129
130    // Then, request that the workspace shuts down.
131    ipc.request_workspace_shutdown(Some(
132        "runtime requested shutdown after posting frame".into(),
133    ))
134    .await?;
135
136    // Finally, return an exit code.
137    Ok(0)
138}
139
140#[expect(clippy::unused_async, reason = "IPC method interface requirement")]
141#[ipc_method]
142/// Test method: prepend a string to the document.
143///
144/// This is a test helper for IPC routing verification during example
145/// development.
146pub async fn test_prepend(document: String, prepend: String) -> String {
147    format!("{prepend}{document}")
148}
149
150use ctb_formats_dcstring::{
151    DcChar, DcMstr, DcMstring, DcRole, DcShorthand, DcString,
152    DcWasmResourceLimits, DcWasmSession, DcWasmWatchdogLimits, SeedGraphIndex,
153    SyntaxRuleResolver, WASM_RESOURCE_ACCOUNTING_VERSION,
154    WasmResourceInterruption, WasmStepOutcome,
155    converters::eval_pure_graph_capability_request, dc,
156};
157use std::collections::HashMap;
158
159/// Authenticated System supervisor bootstrap admission and compiled local resource counters.
160///
161/// The runtime supervisor is not an ordinary user document: it is instantiated only by the host
162/// bootstrap entrypoint from an unpinned single-Short-Dc document whose active definition and
163/// transitive dependency subgraph carry authenticated bundled System provenance. User quota
164/// configuration is validated and compiled once at admission (or at an explicit task/step
165/// boundary) into compact local integer counters (`compiled_limits`) so execution never reads
166/// mutable graph state per instruction.
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct SystemSupervisorAdmission {
169    /// Short Dc entry point of the System supervisor base document.
170    pub entry_dc: DcChar,
171    /// Active System-block graph node ID holding the supervisor's canonical decomposition.
172    pub supervisor_revision_node_id: u128,
173    /// Sorted, deduplicated System-block node IDs in the supervisor's transitive dependency snapshot.
174    pub dependency_snapshot_node_ids: Vec<u128>,
175    /// Deterministic resource-accounting rule version (`WASM_RESOURCE_ACCOUNTING_VERSION`).
176    pub accounting_version: u32,
177    /// Compiled local integer resource counters (clamped by emergency host watchdog bounds).
178    pub compiled_limits: DcWasmResourceLimits,
179    /// Canonical 76-byte serialized snapshot of `compiled_limits` recorded in execution traces.
180    pub effective_config_bytes: Vec<u8>,
181}
182
183impl SystemSupervisorAdmission {
184    /// Canonical unpinned 1-Short-Dc bootstrap entry for the standalone Dc document execution
185    /// kernel (`Dc 1936` `"Dc document execution kernel"`).
186    pub const EXECUTION_KERNEL_ENTRY_DC: DcChar =
187        dc::DC_DC_DOCUMENT_EXECUTION_KERNEL;
188
189    /// Canonical unpinned 1-Short-Dc bootstrap entry for the full Collective Toolbox workspace
190    /// supervisor (`Dc 1937` `"Collective Toolbox Workspace"`).
191    pub const WORKSPACE_SUPERVISOR_ENTRY_DC: DcChar =
192        dc::DC_COLLECTIVE_TOOLBOX_WORKSPACE;
193
194    /// Resolves and authenticates the standalone execution kernel (`Dc 1936`
195    /// `"Dc document execution kernel"`) from the application-bundled System graph
196    /// (`SeedGraphIndex::shared()`), validates `user_limits` through the supervisor Dc-WASM
197    /// definition, and clamps emergency host `watchdog` bounds.
198    ///
199    /// # Errors
200    /// Returns an error if loading the bundled System graph fails or `user_limits` is rejected.
201    pub fn admit_execution_kernel(
202        user_limits: DcWasmResourceLimits,
203        watchdog: DcWasmWatchdogLimits,
204    ) -> Result<Self> {
205        let seed_graph = SeedGraphIndex::shared()?;
206        let entry = DcShorthand::from_global_id(
207            Self::EXECUTION_KERNEL_ENTRY_DC.to_u128(),
208        );
209        Self::admit_from_bootstrap_tokens(
210            seed_graph,
211            &[entry],
212            user_limits,
213            watchdog,
214        )
215    }
216
217    /// Resolves and authenticates the standalone execution kernel (`Dc 1936`
218    /// `"Dc document execution kernel"`) from the application-bundled System graph with default
219    /// resource and watchdog limits.
220    ///
221    /// # Errors
222    /// Returns an error if loading or authenticating the bundled System supervisor fails.
223    pub fn admit_execution_kernel_default() -> Result<Self> {
224        Self::admit_execution_kernel(
225            DcWasmResourceLimits::default(),
226            DcWasmWatchdogLimits::default(),
227        )
228    }
229
230    /// Resolves and validates a graph-backed user quota configuration node (`user_config_node_id`)
231    /// through the standalone execution kernel (`Dc 1936` `"Dc document execution kernel"`).
232    ///
233    /// # Errors
234    /// Returns an error if the supervisor or configuration node cannot be resolved or validated.
235    pub fn admit_execution_kernel_from_graph_config(
236        seed_graph: &SeedGraphIndex,
237        user_config_node_id: u128,
238        watchdog: DcWasmWatchdogLimits,
239    ) -> Result<Self> {
240        let entry = DcShorthand::from_global_id(
241            Self::EXECUTION_KERNEL_ENTRY_DC.to_u128(),
242        );
243        Self::admit_from_graph_config_node(
244            seed_graph,
245            &[entry],
246            user_config_node_id,
247            watchdog,
248        )
249    }
250
251    /// Resolves and authenticates the full workspace supervisor (`Dc 1937`
252    /// `"Collective Toolbox Workspace"`) from the application-bundled System graph
253    /// (`SeedGraphIndex::shared()`), validates `user_limits` through the supervisor Dc-WASM
254    /// definition, and clamps emergency host `watchdog` bounds.
255    ///
256    /// # Errors
257    /// Returns an error if loading the bundled System graph fails or `user_limits` is rejected.
258    pub fn admit_workspace_supervisor(
259        user_limits: DcWasmResourceLimits,
260        watchdog: DcWasmWatchdogLimits,
261    ) -> Result<Self> {
262        let seed_graph = SeedGraphIndex::shared()?;
263        let entry = DcShorthand::from_global_id(
264            Self::WORKSPACE_SUPERVISOR_ENTRY_DC.to_u128(),
265        );
266        Self::admit_from_bootstrap_tokens(
267            seed_graph,
268            &[entry],
269            user_limits,
270            watchdog,
271        )
272    }
273
274    /// Resolves and authenticates the full workspace supervisor (`Dc 1937`
275    /// `"Collective Toolbox Workspace"`) from the application-bundled System graph with default
276    /// resource and watchdog limits.
277    ///
278    /// # Errors
279    /// Returns an error if loading or authenticating the bundled System supervisor fails.
280    pub fn admit_workspace_supervisor_default() -> Result<Self> {
281        Self::admit_workspace_supervisor(
282            DcWasmResourceLimits::default(),
283            DcWasmWatchdogLimits::default(),
284        )
285    }
286
287    /// Resolves and validates a graph-backed user quota configuration node (`user_config_node_id`)
288    /// through the full workspace supervisor (`Dc 1937` `"Collective Toolbox Workspace"`).
289    ///
290    /// # Errors
291    /// Returns an error if the supervisor or configuration node cannot be resolved or validated.
292    pub fn admit_workspace_supervisor_from_graph_config(
293        seed_graph: &SeedGraphIndex,
294        user_config_node_id: u128,
295        watchdog: DcWasmWatchdogLimits,
296    ) -> Result<Self> {
297        let entry = DcShorthand::from_global_id(
298            Self::WORKSPACE_SUPERVISOR_ENTRY_DC.to_u128(),
299        );
300        Self::admit_from_graph_config_node(
301            seed_graph,
302            &[entry],
303            user_config_node_id,
304            watchdog,
305        )
306    }
307
308    /// Resolves and authenticates the unpinned 1-Short-Dc System supervisor bootstrap document
309    /// from `seed_graph`, validates `user_limits` (executing the System supervisor Dc-WASM
310    /// definition when non-empty), clamps emergency host `watchdog` bounds,
311    /// and compiles the local integer counters and canonical config snapshot.
312    ///
313    /// # Errors
314    /// Returns an error if `bootstrap_tokens` is pinned with `Dc 641`, contains multiple tokens
315    /// or a non-Short Dc, lacks authenticated bundled System provenance, or specifies an invalid
316    /// `user_limits` configuration.
317    pub fn admit_from_bootstrap_tokens(
318        seed_graph: &SeedGraphIndex,
319        bootstrap_tokens: &[DcShorthand],
320        user_limits: DcWasmResourceLimits,
321        watchdog: DcWasmWatchdogLimits,
322    ) -> Result<Self> {
323        let resolved = seed_graph
324            .resolve_trusted_system_supervisor_bootstrap_tokens(
325                bootstrap_tokens,
326            )?;
327        let validated_user_limits =
328            Self::validate_limits_with_supervisor_tokens(
329                &resolved.definition_tokens,
330                user_limits,
331            )?;
332        ensure!(
333            validated_user_limits.accounting_version
334                == WASM_RESOURCE_ACCOUNTING_VERSION,
335            "Unsupported WASM resource accounting version {} in user quota configuration (expected {})",
336            validated_user_limits.accounting_version,
337            WASM_RESOURCE_ACCOUNTING_VERSION
338        );
339        ensure!(
340            validated_user_limits.max_instructions_per_step > 0,
341            "Supervisor compute_quota (max_instructions_per_step) must be > 0"
342        );
343        ensure!(
344            validated_user_limits.max_memory_pages > 0,
345            "Supervisor memory_quota_pages (max_memory_pages) must be > 0"
346        );
347        let compiled_limits =
348            validated_user_limits.apply_watchdog_bounds(watchdog);
349        let effective_config_bytes =
350            compiled_limits.encode_canonical_config_bytes();
351        Ok(Self {
352            entry_dc: resolved.entry_dc,
353            supervisor_revision_node_id: resolved.supervisor_revision_node_id,
354            dependency_snapshot_node_ids: resolved.dependency_snapshot_node_ids,
355            accounting_version: compiled_limits.accounting_version,
356            compiled_limits,
357            effective_config_bytes,
358        })
359    }
360
361    /// Resolves and validates a graph-backed user quota configuration node (`user_config_node_id`)
362    /// through the trusted System supervisor bootstrap document (`bootstrap_tokens`).
363    ///
364    /// # Errors
365    /// Returns an error if the supervisor bootstrap tokens fail provenance verification, if the
366    /// graph configuration node is missing/retracted or malformed, or if the supervisor rejects
367    /// the configuration.
368    pub fn admit_from_graph_config_node(
369        seed_graph: &SeedGraphIndex,
370        bootstrap_tokens: &[DcShorthand],
371        user_config_node_id: u128,
372        watchdog: DcWasmWatchdogLimits,
373    ) -> Result<Self> {
374        let active_config_id = seed_graph
375            .resolve_latest_node_id(user_config_node_id)
376            .with_context(|| {
377                format!(
378                    "User quota configuration graph node l{user_config_node_id} is retracted or missing"
379                )
380            })?;
381        let config_node = seed_graph
382            .get_node(active_config_id)
383            .with_context(|| {
384                format!(
385                    "User quota configuration graph node l{active_config_id} not found in graph"
386                )
387            })?;
388        let parsed_limits =
389            Self::decode_graph_quota_config_tokens(&config_node.tokens)?;
390        Self::admit_from_bootstrap_tokens(
391            seed_graph,
392            bootstrap_tokens,
393            parsed_limits,
394            watchdog,
395        )
396    }
397
398    /// Encodes `limits` as a graph node token sequence (`Dc 310 "Begin list"` of 76 canonical
399    /// config bytes as `DcChar::from_unicode`, terminated by `Dc 311 "End list"`).
400    #[must_use]
401    pub fn encode_graph_quota_config_tokens(
402        limits: &DcWasmResourceLimits,
403    ) -> Vec<DcShorthand> {
404        let bytes = limits.encode_canonical_config_bytes();
405        let mut tokens = Vec::with_capacity(bytes.len().saturating_add(2));
406        tokens.push(DcShorthand::from_global_id(dc::DC_BEGIN_LIST.to_u128()));
407        for b in bytes {
408            tokens.push(DcShorthand::Unicode(u32::from(b)));
409        }
410        tokens.push(DcShorthand::from_global_id(dc::DC_END_LIST.to_u128()));
411        tokens
412    }
413
414    /// Decodes a graph-backed user quota configuration token sequence produced by
415    /// [`Self::encode_graph_quota_config_tokens`].
416    ///
417    /// # Errors
418    /// Returns an error if `tokens` is not a `Dc 310`..`Dc 311` list of 76 canonical config bytes.
419    pub fn decode_graph_quota_config_tokens(
420        tokens: &[DcShorthand],
421    ) -> Result<DcWasmResourceLimits> {
422        let open_list =
423            DcShorthand::from_global_id(dc::DC_BEGIN_LIST.to_u128());
424        let close_list = DcShorthand::from_global_id(dc::DC_END_LIST.to_u128());
425        ensure!(
426            tokens.first() == Some(&open_list)
427                && tokens.last() == Some(&close_list),
428            "Graph user quota configuration node must be enclosed in Dc 310 (Begin list) .. Dc 311 (End list)"
429        );
430        let inner = tokens
431            .get(1..tokens.len().saturating_sub(1))
432            .context("Graph user quota configuration node is too short")?;
433        let mut bytes = Vec::with_capacity(inner.len());
434        for &tok in inner {
435            let DcShorthand::Unicode(code) = tok else {
436                bail!(
437                    "Invalid token {tok} in graph user quota configuration node"
438                );
439            };
440            let byte = u8::try_from(code).with_context(|| {
441                format!(
442                    "Out-of-range byte U+{code:04X} in graph user quota configuration node"
443                )
444            })?;
445            bytes.push(byte);
446        }
447        DcWasmResourceLimits::decode_canonical_config_bytes(&bytes)
448    }
449
450    fn validate_limits_with_supervisor_tokens(
451        definition_tokens: &[DcShorthand],
452        user_limits: DcWasmResourceLimits,
453    ) -> Result<DcWasmResourceLimits> {
454        static SUPERVISOR_LIMITS_CACHE: std::sync::OnceLock<
455            std::sync::Mutex<
456                std::collections::HashMap<
457                    (Vec<DcShorthand>, Vec<u8>),
458                    DcWasmResourceLimits,
459                >,
460            >,
461        > = std::sync::OnceLock::new();
462
463        ctb_wasm_substitutes::ensure_registered();
464        if definition_tokens.len() <= 2 {
465            return Ok(user_limits);
466        }
467        let encoded_cfg = user_limits.encode_canonical_config_bytes();
468        let cache_key = (definition_tokens.to_vec(), encoded_cfg.clone());
469        let cache = SUPERVISOR_LIMITS_CACHE
470            .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
471        if let Ok(guard) = cache.lock()
472            && let Some(&cached) = guard.get(&cache_key)
473        {
474            return Ok(cached);
475        }
476        let mut sup_doc = DcMstring::new();
477        for &tok in definition_tokens {
478            let gid = tok.to_global_id()?;
479            sup_doc.push_char(DcChar::from_u128(gid));
480        }
481        let mut input_doc = DcMstring::new();
482        for b in encoded_cfg {
483            let ch = DcChar::from_unicode(u32::from(b))?;
484            input_doc.push_char(ch);
485        }
486        let mut session =
487            DcWasmSession::from_dc_wasm(&sup_doc, &input_doc, None)
488                .context("Failed to instantiate System supervisor Dc-WASM document")?;
489        let validated = match session.step()? {
490            WasmStepOutcome::Complete(out_doc) => {
491                if out_doc.as_bytes().is_empty() {
492                    user_limits
493                } else {
494                    let out_str = out_doc.to_dc_string()?;
495                    let mut out_bytes = Vec::with_capacity(76);
496                    for ch in out_str.chars() {
497                        let code = ch.to_unicode()?;
498                        let b = u8::try_from(code).context(
499                            "Supervisor output config contains non-byte character",
500                        )?;
501                        out_bytes.push(b);
502                    }
503                    DcWasmResourceLimits::decode_canonical_config_bytes(&out_bytes)?
504                }
505            }
506            other => bail!(
507                "System supervisor validation step must return Complete(config), got {other:?}"
508            ),
509        };
510        if let Ok(mut guard) = cache.lock() {
511            if guard.len() >= 256 {
512                guard.clear();
513            }
514            guard.insert(cache_key, validated);
515        }
516        Ok(validated)
517    }
518
519    /// Verifies that an ordinary user document does not attempt to claim System supervisor
520    /// privilege.
521    ///
522    /// An ordinary document's leading `Dc 641` graph pin or reference to `supervisor_entry_dc`
523    /// is **not** an elevation attempt: valid pinned ordinary documents and ordinary documents
524    /// referencing `supervisor_entry_dc` execute normally without supervisor authority.
525    /// Actual attempts by an ordinary document to assert workspace supervisor role
526    /// (`Dc 527 "Execution environment process role is workspace supervisor"` = `Dc 517 "Boolean true"`)
527    /// or inline bundled seed-graph provenance (`Dc 635` = `Dc 636`) are denied.
528    ///
529    /// # Errors
530    /// Returns an error if `ordinary_doc_tokens` explicitly claims supervisor privilege.
531    pub fn verify_ordinary_document_cannot_elevate(
532        ordinary_doc_tokens: &[DcShorthand],
533        _supervisor_entry_dc: DcChar,
534    ) -> Result<()> {
535        let role_supervisor = DcShorthand::Short(527);
536        let bool_true =
537            DcShorthand::from_global_id(dc::DC_BOOLEAN_TRUE.to_u128());
538        let seed_source = DcShorthand::from_global_id(
539            dc::DC_COLLECTIVE_TOOLBOX_SEED_GRAPH_DATA_SOURCE.to_u128(),
540        );
541        let bundled_csv = DcShorthand::from_global_id(
542            dc::DC_COLLECTIVE_TOOLBOX_DC_CSV_SEED_DATABASE.to_u128(),
543        );
544        for window in ordinary_doc_tokens.windows(2) {
545            if window == [role_supervisor, bool_true] {
546                bail!(
547                    "Ordinary user document cannot elevate privilege by asserting Dc 527 (Execution environment process role is workspace supervisor) = true"
548                );
549            }
550            if window == [seed_source, bundled_csv] {
551                bail!(
552                    "Ordinary user document cannot elevate privilege by asserting inline Dc 635/636 bundled seed-graph provenance"
553                );
554            }
555        }
556        Ok(())
557    }
558
559    /// Verifies that a raw [`DcMstr`] ordinary document does not attempt to claim System
560    /// supervisor privilege.
561    ///
562    /// # Errors
563    /// Returns an error if `ordinary_doc` contains an inline supervisor privilege claim.
564    pub fn verify_ordinary_dc_document_cannot_elevate(
565        ordinary_doc: &DcMstr,
566        supervisor_entry_dc: DcChar,
567    ) -> Result<()> {
568        let dc_str = ordinary_doc.to_dc_string()?;
569        let mut tokens = Vec::with_capacity(dc_str.len());
570        for ch in dc_str.chars() {
571            tokens.push(DcShorthand::from_global_id(ch.to_u128()));
572        }
573        Self::verify_ordinary_document_cannot_elevate(
574            &tokens,
575            supervisor_entry_dc,
576        )
577    }
578
579    /// Scans `doc` Dc-by-Dc (skipping escaped tokens, literal strings, identifiers, binary
580    /// payloads, and source comments) to locate the first unquoted `[pin_description]`
581    /// (`Dc 641` System-block revision pin), returning `(pin_tokens, pin_node_id)`.
582    ///
583    /// # Errors
584    /// Returns an error if `doc` contains invalid DcTF bytes or a malformed `[pin_description]`.
585    pub fn scan_first_pin_description(
586        doc: &DcMstr,
587        resolver: &dyn ctb_formats_dcstring::SyntaxRuleResolver,
588    ) -> Result<Option<(Vec<DcChar>, u128)>> {
589        use ctb_formats_dcstring::global_graph_layout::{
590            SYSTEM_REGION_END, SYSTEM_REGION_START,
591            unsupported_graph_block_description,
592        };
593        use ctb_formats_dcstring::syntax::{DcRole, SyntaxTerm};
594        use ctb_formats_dcstring::{
595            DcByteSpan, DcCharExt, DcDocumentNavigator, SyntaxEvalContext,
596        };
597
598        let chars: Vec<DcChar> = doc.to_dc_string()?.chars().collect();
599        let mut idx = 0usize;
600        while let Some(&ch) = chars.get(idx) {
601            if ch.fills_role_with(DcRole::Escape, resolver) {
602                idx = idx.saturating_add(2);
603                continue;
604            }
605            let skip_closer_role = if ch
606                .fills_role_with(DcRole::BeginLiteral, resolver)
607            {
608                Some(DcRole::EndLiteral)
609            } else if ch.fills_role_with(DcRole::BeginIdentifier, resolver) {
610                Some(DcRole::EndIdentifier)
611            } else if ch
612                .fills_role_with(DcRole::StartEncapsulationBinary, resolver)
613            {
614                Some(DcRole::EndEncapsulationBinary)
615            } else if ch
616                .fills_role_with(DcRole::BeginSingleLineComment, resolver)
617                || ch.fills_role_with(
618                    DcRole::BeginSingleLineCommentNewLine,
619                    resolver,
620                )
621            {
622                Some(DcRole::EndSingleLineComment)
623            } else if ch.fills_role_with(DcRole::BeginBlockComment, resolver)
624                || ch
625                    .fills_role_with(DcRole::BeginBlockCommentNewLine, resolver)
626            {
627                Some(DcRole::EndBlockComment)
628            } else {
629                None
630            };
631            if let Some(closer_role) = skip_closer_role {
632                idx = idx.saturating_add(1);
633                while let Some(&inner_ch) = chars.get(idx) {
634                    if inner_ch.fills_role_with(DcRole::Escape, resolver) {
635                        idx = idx.saturating_add(2);
636                        continue;
637                    }
638                    idx = idx.saturating_add(1);
639                    if inner_ch.fills_role_with(closer_role, resolver) {
640                        break;
641                    }
642                }
643                continue;
644            }
645            if ch.fills_role_with(
646                DcRole::GlobalGraphSystemBlockMostRecentNodeId,
647                resolver,
648            ) {
649                let mut tail_mstr = DcMstring::new();
650                for &tok in chars.get(idx..).into_iter().flatten() {
651                    tail_mstr.push_char(tok);
652                }
653                let mut nav = DcDocumentNavigator::from_mstr(&tail_mstr);
654                let start_pos = nav.position();
655                let mut ctx = SyntaxEvalContext::new(resolver, None);
656                let matched = nav.eval_term_single(
657                    &SyntaxTerm::NamedConstruct {
658                        name: "pin_description".to_owned(),
659                        subtype: None,
660                        capture_var: None,
661                    },
662                    &mut ctx,
663                )?;
664                ensure!(
665                    matched && !ctx.has_errors && nav.position() > start_pos,
666                    "Malformed [pin_description] starting at Dc 641 in document"
667                );
668                let pin_end = nav.position();
669                let pin_u128s =
670                    nav.read_tokens_in_span(DcByteSpan::new(start_pos, pin_end))?;
671                let pin_tokens: Vec<DcChar> =
672                    pin_u128s.into_iter().map(DcChar::from_u128).collect();
673                let second = pin_tokens.get(1).copied().context(
674                    "Missing System-block node ID operand after Dc 641",
675                )?;
676                let pin_id = if second.fills_role_with(DcRole::Escape, resolver)
677                    || second.fills_role_with(
678                        DcRole::QuoteFollowingDcAsAtom,
679                        resolver,
680                    )
681                {
682                    pin_tokens
683                        .get(2)
684                        .copied()
685                        .context("Dangling escape in Dc 641 pin_description")?
686                        .to_u128()
687                } else {
688                    second.to_u128()
689                };
690                if let Some(block_desc) =
691                    unsupported_graph_block_description(pin_id)
692                {
693                    bail!(
694                        "Unsupported graph block pin in Dc 641: node ID l{pin_id} targets {block_desc}"
695                    );
696                }
697                ensure!(
698                    (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&pin_id),
699                    "Invalid System-block most recent node ID {pin_id} for Dc 641: expected System block range {SYSTEM_REGION_START}..={SYSTEM_REGION_END}"
700                );
701                return Ok(Some((pin_tokens, pin_id)));
702            }
703            idx = idx.saturating_add(1);
704        }
705        Ok(None)
706    }
707
708    /// Quotes `doc` as a typed Dc `[string]` literal (`Dc 260 "Begin literal value"`,
709    /// `Dc 262 "Begin type definition"`, `Dc 264 "Built-in type identifier: String"`,
710    /// `Dc 263 "End type definition"`, escaped payload, `Dc 261 "End literal value"`).
711    ///
712    /// # Errors
713    /// Returns an error if `doc` contains malformed DcTF bytes.
714    pub fn quote_dc_document_as_string_literal(
715        doc: &DcMstr,
716        resolver: &dyn ctb_formats_dcstring::SyntaxRuleResolver,
717    ) -> Result<Vec<DcChar>> {
718        use ctb_formats_dcstring::DcCharExt;
719        use ctb_formats_dcstring::syntax::DcRole;
720
721        let chars: Vec<DcChar> = doc.to_dc_string()?.chars().collect();
722        let mut out = Vec::with_capacity(chars.len().saturating_add(6));
723        out.push(dc::DC_BEGIN_LITERAL);
724        out.push(dc::DC_BEGIN_TYPE_DEF);
725        out.push(dc::DC_TYPE_STRING);
726        out.push(dc::DC_END_TYPE_DEF);
727        for ch in chars {
728            if ch.fills_role_with(DcRole::Escape, resolver)
729                || ch.fills_role_with(DcRole::EndLiteral, resolver)
730                || ch.fills_role_with(DcRole::QuoteFollowingDcAsAtom, resolver)
731            {
732                out.push(dc::DC_ESCAPE);
733            }
734            out.push(ch);
735        }
736        out.push(dc::DC_END_LITERAL);
737        Ok(out)
738    }
739
740    /// Admits the `Dc 1936` (`Dc document execution kernel`) supervisor with
741    /// bounded CLI compilation and execution quotas sufficient to self-host
742    /// StageR 3 (`f1681`) and StageL 3 (`f1680`) pipelines while still enforcing
743    /// deterministic compute, memory, and output limits.
744    ///
745    /// # Errors
746    /// Returns an error if resolving or executing `Dc 1936` fails.
747    pub fn admit_cli_execution_kernel() -> Result<Self> {
748        let limits = DcWasmResourceLimits::default()
749            .with_max_instructions_per_step(4_000_000_000)
750            .with_max_memory_pages(8192)
751            .with_max_step_output_bytes(32 * 1024 * 1024)
752            .with_max_session_output_bytes(64 * 1024 * 1024)
753            .with_max_capability_payload_bytes(32 * 1024 * 1024);
754        let watchdog = DcWasmWatchdogLimits::default()
755            .with_physical_max_memory_pages(8192)
756            .with_hard_max_instructions_per_step(4_000_000_000);
757        Self::admit_execution_kernel(limits, watchdog)
758    }
759
760    /// Compiles an arbitrary executable Dc document `doc` into a `Dc 1927`..`Dc 1928` Dc-WASM
761    /// program by evaluating `[Dc 1938 <pin_description> [Dc 2608 <quoted_doc>]]` (or unpinned
762    /// `[Dc 2608 <quoted_doc>]`) under `shared_quota`, ensuring compilation runs under the
763    /// exact same resource quotas as target execution.
764    ///
765    /// # Errors
766    /// Returns an error if `doc` attempts privilege elevation, fails pin/converter resolution,
767    /// traps during compilation, or exhausts `shared_quota`.
768    pub fn compile_dc_document_to_wasm_with_shared_quota(
769        &self,
770        doc: &DcMstr,
771        resolver: &dyn ctb_formats_dcstring::SyntaxRuleResolver,
772        shared_quota: ctb_formats_dcstring::converters::wasm::SharedWasmTaskQuota,
773    ) -> Result<(DcMstring, Option<u128>)> {
774        use ctb_formats_dcstring::{
775            DcExpressionEvaluator, SharedQuotaDcExpressionEvaluator,
776        };
777
778        Self::verify_ordinary_dc_document_cannot_elevate(doc, self.entry_dc)?;
779        let opt_pin = Self::scan_first_pin_description(doc, resolver)?;
780        let quoted_doc =
781            Self::quote_dc_document_as_string_literal(doc, resolver)?;
782        let mut dispatch_tokens =
783            Vec::with_capacity(quoted_doc.len().saturating_add(6));
784        let pin_id = if let Some((pin_tokens, id)) = opt_pin {
785            dispatch_tokens.push(dc::DC_RESOLVE_TO_PIN);
786            dispatch_tokens.extend(pin_tokens);
787            Some(id)
788        } else {
789            None
790        };
791        dispatch_tokens.push(dc::DC_CONVERT_DC_STRING_TO_WASM);
792        dispatch_tokens.extend(quoted_doc);
793
794        let evaluator = SharedQuotaDcExpressionEvaluator::with_shared_task_quota(
795            shared_quota,
796        );
797        let wasm_chars = evaluator
798            .eval_stream_splice(&dispatch_tokens, resolver)?
799            .context("ConvertDcStringToWasm did not produce a Dc-WASM program")?;
800        let mut wasm_dc_str =
801            DcString::with_capacity(wasm_chars.len().saturating_mul(4));
802        for ch in wasm_chars {
803            wasm_dc_str.push(ch);
804        }
805        let wasm_doc = DcMstring::from_dc_str_with_policy_and_resolver(
806            &wasm_dc_str,
807            &ctb_formats_dcstring::DcProjectionPolicy::strict(),
808            resolver,
809        )?;
810        Ok((wasm_doc, pin_id))
811    }
812}
813
814/// Native Document Character runtime value.
815#[derive(Debug, Clone, PartialEq, Eq)]
816pub enum RuntimeValue {
817    /// Document Character string representation without premature UTF-8
818    /// decoding.
819    DcStr(DcString),
820    /// Numeric value.
821    Number(i64),
822    /// Structured list of runtime values.
823    List(Vec<RuntimeValue>),
824    /// 0-bit unit value for statements or void routines.
825    Unit,
826    /// Unreachable value.
827    Never,
828}
829
830/// Capability privilege requested by a running document.
831#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
832pub enum Privilege {
833    /// Filesystem input/output.
834    FileIo,
835    /// Network communication.
836    Network,
837    /// High-resolution timers or performance counters.
838    HighResolutionTimers,
839    /// Excessive compute budget exhausted before the document is fully parsed.
840    ExcessiveCompute,
841    /// Read-only minimal query of the active System graph (`Dc 1939`).
842    SystemGraphQuery,
843    /// Pure child WebAssembly execution (`Dc 1940`) under shared task quotas.
844    ExecutePureWasm,
845    /// Custom privileged operation.
846    Custom(String),
847}
848
849impl Privilege {
850    /// Classifies a capability request `DcMstr` emitted by a WASM module
851    /// (`WasmStepStatus::RequestCapability`) against `resolver`.
852    #[must_use]
853    pub fn from_request_dc_with_resolver(
854        request: &DcMstr,
855        resolver: &dyn SyntaxRuleResolver,
856    ) -> Self {
857        if let Ok(dc_str) = request.to_dc_string()
858            && let Some(first) = dc_str.chars().next()
859        {
860            let first_u = first.to_u128();
861            if resolver
862                .token_fills_role(first_u, DcRole::MinimalSystemGraphQuery)
863            {
864                return Self::SystemGraphQuery;
865            }
866            if resolver
867                .token_fills_role(first_u, DcRole::ExecutePureWasmProgram)
868            {
869                return Self::ExecutePureWasm;
870            }
871        }
872        Self::from_request_dc_ascii_fallback(request)
873    }
874
875    /// Classifies a capability request `DcMstr` emitted by a WASM module
876    /// (`WasmStepStatus::RequestCapability`) using the default syntax resolver.
877    #[must_use]
878    pub fn from_request_dc(request: &DcMstr) -> Self {
879        let default_res =
880            ctb_formats_dcstring::syntax::default_syntax_resolver();
881        Self::from_request_dc_with_resolver(request, default_res.as_ref())
882    }
883
884    fn from_request_dc_ascii_fallback(request: &DcMstr) -> Self {
885        let mut ascii = String::new();
886        if let Ok(dc_str) = request.to_dc_string() {
887            for ch in dc_str.chars() {
888                if let Ok(code) = ch.to_unicode()
889                    && let Some(c) = char::from_u32(code)
890                    && (c.is_ascii_alphanumeric() || c == '_' || c == ':')
891                {
892                    ascii.push(c);
893                }
894            }
895        }
896        match ascii.as_str() {
897            "FileIo" | "file_io" => Self::FileIo,
898            "Network" | "network" => Self::Network,
899            "HighResolutionTimers" | "timers" => Self::HighResolutionTimers,
900            "ExcessiveCompute" | "excessive_compute" => Self::ExcessiveCompute,
901            other => Self::Custom(other.to_owned()),
902        }
903    }
904}
905
906/// Result of running a [`DcWasmSession`] under [`ExecutionContext`].
907#[derive(Debug, Clone, PartialEq, Eq)]
908pub struct WasmExecutionResult {
909    /// Final output `DcMstring` (or empty if execution broke out early via `BreakOutResumeNext`).
910    pub output: DcMstring,
911    /// Intermediate frame outputs emitted via `WasmStepStatus::YieldFrame` (`1`).
912    pub frames: Vec<DcMstring>,
913    /// True if execution broke out early via `PermissionDecision::BreakOutResumeNext`
914    /// (e.g., due to `Privilege::ExcessiveCompute`).
915    pub broke_out_early: bool,
916}
917
918/// Multi-state capability permission decision.
919#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
920pub enum PermissionDecision {
921    /// Deny the permission visibly to the document.
922    Deny,
923    /// Automatically return spoofed/mocked data.
924    AutoMock,
925    /// Provide a custom replacement interface with user-specified mock
926    /// methods.
927    ManualMock,
928    /// Allow the permission (gated behind warning UI when parse errors exist).
929    Allow,
930    /// Break out of infinite loops or excessive compute and resume executing
931    /// and printing the document on the next Dc.
932    BreakOutResumeNext,
933}
934
935/// Observable execution trace event recorded during a [`DcWasmSession`] run.
936///
937/// Distinguishes logical document progress (`YieldFrame`, `CapabilityInteraction`, `Complete`)
938/// from external physical VM resource interruptions (`ResourceInterruption`). A changed
939/// compiler's physical instruction count is never treated as proof that replay reached the
940/// same logical point.
941#[derive(Debug, Clone, PartialEq, Eq)]
942pub enum WasmTraceEvent {
943    /// Emitted a streaming frame (`WasmStepStatus::YieldFrame`) at the given logical step index.
944    YieldFrame {
945        /// 0-based logical step index (`YieldFrame` / `RequestCapability` / `Complete` ordinal).
946        logical_step: usize,
947        /// Emitted frame document.
948        frame: DcMstring,
949    },
950    /// Requested a host capability (`WasmStepStatus::RequestCapability`) and received a
951    /// host authorization decision and response payload.
952    CapabilityInteraction {
953        /// 0-based logical step index at which the capability was requested.
954        logical_step: usize,
955        /// Classified capability privilege.
956        privilege: Privilege,
957        /// Raw capability request document emitted by the WASM module.
958        request: DcMstring,
959        /// Host capability decision applied during this run.
960        decision: PermissionDecision,
961        /// Response/mock document written back to the module's input mailbox (empty if broke out early).
962        response: DcMstring,
963    },
964    /// External resource interruption raised by VM budgets (`ComputeQuotaExhausted`,
965    /// `MemoryLimitExceeded`, `TableLimitExceeded`, `StepOutputSliceTooLarge`,
966    /// `SessionOutputBudgetExceeded`, `CapabilityPayloadTooLarge`,
967    /// `TraceBufferBudgetExceeded`) or host step budget exhaustion.
968    ResourceInterruption {
969        /// Number of completed logical steps before the interruption occurred.
970        after_logical_steps: usize,
971        /// Physical VM resource interruption (or `None` if triggered by the outer host step counter).
972        interruption: Option<WasmResourceInterruption>,
973        /// Host decision for `Privilege::ExcessiveCompute`.
974        decision: PermissionDecision,
975    },
976    /// Non-resource guest WebAssembly trap (e.g., `unreachable`, integer divide by zero,
977    /// out-of-bounds memory access) captured after `after_logical_steps` completed logical steps
978    /// while preserving all prior yielded frames and capability events in the trace.
979    NonResourceTrap {
980        /// Number of completed logical steps before the trap occurred.
981        after_logical_steps: usize,
982        /// Diagnostic trap message captured from the WebAssembly runtime.
983        trap_message: String,
984    },
985    /// Completed execution (`WasmStepStatus::Complete`) with the final output document.
986    Complete {
987        /// 0-based logical step index of completion.
988        logical_step: usize,
989        /// Final output document.
990        output: DcMstring,
991    },
992}
993
994impl WasmTraceEvent {
995    /// Deterministic byte size of this trace event for `max_trace_bytes` accounting.
996    #[must_use]
997    pub fn estimated_trace_bytes(&self) -> usize {
998        match self {
999            Self::YieldFrame { frame, .. } => {
1000                16usize.saturating_add(frame.as_bytes().len())
1001            }
1002            Self::CapabilityInteraction {
1003                request, response, ..
1004            } => 24usize
1005                .saturating_add(request.as_bytes().len())
1006                .saturating_add(response.as_bytes().len()),
1007            Self::ResourceInterruption { .. } => 32usize,
1008            Self::NonResourceTrap { trap_message, .. } => {
1009                24usize.saturating_add(trap_message.len())
1010            }
1011            Self::Complete { output, .. } => {
1012                16usize.saturating_add(output.as_bytes().len())
1013            }
1014        }
1015    }
1016}
1017
1018/// Complete observable execution trace and result of a [`DcWasmSession`] run,
1019/// including the active System supervisor revision, dependency snapshot, accounting version,
1020/// and canonical resource configuration snapshot required for deterministic replay.
1021#[derive(Debug, Clone, PartialEq, Eq)]
1022pub struct WasmExecutionTrace {
1023    /// Final execution result (`output`, `frames`, `broke_out_early`).
1024    pub result: WasmExecutionResult,
1025    /// Ordered sequence of logical trace events, resource interruptions, and non-resource traps.
1026    pub events: Vec<WasmTraceEvent>,
1027    /// Active System-block graph node ID of the System supervisor base document (if admitted).
1028    pub supervisor_revision_node_id: Option<u128>,
1029    /// Sorted, deduplicated System-block node IDs in the supervisor's transitive dependency snapshot.
1030    pub dependency_snapshot_node_ids: Vec<u128>,
1031    /// Deterministic resource-accounting rule version (`WASM_RESOURCE_ACCOUNTING_VERSION`).
1032    pub accounting_version: u32,
1033    /// Canonical 76-byte serialized snapshot of effective [`DcWasmResourceLimits`].
1034    pub effective_config_bytes: Vec<u8>,
1035    /// 1-based ordinal of the last operation interrupted by `ComputeQuotaExhausted` (if any).
1036    pub last_interrupted_op_ordinal: Option<u64>,
1037    /// Required cost of the last operation interrupted by `ComputeQuotaExhausted` (if any).
1038    pub last_interrupted_op_required_cost: Option<u64>,
1039    /// Cumulative trace buffer bytes consumed across `events`.
1040    pub cumulative_trace_bytes: usize,
1041}
1042
1043impl WasmExecutionTrace {
1044    /// Returns the terminal `ResourceInterruption` event if execution was halted by a denied
1045    /// resource interruption (`decision != PermissionDecision::BreakOutResumeNext` and
1046    /// `decision != PermissionDecision::Allow`).
1047    #[must_use]
1048    pub fn denied_resource_interruption(
1049        &self,
1050    ) -> Option<(usize, Option<&WasmResourceInterruption>, PermissionDecision)>
1051    {
1052        if let Some(WasmTraceEvent::ResourceInterruption {
1053            after_logical_steps,
1054            interruption,
1055            decision,
1056        }) = self.events.last()
1057            && *decision != PermissionDecision::BreakOutResumeNext
1058            && *decision != PermissionDecision::Allow
1059        {
1060            return Some((
1061                *after_logical_steps,
1062                interruption.as_ref(),
1063                *decision,
1064            ));
1065        }
1066        None
1067    }
1068
1069    /// Returns the terminal `NonResourceTrap` event if execution terminated due to a non-resource
1070    /// guest WebAssembly trap.
1071    #[must_use]
1072    pub fn non_resource_trap(&self) -> Option<(usize, &str)> {
1073        if let Some(WasmTraceEvent::NonResourceTrap {
1074            after_logical_steps,
1075            trap_message,
1076        }) = self.events.last()
1077        {
1078            return Some((*after_logical_steps, trap_message.as_str()));
1079        }
1080        None
1081    }
1082
1083    /// Returns `Err` if the trace terminated due to a denied resource interruption or a
1084    /// non-resource guest WebAssembly trap, or `Ok(())` if the trace completed or broke out
1085    /// via `PermissionDecision::BreakOutResumeNext`.
1086    ///
1087    /// # Errors
1088    /// Returns an error describing the denied resource interruption or non-resource trap.
1089    pub fn ensure_not_denied(&self) -> Result<()> {
1090        if let Some((steps, interruption, decision)) =
1091            self.denied_resource_interruption()
1092        {
1093            if let Some(intr) = interruption {
1094                return Err(anyhow::Error::new(intr.clone()).context(format!(
1095                    "Execution terminated after {steps} logical steps on VM resource interruption ({intr}); Privilege::ExcessiveCompute decision was {decision:?}"
1096                )));
1097            }
1098            bail!(
1099                "Execution denied by capability policy after {steps} logical steps ({decision:?})"
1100            );
1101        }
1102        if let Some((steps, trap_message)) = self.non_resource_trap() {
1103            bail!(
1104                "Execution terminated after {steps} logical steps on non-resource WebAssembly trap: {trap_message}"
1105            );
1106        }
1107        Ok(())
1108    }
1109}
1110
1111/// Execution context for document evaluation and capability permission gating.
1112///
1113/// Capability authorization lives strictly in the host (`ExecutionContext`). Historical
1114/// System-block graph pinning (`Dc 641` `"Global graph system block most recent node ID at time of document creation"`)
1115/// applies only to language and document semantics and never grants, restores, or modifies
1116/// host security permissions or capability policies.
1117#[derive(Debug, Clone, Default)]
1118pub struct ExecutionContext {
1119    /// Active variable bindings.
1120    pub bindings: HashMap<String, RuntimeValue>,
1121    /// Whether the parsed document contains syntax or framing errors.
1122    pub has_errors: bool,
1123    /// Count of compute steps consumed.
1124    pub compute_steps: usize,
1125    /// Maximum allowed compute steps before raising a budget interruption.
1126    pub max_compute_steps: usize,
1127    /// Portable compute quota units granted each time `Privilege::ExcessiveCompute`
1128    /// is approved with [`PermissionDecision::Allow`].
1129    pub compute_quota_grant: u64,
1130    /// Host-configured per-privilege authorization overrides.
1131    privilege_overrides: HashMap<Privilege, PermissionDecision>,
1132    /// Optional authenticated System supervisor admission metadata recorded in execution traces.
1133    pub supervisor_admission: Option<SystemSupervisorAdmission>,
1134}
1135
1136impl ExecutionContext {
1137    /// Creates a new execution context with default limits.
1138    #[must_use]
1139    pub fn new(has_errors: bool) -> Self {
1140        ctb_wasm_substitutes::ensure_registered();
1141        Self {
1142            bindings: HashMap::new(),
1143            has_errors,
1144            compute_steps: 0,
1145            max_compute_steps: 1_000_000,
1146            compute_quota_grant:
1147                ctb_formats_dcstring::DEFAULT_MAX_WASM_INSTRUCTIONS_PER_STEP,
1148            privilege_overrides: HashMap::new(),
1149            supervisor_admission: None,
1150        }
1151    }
1152
1153    /// Creates a new execution context authenticated against the bundled standalone execution
1154    /// kernel (`Dc 1936` `"Dc document execution kernel"`).
1155    ///
1156    /// # Errors
1157    /// Returns an error if loading or authenticating the bundled System execution kernel fails.
1158    pub fn new_execution_kernel(has_errors: bool) -> Result<Self> {
1159        let admission =
1160            SystemSupervisorAdmission::admit_execution_kernel_default()?;
1161        Ok(Self::new(has_errors).with_system_supervisor_admission(admission))
1162    }
1163
1164    /// Creates a new execution context authenticated against the bundled workspace supervisor
1165    /// (`Dc 1937` `"Collective Toolbox Workspace"`).
1166    ///
1167    /// # Errors
1168    /// Returns an error if loading or authenticating the bundled workspace supervisor fails.
1169    pub fn new_workspace_supervisor(has_errors: bool) -> Result<Self> {
1170        let admission =
1171            SystemSupervisorAdmission::admit_workspace_supervisor_default()?;
1172        Ok(Self::new(has_errors).with_system_supervisor_admission(admission))
1173    }
1174
1175    /// Builder-style method attaching an authenticated [`SystemSupervisorAdmission`] to this
1176    /// execution context so all execution traces record the supervisor revision, dependency
1177    /// snapshot, accounting version, and canonical configuration snapshot.
1178    #[must_use]
1179    pub fn with_system_supervisor_admission(
1180        mut self,
1181        admission: SystemSupervisorAdmission,
1182    ) -> Self {
1183        self.supervisor_admission = Some(admission);
1184        self
1185    }
1186
1187    /// Authenticates and admits the unpinned 1-Short-Dc System supervisor bootstrap document
1188    /// from `seed_graph` and attaches it to this execution context.
1189    ///
1190    /// # Errors
1191    /// Returns an error if `bootstrap_tokens` is pinned, multi-token, non-Short-Dc, lacks
1192    /// authenticated bundled System provenance, or specifies invalid resource limits.
1193    pub fn admit_system_supervisor(
1194        &mut self,
1195        seed_graph: &SeedGraphIndex,
1196        bootstrap_tokens: &[DcShorthand],
1197        user_limits: DcWasmResourceLimits,
1198        watchdog: DcWasmWatchdogLimits,
1199    ) -> Result<&SystemSupervisorAdmission> {
1200        let admission = SystemSupervisorAdmission::admit_from_bootstrap_tokens(
1201            seed_graph,
1202            bootstrap_tokens,
1203            user_limits,
1204            watchdog,
1205        )?;
1206        self.supervisor_admission = Some(admission);
1207        self.supervisor_admission
1208            .as_ref()
1209            .context("supervisor_admission was just populated")
1210    }
1211
1212    /// Builder-style method configuring the portable compute quota grant added when
1213    /// `Privilege::ExcessiveCompute` is approved with [`PermissionDecision::Allow`].
1214    #[must_use]
1215    pub const fn with_compute_quota_grant(mut self, grant: u64) -> Self {
1216        self.compute_quota_grant = grant;
1217        self
1218    }
1219
1220    /// Configures a host capability policy override for `privilege`.
1221    pub fn set_privilege_decision(
1222        &mut self,
1223        privilege: Privilege,
1224        decision: PermissionDecision,
1225    ) {
1226        self.privilege_overrides.insert(privilege, decision);
1227    }
1228
1229    /// Builder-style method configuring a host capability policy override for `privilege`.
1230    #[must_use]
1231    pub fn with_privilege_decision(
1232        mut self,
1233        privilege: Privilege,
1234        decision: PermissionDecision,
1235    ) -> Self {
1236        self.set_privilege_decision(privilege, decision);
1237        self
1238    }
1239
1240    /// Evaluates a permission request against the current host policy, strongly steering
1241    /// toward mocking or denying if `has_errors` is true.
1242    ///
1243    /// Historical `Dc 641` graph pins on documents or WASM sessions are intentionally
1244    /// excluded from capability evaluation so historical pinning can never grant or restore
1245    /// obsolete security permissions.
1246    #[must_use]
1247    pub fn request_permission(
1248        &self,
1249        privilege: &Privilege,
1250    ) -> PermissionDecision {
1251        if let Some(&override_decision) =
1252            self.privilege_overrides.get(privilege)
1253        {
1254            if self.has_errors
1255                && override_decision == PermissionDecision::Allow
1256                && !matches!(privilege, Privilege::ExcessiveCompute)
1257            {
1258                return PermissionDecision::AutoMock;
1259            }
1260            return override_decision;
1261        }
1262
1263        if matches!(privilege, Privilege::ExcessiveCompute) {
1264            // For compute exhaustion, default to offering breakout to resume
1265            // execution/printing on the next Dc.
1266            return PermissionDecision::BreakOutResumeNext;
1267        }
1268
1269        if self.has_errors {
1270            // Strongly steer away from Allow when document has errors
1271            PermissionDecision::AutoMock
1272        } else if matches!(
1273            privilege,
1274            Privilege::SystemGraphQuery | Privilege::ExecutePureWasm
1275        ) {
1276            PermissionDecision::Allow
1277        } else {
1278            PermissionDecision::Deny
1279        }
1280    }
1281
1282    /// Increments compute step count, checking if the compute budget is
1283    /// exhausted. If exhausted, raises a permission request for
1284    /// `Privilege::ExcessiveCompute`.
1285    pub fn step(&mut self) -> Result<PermissionDecision, anyhow::Error> {
1286        self.compute_steps = self.compute_steps.saturating_add(1);
1287        if self.compute_steps > self.max_compute_steps {
1288            let decision =
1289                self.request_permission(&Privilege::ExcessiveCompute);
1290            if decision == PermissionDecision::Allow {
1291                self.max_compute_steps = self.compute_steps;
1292                return Ok(PermissionDecision::Allow);
1293            }
1294            if decision == PermissionDecision::BreakOutResumeNext {
1295                // Reset or allow caller to break out and resume at the next Dc
1296                return Ok(PermissionDecision::BreakOutResumeNext);
1297            }
1298            anyhow::bail!(
1299                "Compute budget exhausted ({} steps); permission denied to continue",
1300                self.max_compute_steps
1301            );
1302        }
1303        Ok(PermissionDecision::Allow)
1304    }
1305
1306    fn default_capability_response(decision: PermissionDecision) -> DcMstring {
1307        let mut resp = DcMstring::new();
1308        match decision {
1309            PermissionDecision::Allow => {
1310                resp.push_char(dc::DC_BOOLEAN_TRUE);
1311            }
1312            PermissionDecision::AutoMock | PermissionDecision::ManualMock => {
1313                resp.push_char(dc::DC_OPTIONAL_ABSENT);
1314            }
1315            PermissionDecision::Deny
1316            | PermissionDecision::BreakOutResumeNext => {
1317                resp.push_char(dc::DC_BOOLEAN_FALSE);
1318            }
1319        }
1320        resp
1321    }
1322
1323    fn build_trace(
1324        &self,
1325        session: Option<&DcWasmSession>,
1326        fallback_limits: DcWasmResourceLimits,
1327        result: WasmExecutionResult,
1328        events: Vec<WasmTraceEvent>,
1329        cumulative_trace_bytes: usize,
1330        interrupted_op_info: Option<(u64, u64)>,
1331    ) -> WasmExecutionTrace {
1332        // Reason for fallback: when supervisor admission was not configured or failed before admission, trace metadata reports the caller's fallback_limits.
1333        let effective_limits = self
1334            .supervisor_admission
1335            .as_ref()
1336            .map_or(fallback_limits, |adm| adm.compiled_limits);
1337        let (
1338            supervisor_revision_node_id,
1339            dependency_snapshot_node_ids,
1340            accounting_version,
1341            effective_config_bytes,
1342        ) = if let Some(adm) = &self.supervisor_admission {
1343            (
1344                Some(adm.supervisor_revision_node_id),
1345                adm.dependency_snapshot_node_ids.clone(),
1346                adm.accounting_version,
1347                adm.effective_config_bytes.clone(),
1348            )
1349        } else {
1350            (
1351                None,
1352                Vec::new(),
1353                effective_limits.accounting_version,
1354                effective_limits.encode_canonical_config_bytes(),
1355            )
1356        };
1357        let (last_interrupted_op_ordinal, last_interrupted_op_required_cost) =
1358            if let Some((ord, cost)) = interrupted_op_info {
1359                (Some(ord), Some(cost))
1360            } else if let Some(s) = session
1361                && s.last_interrupted_op_ordinal().is_some()
1362            {
1363                (
1364                    s.last_interrupted_op_ordinal(),
1365                    s.last_interrupted_op_required_cost(),
1366                )
1367            } else {
1368                (None, None)
1369            };
1370        WasmExecutionTrace {
1371            result,
1372            events,
1373            supervisor_revision_node_id,
1374            dependency_snapshot_node_ids,
1375            accounting_version,
1376            effective_config_bytes,
1377            last_interrupted_op_ordinal,
1378            last_interrupted_op_required_cost,
1379            cumulative_trace_bytes,
1380        }
1381    }
1382
1383    /// Appends `event` to `events` if within `max_trace_bytes`; otherwise records a
1384    /// `WasmResourceInterruption::TraceBufferBudgetExceeded` event and returns `Err(())`.
1385    fn push_trace_event_bounded(
1386        &self,
1387        events: &mut Vec<WasmTraceEvent>,
1388        cumulative_trace_bytes: &mut usize,
1389        max_trace_bytes: usize,
1390        after_logical_steps: usize,
1391        event: WasmTraceEvent,
1392    ) -> std::result::Result<(), ()> {
1393        let event_bytes = event.estimated_trace_bytes();
1394        let next_bytes = cumulative_trace_bytes.saturating_add(event_bytes);
1395        if next_bytes > max_trace_bytes {
1396            let decision =
1397                self.request_permission(&Privilege::ExcessiveCompute);
1398            let intr_event = WasmTraceEvent::ResourceInterruption {
1399                after_logical_steps,
1400                interruption: Some(
1401                    WasmResourceInterruption::TraceBufferBudgetExceeded {
1402                        cumulative_trace_bytes: next_bytes,
1403                        max_trace_bytes,
1404                    },
1405                ),
1406                decision,
1407            };
1408            *cumulative_trace_bytes = cumulative_trace_bytes
1409                .saturating_add(intr_event.estimated_trace_bytes());
1410            events.push(intr_event);
1411            return Err(());
1412        }
1413        *cumulative_trace_bytes = next_bytes;
1414        events.push(event);
1415        Ok(())
1416    }
1417
1418    fn handle_session_error_into_trace(
1419        &self,
1420        session: Option<&DcWasmSession>,
1421        fallback_limits: DcWasmResourceLimits,
1422        err: anyhow::Error,
1423        after_logical_steps: usize,
1424        frames: Vec<DcMstring>,
1425        mut events: Vec<WasmTraceEvent>,
1426        mut cumulative_trace_bytes: usize,
1427        interrupted_op_info: Option<(u64, u64)>,
1428    ) -> WasmExecutionTrace {
1429        // Reason for fallback: when session initialization failed before a DcWasmSession was constructed, trace budget enforcement uses fallback_limits.max_trace_bytes.
1430        let max_trace_bytes =
1431            session.map_or(fallback_limits.max_trace_bytes, |s| {
1432                s.resource_limits().max_trace_bytes
1433            });
1434        if let Some(interruption) =
1435            err.downcast_ref::<WasmResourceInterruption>().cloned()
1436        {
1437            let decision =
1438                self.request_permission(&Privilege::ExcessiveCompute);
1439            let _ = self.push_trace_event_bounded(
1440                &mut events,
1441                &mut cumulative_trace_bytes,
1442                max_trace_bytes,
1443                after_logical_steps,
1444                WasmTraceEvent::ResourceInterruption {
1445                    after_logical_steps,
1446                    interruption: Some(interruption),
1447                    decision,
1448                },
1449            );
1450        } else {
1451            let _ = self.push_trace_event_bounded(
1452                &mut events,
1453                &mut cumulative_trace_bytes,
1454                max_trace_bytes,
1455                after_logical_steps,
1456                WasmTraceEvent::NonResourceTrap {
1457                    after_logical_steps,
1458                    trap_message: format!("{err:#}"),
1459                },
1460            );
1461        }
1462        self.build_trace(
1463            session,
1464            fallback_limits,
1465            WasmExecutionResult {
1466                output: DcMstring::new(),
1467                frames,
1468                broke_out_early: true,
1469            },
1470            events,
1471            cumulative_trace_bytes,
1472            interrupted_op_info,
1473        )
1474    }
1475
1476    /// Drives a [`DcWasmSession`] over `input` and records the full [`WasmExecutionTrace`]
1477    /// (distinguishing logical document progress from physical VM resource interruptions and
1478    /// non-resource guest traps).
1479    ///
1480    /// Both physical VM resource interruptions and non-resource guest traps preserve all
1481    /// accumulated `frames` and `events` in the returned [`WasmExecutionTrace`] so the finite
1482    /// prefix can be inspected and deterministically replayed. Call
1483    /// [`WasmExecutionTrace::ensure_not_denied`] to convert denied resource interruptions or
1484    /// non-resource traps into `Err`.
1485    ///
1486    /// # Errors
1487    /// Returns an error if `capability_handler` fails.
1488    pub fn execute_wasm_session_with_trace<F>(
1489        &mut self,
1490        session: &mut DcWasmSession,
1491        input: &DcMstr,
1492        capability_handler: F,
1493    ) -> Result<WasmExecutionTrace>
1494    where
1495        F: FnMut(&Privilege, PermissionDecision, &DcMstr) -> Result<DcMstring>,
1496    {
1497        self.execute_wasm_session_with_trace_inner(
1498            session,
1499            input,
1500            None,
1501            capability_handler,
1502        )
1503    }
1504
1505    fn execute_wasm_session_with_trace_inner<F>(
1506        &mut self,
1507        session: &mut DcWasmSession,
1508        input: &DcMstr,
1509        resolver: Option<&dyn SyntaxRuleResolver>,
1510        mut capability_handler: F,
1511    ) -> Result<WasmExecutionTrace>
1512    where
1513        F: FnMut(&Privilege, PermissionDecision, &DcMstr) -> Result<DcMstring>,
1514    {
1515        ctb_wasm_substitutes::ensure_registered();
1516        if let Some(adm) = &self.supervisor_admission
1517            && !session.has_shared_task_quota()
1518        {
1519            session.set_resource_limits(adm.compiled_limits);
1520        }
1521        let fallback_limits = session.resource_limits();
1522        let max_trace_bytes = fallback_limits.max_trace_bytes;
1523        let mut frames = Vec::new();
1524        let mut events = Vec::new();
1525        let mut cumulative_trace_bytes = 0usize;
1526        let mut last_interrupted_op: Option<(u64, u64)> = None;
1527
1528        if let Err(err) = session.provide_input(input) {
1529            return Ok(self.handle_session_error_into_trace(
1530                Some(session),
1531                fallback_limits,
1532                err,
1533                0,
1534                frames,
1535                events,
1536                cumulative_trace_bytes,
1537                last_interrupted_op,
1538            ));
1539        }
1540
1541        let mut logical_step = 0usize;
1542        loop {
1543            let budget_decision = match self.step() {
1544                Ok(d) => d,
1545                Err(_err) => {
1546                    let decision =
1547                        self.request_permission(&Privilege::ExcessiveCompute);
1548                    let _ = self.push_trace_event_bounded(
1549                        &mut events,
1550                        &mut cumulative_trace_bytes,
1551                        max_trace_bytes,
1552                        logical_step,
1553                        WasmTraceEvent::ResourceInterruption {
1554                            after_logical_steps: logical_step,
1555                            interruption: None,
1556                            decision,
1557                        },
1558                    );
1559                    return Ok(self.build_trace(
1560                        Some(session),
1561                        fallback_limits,
1562                        WasmExecutionResult {
1563                            output: DcMstring::new(),
1564                            frames,
1565                            broke_out_early: true,
1566                        },
1567                        events,
1568                        cumulative_trace_bytes,
1569                        last_interrupted_op,
1570                    ));
1571                }
1572            };
1573            if budget_decision == PermissionDecision::BreakOutResumeNext
1574                || budget_decision == PermissionDecision::Deny
1575            {
1576                let _ = self.push_trace_event_bounded(
1577                    &mut events,
1578                    &mut cumulative_trace_bytes,
1579                    max_trace_bytes,
1580                    logical_step,
1581                    WasmTraceEvent::ResourceInterruption {
1582                        after_logical_steps: logical_step,
1583                        interruption: None,
1584                        decision: budget_decision,
1585                    },
1586                );
1587                return Ok(self.build_trace(
1588                    Some(session),
1589                    fallback_limits,
1590                    WasmExecutionResult {
1591                        output: DcMstring::new(),
1592                        frames,
1593                        broke_out_early: true,
1594                    },
1595                    events,
1596                    cumulative_trace_bytes,
1597                    last_interrupted_op,
1598                ));
1599            }
1600
1601            let step_outcome = match session.step() {
1602                Ok(outcome) => outcome,
1603                Err(err) => {
1604                    if let Some(
1605                        WasmResourceInterruption::ComputeQuotaExhausted {
1606                            limit,
1607                        },
1608                    ) = err.downcast_ref::<WasmResourceInterruption>().cloned()
1609                    {
1610                        if let (Some(ord), Some(cost)) = (
1611                            session.last_interrupted_op_ordinal(),
1612                            session.last_interrupted_op_required_cost(),
1613                        ) {
1614                            last_interrupted_op = Some((ord, cost));
1615                        }
1616                        let decision = self
1617                            .request_permission(&Privilege::ExcessiveCompute);
1618                        if self
1619                            .push_trace_event_bounded(
1620                                &mut events,
1621                                &mut cumulative_trace_bytes,
1622                                max_trace_bytes,
1623                                logical_step,
1624                                WasmTraceEvent::ResourceInterruption {
1625                                    after_logical_steps: logical_step,
1626                                    interruption: Some(
1627                                        WasmResourceInterruption::ComputeQuotaExhausted {
1628                                            limit,
1629                                        },
1630                                    ),
1631                                    decision,
1632                                },
1633                            )
1634                            .is_err()
1635                        {
1636                            return Ok(self.build_trace(
1637                                Some(session),
1638                                fallback_limits,
1639                                WasmExecutionResult {
1640                                    output: DcMstring::new(),
1641                                    frames,
1642                                    broke_out_early: true,
1643                                },
1644                                events,
1645                                cumulative_trace_bytes,
1646                                last_interrupted_op,
1647                            ));
1648                        }
1649                        if decision == PermissionDecision::Allow {
1650                            session.increase_compute_quota(
1651                                self.compute_quota_grant.max(1),
1652                            );
1653                            continue;
1654                        }
1655                        return Ok(self.build_trace(
1656                            Some(session),
1657                            fallback_limits,
1658                            WasmExecutionResult {
1659                                output: DcMstring::new(),
1660                                frames,
1661                                broke_out_early: true,
1662                            },
1663                            events,
1664                            cumulative_trace_bytes,
1665                            last_interrupted_op,
1666                        ));
1667                    }
1668                    return Ok(self.handle_session_error_into_trace(
1669                        Some(session),
1670                        fallback_limits,
1671                        err,
1672                        logical_step,
1673                        frames,
1674                        events,
1675                        cumulative_trace_bytes,
1676                        last_interrupted_op,
1677                    ));
1678                }
1679            };
1680
1681            match step_outcome {
1682                WasmStepOutcome::Complete(output) => {
1683                    if self
1684                        .push_trace_event_bounded(
1685                            &mut events,
1686                            &mut cumulative_trace_bytes,
1687                            max_trace_bytes,
1688                            logical_step,
1689                            WasmTraceEvent::Complete {
1690                                logical_step,
1691                                output: output.clone(),
1692                            },
1693                        )
1694                        .is_err()
1695                    {
1696                        return Ok(self.build_trace(
1697                            Some(session),
1698                            fallback_limits,
1699                            WasmExecutionResult {
1700                                output: DcMstring::new(),
1701                                frames,
1702                                broke_out_early: true,
1703                            },
1704                            events,
1705                            cumulative_trace_bytes,
1706                            last_interrupted_op,
1707                        ));
1708                    }
1709                    return Ok(self.build_trace(
1710                        Some(session),
1711                        fallback_limits,
1712                        WasmExecutionResult {
1713                            output,
1714                            frames,
1715                            broke_out_early: false,
1716                        },
1717                        events,
1718                        cumulative_trace_bytes,
1719                        last_interrupted_op,
1720                    ));
1721                }
1722                WasmStepOutcome::YieldFrame(frame) => {
1723                    if self
1724                        .push_trace_event_bounded(
1725                            &mut events,
1726                            &mut cumulative_trace_bytes,
1727                            max_trace_bytes,
1728                            logical_step,
1729                            WasmTraceEvent::YieldFrame {
1730                                logical_step,
1731                                frame: frame.clone(),
1732                            },
1733                        )
1734                        .is_err()
1735                    {
1736                        return Ok(self.build_trace(
1737                            Some(session),
1738                            fallback_limits,
1739                            WasmExecutionResult {
1740                                output: DcMstring::new(),
1741                                frames,
1742                                broke_out_early: true,
1743                            },
1744                            events,
1745                            cumulative_trace_bytes,
1746                            last_interrupted_op,
1747                        ));
1748                    }
1749                    frames.push(frame);
1750                    logical_step = logical_step.saturating_add(1);
1751                }
1752                WasmStepOutcome::RequestCapability(req_dc) => {
1753                    let privilege = if let Some(res) = resolver {
1754                        Privilege::from_request_dc_with_resolver(&req_dc, res)
1755                    } else {
1756                        Privilege::from_request_dc(&req_dc)
1757                    };
1758                    let decision = self.request_permission(&privilege);
1759                    if decision == PermissionDecision::BreakOutResumeNext {
1760                        let _ = self.push_trace_event_bounded(
1761                            &mut events,
1762                            &mut cumulative_trace_bytes,
1763                            max_trace_bytes,
1764                            logical_step,
1765                            WasmTraceEvent::CapabilityInteraction {
1766                                logical_step,
1767                                privilege,
1768                                request: req_dc,
1769                                decision,
1770                                response: DcMstring::new(),
1771                            },
1772                        );
1773                        return Ok(self.build_trace(
1774                            Some(session),
1775                            fallback_limits,
1776                            WasmExecutionResult {
1777                                output: DcMstring::new(),
1778                                frames,
1779                                broke_out_early: true,
1780                            },
1781                            events,
1782                            cumulative_trace_bytes,
1783                            last_interrupted_op,
1784                        ));
1785                    }
1786                    let response =
1787                        match capability_handler(&privilege, decision, &req_dc)
1788                        {
1789                            Ok(r) => r,
1790                            Err(err)
1791                                if err
1792                                    .downcast_ref::<WasmResourceInterruption>()
1793                                    .is_some() =>
1794                            {
1795                                return Ok(self
1796                                    .handle_session_error_into_trace(
1797                                        Some(session),
1798                                        fallback_limits,
1799                                        err,
1800                                        logical_step,
1801                                        frames,
1802                                        events,
1803                                        cumulative_trace_bytes,
1804                                        last_interrupted_op,
1805                                    ));
1806                            }
1807                            Err(err) => return Err(err),
1808                        };
1809                    if self
1810                        .push_trace_event_bounded(
1811                            &mut events,
1812                            &mut cumulative_trace_bytes,
1813                            max_trace_bytes,
1814                            logical_step,
1815                            WasmTraceEvent::CapabilityInteraction {
1816                                logical_step,
1817                                privilege,
1818                                request: req_dc,
1819                                decision,
1820                                response: response.clone(),
1821                            },
1822                        )
1823                        .is_err()
1824                    {
1825                        return Ok(self.build_trace(
1826                            Some(session),
1827                            fallback_limits,
1828                            WasmExecutionResult {
1829                                output: DcMstring::new(),
1830                                frames,
1831                                broke_out_early: true,
1832                            },
1833                            events,
1834                            cumulative_trace_bytes,
1835                            last_interrupted_op,
1836                        ));
1837                    }
1838                    logical_step = logical_step.saturating_add(1);
1839                    if let Err(err) =
1840                        session.provide_capability_response(&response)
1841                    {
1842                        return Ok(self.handle_session_error_into_trace(
1843                            Some(session),
1844                            fallback_limits,
1845                            err,
1846                            logical_step,
1847                            frames,
1848                            events,
1849                            cumulative_trace_bytes,
1850                            last_interrupted_op,
1851                        ));
1852                    }
1853                }
1854            }
1855        }
1856    }
1857
1858    /// Drives a [`DcWasmSession`] with the default capability response encoder
1859    /// and pure `Dc 1939`/`Dc 1940` capability dispatch against `resolver`.
1860    ///
1861    /// # Errors
1862    /// Returns an error if a non-resource capability handler fails.
1863    pub fn execute_wasm_session_default_with_resolver_and_trace(
1864        &mut self,
1865        session: &mut DcWasmSession,
1866        input: &DcMstr,
1867        resolver: &dyn SyntaxRuleResolver,
1868    ) -> Result<WasmExecutionTrace> {
1869        let shared_quota = session.shared_task_quota();
1870        self.execute_wasm_session_with_trace_inner(
1871            session,
1872            input,
1873            Some(resolver),
1874            move |privilege, decision, req| {
1875                if decision == PermissionDecision::Allow
1876                    && matches!(
1877                        privilege,
1878                        Privilege::SystemGraphQuery
1879                            | Privilege::ExecutePureWasm
1880                    )
1881                {
1882                    return eval_pure_graph_capability_request(
1883                        req,
1884                        resolver,
1885                        shared_quota.clone(),
1886                        0,
1887                    );
1888                }
1889                Ok(Self::default_capability_response(decision))
1890            },
1891        )
1892    }
1893
1894    /// Drives a [`DcWasmSession`] with the default capability response encoder and returns
1895    /// the full [`WasmExecutionTrace`].
1896    ///
1897    /// # Errors
1898    /// Returns an error if the capability handler fails.
1899    pub fn execute_wasm_session_default_with_trace(
1900        &mut self,
1901        session: &mut DcWasmSession,
1902        input: &DcMstr,
1903    ) -> Result<WasmExecutionTrace> {
1904        let default_res =
1905            ctb_formats_dcstring::syntax::default_syntax_resolver();
1906        self.execute_wasm_session_default_with_resolver_and_trace(
1907            session,
1908            input,
1909            default_res.as_ref(),
1910        )
1911    }
1912
1913    /// Compiles and executes an arbitrary ordinary Dc document `ordinary_doc` through the
1914    /// `Dc 1936` execution kernel pipeline (`[Dc 1938 <pin> [Dc 2608 <quoted_doc>]]`), sharing
1915    /// one [`ctb_formats_dcstring::converters::wasm::SharedWasmTaskQuota`] across both
1916    /// compilation (`Dc 2608` + any graph converter routine) and target `.WASM` execution.
1917    ///
1918    /// # Errors
1919    /// Returns an error if `ordinary_doc` attempts privilege elevation, fails compilation/assembly,
1920    /// or fails capability handling.
1921    pub fn execute_dc_document_default_with_trace(
1922        &mut self,
1923        ordinary_doc: &DcMstr,
1924        input: &DcMstr,
1925        resolver: &dyn ctb_formats_dcstring::SyntaxRuleResolver,
1926    ) -> Result<WasmExecutionTrace> {
1927        use ctb_formats_dcstring::converters::wasm::SharedWasmTaskQuota;
1928
1929        let adm = if let Some(existing) = &self.supervisor_admission {
1930            existing.clone()
1931        } else {
1932            let default_adm =
1933                SystemSupervisorAdmission::admit_execution_kernel_default()?;
1934            self.supervisor_admission = Some(default_adm.clone());
1935            default_adm
1936        };
1937        let mut active_limits = adm.compiled_limits;
1938        let mut compile_events = Vec::new();
1939        let mut compile_trace_bytes = 0usize;
1940
1941        let (wasm_doc, opt_pin_id, shared_quota) = loop {
1942            let shared_quota = SharedWasmTaskQuota::new(active_limits);
1943            match adm.compile_dc_document_to_wasm_with_shared_quota(
1944                ordinary_doc,
1945                resolver,
1946                shared_quota.clone(),
1947            ) {
1948                Ok((wasm_doc, opt_pin_id)) => {
1949                    break (wasm_doc, opt_pin_id, shared_quota);
1950                }
1951                Err(err) => {
1952                    if let Some(
1953                        WasmResourceInterruption::ComputeQuotaExhausted {
1954                            limit,
1955                        },
1956                    ) = err.downcast_ref::<WasmResourceInterruption>().cloned()
1957                    {
1958                        let decision =
1959                            self.request_permission(&Privilege::ExcessiveCompute);
1960                        if self
1961                            .push_trace_event_bounded(
1962                                &mut compile_events,
1963                                &mut compile_trace_bytes,
1964                                active_limits.max_trace_bytes,
1965                                0,
1966                                WasmTraceEvent::ResourceInterruption {
1967                                    after_logical_steps: 0,
1968                                    interruption: Some(
1969                                        WasmResourceInterruption::ComputeQuotaExhausted {
1970                                            limit,
1971                                        },
1972                                    ),
1973                                    decision,
1974                                },
1975                            )
1976                            .is_err()
1977                        {
1978                            return Ok(self.build_trace(
1979                                None,
1980                                active_limits,
1981                                WasmExecutionResult {
1982                                    output: DcMstring::new(),
1983                                    frames: Vec::new(),
1984                                    broke_out_early: true,
1985                                },
1986                                compile_events,
1987                                compile_trace_bytes,
1988                                None,
1989                            ));
1990                        }
1991                        if decision == PermissionDecision::Allow {
1992                            active_limits.max_instructions_per_step =
1993                                active_limits
1994                                    .max_instructions_per_step
1995                                    .saturating_add(
1996                                        self.compute_quota_grant.max(1),
1997                                    );
1998                            continue;
1999                        }
2000                        return Ok(self.build_trace(
2001                            None,
2002                            active_limits,
2003                            WasmExecutionResult {
2004                                output: DcMstring::new(),
2005                                frames: Vec::new(),
2006                                broke_out_early: true,
2007                            },
2008                            compile_events,
2009                            compile_trace_bytes,
2010                            None,
2011                        ));
2012                    }
2013                    if err.downcast_ref::<WasmResourceInterruption>().is_some() {
2014                        return Ok(self.handle_session_error_into_trace(
2015                            None,
2016                            active_limits,
2017                            err,
2018                            0,
2019                            Vec::new(),
2020                            compile_events,
2021                            compile_trace_bytes,
2022                            None,
2023                        ));
2024                    }
2025                    return Err(err);
2026                }
2027            }
2028        };
2029
2030        let most_recent_id = opt_pin_id.or_else(|| {
2031            resolver
2032                .seed_graph()
2033                .and_then(SeedGraphIndex::system_block_most_recent_node_id)
2034        });
2035        let exec_pinned = if let Some(pin_id) = opt_pin_id {
2036            if let Some(sg) = resolver.seed_graph()
2037                && !sg.is_from_asset_bundle()
2038            {
2039                let pinned_sg = std::sync::Arc::new(
2040                    SeedGraphIndex::from_nodes_at_most_recent(
2041                        sg.nodes().to_vec(),
2042                        pin_id,
2043                    ),
2044                );
2045                Some(std::sync::Arc::new(
2046                    ctb_formats_dcstring::syntax::DatasetRuleResolver::from_seed_graph_arc(
2047                        pinned_sg,
2048                    )?,
2049                ))
2050            } else {
2051                Some(
2052                    ctb_formats_dcstring::syntax::syntax_resolver_at_most_recent(
2053                        pin_id,
2054                    )?,
2055                )
2056            }
2057        } else {
2058            None
2059        };
2060        let exec_res: &dyn ctb_formats_dcstring::SyntaxRuleResolver =
2061            if let Some(ref pinned) = exec_pinned {
2062                pinned.as_ref()
2063            } else {
2064                resolver
2065            };
2066
2067        let wasm_asm_res: &dyn ctb_formats_dcstring::SyntaxRuleResolver =
2068            if exec_res.resolve_named_type("wasm_routine").is_some() {
2069                exec_res
2070            } else {
2071                resolver
2072            };
2073
2074        let mut session = match DcWasmSession::from_dc_wasm_with_limits(
2075            &wasm_doc,
2076            input,
2077            most_recent_id,
2078            wasm_asm_res,
2079            active_limits,
2080        )
2081        .and_then(|s| s.with_shared_task_quota(shared_quota))
2082        {
2083            Ok(s) => s,
2084            Err(err) => {
2085                if err.downcast_ref::<WasmResourceInterruption>().is_some() {
2086                    return Ok(self.handle_session_error_into_trace(
2087                        None,
2088                        active_limits,
2089                        err,
2090                        0,
2091                        Vec::new(),
2092                        compile_events,
2093                        compile_trace_bytes,
2094                        None,
2095                    ));
2096                }
2097                return Err(err);
2098            }
2099        };
2100
2101        let mut trace = self.execute_wasm_session_default_with_resolver_and_trace(
2102            &mut session,
2103            input,
2104            exec_res,
2105        )?;
2106        if !compile_events.is_empty() {
2107            compile_events.extend(trace.events);
2108            trace.events = compile_events;
2109        }
2110        Ok(trace)
2111    }
2112
2113    /// Verifies that an ordinary Dc-WASM document does not attempt to elevate to System
2114    /// supervisor privilege, then instantiates and executes it without granting supervisor
2115    /// authority (even if the document carries a leading `Dc 641` pin or references
2116    /// `supervisor_entry_dc`).
2117    ///
2118    /// # Errors
2119    /// Returns an error if `ordinary_doc` attempts to claim supervisor privilege or fails
2120    /// to assemble/instantiate.
2121    pub fn execute_ordinary_dc_wasm_default_with_trace(
2122        &mut self,
2123        ordinary_doc: &DcMstr,
2124        input: &DcMstr,
2125        most_recent_node_id: Option<u128>,
2126        supervisor_entry_dc: DcChar,
2127    ) -> Result<WasmExecutionTrace> {
2128        SystemSupervisorAdmission::verify_ordinary_dc_document_cannot_elevate(
2129            ordinary_doc,
2130            supervisor_entry_dc,
2131        )?;
2132        let mut session = DcWasmSession::from_dc_wasm(
2133            ordinary_doc,
2134            input,
2135            most_recent_node_id,
2136        )?;
2137        self.execute_wasm_session_default_with_trace(&mut session, input)
2138    }
2139
2140    /// Replays a [`DcWasmSession`] against a previously recorded [`WasmExecutionTrace`]:
2141    /// - Verifies that the active accounting version and canonical resource configuration match.
2142    /// - Compares every capability request (`Privilege` and `DcMstring` request payload) emitted by
2143    ///   the document at each logical step, then supplies the recorded allow/deny/mock response.
2144    /// - Actually executes `session.step()` at every recorded resource interruption boundary and
2145    ///   verifies that the module triggers the recorded `WasmResourceInterruption` at the exact
2146    ///   recorded `last_interrupted_op_ordinal` and `last_interrupted_op_required_cost`.
2147    ///
2148    /// # Errors
2149    /// Returns an error if the document's capability requests, yielded frames, completion
2150    /// output, or trap/interruption behavior diverge from `recorded_trace`.
2151    pub fn replay_wasm_session_trace(
2152        &mut self,
2153        session: &mut DcWasmSession,
2154        input: &DcMstr,
2155        recorded_trace: &WasmExecutionTrace,
2156    ) -> Result<WasmExecutionTrace> {
2157        self.replay_wasm_session_trace_with_prefix(
2158            session,
2159            input,
2160            recorded_trace,
2161            Vec::new(),
2162            0,
2163            0,
2164            None,
2165        )
2166    }
2167
2168    #[allow(
2169        clippy::too_many_arguments,
2170        clippy::too_many_lines,
2171        reason = "Replay state machine threads construction prefix events and config snapshot"
2172    )]
2173    fn replay_wasm_session_trace_with_prefix(
2174        &mut self,
2175        session: &mut DcWasmSession,
2176        input: &DcMstr,
2177        recorded_trace: &WasmExecutionTrace,
2178        mut events: Vec<WasmTraceEvent>,
2179        mut cumulative_trace_bytes: usize,
2180        mut event_idx: usize,
2181        initial_limits_override: Option<DcWasmResourceLimits>,
2182    ) -> Result<WasmExecutionTrace> {
2183        ctb_wasm_substitutes::ensure_registered();
2184        ensure!(
2185            recorded_trace.accounting_version
2186                == WASM_RESOURCE_ACCOUNTING_VERSION,
2187            "Replay accounting_version mismatch: recorded {}, runtime {}",
2188            recorded_trace.accounting_version,
2189            WASM_RESOURCE_ACCOUNTING_VERSION
2190        );
2191        let decoded_limits =
2192            DcWasmResourceLimits::decode_canonical_config_bytes(
2193                &recorded_trace.effective_config_bytes,
2194            )
2195            .ok();
2196        if let Some(adm) = &self.supervisor_admission {
2197            if initial_limits_override.is_none()
2198                && session.total_instructions_executed() == 0
2199            {
2200                session.set_resource_limits(adm.compiled_limits);
2201            }
2202        } else if let Some(rec_limits) = decoded_limits
2203            && initial_limits_override.is_none()
2204            && session.total_instructions_executed() == 0
2205        {
2206            session.set_resource_limits(rec_limits);
2207        }
2208        // Reason for fallback: fallback to session's active limits only if a legacy/synthetic trace omitted canonical config bytes.
2209        let fallback_limits = initial_limits_override.unwrap_or_else(|| {
2210            decoded_limits.unwrap_or_else(|| session.resource_limits())
2211        });
2212        let max_trace_bytes = fallback_limits.max_trace_bytes;
2213        let mut frames = Vec::new();
2214        let mut last_interrupted_op: Option<(u64, u64)> = None;
2215        let finalize_checked_trace =
2216            |mut trace: WasmExecutionTrace| -> Result<WasmExecutionTrace> {
2217                if trace.supervisor_revision_node_id.is_none()
2218                    && recorded_trace.supervisor_revision_node_id.is_some()
2219                {
2220                    trace.supervisor_revision_node_id =
2221                        recorded_trace.supervisor_revision_node_id;
2222                    trace.dependency_snapshot_node_ids =
2223                        recorded_trace.dependency_snapshot_node_ids.clone();
2224                }
2225                ensure!(
2226                    &trace == recorded_trace,
2227                    "Replay terminated without matching the complete recorded trace and result"
2228                );
2229                Ok(trace)
2230            };
2231
2232        let record_replay_error =
2233            |this: &Self,
2234             session_opt: Option<&DcWasmSession>,
2235             err: anyhow::Error,
2236             step_idx: usize,
2237             cur_event_idx: usize,
2238             frames_vec: Vec<DcMstring>,
2239             mut events_vec: Vec<WasmTraceEvent>,
2240             mut trace_bytes: usize,
2241             interrupted_op: Option<(u64, u64)>|
2242             -> Result<WasmExecutionTrace> {
2243                let expected = recorded_trace
2244                    .events
2245                    .get(cur_event_idx)
2246                    .with_context(|| {
2247                        format!(
2248                            "Replay encountered error ({err:#}) at logical step {step_idx} beyond recorded trace length ({})",
2249                            recorded_trace.events.len()
2250                        )
2251                    })?;
2252                if let Some(actual_intr) =
2253                    err.downcast_ref::<WasmResourceInterruption>().cloned()
2254                {
2255                    let WasmTraceEvent::ResourceInterruption {
2256                        after_logical_steps,
2257                        interruption: Some(rec_intr),
2258                        decision,
2259                    } = expected
2260                    else {
2261                        bail!(
2262                            "Replay resource interruption mismatch at logical step {step_idx}: expected {expected:?}, got {actual_intr:?}"
2263                        );
2264                    };
2265                    ensure!(
2266                        *after_logical_steps == step_idx
2267                            && rec_intr == &actual_intr,
2268                        "Replay resource interruption mismatch at logical step {step_idx}: expected ({after_logical_steps}, {rec_intr:?}), got ({step_idx}, {actual_intr:?})"
2269                    );
2270                    let ev = WasmTraceEvent::ResourceInterruption {
2271                        after_logical_steps: step_idx,
2272                        interruption: Some(actual_intr),
2273                        decision: *decision,
2274                    };
2275                    trace_bytes =
2276                        trace_bytes.saturating_add(ev.estimated_trace_bytes());
2277                    events_vec.push(ev);
2278                    return finalize_checked_trace(this.build_trace(
2279                        session_opt,
2280                        fallback_limits,
2281                        WasmExecutionResult {
2282                            output: DcMstring::new(),
2283                            frames: frames_vec,
2284                            broke_out_early: true,
2285                        },
2286                        events_vec,
2287                        trace_bytes,
2288                        interrupted_op,
2289                    ));
2290                }
2291                let WasmTraceEvent::NonResourceTrap {
2292                    after_logical_steps,
2293                    ..
2294                } = expected
2295                else {
2296                    bail!(
2297                        "Replay non-resource trap mismatch at logical step {step_idx}: expected {expected:?}, got {err:#}"
2298                    );
2299                };
2300                ensure!(
2301                    *after_logical_steps == step_idx,
2302                    "Replay non-resource trap logical step mismatch: expected {after_logical_steps}, got {step_idx}"
2303                );
2304                let ev = WasmTraceEvent::NonResourceTrap {
2305                    after_logical_steps: step_idx,
2306                    trap_message: format!("{err:#}"),
2307                };
2308                trace_bytes =
2309                    trace_bytes.saturating_add(ev.estimated_trace_bytes());
2310                events_vec.push(ev);
2311                finalize_checked_trace(this.build_trace(
2312                    session_opt,
2313                    fallback_limits,
2314                    WasmExecutionResult {
2315                        output: DcMstring::new(),
2316                        frames: frames_vec,
2317                        broke_out_early: true,
2318                    },
2319                    events_vec,
2320                    trace_bytes,
2321                    interrupted_op,
2322                ))
2323            };
2324
2325        if let Err(err) = session.provide_input(input) {
2326            return record_replay_error(
2327                self,
2328                Some(session),
2329                err,
2330                0,
2331                event_idx,
2332                frames,
2333                events,
2334                cumulative_trace_bytes,
2335                last_interrupted_op,
2336            );
2337        }
2338        let mut logical_step = 0usize;
2339
2340        loop {
2341            if let Some(WasmTraceEvent::ResourceInterruption {
2342                after_logical_steps,
2343                interruption: None,
2344                decision,
2345            }) = recorded_trace.events.get(event_idx)
2346                && *after_logical_steps == logical_step
2347            {
2348                let ev = WasmTraceEvent::ResourceInterruption {
2349                    after_logical_steps: *after_logical_steps,
2350                    interruption: None,
2351                    decision: *decision,
2352                };
2353                cumulative_trace_bytes = cumulative_trace_bytes
2354                    .saturating_add(ev.estimated_trace_bytes());
2355                events.push(ev);
2356                if *decision == PermissionDecision::Allow {
2357                    event_idx = event_idx.saturating_add(1);
2358                    continue;
2359                }
2360                return finalize_checked_trace(self.build_trace(
2361                    Some(session),
2362                    fallback_limits,
2363                    WasmExecutionResult {
2364                        output: DcMstring::new(),
2365                        frames,
2366                        broke_out_early: true,
2367                    },
2368                    events,
2369                    cumulative_trace_bytes,
2370                    last_interrupted_op,
2371                ));
2372            }
2373
2374            let expected_event =
2375                recorded_trace.events.get(event_idx).with_context(|| {
2376                    format!(
2377                        "Replay exceeded recorded trace length ({}) at logical step {logical_step}",
2378                        recorded_trace.events.len()
2379                    )
2380                })?;
2381
2382            let step_outcome = match session.step() {
2383                Ok(outcome) => outcome,
2384                Err(err) => {
2385                    if let Some(
2386                        WasmResourceInterruption::ComputeQuotaExhausted {
2387                            limit,
2388                        },
2389                    ) = err.downcast_ref::<WasmResourceInterruption>().cloned()
2390                    {
2391                        let ord = session
2392                            .last_interrupted_op_ordinal()
2393                            .context("ComputeQuotaExhausted during replay missing last_interrupted_op_ordinal")?;
2394                        let cost = session
2395                            .last_interrupted_op_required_cost()
2396                            .context("ComputeQuotaExhausted during replay missing last_interrupted_op_required_cost")?;
2397                        last_interrupted_op = Some((ord, cost));
2398
2399                        let WasmTraceEvent::ResourceInterruption {
2400                            after_logical_steps,
2401                            interruption:
2402                                Some(
2403                                    WasmResourceInterruption::ComputeQuotaExhausted {
2404                                        limit: rec_limit,
2405                                    },
2406                                ),
2407                            decision,
2408                        } = expected_event
2409                        else {
2410                            bail!(
2411                                "Replay hit ComputeQuotaExhausted {{ limit: {limit} }} at logical step {logical_step} (op {ord}, cost {cost}), but recorded event was {expected_event:?}"
2412                            );
2413                        };
2414                        ensure!(
2415                            *after_logical_steps == logical_step
2416                                && *rec_limit == limit,
2417                            "Replay ComputeQuotaExhausted mismatch at logical step {logical_step}: expected (step {after_logical_steps}, limit {rec_limit}), got (step {logical_step}, limit {limit})"
2418                        );
2419                        // Reason for fallback: an out-of-range tail slice means no further events exist.
2420                        let has_later_compute_interruption = recorded_trace
2421                            .events
2422                            .get(event_idx.saturating_add(1)..)
2423                            .unwrap_or(&[])
2424                            .iter()
2425                            .any(|e| {
2426                                matches!(
2427                                    e,
2428                                    WasmTraceEvent::ResourceInterruption {
2429                                        interruption: Some(
2430                                            WasmResourceInterruption::ComputeQuotaExhausted { .. }
2431                                        ),
2432                                        ..
2433                                    }
2434                                )
2435                            });
2436                        if !has_later_compute_interruption {
2437                            ensure!(
2438                                recorded_trace.last_interrupted_op_ordinal
2439                                    == Some(ord)
2440                                    && recorded_trace
2441                                        .last_interrupted_op_required_cost
2442                                        == Some(cost),
2443                                "Replay interrupted op mismatch at logical step {logical_step}: expected ordinal {:?} (cost {:?}), got ordinal {ord} (cost {cost})",
2444                                recorded_trace.last_interrupted_op_ordinal,
2445                                recorded_trace.last_interrupted_op_required_cost
2446                            );
2447                        }
2448                        let ev = WasmTraceEvent::ResourceInterruption {
2449                            after_logical_steps: logical_step,
2450                            interruption: Some(
2451                                WasmResourceInterruption::ComputeQuotaExhausted {
2452                                    limit,
2453                                },
2454                            ),
2455                            decision: *decision,
2456                        };
2457                        cumulative_trace_bytes = cumulative_trace_bytes
2458                            .saturating_add(ev.estimated_trace_bytes());
2459                        events.push(ev);
2460                        if *decision == PermissionDecision::Allow {
2461                            session.increase_compute_quota(
2462                                self.compute_quota_grant.max(1),
2463                            );
2464                            event_idx = event_idx.saturating_add(1);
2465                            continue;
2466                        }
2467                        return finalize_checked_trace(self.build_trace(
2468                            Some(session),
2469                            fallback_limits,
2470                            WasmExecutionResult {
2471                                output: DcMstring::new(),
2472                                frames,
2473                                broke_out_early: true,
2474                            },
2475                            events,
2476                            cumulative_trace_bytes,
2477                            last_interrupted_op,
2478                        ));
2479                    }
2480                    return record_replay_error(
2481                        self,
2482                        Some(session),
2483                        err,
2484                        logical_step,
2485                        event_idx,
2486                        frames,
2487                        events,
2488                        cumulative_trace_bytes,
2489                        last_interrupted_op,
2490                    );
2491                }
2492            };
2493
2494            if let WasmTraceEvent::ResourceInterruption {
2495                after_logical_steps: exp_step,
2496                interruption:
2497                    Some(
2498                        WasmResourceInterruption::TraceBufferBudgetExceeded {
2499                            cumulative_trace_bytes: exp_cum_bytes,
2500                            max_trace_bytes: exp_max_bytes,
2501                        },
2502                    ),
2503                decision: rec_decision,
2504            } = expected_event
2505            {
2506                let candidate_bytes = match &step_outcome {
2507                    WasmStepOutcome::YieldFrame(frame) => {
2508                        WasmTraceEvent::YieldFrame {
2509                            logical_step,
2510                            frame: frame.clone(),
2511                        }
2512                        .estimated_trace_bytes()
2513                    }
2514                    WasmStepOutcome::Complete(output) => {
2515                        WasmTraceEvent::Complete {
2516                            logical_step,
2517                            output: output.clone(),
2518                        }
2519                        .estimated_trace_bytes()
2520                    }
2521                    WasmStepOutcome::RequestCapability(req_dc) => {
2522                        let privilege = Privilege::from_request_dc(req_dc);
2523                        let resp =
2524                            Self::default_capability_response(*rec_decision);
2525                        WasmTraceEvent::CapabilityInteraction {
2526                            logical_step,
2527                            privilege,
2528                            request: req_dc.clone(),
2529                            decision: *rec_decision,
2530                            response: resp,
2531                        }
2532                        .estimated_trace_bytes()
2533                    }
2534                };
2535                let next_bytes =
2536                    cumulative_trace_bytes.saturating_add(candidate_bytes);
2537                ensure!(
2538                    *exp_step == logical_step
2539                        && next_bytes > max_trace_bytes
2540                        && *exp_cum_bytes == next_bytes
2541                        && *exp_max_bytes == max_trace_bytes,
2542                    "Replay TraceBufferBudgetExceeded mismatch at logical step {logical_step}"
2543                );
2544                let ev = WasmTraceEvent::ResourceInterruption {
2545                    after_logical_steps: logical_step,
2546                    interruption: Some(
2547                        WasmResourceInterruption::TraceBufferBudgetExceeded {
2548                            cumulative_trace_bytes: next_bytes,
2549                            max_trace_bytes,
2550                        },
2551                    ),
2552                    decision: *rec_decision,
2553                };
2554                cumulative_trace_bytes = cumulative_trace_bytes
2555                    .saturating_add(ev.estimated_trace_bytes());
2556                events.push(ev);
2557                return finalize_checked_trace(self.build_trace(
2558                    Some(session),
2559                    fallback_limits,
2560                    WasmExecutionResult {
2561                        output: DcMstring::new(),
2562                        frames,
2563                        broke_out_early: true,
2564                    },
2565                    events,
2566                    cumulative_trace_bytes,
2567                    last_interrupted_op,
2568                ));
2569            }
2570
2571            match (step_outcome, expected_event) {
2572                (
2573                    WasmStepOutcome::YieldFrame(frame),
2574                    WasmTraceEvent::YieldFrame {
2575                        logical_step: exp_step,
2576                        frame: exp_frame,
2577                    },
2578                ) => {
2579                    ensure!(
2580                        logical_step == *exp_step && &frame == exp_frame,
2581                        "Replay YieldFrame mismatch at logical step {logical_step}: expected frame {exp_frame:?}, got {frame:?}"
2582                    );
2583                    let _ = self.push_trace_event_bounded(
2584                        &mut events,
2585                        &mut cumulative_trace_bytes,
2586                        max_trace_bytes,
2587                        logical_step,
2588                        WasmTraceEvent::YieldFrame {
2589                            logical_step,
2590                            frame: frame.clone(),
2591                        },
2592                    );
2593                    frames.push(frame);
2594                    logical_step = logical_step.saturating_add(1);
2595                    event_idx = event_idx.saturating_add(1);
2596                }
2597                (
2598                    WasmStepOutcome::RequestCapability(req_dc),
2599                    WasmTraceEvent::CapabilityInteraction {
2600                        logical_step: exp_step,
2601                        privilege: exp_priv,
2602                        request: exp_req,
2603                        decision: rec_decision,
2604                        response: rec_response,
2605                    },
2606                ) => {
2607                    let privilege = Privilege::from_request_dc(&req_dc);
2608                    ensure!(
2609                        logical_step == *exp_step
2610                            && &privilege == exp_priv
2611                            && &req_dc == exp_req,
2612                        "Replay capability request mismatch at logical step {logical_step}: expected ({exp_priv:?}, {exp_req:?}), got ({privilege:?}, {req_dc:?})"
2613                    );
2614                    let _ = self.push_trace_event_bounded(
2615                        &mut events,
2616                        &mut cumulative_trace_bytes,
2617                        max_trace_bytes,
2618                        logical_step,
2619                        WasmTraceEvent::CapabilityInteraction {
2620                            logical_step,
2621                            privilege,
2622                            request: req_dc,
2623                            decision: *rec_decision,
2624                            response: rec_response.clone(),
2625                        },
2626                    );
2627                    if *rec_decision == PermissionDecision::BreakOutResumeNext {
2628                        return finalize_checked_trace(self.build_trace(
2629                            Some(session),
2630                            fallback_limits,
2631                            WasmExecutionResult {
2632                                output: DcMstring::new(),
2633                                frames,
2634                                broke_out_early: true,
2635                            },
2636                            events,
2637                            cumulative_trace_bytes,
2638                            last_interrupted_op,
2639                        ));
2640                    }
2641                    logical_step = logical_step.saturating_add(1);
2642                    event_idx = event_idx.saturating_add(1);
2643                    if let Err(err) =
2644                        session.provide_capability_response(rec_response)
2645                    {
2646                        return record_replay_error(
2647                            self,
2648                            Some(session),
2649                            err,
2650                            logical_step,
2651                            event_idx,
2652                            frames,
2653                            events,
2654                            cumulative_trace_bytes,
2655                            last_interrupted_op,
2656                        );
2657                    }
2658                }
2659                (
2660                    WasmStepOutcome::Complete(output),
2661                    WasmTraceEvent::Complete {
2662                        logical_step: exp_step,
2663                        output: exp_output,
2664                    },
2665                ) => {
2666                    ensure!(
2667                        logical_step == *exp_step && &output == exp_output,
2668                        "Replay Complete output mismatch at logical step {logical_step}: expected {exp_output:?}, got {output:?}"
2669                    );
2670                    let _ = self.push_trace_event_bounded(
2671                        &mut events,
2672                        &mut cumulative_trace_bytes,
2673                        max_trace_bytes,
2674                        logical_step,
2675                        WasmTraceEvent::Complete {
2676                            logical_step,
2677                            output: output.clone(),
2678                        },
2679                    );
2680                    return finalize_checked_trace(self.build_trace(
2681                        Some(session),
2682                        fallback_limits,
2683                        WasmExecutionResult {
2684                            output,
2685                            frames,
2686                            broke_out_early: false,
2687                        },
2688                        events,
2689                        cumulative_trace_bytes,
2690                        last_interrupted_op,
2691                    ));
2692                }
2693                (actual, expected) => {
2694                    bail!(
2695                        "Replay trace divergence at logical step {logical_step}: expected {expected:?}, got {actual:?}"
2696                    );
2697                }
2698            }
2699        }
2700    }
2701
2702    /// Drives a [`DcWasmSession`] over `input` using the standard 32-byte linear-memory
2703    /// mailbox ABI and `step() -> StatusCode` protocol:
2704    /// - `0 = Complete`: returns `WasmExecutionResult` with the final `DcMstring` output.
2705    /// - `1 = YieldFrame`: appends the yielded `DcMstring` frame to `frames` and resumes.
2706    /// - `2 = RequestCapability`: classifies the requested [`Privilege`], evaluates
2707    ///   `self.request_permission`, invokes `capability_handler` to produce the response
2708    ///   `DcMstring`, writes that response into the session's input mailbox, and resumes.
2709    /// - If `self.step()` or `self.request_permission` returns
2710    ///   [`PermissionDecision::BreakOutResumeNext`], stops immediately with
2711    ///   `broke_out_early: true`.
2712    pub fn execute_wasm_session<F>(
2713        &mut self,
2714        session: &mut DcWasmSession,
2715        input: &DcMstr,
2716        capability_handler: F,
2717    ) -> Result<WasmExecutionResult>
2718    where
2719        F: FnMut(&Privilege, PermissionDecision, &DcMstr) -> Result<DcMstring>,
2720    {
2721        let trace = self.execute_wasm_session_with_trace(
2722            session,
2723            input,
2724            capability_handler,
2725        )?;
2726        trace.ensure_not_denied()?;
2727        Ok(trace.result)
2728    }
2729
2730    /// Drives a [`DcWasmSession`] with a default capability response encoder:
2731    /// - `PermissionDecision::Allow` -> `Dc 517 "Boolean true"`
2732    /// - `PermissionDecision::AutoMock` / `PermissionDecision::ManualMock` -> `Dc 316 "Optional value absent"`
2733    /// - `PermissionDecision::Deny` -> `Dc 518 "Boolean false"`
2734    pub fn execute_wasm_session_default(
2735        &mut self,
2736        session: &mut DcWasmSession,
2737        input: &DcMstr,
2738    ) -> Result<WasmExecutionResult> {
2739        let trace =
2740            self.execute_wasm_session_default_with_trace(session, input)?;
2741        trace.ensure_not_denied()?;
2742        Ok(trace.result)
2743    }
2744
2745    /// Instantiates and executes compiled `.wasm` module bytes over `input` with explicit
2746    /// [`ctb_formats_dcstring::DcWasmResourceLimits`], capturing construction-time resource
2747    /// interruptions (initial memory/table limits or `start` compute_quota exhaustion) and
2748    /// `start`-section non-resource traps in the returned [`WasmExecutionTrace`].
2749    ///
2750    /// # Errors
2751    /// Returns an error if the module fails to parse or if `capability_handler` fails.
2752    pub fn execute_wasm_bytes_with_trace<F>(
2753        &mut self,
2754        wasm_bytes: &[u8],
2755        input: &DcMstr,
2756        most_recent_node_id: Option<u128>,
2757        mut resource_limits: ctb_formats_dcstring::DcWasmResourceLimits,
2758        capability_handler: F,
2759    ) -> Result<WasmExecutionTrace>
2760    where
2761        F: FnMut(&Privilege, PermissionDecision, &DcMstr) -> Result<DcMstring>,
2762    {
2763        let initial_limits = resource_limits;
2764        let mut pre_events = Vec::new();
2765        let mut pre_bytes = 0usize;
2766        let mut session = loop {
2767            match DcWasmSession::from_wasm_bytes_with_limits(
2768                wasm_bytes,
2769                input,
2770                most_recent_node_id,
2771                resource_limits,
2772            ) {
2773                Ok(s) => break s,
2774                Err(err) => {
2775                    if let Some(
2776                        WasmResourceInterruption::ComputeQuotaExhausted {
2777                            limit,
2778                        },
2779                    ) = err.downcast_ref::<WasmResourceInterruption>().cloned()
2780                    {
2781                        let decision = self
2782                            .request_permission(&Privilege::ExcessiveCompute);
2783                        let ev = WasmTraceEvent::ResourceInterruption {
2784                            after_logical_steps: 0,
2785                            interruption: Some(
2786                                WasmResourceInterruption::ComputeQuotaExhausted {
2787                                    limit,
2788                                },
2789                            ),
2790                            decision,
2791                        };
2792                        pre_bytes = pre_bytes
2793                            .saturating_add(ev.estimated_trace_bytes());
2794                        pre_events.push(ev);
2795                        if decision == PermissionDecision::Allow {
2796                            resource_limits.max_instructions_per_step =
2797                                resource_limits
2798                                    .max_instructions_per_step
2799                                    .saturating_add(
2800                                        self.compute_quota_grant.max(1),
2801                                    );
2802                            continue;
2803                        }
2804                        return Ok(self.build_trace(
2805                            None,
2806                            initial_limits,
2807                            WasmExecutionResult {
2808                                output: DcMstring::new(),
2809                                frames: Vec::new(),
2810                                broke_out_early: true,
2811                            },
2812                            pre_events,
2813                            pre_bytes,
2814                            None,
2815                        ));
2816                    }
2817                    if err.downcast_ref::<WasmResourceInterruption>().is_some()
2818                        || err
2819                            .downcast_ref::<ctb_formats_dcstring::WasmStartSectionTrap>()
2820                            .is_some()
2821                    {
2822                        return Ok(self.handle_session_error_into_trace(
2823                            None,
2824                            initial_limits,
2825                            err,
2826                            0,
2827                            Vec::new(),
2828                            pre_events,
2829                            pre_bytes,
2830                            None,
2831                        ));
2832                    }
2833                    return Err(err);
2834                }
2835            }
2836        };
2837        let mut trace = self.execute_wasm_session_with_trace(
2838            &mut session,
2839            input,
2840            capability_handler,
2841        )?;
2842        if !pre_events.is_empty() {
2843            trace.cumulative_trace_bytes =
2844                pre_bytes.saturating_add(trace.cumulative_trace_bytes);
2845            pre_events.extend(trace.events);
2846            trace.events = pre_events;
2847            trace.effective_config_bytes =
2848                initial_limits.encode_canonical_config_bytes();
2849        }
2850        Ok(trace)
2851    }
2852
2853    /// Replays compiled `.wasm` module bytes against a recorded [`WasmExecutionTrace`],
2854    /// actually instantiating and running the module to verify construction-time resource
2855    /// interruptions, `start`-section non-resource traps, and `provide_input` / `step` events.
2856    ///
2857    /// # Errors
2858    /// Returns an error if replay diverges from `recorded_trace`.
2859    pub fn replay_wasm_bytes_trace(
2860        &mut self,
2861        wasm_bytes: &[u8],
2862        input: &DcMstr,
2863        most_recent_node_id: Option<u128>,
2864        mut resource_limits: ctb_formats_dcstring::DcWasmResourceLimits,
2865        recorded_trace: &WasmExecutionTrace,
2866    ) -> Result<WasmExecutionTrace> {
2867        ensure!(
2868            recorded_trace.accounting_version
2869                == WASM_RESOURCE_ACCOUNTING_VERSION,
2870            "Replay accounting_version mismatch: recorded {}, runtime {}",
2871            recorded_trace.accounting_version,
2872            WASM_RESOURCE_ACCOUNTING_VERSION
2873        );
2874        if let Ok(decoded) =
2875            DcWasmResourceLimits::decode_canonical_config_bytes(
2876                &recorded_trace.effective_config_bytes,
2877            )
2878        {
2879            resource_limits = decoded;
2880        }
2881        let initial_limits = resource_limits;
2882        let mut pre_events = Vec::new();
2883        let mut pre_bytes = 0usize;
2884        let mut event_cursor = 0usize;
2885
2886        let mut session = loop {
2887            match DcWasmSession::from_wasm_bytes_with_limits(
2888                wasm_bytes,
2889                input,
2890                most_recent_node_id,
2891                resource_limits,
2892            ) {
2893                Ok(s) => break s,
2894                Err(err) => {
2895                    let expected = recorded_trace
2896                        .events
2897                        .get(event_cursor)
2898                        .with_context(|| {
2899                            format!(
2900                                "Replay encountered construction error ({err:#}) beyond recorded trace length ({})",
2901                                recorded_trace.events.len()
2902                            )
2903                        })?;
2904                    if let Some(actual_intr) =
2905                        err.downcast_ref::<WasmResourceInterruption>().cloned()
2906                    {
2907                        let WasmTraceEvent::ResourceInterruption {
2908                            after_logical_steps,
2909                            interruption: Some(rec_intr),
2910                            decision,
2911                        } = expected
2912                        else {
2913                            bail!(
2914                                "Replay construction resource interruption mismatch: expected {expected:?}, got {actual_intr:?}"
2915                            );
2916                        };
2917                        ensure!(
2918                            *after_logical_steps == 0
2919                                && rec_intr == &actual_intr,
2920                            "Replay construction resource interruption mismatch: expected ({after_logical_steps}, {rec_intr:?}), got (0, {actual_intr:?})"
2921                        );
2922                        let ev = WasmTraceEvent::ResourceInterruption {
2923                            after_logical_steps: 0,
2924                            interruption: Some(actual_intr.clone()),
2925                            decision: *decision,
2926                        };
2927                        pre_bytes = pre_bytes
2928                            .saturating_add(ev.estimated_trace_bytes());
2929                        pre_events.push(ev);
2930                        event_cursor = event_cursor.saturating_add(1);
2931                        if matches!(
2932                            actual_intr,
2933                            WasmResourceInterruption::ComputeQuotaExhausted { .. }
2934                        ) && *decision == PermissionDecision::Allow
2935                        {
2936                            resource_limits.max_instructions_per_step =
2937                                resource_limits
2938                                    .max_instructions_per_step
2939                                    .saturating_add(
2940                                        self.compute_quota_grant.max(1),
2941                                    );
2942                            continue;
2943                        }
2944                        let mut trace = self.build_trace(
2945                            None,
2946                            initial_limits,
2947                            WasmExecutionResult {
2948                                output: DcMstring::new(),
2949                                frames: Vec::new(),
2950                                broke_out_early: true,
2951                            },
2952                            pre_events,
2953                            pre_bytes,
2954                            None,
2955                        );
2956                        if trace.supervisor_revision_node_id.is_none()
2957                            && recorded_trace
2958                                .supervisor_revision_node_id
2959                                .is_some()
2960                        {
2961                            trace.supervisor_revision_node_id =
2962                                recorded_trace.supervisor_revision_node_id;
2963                            trace.dependency_snapshot_node_ids = recorded_trace
2964                                .dependency_snapshot_node_ids
2965                                .clone();
2966                        }
2967                        ensure!(
2968                            &trace == recorded_trace,
2969                            "Replay terminated without matching the complete recorded trace and result"
2970                        );
2971                        return Ok(trace);
2972                    }
2973                    if err
2974                        .downcast_ref::<ctb_formats_dcstring::WasmStartSectionTrap>()
2975                        .is_some()
2976                    {
2977                        let WasmTraceEvent::NonResourceTrap {
2978                            after_logical_steps,
2979                            ..
2980                        } = expected
2981                        else {
2982                            bail!(
2983                                "Replay construction start trap mismatch: expected {expected:?}, got {err:#}"
2984                            );
2985                        };
2986                        ensure!(
2987                            *after_logical_steps == 0,
2988                            "Replay construction start trap logical step mismatch: expected {after_logical_steps}, got 0"
2989                        );
2990                        let ev = WasmTraceEvent::NonResourceTrap {
2991                            after_logical_steps: 0,
2992                            trap_message: format!("{err:#}"),
2993                        };
2994                        pre_bytes = pre_bytes
2995                            .saturating_add(ev.estimated_trace_bytes());
2996                        pre_events.push(ev);
2997                        let mut trace = self.build_trace(
2998                            None,
2999                            initial_limits,
3000                            WasmExecutionResult {
3001                                output: DcMstring::new(),
3002                                frames: Vec::new(),
3003                                broke_out_early: true,
3004                            },
3005                            pre_events,
3006                            pre_bytes,
3007                            None,
3008                        );
3009                        if trace.supervisor_revision_node_id.is_none()
3010                            && recorded_trace
3011                                .supervisor_revision_node_id
3012                                .is_some()
3013                        {
3014                            trace.supervisor_revision_node_id =
3015                                recorded_trace.supervisor_revision_node_id;
3016                            trace.dependency_snapshot_node_ids = recorded_trace
3017                                .dependency_snapshot_node_ids
3018                                .clone();
3019                        }
3020                        ensure!(
3021                            &trace == recorded_trace,
3022                            "Replay terminated without matching the complete recorded trace and result"
3023                        );
3024                        return Ok(trace);
3025                    }
3026                    return Err(err);
3027                }
3028            }
3029        };
3030        self.replay_wasm_session_trace_with_prefix(
3031            &mut session,
3032            input,
3033            recorded_trace,
3034            pre_events,
3035            pre_bytes,
3036            event_cursor,
3037            Some(initial_limits),
3038        )
3039    }
3040}
3041
3042#[cfg(test)]
3043#[allow(
3044    clippy::panic,
3045    clippy::expect_used,
3046    clippy::unwrap_used,
3047    clippy::unwrap_in_result,
3048    clippy::panic_in_result_fn,
3049    clippy::indexing_slicing,
3050    clippy::arithmetic_side_effects,
3051    reason = "Standard repository test boilerplate"
3052)]
3053mod tests {
3054    use super::*;
3055
3056    #[crate::ctb_test]
3057    fn can_start() {
3058        // Basic test that start() doesn't panic
3059        start(vec![1, 2, 3]);
3060    }
3061
3062    #[crate::ctb_test]
3063    fn test_permission_steering_on_document_errors() {
3064        let valid_ctx = ExecutionContext::new(false);
3065        assert_eq!(
3066            valid_ctx.request_permission(&Privilege::FileIo),
3067            PermissionDecision::Deny
3068        );
3069        assert_eq!(
3070            valid_ctx.request_permission(&Privilege::Network),
3071            PermissionDecision::Deny
3072        );
3073        let allowed_ctx = valid_ctx
3074            .with_privilege_decision(Privilege::FileIo, PermissionDecision::Allow);
3075        assert_eq!(allowed_ctx.request_permission(&Privilege::FileIo), PermissionDecision::Allow);
3076
3077        let error_ctx = ExecutionContext::new(true);
3078        assert_eq!(
3079            error_ctx.request_permission(&Privilege::FileIo),
3080            PermissionDecision::AutoMock
3081        );
3082    }
3083
3084    #[crate::ctb_test]
3085    fn test_excessive_compute_breakout() {
3086        let mut ctx = ExecutionContext::new(false);
3087        ctx.max_compute_steps = 2;
3088        assert_eq!(ctx.step().unwrap(), PermissionDecision::Allow);
3089        assert_eq!(ctx.step().unwrap(), PermissionDecision::Allow);
3090        // Exceeding budget triggers breakout to resume on next Dc
3091        assert_eq!(ctx.step().unwrap(), PermissionDecision::BreakOutResumeNext);
3092    }
3093
3094    #[crate::ctb_test]
3095    fn test_execute_wasm_session_yield_capability_and_breakout() -> Result<()> {
3096        use ctb_formats_dcstring::{DcChar, DcMixedEncode};
3097
3098        let i32_dc =
3099            DcChar::from_u128(crate::FormatId::I32.dc_id().unwrap());
3100
3101        // Build a stateful Dc-WASM routine using mem[64] as phase counter:
3102        // Phase 0: copies input to output and returns 1 (YieldFrame), sets mem[64] = 1
3103        // Phase 1: copies input ("FileIo") to output and returns 2 (RequestCapability), sets mem[64] = 2
3104        // Phase 2: copies capability response (from input mailbox) to output and returns 0 (Complete)
3105        let mut routine_doc = DcMstring::new();
3106        routine_doc.push_char(DcChar::from_short(260));
3107        routine_doc.push_char(DcChar::from_short(262));
3108        routine_doc.push_char(DcChar::from_short(280));
3109        routine_doc.push_char(i32_dc);
3110        routine_doc.push_char(DcChar::from_short(263));
3111
3112        // Always echo current input mailbox (0..8) to output mailbox (8..16)
3113        routine_doc.push_char(DcChar::from_short(712));
3114        i32::encode_dc_mixed(&8, &mut routine_doc)?;
3115        routine_doc.push_char(DcChar::from_short(712));
3116        i32::encode_dc_mixed(&0, &mut routine_doc)?;
3117        routine_doc.push_char(DcChar::from_short(687));
3118        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3119        u32::encode_dc_mixed(&2, &mut routine_doc)?;
3120        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3121        routine_doc.push_char(DcChar::from_short(701));
3122        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3123        u32::encode_dc_mixed(&2, &mut routine_doc)?;
3124        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3125
3126        routine_doc.push_char(DcChar::from_short(712));
3127        i32::encode_dc_mixed(&12, &mut routine_doc)?;
3128        routine_doc.push_char(DcChar::from_short(712));
3129        i32::encode_dc_mixed(&4, &mut routine_doc)?;
3130        routine_doc.push_char(DcChar::from_short(687));
3131        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3132        u32::encode_dc_mixed(&2, &mut routine_doc)?;
3133        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3134        routine_doc.push_char(DcChar::from_short(701));
3135        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3136        u32::encode_dc_mixed(&2, &mut routine_doc)?;
3137        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3138
3139        // Check mem[64] == 0 (`i32.eqz` = Dc 716)
3140        routine_doc.push_char(DcChar::from_short(712));
3141        i32::encode_dc_mixed(&64, &mut routine_doc)?;
3142        routine_doc.push_char(DcChar::from_short(687));
3143        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3144        u32::encode_dc_mixed(&2, &mut routine_doc)?;
3145        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3146        routine_doc.push_char(DcChar::from_short(716)); // i32.eqz
3147        routine_doc.push_char(DcChar::from_short(651)); // if (result i32)
3148        routine_doc.push_char(i32_dc);
3149        // mem[64] = 1; return 1 (YieldFrame)
3150        routine_doc.push_char(DcChar::from_short(712));
3151        i32::encode_dc_mixed(&64, &mut routine_doc)?;
3152        routine_doc.push_char(DcChar::from_short(712));
3153        i32::encode_dc_mixed(&1, &mut routine_doc)?;
3154        routine_doc.push_char(DcChar::from_short(701));
3155        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3156        u32::encode_dc_mixed(&2, &mut routine_doc)?;
3157        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3158        routine_doc.push_char(DcChar::from_short(712));
3159        i32::encode_dc_mixed(&1, &mut routine_doc)?;
3160        routine_doc.push_char(DcChar::from_short(652)); // else
3161        // Check mem[64] == 1 (`i32.eq` = Dc 717)
3162        routine_doc.push_char(DcChar::from_short(712));
3163        i32::encode_dc_mixed(&64, &mut routine_doc)?;
3164        routine_doc.push_char(DcChar::from_short(687));
3165        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3166        u32::encode_dc_mixed(&2, &mut routine_doc)?;
3167        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3168        routine_doc.push_char(DcChar::from_short(712));
3169        i32::encode_dc_mixed(&1, &mut routine_doc)?;
3170        routine_doc.push_char(DcChar::from_short(717)); // i32.eq
3171        routine_doc.push_char(DcChar::from_short(651)); // if (result i32)
3172        routine_doc.push_char(i32_dc);
3173        // mem[64] = 2; return 2 (RequestCapability)
3174        routine_doc.push_char(DcChar::from_short(712));
3175        i32::encode_dc_mixed(&64, &mut routine_doc)?;
3176        routine_doc.push_char(DcChar::from_short(712));
3177        i32::encode_dc_mixed(&2, &mut routine_doc)?;
3178        routine_doc.push_char(DcChar::from_short(701));
3179        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3180        u32::encode_dc_mixed(&2, &mut routine_doc)?;
3181        u32::encode_dc_mixed(&0, &mut routine_doc)?;
3182        routine_doc.push_char(DcChar::from_short(712));
3183        i32::encode_dc_mixed(&2, &mut routine_doc)?;
3184        routine_doc.push_char(DcChar::from_short(652)); // else
3185        // return 0 (Complete)
3186        routine_doc.push_char(DcChar::from_short(712));
3187        i32::encode_dc_mixed(&0, &mut routine_doc)?;
3188        routine_doc.push_char(DcChar::from_short(658)); // end inner if
3189        routine_doc.push_char(DcChar::from_short(658)); // end outer if
3190        routine_doc.push_char(DcChar::from_short(261));
3191
3192        let mut input = DcMstring::new();
3193        input.push_str("FileIo");
3194
3195        // 1. Explicit FileIo grant: response is `Dc 517 "Boolean true"`
3196        let mut session_ok = DcWasmSession::from_dc_wasm(&routine_doc, &input, None)?;
3197        let mut valid_ctx = ExecutionContext::new(false)
3198            .with_privilege_decision(Privilege::FileIo, PermissionDecision::Allow);
3199        let res_ok = valid_ctx.execute_wasm_session_default(&mut session_ok, &input)?;
3200        assert!(!res_ok.broke_out_early);
3201        assert_eq!(res_ok.frames.len(), 1);
3202        assert_eq!(res_ok.frames[0], input);
3203        let mut expected_allow = DcMstring::new();
3204        expected_allow.push_char(dc::DC_BOOLEAN_TRUE);
3205        assert_eq!(res_ok.output, expected_allow);
3206
3207        // 2. Document with parse errors (`has_errors = true`): capability steers to `AutoMock` -> `Dc 316 "Optional value absent"`
3208        let mut session_err = DcWasmSession::from_dc_wasm(&routine_doc, &input, None)?;
3209        let mut error_ctx = ExecutionContext::new(true);
3210        let res_err = error_ctx.execute_wasm_session_default(&mut session_err, &input)?;
3211        assert!(!res_err.broke_out_early);
3212        assert_eq!(res_err.frames.len(), 1);
3213        let mut expected_mock = DcMstring::new();
3214        expected_mock.push_char(dc::DC_OPTIONAL_ABSENT);
3215        assert_eq!(res_err.output, expected_mock);
3216
3217        // 3. Budget exhaustion (`max_compute_steps = 1`): yields 1 frame, then breaks out early on step 2
3218        let mut session_budget = DcWasmSession::from_dc_wasm(&routine_doc, &input, None)?;
3219        let mut budget_ctx = ExecutionContext::new(false);
3220        budget_ctx.max_compute_steps = 1;
3221        let res_budget = budget_ctx.execute_wasm_session_default(&mut session_budget, &input)?;
3222        assert!(res_budget.broke_out_early);
3223        assert_eq!(res_budget.frames.len(), 1);
3224
3225        Ok(())
3226    }
3227
3228    #[crate::ctb_test]
3229    fn test_gate2_tight_wasm_loop_triggers_excessive_compute_and_records_resource_event()
3230    -> Result<()> {
3231        use ctb_formats_dcstring::{
3232            DcChar, DcMixedEncode, DcWasmResourceLimits,
3233        };
3234
3235        let i32_dc =
3236            DcChar::from_u128(crate::FormatId::I32.dc_id().unwrap());
3237        let mut loop_doc = DcMstring::new();
3238        loop_doc.push_char(DcChar::from_short(260));
3239        loop_doc.push_char(DcChar::from_short(262));
3240        loop_doc.push_char(DcChar::from_short(280));
3241        loop_doc.push_char(i32_dc);
3242        loop_doc.push_char(DcChar::from_short(263));
3243        loop_doc.push_char(DcChar::from_short(650)); // WASM loop
3244        loop_doc.push_char(DcChar::from_short(316)); // empty blocktype (Dc 316 -> 0x40)
3245        loop_doc.push_char(DcChar::from_short(659)); // WASM br 0
3246        u32::encode_dc_mixed(&0, &mut loop_doc)?;
3247        loop_doc.push_char(DcChar::from_short(658)); // WASM end
3248        loop_doc.push_char(DcChar::from_short(712)); // i32.const 0
3249        i32::encode_dc_mixed(&0, &mut loop_doc)?;
3250        loop_doc.push_char(DcChar::from_short(261));
3251
3252        let input = DcMstring::new();
3253        let limits =
3254            DcWasmResourceLimits::default().with_max_instructions_per_step(250);
3255
3256        // 1. Default policy (`BreakOutResumeNext` on `ExcessiveCompute`) breaks out cleanly
3257        //    and records `WasmTraceEvent::ResourceInterruption` with `ComputeQuotaExhausted`.
3258        let mut session = DcWasmSession::from_dc_wasm(&loop_doc, &input, None)?
3259            .with_resource_limits(limits);
3260        let mut ctx = ExecutionContext::new(false);
3261        let trace = ctx.execute_wasm_session_default_with_trace(&mut session, &input)?;
3262        assert!(trace.result.broke_out_early);
3263        assert_eq!(
3264            trace.events,
3265            vec![WasmTraceEvent::ResourceInterruption {
3266                after_logical_steps: 0,
3267                interruption: Some(
3268                    WasmResourceInterruption::ComputeQuotaExhausted {
3269                        limit: 250
3270                    }
3271                ),
3272                decision: PermissionDecision::BreakOutResumeNext,
3273            }]
3274        );
3275
3276        // 2. Host policy overriding `ExcessiveCompute` to `Deny` preserves the denied
3277        //    `ResourceInterruption` in `execute_wasm_session_default_with_trace` while
3278        //    returning an error from `execute_wasm_session_default` / `ensure_not_denied`.
3279        let mut deny_session =
3280            DcWasmSession::from_dc_wasm(&loop_doc, &input, None)?
3281                .with_resource_limits(limits);
3282        let mut deny_ctx = ExecutionContext::new(false).with_privilege_decision(
3283            Privilege::ExcessiveCompute,
3284            PermissionDecision::Deny,
3285        );
3286        let denied_trace = deny_ctx
3287            .execute_wasm_session_default_with_trace(&mut deny_session, &input)?;
3288        assert!(denied_trace.ensure_not_denied().is_err());
3289        assert!(
3290            deny_ctx
3291                .execute_wasm_session_default(&mut deny_session, &input)
3292                .is_err()
3293        );
3294        Ok(())
3295    }
3296
3297    #[crate::ctb_test]
3298    fn test_gate2_historical_graph_pin_never_grants_or_restores_capabilities()
3299    -> Result<()> {
3300        use ctb_formats_dcstring::{DcChar, DcMixedEncode};
3301
3302        let i32_dc =
3303            DcChar::from_u128(crate::FormatId::I32.dc_id().unwrap());
3304        // Routine that requests capability on step 0 (mem[64] == 0 -> sets mem[64] = 1, returns 2)
3305        // and echoes the host's capability response on step 1 (returns 0).
3306        let mut cap_doc = DcMstring::new();
3307        cap_doc.push_char(DcChar::from_short(260));
3308        cap_doc.push_char(DcChar::from_short(262));
3309        cap_doc.push_char(DcChar::from_short(280));
3310        cap_doc.push_char(i32_dc);
3311        cap_doc.push_char(DcChar::from_short(263));
3312        // Echo input mailbox (0..8) -> output mailbox (8..16)
3313        cap_doc.push_char(DcChar::from_short(712));
3314        i32::encode_dc_mixed(&8, &mut cap_doc)?;
3315        cap_doc.push_char(DcChar::from_short(712));
3316        i32::encode_dc_mixed(&0, &mut cap_doc)?;
3317        cap_doc.push_char(DcChar::from_short(687));
3318        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3319        u32::encode_dc_mixed(&2, &mut cap_doc)?;
3320        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3321        cap_doc.push_char(DcChar::from_short(701));
3322        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3323        u32::encode_dc_mixed(&2, &mut cap_doc)?;
3324        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3325
3326        cap_doc.push_char(DcChar::from_short(712));
3327        i32::encode_dc_mixed(&12, &mut cap_doc)?;
3328        cap_doc.push_char(DcChar::from_short(712));
3329        i32::encode_dc_mixed(&4, &mut cap_doc)?;
3330        cap_doc.push_char(DcChar::from_short(687));
3331        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3332        u32::encode_dc_mixed(&2, &mut cap_doc)?;
3333        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3334        cap_doc.push_char(DcChar::from_short(701));
3335        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3336        u32::encode_dc_mixed(&2, &mut cap_doc)?;
3337        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3338
3339        cap_doc.push_char(DcChar::from_short(712));
3340        i32::encode_dc_mixed(&64, &mut cap_doc)?;
3341        cap_doc.push_char(DcChar::from_short(687));
3342        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3343        u32::encode_dc_mixed(&2, &mut cap_doc)?;
3344        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3345        cap_doc.push_char(DcChar::from_short(716)); // i32.eqz
3346        cap_doc.push_char(DcChar::from_short(651)); // if (result i32)
3347        cap_doc.push_char(i32_dc);
3348        cap_doc.push_char(DcChar::from_short(712));
3349        i32::encode_dc_mixed(&64, &mut cap_doc)?;
3350        cap_doc.push_char(DcChar::from_short(712));
3351        i32::encode_dc_mixed(&1, &mut cap_doc)?;
3352        cap_doc.push_char(DcChar::from_short(701));
3353        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3354        u32::encode_dc_mixed(&2, &mut cap_doc)?;
3355        u32::encode_dc_mixed(&0, &mut cap_doc)?;
3356        cap_doc.push_char(DcChar::from_short(712));
3357        i32::encode_dc_mixed(&2, &mut cap_doc)?; // RequestCapability
3358        cap_doc.push_char(DcChar::from_short(652)); // else
3359        cap_doc.push_char(DcChar::from_short(712));
3360        i32::encode_dc_mixed(&0, &mut cap_doc)?; // Complete
3361        cap_doc.push_char(DcChar::from_short(658));
3362        cap_doc.push_char(DcChar::from_short(261));
3363
3364        let mut input = DcMstring::new();
3365        input.push_str("Network");
3366
3367        let mut expected_deny = DcMstring::new();
3368        expected_deny.push_char(dc::DC_BOOLEAN_FALSE);
3369
3370        // Even when a session is pinned to an early historical Dc 641 watermark, a host policy
3371        // denying `Privilege::Network` strictly denies the request.
3372        for pin in [None, Some(8_589_934_592_u128), Some(8_589_940_000_u128)] {
3373            let mut session =
3374                DcWasmSession::from_dc_wasm(&cap_doc, &input, pin)?;
3375            let mut host_ctx = ExecutionContext::new(false)
3376                .with_privilege_decision(
3377                    Privilege::Network,
3378                    PermissionDecision::Deny,
3379                );
3380            let res =
3381                host_ctx.execute_wasm_session_default(&mut session, &input)?;
3382            assert_eq!(res.output, expected_deny);
3383        }
3384        Ok(())
3385    }
3386
3387    #[crate::ctb_test]
3388    fn test_gate2_capability_trace_replay_compares_requests_and_ignores_compiler_instruction_counts()
3389    -> Result<()> {
3390        use ctb_formats_dcstring::{
3391            DcChar, DcMixedEncode, DcWasmResourceLimits,
3392        };
3393
3394        let i32_dc =
3395            DcChar::from_u128(crate::FormatId::I32.dc_id().unwrap());
3396        let build_cap_routine = |nop_padding: usize| -> Result<DcMstring> {
3397            let mut doc = DcMstring::new();
3398            doc.push_char(DcChar::from_short(260));
3399            doc.push_char(DcChar::from_short(262));
3400            doc.push_char(DcChar::from_short(280));
3401            doc.push_char(i32_dc);
3402            doc.push_char(DcChar::from_short(263));
3403            for _ in 0..nop_padding {
3404                doc.push_char(DcChar::from_short(648)); // WASM nop (0x01)
3405            }
3406            // Echo input mailbox (0..8) -> output mailbox (8..16)
3407            doc.push_char(DcChar::from_short(712));
3408            i32::encode_dc_mixed(&8, &mut doc)?;
3409            doc.push_char(DcChar::from_short(712));
3410            i32::encode_dc_mixed(&0, &mut doc)?;
3411            doc.push_char(DcChar::from_short(687));
3412            u32::encode_dc_mixed(&0, &mut doc)?;
3413            u32::encode_dc_mixed(&2, &mut doc)?;
3414            u32::encode_dc_mixed(&0, &mut doc)?;
3415            doc.push_char(DcChar::from_short(701));
3416            u32::encode_dc_mixed(&0, &mut doc)?;
3417            u32::encode_dc_mixed(&2, &mut doc)?;
3418            u32::encode_dc_mixed(&0, &mut doc)?;
3419
3420            doc.push_char(DcChar::from_short(712));
3421            i32::encode_dc_mixed(&12, &mut doc)?;
3422            doc.push_char(DcChar::from_short(712));
3423            i32::encode_dc_mixed(&4, &mut doc)?;
3424            doc.push_char(DcChar::from_short(687));
3425            u32::encode_dc_mixed(&0, &mut doc)?;
3426            u32::encode_dc_mixed(&2, &mut doc)?;
3427            u32::encode_dc_mixed(&0, &mut doc)?;
3428            doc.push_char(DcChar::from_short(701));
3429            u32::encode_dc_mixed(&0, &mut doc)?;
3430            u32::encode_dc_mixed(&2, &mut doc)?;
3431            u32::encode_dc_mixed(&0, &mut doc)?;
3432
3433            doc.push_char(DcChar::from_short(712));
3434            i32::encode_dc_mixed(&64, &mut doc)?;
3435            doc.push_char(DcChar::from_short(687));
3436            u32::encode_dc_mixed(&0, &mut doc)?;
3437            u32::encode_dc_mixed(&2, &mut doc)?;
3438            u32::encode_dc_mixed(&0, &mut doc)?;
3439            doc.push_char(DcChar::from_short(716)); // i32.eqz
3440            doc.push_char(DcChar::from_short(651)); // if (result i32)
3441            doc.push_char(i32_dc);
3442            doc.push_char(DcChar::from_short(712));
3443            i32::encode_dc_mixed(&64, &mut doc)?;
3444            doc.push_char(DcChar::from_short(712));
3445            i32::encode_dc_mixed(&1, &mut doc)?;
3446            doc.push_char(DcChar::from_short(701));
3447            u32::encode_dc_mixed(&0, &mut doc)?;
3448            u32::encode_dc_mixed(&2, &mut doc)?;
3449            u32::encode_dc_mixed(&0, &mut doc)?;
3450            doc.push_char(DcChar::from_short(712));
3451            i32::encode_dc_mixed(&2, &mut doc)?; // RequestCapability
3452            doc.push_char(DcChar::from_short(652)); // else
3453            doc.push_char(DcChar::from_short(712));
3454            i32::encode_dc_mixed(&0, &mut doc)?; // Complete
3455            doc.push_char(DcChar::from_short(658));
3456            doc.push_char(DcChar::from_short(261));
3457            Ok(doc)
3458        };
3459
3460        let routine_v1 = build_cap_routine(0)?;
3461        let routine_v2_extra_instrs = build_cap_routine(300)?;
3462
3463        let mut file_io_input = DcMstring::new();
3464        file_io_input.push_str("FileIo");
3465
3466        // Record trace under `Allow` policy
3467        let mut rec_session =
3468            DcWasmSession::from_dc_wasm(&routine_v1, &file_io_input, None)?;
3469        let mut rec_ctx = ExecutionContext::new(false)
3470            .with_privilege_decision(Privilege::FileIo, PermissionDecision::Allow);
3471        let recorded_trace = rec_ctx
3472            .execute_wasm_session_default_with_trace(
3473                &mut rec_session,
3474                &file_io_input,
3475            )?;
3476        assert!(!recorded_trace.result.broke_out_early);
3477        assert_eq!(recorded_trace.events.len(), 2);
3478
3479        // 1. Replay against a recompiled module with different physical instruction counts
3480        //    succeeds and reproduces the exact logical trace and recorded response, even if
3481        //    the current `ExecutionContext` has `Deny` configured for live runs.
3482        let mut replay_session = DcWasmSession::from_dc_wasm(
3483            &routine_v2_extra_instrs,
3484            &file_io_input,
3485            None,
3486        )?;
3487        let mut replay_ctx = ExecutionContext::new(false)
3488            .with_privilege_decision(Privilege::FileIo, PermissionDecision::Deny);
3489        let replayed = replay_ctx.replay_wasm_session_trace(
3490            &mut replay_session,
3491            &file_io_input,
3492            &recorded_trace,
3493        )?;
3494        assert_eq!(replayed, recorded_trace);
3495        let mut trailing_trace = recorded_trace.clone();
3496        trailing_trace.events.push(recorded_trace.events.last().unwrap().clone());
3497        let mut trailing_session =
3498            DcWasmSession::from_dc_wasm(&routine_v1, &file_io_input, None)?;
3499        assert!(replay_ctx.replay_wasm_session_trace(
3500            &mut trailing_session, &file_io_input, &trailing_trace,
3501        ).is_err());
3502        let mut wrong_result_trace = recorded_trace.clone();
3503        wrong_result_trace.result.broke_out_early = true;
3504        let mut wrong_result_session =
3505            DcWasmSession::from_dc_wasm(&routine_v1, &file_io_input, None)?;
3506        assert!(replay_ctx.replay_wasm_session_trace(
3507            &mut wrong_result_session, &file_io_input, &wrong_result_trace,
3508        ).is_err());
3509        assert_ne!(
3510            rec_session.total_instructions_executed(),
3511            replay_session.total_instructions_executed()
3512        );
3513
3514        // 2. Replay detects a changed capability request (`Network` instead of `FileIo`) and errors.
3515        let mut net_input = DcMstring::new();
3516        net_input.push_str("Network");
3517        let mut bad_replay_session =
3518            DcWasmSession::from_dc_wasm(&routine_v1, &net_input, None)?;
3519        let mismatch_err = replay_ctx
3520            .replay_wasm_session_trace(
3521                &mut bad_replay_session,
3522                &net_input,
3523                &recorded_trace,
3524            )
3525            .expect_err("Divergent capability request during replay must fail");
3526        assert!(
3527            mismatch_err
3528                .to_string()
3529                .contains("Replay capability request mismatch"),
3530            "Unexpected error: {mismatch_err}"
3531        );
3532
3533        // 3. Record a trace interrupted by compute_quota exhaustion and verify replay actually
3534        //    executes `session.step()` under the recorded configuration and triggers the exact
3535        //    recorded `WasmResourceInterruption` at `last_interrupted_op_ordinal`.
3536        let low_compute_quota =
3537            DcWasmResourceLimits::default().with_max_instructions_per_step(1);
3538        let mut interrupted_session = DcWasmSession::from_dc_wasm(
3539            &routine_v2_extra_instrs,
3540            &file_io_input,
3541            None,
3542        )?
3543        .with_resource_limits(low_compute_quota);
3544        let mut int_ctx = ExecutionContext::new(false);
3545        let interrupted_trace = int_ctx
3546            .execute_wasm_session_default_with_trace(
3547                &mut interrupted_session,
3548                &file_io_input,
3549            )?;
3550        assert!(interrupted_trace.result.broke_out_early);
3551        assert_eq!(interrupted_trace.last_interrupted_op_ordinal, Some(2));
3552        assert_eq!(
3553            interrupted_trace.last_interrupted_op_required_cost,
3554            Some(1)
3555        );
3556
3557        let mut fast_replay_session = DcWasmSession::from_dc_wasm(
3558            &routine_v2_extra_instrs,
3559            &file_io_input,
3560            None,
3561        )?;
3562        let replayed_int = replay_ctx.replay_wasm_session_trace(
3563            &mut fast_replay_session,
3564            &file_io_input,
3565            &interrupted_trace,
3566        )?;
3567        assert_eq!(replayed_int, interrupted_trace);
3568        assert_eq!(fast_replay_session.total_instructions_executed(), 1);
3569        assert_eq!(
3570            fast_replay_session.last_interrupted_op_ordinal(),
3571            Some(2)
3572        );
3573        assert_eq!(
3574            fast_replay_session.last_interrupted_op_required_cost(),
3575            Some(1)
3576        );
3577
3578        // Tampering with `last_interrupted_op_ordinal` in the recorded trace must fail replay verification.
3579        let mut forged_ordinal_trace = interrupted_trace.clone();
3580        forged_ordinal_trace.last_interrupted_op_ordinal = Some(99);
3581        let mut forged_replay_session = DcWasmSession::from_dc_wasm(
3582            &routine_v2_extra_instrs,
3583            &file_io_input,
3584            None,
3585        )?;
3586        assert!(
3587            replay_ctx
3588                .replay_wasm_session_trace(
3589                    &mut forged_replay_session,
3590                    &file_io_input,
3591                    &forged_ordinal_trace,
3592                )
3593                .is_err()
3594        );
3595        Ok(())
3596    }
3597
3598    #[crate::ctb_test]
3599    fn test_gate2_denied_and_construction_resource_interruptions_preserve_and_replay_traces()
3600    -> Result<()> {
3601        use ctb_formats_dcstring::{
3602            DcChar, DcMixedEncode, DcWasmResourceLimits,
3603            WasmResourceInterruption,
3604        };
3605
3606        let i32_dc =
3607            DcChar::from_u128(crate::FormatId::I32.dc_id().unwrap());
3608
3609        // Routine that:
3610        // - Step 0 (mem[64] == 0): sets mem[64] = 1, echoes input to output, returns 1 (YieldFrame)
3611        // - Step 1 (mem[64] == 1): sets mem[64] = 2, echoes input to output, returns 2 (RequestCapability)
3612        // - Step 2 (mem[64] == 2): enters a tight loop that exhausts instruction compute_quota
3613        let mut multi_doc = DcMstring::new();
3614        multi_doc.push_char(DcChar::from_short(260));
3615        multi_doc.push_char(DcChar::from_short(262));
3616        multi_doc.push_char(DcChar::from_short(280));
3617        multi_doc.push_char(i32_dc);
3618        multi_doc.push_char(DcChar::from_short(263));
3619        // Echo input mailbox (0..8) -> output mailbox (8..16)
3620        multi_doc.push_char(DcChar::from_short(712));
3621        i32::encode_dc_mixed(&8, &mut multi_doc)?;
3622        multi_doc.push_char(DcChar::from_short(712));
3623        i32::encode_dc_mixed(&0, &mut multi_doc)?;
3624        multi_doc.push_char(DcChar::from_short(687));
3625        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3626        u32::encode_dc_mixed(&2, &mut multi_doc)?;
3627        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3628        multi_doc.push_char(DcChar::from_short(701));
3629        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3630        u32::encode_dc_mixed(&2, &mut multi_doc)?;
3631        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3632        multi_doc.push_char(DcChar::from_short(712));
3633        i32::encode_dc_mixed(&12, &mut multi_doc)?;
3634        multi_doc.push_char(DcChar::from_short(712));
3635        i32::encode_dc_mixed(&4, &mut multi_doc)?;
3636        multi_doc.push_char(DcChar::from_short(687));
3637        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3638        u32::encode_dc_mixed(&2, &mut multi_doc)?;
3639        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3640        multi_doc.push_char(DcChar::from_short(701));
3641        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3642        u32::encode_dc_mixed(&2, &mut multi_doc)?;
3643        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3644
3645        // Read phase = mem[64]
3646        multi_doc.push_char(DcChar::from_short(712));
3647        i32::encode_dc_mixed(&64, &mut multi_doc)?;
3648        multi_doc.push_char(DcChar::from_short(687));
3649        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3650        u32::encode_dc_mixed(&2, &mut multi_doc)?;
3651        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3652        multi_doc.push_char(DcChar::from_short(716)); // i32.eqz (phase == 0)
3653        multi_doc.push_char(DcChar::from_short(651)); // if (result i32)
3654        multi_doc.push_char(i32_dc);
3655        multi_doc.push_char(DcChar::from_short(712));
3656        i32::encode_dc_mixed(&64, &mut multi_doc)?;
3657        multi_doc.push_char(DcChar::from_short(712));
3658        i32::encode_dc_mixed(&1, &mut multi_doc)?;
3659        multi_doc.push_char(DcChar::from_short(701));
3660        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3661        u32::encode_dc_mixed(&2, &mut multi_doc)?;
3662        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3663        multi_doc.push_char(DcChar::from_short(712));
3664        i32::encode_dc_mixed(&1, &mut multi_doc)?; // return 1 (YieldFrame)
3665        multi_doc.push_char(DcChar::from_short(652)); // else
3666        // Check if mem[64] == 1
3667        multi_doc.push_char(DcChar::from_short(712));
3668        i32::encode_dc_mixed(&64, &mut multi_doc)?;
3669        multi_doc.push_char(DcChar::from_short(687));
3670        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3671        u32::encode_dc_mixed(&2, &mut multi_doc)?;
3672        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3673        multi_doc.push_char(DcChar::from_short(712));
3674        i32::encode_dc_mixed(&1, &mut multi_doc)?;
3675        multi_doc.push_char(DcChar::from_short(717)); // i32.eq
3676        multi_doc.push_char(DcChar::from_short(651)); // if (result i32)
3677        multi_doc.push_char(i32_dc);
3678        multi_doc.push_char(DcChar::from_short(712));
3679        i32::encode_dc_mixed(&64, &mut multi_doc)?;
3680        multi_doc.push_char(DcChar::from_short(712));
3681        i32::encode_dc_mixed(&2, &mut multi_doc)?;
3682        multi_doc.push_char(DcChar::from_short(701));
3683        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3684        u32::encode_dc_mixed(&2, &mut multi_doc)?;
3685        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3686        multi_doc.push_char(DcChar::from_short(712));
3687        i32::encode_dc_mixed(&2, &mut multi_doc)?; // return 2 (RequestCapability)
3688        multi_doc.push_char(DcChar::from_short(652)); // else (phase == 2: tight loop)
3689        multi_doc.push_char(DcChar::from_short(650)); // loop
3690        multi_doc.push_char(DcChar::from_short(316)); // empty blocktype
3691        multi_doc.push_char(DcChar::from_short(659)); // br 0
3692        u32::encode_dc_mixed(&0, &mut multi_doc)?;
3693        multi_doc.push_char(DcChar::from_short(658)); // end loop
3694        multi_doc.push_char(DcChar::from_short(712));
3695        i32::encode_dc_mixed(&0, &mut multi_doc)?;
3696        multi_doc.push_char(DcChar::from_short(658)); // end inner if
3697        multi_doc.push_char(DcChar::from_short(658)); // end outer if
3698        multi_doc.push_char(DcChar::from_short(261));
3699
3700        let mut input = DcMstring::new();
3701        input.push_str("FileIo");
3702
3703        let limits =
3704            DcWasmResourceLimits::default().with_max_instructions_per_step(200);
3705        let mut session = DcWasmSession::from_dc_wasm(&multi_doc, &input, None)?
3706            .with_resource_limits(limits);
3707        let mut deny_ctx = ExecutionContext::new(false)
3708            .with_privilege_decision(Privilege::FileIo, PermissionDecision::Allow)
3709            .with_privilege_decision(
3710                Privilege::ExcessiveCompute,
3711                PermissionDecision::Deny,
3712            );
3713
3714        // 1. `execute_wasm_session_default_with_trace` preserves the yielded frame (step 0),
3715        //    the capability interaction (step 1), and the denied ResourceInterruption (step 2).
3716        let denied_trace = deny_ctx
3717            .execute_wasm_session_default_with_trace(&mut session, &input)?;
3718        assert!(denied_trace.result.broke_out_early);
3719        assert_eq!(denied_trace.result.frames, vec![input.clone()]);
3720        assert_eq!(denied_trace.events.len(), 3);
3721        assert_eq!(
3722            denied_trace.denied_resource_interruption(),
3723            Some((
3724                2,
3725                Some(&WasmResourceInterruption::ComputeQuotaExhausted {
3726                    limit: 200
3727                }),
3728                PermissionDecision::Deny,
3729            ))
3730        );
3731        assert!(denied_trace.ensure_not_denied().is_err());
3732
3733        // 2. Replaying `denied_trace` reproduces the exact finite prefix and denied interruption.
3734        let mut replay_session =
3735            DcWasmSession::from_dc_wasm(&multi_doc, &input, None)?;
3736        let mut replay_ctx = ExecutionContext::new(false);
3737        let replayed = replay_ctx.replay_wasm_session_trace(
3738            &mut replay_session,
3739            &input,
3740            &denied_trace,
3741        )?;
3742        assert_eq!(replayed, denied_trace);
3743
3744        // 3. Construction-time resource interruption (looping `start` section) is captured in
3745        //    `execute_wasm_bytes_with_trace` and replayed via `replay_wasm_bytes_trace`.
3746        let looping_start = [
3747            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
3748            0x01, 0x04, 0x01, 0x60, 0x00, 0x00,
3749            0x03, 0x02, 0x01, 0x00,
3750            0x05, 0x03, 0x01, 0x00, 0x01,
3751            0x07, 0x11, 0x02, 0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
3752            0x04, b'm', b'a', b'i', b'n', 0x00, 0x00,
3753            0x08, 0x01, 0x00,
3754            0x0a, 0x09, 0x01, 0x07, 0x00, 0x03, 0x40, 0x0c, 0x00, 0x0b, 0x0b,
3755        ];
3756        let start_trace = deny_ctx.execute_wasm_bytes_with_trace(
3757            &looping_start,
3758            &input,
3759            None,
3760            limits,
3761            |_p, d, _r| Ok(ExecutionContext::default_capability_response(d)),
3762        )?;
3763        assert_eq!(
3764            start_trace.denied_resource_interruption(),
3765            Some((
3766                0,
3767                Some(&WasmResourceInterruption::ComputeQuotaExhausted {
3768                    limit: 200
3769                }),
3770                PermissionDecision::Deny,
3771            ))
3772        );
3773        let replayed_start = replay_ctx.replay_wasm_bytes_trace(
3774            &looping_start,
3775            &input,
3776            None,
3777            limits,
3778            &start_trace,
3779        )?;
3780        assert_eq!(replayed_start, start_trace);
3781
3782        // 4. Granting additional compute quota (`PermissionDecision::Allow` on `Privilege::ExcessiveCompute`
3783        //    with `with_compute_quota_grant`) resumes a paused multi-step module without repeating
3784        //    earlier yielded frames, and replays identically.
3785        let mut bounded_doc = DcMstring::new();
3786        bounded_doc.push_char(DcChar::from_short(260));
3787        bounded_doc.push_char(DcChar::from_short(262));
3788        bounded_doc.push_char(DcChar::from_short(280));
3789        bounded_doc.push_char(i32_dc);
3790        bounded_doc.push_char(DcChar::from_short(263));
3791        // Echo input mailbox (0..8) to output mailbox (8..16)
3792        bounded_doc.push_char(DcChar::from_short(712));
3793        i32::encode_dc_mixed(&8, &mut bounded_doc)?;
3794        bounded_doc.push_char(DcChar::from_short(712));
3795        i32::encode_dc_mixed(&0, &mut bounded_doc)?;
3796        bounded_doc.push_char(DcChar::from_short(687));
3797        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3798        u32::encode_dc_mixed(&2, &mut bounded_doc)?;
3799        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3800        bounded_doc.push_char(DcChar::from_short(701));
3801        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3802        u32::encode_dc_mixed(&2, &mut bounded_doc)?;
3803        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3804        bounded_doc.push_char(DcChar::from_short(712));
3805        i32::encode_dc_mixed(&12, &mut bounded_doc)?;
3806        bounded_doc.push_char(DcChar::from_short(712));
3807        i32::encode_dc_mixed(&4, &mut bounded_doc)?;
3808        bounded_doc.push_char(DcChar::from_short(687));
3809        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3810        u32::encode_dc_mixed(&2, &mut bounded_doc)?;
3811        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3812        bounded_doc.push_char(DcChar::from_short(701));
3813        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3814        u32::encode_dc_mixed(&2, &mut bounded_doc)?;
3815        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3816        // Check phase at mem[64]: if 0 -> set mem[64]=1 and return 1 (YieldFrame); else -> return 0 (Complete)
3817        bounded_doc.push_char(DcChar::from_short(712));
3818        i32::encode_dc_mixed(&64, &mut bounded_doc)?;
3819        bounded_doc.push_char(DcChar::from_short(687));
3820        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3821        u32::encode_dc_mixed(&2, &mut bounded_doc)?;
3822        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3823        bounded_doc.push_char(DcChar::from_short(716)); // i32.eqz
3824        bounded_doc.push_char(DcChar::from_short(651)); // if (result i32)
3825        bounded_doc.push_char(i32_dc);
3826        bounded_doc.push_char(DcChar::from_short(712));
3827        i32::encode_dc_mixed(&64, &mut bounded_doc)?;
3828        bounded_doc.push_char(DcChar::from_short(712));
3829        i32::encode_dc_mixed(&1, &mut bounded_doc)?;
3830        bounded_doc.push_char(DcChar::from_short(701));
3831        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3832        u32::encode_dc_mixed(&2, &mut bounded_doc)?;
3833        u32::encode_dc_mixed(&0, &mut bounded_doc)?;
3834        bounded_doc.push_char(DcChar::from_short(712));
3835        i32::encode_dc_mixed(&1, &mut bounded_doc)?;
3836        bounded_doc.push_char(DcChar::from_short(652)); // else
3837        bounded_doc.push_char(DcChar::from_short(712));
3838        i32::encode_dc_mixed(&0, &mut bounded_doc)?;
3839        bounded_doc.push_char(DcChar::from_short(658)); // end if
3840        bounded_doc.push_char(DcChar::from_short(261));
3841
3842        // Step 0 consumes 1 V2 checkpoint unit; step 1 consumes 1 unit (2 total).
3843        // Start with quota 1 so step 0 succeeds (`YieldFrame`), step 1 triggers `ComputeQuotaExhausted`,
3844        // and granting +50 via `PermissionDecision::Allow` resumes step 1 to completion.
3845        let tight_limits =
3846            DcWasmResourceLimits::default().with_max_instructions_per_step(1);
3847        let mut resumable_session =
3848            DcWasmSession::from_dc_wasm(&bounded_doc, &input, None)?
3849                .with_resource_limits(tight_limits);
3850        let mut allow_ctx = ExecutionContext::new(false)
3851            .with_privilege_decision(
3852                Privilege::ExcessiveCompute,
3853                PermissionDecision::Allow,
3854            )
3855            .with_compute_quota_grant(50);
3856        let resumed_trace = allow_ctx
3857            .execute_wasm_session_default_with_trace(&mut resumable_session, &input)?;
3858        assert!(!resumed_trace.result.broke_out_early);
3859        assert_eq!(resumed_trace.result.frames, vec![input.clone()]);
3860        assert_eq!(resumed_trace.result.output, input);
3861        assert!(resumed_trace.events.iter().any(|e| matches!(
3862            e,
3863            WasmTraceEvent::ResourceInterruption {
3864                after_logical_steps: 1,
3865                interruption: Some(WasmResourceInterruption::ComputeQuotaExhausted { limit: 1 }),
3866                decision: PermissionDecision::Allow,
3867            }
3868        )));
3869
3870        let mut replay_resumed_session =
3871            DcWasmSession::from_dc_wasm(&bounded_doc, &input, None)?
3872                .with_resource_limits(tight_limits);
3873        let mut replay_allow_ctx =
3874            ExecutionContext::new(false).with_compute_quota_grant(50);
3875        let replayed_resumed = replay_allow_ctx.replay_wasm_session_trace(
3876            &mut replay_resumed_session,
3877            &input,
3878            &resumed_trace,
3879        )?;
3880        assert_eq!(replayed_resumed, resumed_trace);
3881
3882        // 5. Non-resource trap inside module `start` (`unreachable` = 0x00) is captured as
3883        //    `WasmTraceEvent::NonResourceTrap` at `after_logical_steps: 0` in `execute_wasm_bytes_with_trace`
3884        //    and verified during `replay_wasm_bytes_trace`.
3885        let trapping_start = [
3886            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
3887            0x01, 0x04, 0x01, 0x60, 0x00, 0x00,
3888            0x03, 0x02, 0x01, 0x00,
3889            0x05, 0x03, 0x01, 0x00, 0x01,
3890            0x07, 0x11, 0x02, 0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
3891            0x04, b'm', b'a', b'i', b'n', 0x00, 0x00,
3892            0x08, 0x01, 0x00,
3893            0x0a, 0x05, 0x01, 0x03, 0x00, 0x00, 0x0b,
3894        ];
3895        let start_trap_trace = deny_ctx.execute_wasm_bytes_with_trace(
3896            &trapping_start,
3897            &input,
3898            None,
3899            limits,
3900            |_p, d, _r| Ok(ExecutionContext::default_capability_response(d)),
3901        )?;
3902        assert!(start_trap_trace.result.broke_out_early);
3903        assert!(matches!(
3904            start_trap_trace.non_resource_trap(),
3905            Some((0, msg)) if msg.contains("start section")
3906        ));
3907        assert!(start_trap_trace.ensure_not_denied().is_err());
3908        let replayed_start_trap = replay_ctx.replay_wasm_bytes_trace(
3909            &trapping_start,
3910            &input,
3911            None,
3912            limits,
3913            &start_trap_trace,
3914        )?;
3915        assert_eq!(replayed_start_trap, start_trap_trace);
3916        Ok(())
3917    }
3918
3919    #[crate::ctb_test]
3920    fn test_gate2_supervisor_admission_trace_metadata_non_resource_trap_and_budgets()
3921    -> Result<()> {
3922        use ctb_formats_dcstring::{DcMixedEncode, LedgerNode};
3923
3924        let sup_dc = DcChar::from_short(999);
3925        let sh_sup = DcShorthand::from_global_id(sup_dc.to_u128());
3926        let base_id: u128 = 8_589_934_592;
3927        let sup_def_id = base_id;
3928        let sup_has_a_id = base_id + 1;
3929        let sup_has_val_id = base_id + 2;
3930        let prov_has_a_id = base_id + 3;
3931        let prov_has_val_id = base_id + 4;
3932        let user_cfg_node_id = base_id + 5;
3933        let user_limits = DcWasmResourceLimits::default()
3934            .with_max_instructions_per_step(5_000)
3935            .with_max_capability_payload_bytes(8)
3936            .with_max_trace_bytes(512);
3937        let bundled_nodes = vec![
3938            LedgerNode {
3939                id: sup_def_id,
3940                tokens: vec![
3941                    DcShorthand::Short(1927),
3942                    DcShorthand::Short(1928),
3943                ],
3944                comment: String::new(),
3945                created_ns: None,
3946            },
3947            LedgerNode {
3948                id: sup_has_a_id,
3949                tokens: vec![
3950                    DcShorthand::Short(584),
3951                    sh_sup,
3952                    DcShorthand::Short(611),
3953                ],
3954                comment: String::new(),
3955                created_ns: None,
3956            },
3957            LedgerNode {
3958                id: sup_has_val_id,
3959                tokens: vec![
3960                    DcShorthand::Short(610),
3961                    DcShorthand::Long(sup_has_a_id),
3962                    DcShorthand::Long(sup_def_id),
3963                ],
3964                comment: String::new(),
3965                created_ns: None,
3966            },
3967            LedgerNode {
3968                id: prov_has_a_id,
3969                tokens: vec![
3970                    DcShorthand::Short(638),
3971                    DcShorthand::Short(584),
3972                    DcShorthand::Short(639),
3973                    DcShorthand::Short(635),
3974                    DcShorthand::Short(310),
3975                    DcShorthand::Short(640),
3976                    DcShorthand::Long(sup_def_id),
3977                    DcShorthand::Short(312),
3978                    DcShorthand::Long(sup_has_a_id),
3979                    DcShorthand::Short(312),
3980                    DcShorthand::Long(sup_has_val_id),
3981                    DcShorthand::Short(311),
3982                ],
3983                comment: String::new(),
3984                created_ns: None,
3985            },
3986            LedgerNode {
3987                id: prov_has_val_id,
3988                tokens: vec![
3989                    DcShorthand::Short(610),
3990                    DcShorthand::Long(prov_has_a_id),
3991                    DcShorthand::Short(636),
3992                ],
3993                comment: String::new(),
3994                created_ns: None,
3995            },
3996            LedgerNode {
3997                id: user_cfg_node_id,
3998                tokens:
3999                    SystemSupervisorAdmission::encode_graph_quota_config_tokens(
4000                        &user_limits,
4001                    ),
4002                comment: String::new(),
4003                created_ns: None,
4004            },
4005        ];
4006        let seed_graph = SeedGraphIndex::from_bundled_nodes(bundled_nodes);
4007
4008        // 1. Valid pinned ordinary documents and ordinary documents referencing `sup_dc`
4009        //    are allowed as ordinary documents (neither grants supervisor authority), while
4010        //    actual attempts to claim supervisor privilege (`Dc 527` = `Dc 517`, `Dc 635` = `Dc 636`,
4011        //    or passing pinned/multi-token documents to `admit_from_bootstrap_tokens`) are denied.
4012        SystemSupervisorAdmission::verify_ordinary_document_cannot_elevate(
4013            &[
4014                DcShorthand::from_global_id(
4015                    dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID
4016                        .to_u128(),
4017                ),
4018                DcShorthand::Long(prov_has_val_id),
4019                sh_sup,
4020            ],
4021            sup_dc,
4022        )?;
4023        SystemSupervisorAdmission::verify_ordinary_document_cannot_elevate(
4024            &[sh_sup, DcShorthand::Short(517)],
4025            sup_dc,
4026        )?;
4027        assert!(
4028            SystemSupervisorAdmission::verify_ordinary_document_cannot_elevate(
4029                &[DcShorthand::Short(527), DcShorthand::Short(517)],
4030                sup_dc,
4031            )
4032            .is_err()
4033        );
4034        assert!(
4035            SystemSupervisorAdmission::verify_ordinary_document_cannot_elevate(
4036                &[DcShorthand::Short(635), DcShorthand::Short(636)],
4037                sup_dc,
4038            )
4039            .is_err()
4040        );
4041        assert!(
4042            SystemSupervisorAdmission::admit_from_bootstrap_tokens(
4043                &seed_graph,
4044                &[
4045                    DcShorthand::from_global_id(
4046                        dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID
4047                            .to_u128()
4048                    ),
4049                    DcShorthand::Long(prov_has_val_id),
4050                    sh_sup,
4051                ],
4052                user_limits,
4053                DcWasmWatchdogLimits::default(),
4054            )
4055            .is_err()
4056        );
4057
4058        // 2. Trusted System supervisor admission resolves graph-backed user quota configuration,
4059        //    compiles local limits clamped by watchdog bounds, and records supervisor revision +
4060        //    dependency snapshot + canonical config in traces.
4061        let watchdog = DcWasmWatchdogLimits {
4062            hard_max_instructions_per_step: 1_000,
4063            ..DcWasmWatchdogLimits::default()
4064        };
4065        let adm_from_node =
4066            SystemSupervisorAdmission::admit_from_graph_config_node(
4067                &seed_graph,
4068                &[sh_sup],
4069                user_cfg_node_id,
4070                watchdog,
4071            )?;
4072        let mut ctx = ExecutionContext::new(false);
4073        let adm = ctx
4074            .admit_system_supervisor(
4075                &seed_graph,
4076                &[sh_sup],
4077                user_limits,
4078                watchdog,
4079            )?
4080            .clone();
4081        assert_eq!(adm, adm_from_node);
4082        assert_eq!(adm.supervisor_revision_node_id, sup_def_id);
4083        assert_eq!(adm.dependency_snapshot_node_ids, vec![sup_def_id]);
4084        assert_eq!(adm.compiled_limits.max_instructions_per_step, 1_000);
4085
4086        // Build a module that yields a frame on step 0, then traps with `unreachable` (Dc 648) on step 1.
4087        let i32_dc =
4088            DcChar::from_u128(crate::FormatId::I32.dc_id().unwrap());
4089        let mut trap_after_frame_doc = DcMstring::new();
4090        trap_after_frame_doc.push_char(DcChar::from_short(260));
4091        trap_after_frame_doc.push_char(DcChar::from_short(262));
4092        trap_after_frame_doc.push_char(DcChar::from_short(280));
4093        trap_after_frame_doc.push_char(i32_dc);
4094        trap_after_frame_doc.push_char(DcChar::from_short(263));
4095        // Copy input (0..8) to output (8..16)
4096        trap_after_frame_doc.push_char(DcChar::from_short(712));
4097        i32::encode_dc_mixed(&8, &mut trap_after_frame_doc)?;
4098        trap_after_frame_doc.push_char(DcChar::from_short(712));
4099        i32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4100        trap_after_frame_doc.push_char(DcChar::from_short(687));
4101        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4102        u32::encode_dc_mixed(&2, &mut trap_after_frame_doc)?;
4103        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4104        trap_after_frame_doc.push_char(DcChar::from_short(701));
4105        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4106        u32::encode_dc_mixed(&2, &mut trap_after_frame_doc)?;
4107        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4108        trap_after_frame_doc.push_char(DcChar::from_short(712));
4109        i32::encode_dc_mixed(&12, &mut trap_after_frame_doc)?;
4110        trap_after_frame_doc.push_char(DcChar::from_short(712));
4111        i32::encode_dc_mixed(&4, &mut trap_after_frame_doc)?;
4112        trap_after_frame_doc.push_char(DcChar::from_short(687));
4113        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4114        u32::encode_dc_mixed(&2, &mut trap_after_frame_doc)?;
4115        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4116        trap_after_frame_doc.push_char(DcChar::from_short(701));
4117        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4118        u32::encode_dc_mixed(&2, &mut trap_after_frame_doc)?;
4119        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4120        // Check mem[64]: if 0 -> set mem[64]=1 and return 1 (YieldFrame); else -> unreachable (Dc 648)
4121        trap_after_frame_doc.push_char(DcChar::from_short(712));
4122        i32::encode_dc_mixed(&64, &mut trap_after_frame_doc)?;
4123        trap_after_frame_doc.push_char(DcChar::from_short(687));
4124        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4125        u32::encode_dc_mixed(&2, &mut trap_after_frame_doc)?;
4126        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4127        trap_after_frame_doc.push_char(DcChar::from_short(716)); // i32.eqz
4128        trap_after_frame_doc.push_char(DcChar::from_short(651)); // if (result i32)
4129        trap_after_frame_doc.push_char(i32_dc);
4130        trap_after_frame_doc.push_char(DcChar::from_short(712));
4131        i32::encode_dc_mixed(&64, &mut trap_after_frame_doc)?;
4132        trap_after_frame_doc.push_char(DcChar::from_short(712));
4133        i32::encode_dc_mixed(&1, &mut trap_after_frame_doc)?;
4134        trap_after_frame_doc.push_char(DcChar::from_short(701));
4135        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4136        u32::encode_dc_mixed(&2, &mut trap_after_frame_doc)?;
4137        u32::encode_dc_mixed(&0, &mut trap_after_frame_doc)?;
4138        trap_after_frame_doc.push_char(DcChar::from_short(712));
4139        i32::encode_dc_mixed(&1, &mut trap_after_frame_doc)?;
4140        trap_after_frame_doc.push_char(DcChar::from_short(652)); // else
4141        trap_after_frame_doc.push_char(DcChar::from_short(647)); // unreachable (Dc 647 = 0x00)
4142        trap_after_frame_doc.push_char(DcChar::from_short(658)); // end if
4143        trap_after_frame_doc.push_char(DcChar::from_short(261));
4144
4145        let mut input = DcMstring::new();
4146        input.push_char(dc::DC_BOOLEAN_TRUE);
4147
4148        // 3. NonResourceTrap preserves the yielded frame at step 0 in `WasmExecutionTrace`,
4149        //    fails `ensure_not_denied()`, and replays deterministically.
4150        let mut trap_session =
4151            DcWasmSession::from_dc_wasm(&trap_after_frame_doc, &input, None)?;
4152        let trap_trace = ctx
4153            .execute_wasm_session_default_with_trace(&mut trap_session, &input)?;
4154        assert_eq!(trap_trace.supervisor_revision_node_id, Some(sup_def_id));
4155        assert_eq!(trap_trace.dependency_snapshot_node_ids, vec![sup_def_id]);
4156        assert_eq!(
4157            trap_trace.accounting_version,
4158            WASM_RESOURCE_ACCOUNTING_VERSION
4159        );
4160        assert_eq!(
4161            trap_trace.effective_config_bytes,
4162            adm.effective_config_bytes
4163        );
4164        assert_eq!(trap_trace.result.frames, vec![input.clone()]);
4165        assert!(trap_trace.non_resource_trap().is_some());
4166        assert!(trap_trace.ensure_not_denied().is_err());
4167
4168        let mut replay_trap_session =
4169            DcWasmSession::from_dc_wasm(&trap_after_frame_doc, &input, None)?;
4170        let mut replay_ctx =
4171            ExecutionContext::new(false).with_system_supervisor_admission(adm);
4172        let replayed_trap = replay_ctx.replay_wasm_session_trace(
4173            &mut replay_trap_session,
4174            &input,
4175            &trap_trace,
4176        )?;
4177        assert_eq!(replayed_trap, trap_trace);
4178
4179        // 4. TraceBufferBudgetExceeded triggers when `max_trace_bytes` is smaller than the first YieldFrame event.
4180        let tiny_trace_limits =
4181            DcWasmResourceLimits::default().with_max_trace_bytes(8);
4182        let mut tiny_trace_session =
4183            DcWasmSession::from_dc_wasm(&trap_after_frame_doc, &input, None)?
4184                .with_resource_limits(tiny_trace_limits);
4185        let mut tiny_ctx = ExecutionContext::new(false).with_privilege_decision(
4186            Privilege::ExcessiveCompute,
4187            PermissionDecision::Deny,
4188        );
4189        let tiny_trace = tiny_ctx.execute_wasm_session_default_with_trace(
4190            &mut tiny_trace_session,
4191            &input,
4192        )?;
4193        assert!(matches!(
4194            tiny_trace.events.last(),
4195            Some(WasmTraceEvent::ResourceInterruption {
4196                after_logical_steps: 0,
4197                interruption: Some(
4198                    WasmResourceInterruption::TraceBufferBudgetExceeded {
4199                        max_trace_bytes: 8,
4200                        ..
4201                    }
4202                ),
4203                decision: PermissionDecision::Deny,
4204            })
4205        ));
4206
4207        // 5. Ordinary pinned documents execute via `execute_ordinary_dc_wasm_default_with_trace`
4208        //    without supervisor privilege, while documents attempting inline elevation are denied.
4209        let head_pin = ctb_formats_dcstring::SeedGraphIndex::shared()?
4210            .system_block_most_recent_node_id()
4211            .unwrap();
4212        let mut pinned_ordinary_doc = DcMstring::new();
4213        pinned_ordinary_doc.push_char(
4214            dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID,
4215        );
4216        pinned_ordinary_doc.push_char(DcChar::from_u128(head_pin));
4217        for ch in trap_after_frame_doc.to_dc_string()?.chars() {
4218            pinned_ordinary_doc.push_char(ch);
4219        }
4220        let mut unprivileged_ctx = ExecutionContext::new(false);
4221        let ordinary_trace = unprivileged_ctx
4222            .execute_ordinary_dc_wasm_default_with_trace(
4223                &pinned_ordinary_doc,
4224                &input,
4225                Some(head_pin),
4226                sup_dc,
4227            )?;
4228        assert_eq!(ordinary_trace.supervisor_revision_node_id, None);
4229        assert_eq!(ordinary_trace.result.frames, vec![input.clone()]);
4230
4231        let mut elevating_ordinary_doc = DcMstring::new();
4232        elevating_ordinary_doc.push_char(DcChar::from_short(527));
4233        elevating_ordinary_doc.push_char(dc::DC_BOOLEAN_TRUE);
4234        assert!(
4235            unprivileged_ctx
4236                .execute_ordinary_dc_wasm_default_with_trace(
4237                    &elevating_ordinary_doc,
4238                    &input,
4239                    None,
4240                    sup_dc,
4241                )
4242                .is_err()
4243        );
4244
4245        // 6. Production bundled System supervisor entries `Dc 1936 "Dc document execution kernel"`
4246        //    and `Dc 1937 "Collective Toolbox Workspace"` resolve directly from `SeedGraphIndex::shared()`,
4247        //    execute their bundled `.WASM` supervisor definitions, and record `Dc 1937`'s dependency
4248        //    on `Dc 1936` in `dependency_snapshot_node_ids`.
4249        let prod_kernel_adm =
4250            SystemSupervisorAdmission::admit_execution_kernel_default()?;
4251        assert_eq!(
4252            prod_kernel_adm.entry_dc,
4253            dc::DC_DC_DOCUMENT_EXECUTION_KERNEL
4254        );
4255        let prod_workspace_adm =
4256            SystemSupervisorAdmission::admit_workspace_supervisor_default()?;
4257        assert_eq!(
4258            prod_workspace_adm.entry_dc,
4259            dc::DC_COLLECTIVE_TOOLBOX_WORKSPACE
4260        );
4261        assert_eq!(
4262            prod_kernel_adm.supervisor_revision_node_id,
4263            prod_workspace_adm.supervisor_revision_node_id
4264        );
4265        let mut kernel_ctx = ExecutionContext::new_execution_kernel(false)?;
4266        let mut prod_session =
4267            DcWasmSession::from_dc_wasm(&trap_after_frame_doc, &input, None)?;
4268        let prod_trace = kernel_ctx.execute_wasm_session_default_with_trace(
4269            &mut prod_session,
4270            &input,
4271        )?;
4272        assert_eq!(
4273            prod_trace.supervisor_revision_node_id,
4274            Some(prod_kernel_adm.supervisor_revision_node_id)
4275        );
4276        Ok(())
4277    }
4278
4279    #[crate::ctb_test]
4280    fn test_gate3_async_event_ordering_prefix_invariance_and_vertical_migration()
4281    -> Result<()> {
4282        use ctb_formats_dcstring::{
4283            DcChar, DcMixedEncode, DcWasmResourceLimits, LedgerNode,
4284        };
4285
4286        let i32_dc =
4287            DcChar::from_u128(crate::FormatId::I32.dc_id().unwrap());
4288
4289        // Build a 5-step Dc-WASM routine using mem[64] as phase counter (0..=4):
4290        // - Step 0 (phase 0): sets mem[64]=1, echoes input mailbox to output, returns 1 (YieldFrame #0)
4291        // - Step 1 (phase 1): sets mem[64]=2, echoes input mailbox to output, returns 2 (RequestCapability #1)
4292        // - Step 2 (phase 2): sets mem[64]=3, echoes capability #1 response to output, returns 1 (YieldFrame #1)
4293        // - Step 3 (phase 3): sets mem[64]=4, writes saved request at mem[128..136] to output, returns 2 (RequestCapability #2)
4294        // - Step 4 (phase 4): echoes capability #2 response to output, returns 0 (Complete)
4295        let mut doc = DcMstring::new();
4296        doc.push_char(DcChar::from_short(260));
4297        doc.push_char(DcChar::from_short(262));
4298        doc.push_char(DcChar::from_short(280));
4299        doc.push_char(i32_dc);
4300        doc.push_char(DcChar::from_short(263));
4301
4302        // Default output mailbox (8..16) = current input mailbox (0..8)
4303        for (dst, src) in [(8i32, 0i32), (12, 4)] {
4304            doc.push_char(DcChar::from_short(712));
4305            i32::encode_dc_mixed(&dst, &mut doc)?;
4306            doc.push_char(DcChar::from_short(712));
4307            i32::encode_dc_mixed(&src, &mut doc)?;
4308            doc.push_char(DcChar::from_short(687));
4309            for imm in [0u32, 2, 0] {
4310                u32::encode_dc_mixed(&imm, &mut doc)?;
4311            }
4312            doc.push_char(DcChar::from_short(701));
4313            for imm in [0u32, 2, 0] {
4314                u32::encode_dc_mixed(&imm, &mut doc)?;
4315            }
4316        }
4317
4318        // Helper closure to emit: if (mem[64] == phase) { mem[64] = phase + 1; ...; return status; } else { ... }
4319        let emit_phase_check = |out: &mut DcMstring, phase: i32| -> Result<()> {
4320            out.push_char(DcChar::from_short(712));
4321            i32::encode_dc_mixed(&64, out)?;
4322            out.push_char(DcChar::from_short(687));
4323            for imm in [0u32, 2, 0] {
4324                u32::encode_dc_mixed(&imm, out)?;
4325            }
4326            out.push_char(DcChar::from_short(712));
4327            i32::encode_dc_mixed(&phase, out)?;
4328            out.push_char(DcChar::from_short(717)); // i32.eq
4329            out.push_char(DcChar::from_short(651)); // if (result i32)
4330            out.push_char(i32_dc);
4331            out.push_char(DcChar::from_short(712));
4332            i32::encode_dc_mixed(&64, out)?;
4333            out.push_char(DcChar::from_short(712));
4334            i32::encode_dc_mixed(&(phase + 1), out)?;
4335            out.push_char(DcChar::from_short(701));
4336            for imm in [0u32, 2, 0] {
4337                u32::encode_dc_mixed(&imm, out)?;
4338            }
4339            Ok(())
4340        };
4341
4342        // Phase 0: return 1 (YieldFrame #0 with initial input)
4343        emit_phase_check(&mut doc, 0)?;
4344        doc.push_char(DcChar::from_short(712));
4345        i32::encode_dc_mixed(&1, &mut doc)?;
4346        doc.push_char(DcChar::from_short(652)); // else
4347
4348        // Phase 1: return 2 (RequestCapability #1)
4349        emit_phase_check(&mut doc, 1)?;
4350        doc.push_char(DcChar::from_short(712));
4351        i32::encode_dc_mixed(&2, &mut doc)?;
4352        doc.push_char(DcChar::from_short(652)); // else
4353
4354        // Phase 2: return 1 (YieldFrame #1 with capability #1's response)
4355        emit_phase_check(&mut doc, 2)?;
4356        doc.push_char(DcChar::from_short(712));
4357        i32::encode_dc_mixed(&1, &mut doc)?;
4358        doc.push_char(DcChar::from_short(652)); // else
4359
4360        // Phase 3: return 2 (RequestCapability #2 with capability #1's response in mailbox)
4361        emit_phase_check(&mut doc, 3)?;
4362        doc.push_char(DcChar::from_short(712));
4363        i32::encode_dc_mixed(&2, &mut doc)?;
4364        doc.push_char(DcChar::from_short(652)); // else
4365
4366        // Phase 4: return 0 (Complete with capability #2's response)
4367        doc.push_char(DcChar::from_short(712));
4368        i32::encode_dc_mixed(&0, &mut doc)?;
4369
4370        // Close all 4 nested `if` blocks and the literal container:
4371        for _ in 0..4 {
4372            doc.push_char(DcChar::from_short(658));
4373        }
4374        doc.push_char(DcChar::from_short(261));
4375
4376        let mut req_input = DcMstring::new();
4377        req_input.push_str("FileIo");
4378
4379        let mut resp_first = DcMstring::new();
4380        resp_first.push_str("first_cap_ok");
4381        let mut resp_second_a = DcMstring::new();
4382        resp_second_a.push_str("second_cap_branch_A");
4383        let mut resp_second_b = DcMstring::new();
4384        resp_second_b.push_str("second_cap_branch_B");
4385        let mut resp_second_denied = DcMstring::new();
4386        resp_second_denied.push_char(dc::DC_BOOLEAN_FALSE);
4387
4388        let run_scenario = |second_resp: DcMstring| -> Result<WasmExecutionTrace> {
4389            let mut session =
4390                DcWasmSession::from_dc_wasm(&doc, &req_input, None)?;
4391            let mut ctx = ExecutionContext::new(false)
4392                .with_privilege_decision(
4393                    Privilege::FileIo,
4394                    PermissionDecision::Allow,
4395                );
4396            let mut call_idx = 0usize;
4397            let first_clone = resp_first.clone();
4398            ctx.execute_wasm_session_with_trace(
4399                &mut session,
4400                &req_input,
4401                |_priv, _dec, _raw| {
4402                    call_idx += 1;
4403                    if call_idx == 1 {
4404                        Ok(first_clone.clone())
4405                    } else {
4406                        Ok(second_resp.clone())
4407                    }
4408                },
4409            )
4410        };
4411
4412        let trace_a = run_scenario(resp_second_a.clone())?;
4413        let trace_b = run_scenario(resp_second_b.clone())?;
4414        let trace_denied = run_scenario(resp_second_denied.clone())?;
4415
4416        // 1. Subsequent outputs diverge after delivery point #2 (step 3):
4417        assert_eq!(trace_a.result.output, resp_second_a);
4418        assert_eq!(trace_b.result.output, resp_second_b);
4419        assert_eq!(trace_denied.result.output, resp_second_denied);
4420        assert_ne!(trace_a.result.output, trace_b.result.output);
4421        assert_ne!(trace_a.result.output, trace_denied.result.output);
4422
4423        // 2. Prefix invariance: all frames (`frames[0..2]`), all earlier events (`events[0..3]`),
4424        //    and the capability request emitted at step 3 (`events[3].request`) are bit-for-bit identical!
4425        assert_eq!(trace_a.result.frames, vec![req_input.clone(), resp_first.clone()]);
4426        assert_eq!(trace_a.result.frames, trace_b.result.frames);
4427        assert_eq!(trace_a.result.frames, trace_denied.result.frames);
4428        assert_eq!(trace_a.events[..3], trace_b.events[..3]);
4429        assert_eq!(trace_a.events[..3], trace_denied.events[..3]);
4430        match (&trace_a.events[3], &trace_b.events[3], &trace_denied.events[3]) {
4431            (
4432                WasmTraceEvent::CapabilityInteraction {
4433                    request: req_a,
4434                    privilege: priv_a,
4435                    ..
4436                },
4437                WasmTraceEvent::CapabilityInteraction {
4438                    request: req_b,
4439                    privilege: priv_b,
4440                    ..
4441                },
4442                WasmTraceEvent::CapabilityInteraction {
4443                    request: req_c,
4444                    privilege: priv_c,
4445                    ..
4446                },
4447            ) => {
4448                assert_eq!(req_a, &resp_first);
4449                assert_eq!(req_a, req_b);
4450                assert_eq!(req_a, req_c);
4451                assert_eq!(
4452                    priv_a,
4453                    &Privilege::Custom("first_cap_ok".to_string())
4454                );
4455                assert_eq!(priv_a, priv_b);
4456                assert_eq!(priv_a, priv_c);
4457            }
4458            other => panic!("Expected CapabilityInteraction at event[3], got {other:?}"),
4459        }
4460
4461        // 3. Replaying each trace reproduces the exact branch output and trace:
4462        for expected_trace in [&trace_a, &trace_b, &trace_denied] {
4463            let mut replay_session =
4464                DcWasmSession::from_dc_wasm(&doc, &req_input, None)?;
4465            let mut replay_ctx = ExecutionContext::new(false);
4466            let replayed = replay_ctx.replay_wasm_session_trace(
4467                &mut replay_session,
4468                &req_input,
4469                expected_trace,
4470            )?;
4471            assert_eq!(&replayed, expected_trace);
4472        }
4473
4474        // 4. Vertical migration across generated System graph snapshots R1 < R2 (and R3 > R2 rejection):
4475        let shared = ctb_formats_dcstring::SeedGraphIndex::shared()?;
4476        let head_pin = shared.system_block_most_recent_node_id().unwrap();
4477        let prev_pin = head_pin.checked_sub(1).unwrap();
4478        for pin in [prev_pin, head_pin] {
4479            let mut pinned_doc = DcMstring::new();
4480            pinned_doc.push_char(
4481                dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID,
4482            );
4483            pinned_doc.push_char(DcChar::from_u128(pin));
4484            for ch in doc.to_dc_string()?.chars() {
4485                pinned_doc.push_char(ch);
4486            }
4487            let pinned_nav = ctb_formats_dcstring::DcDocumentNavigator::from_mstr(&pinned_doc);
4488            assert_eq!(pinned_nav.document_most_recent_node_id(), Some(pin));
4489            let pinned_resolver = pinned_nav.effective_resolver();
4490            let mut pinned_session =
4491                DcWasmSession::from_dc_wasm_with_resolver(
4492                    &doc,
4493                    &req_input,
4494                    Some(pin),
4495                    pinned_resolver.as_ref(),
4496                )?;
4497            let mut replay_ctx = ExecutionContext::new(false);
4498            let replayed_pinned = replay_ctx.replay_wasm_session_trace(
4499                &mut pinned_session,
4500                &req_input,
4501                &trace_a,
4502            )?;
4503            assert_eq!(replayed_pinned, trace_a);
4504        }
4505        // Future pin R3 = head_pin + 1 must fail before any capability request is issued:
4506        let future_pin = head_pin.checked_add(1).unwrap();
4507        let mut future_doc = DcMstring::new();
4508        future_doc.push_char(
4509            dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID,
4510        );
4511        future_doc.push_char(DcChar::from_u128(future_pin));
4512        for ch in doc.to_dc_string()?.chars() {
4513            future_doc.push_char(ch);
4514        }
4515        assert!(
4516            DcWasmSession::from_dc_wasm(&future_doc, &req_input, None).is_err(),
4517            "Future Dc 641 snapshot pin must be rejected before execution"
4518        );
4519
4520        let _ = (DcWasmResourceLimits::default(), LedgerNode {
4521            id: 0,
4522            tokens: Vec::new(),
4523            comment: String::new(),
4524            created_ns: None,
4525        });
4526        Ok(())
4527    }
4528
4529    fn build_minimal_constant_output_wasm_doc(
4530        output_byte: u8,
4531        spin_iters: u32,
4532    ) -> Result<DcMstring> {
4533        let spin_wat = if spin_iters == 0 {
4534            String::new()
4535        } else {
4536            format!(
4537                "(local $i i32)\n    (set $i {spin_iters})\n    (block $done (loop $lp (br_if $done (i32.eqz $i)) (set $i (i32.sub $i 1)) (br $lp)))"
4538            )
4539        };
4540        let wat = format!(
4541            r#"(module
4542  (memory (export "memory") 1)
4543  (func (export "step") (result i32)
4544    {spin_wat}
4545    (i32.store8 256 {output_byte})
4546    (i32.store 8 256)
4547    (i32.store 12 1)
4548    (i32.const 0)))"#
4549        );
4550        let shorthands = ctb_formats_dcstring::wat_to_dc_shorthands(&wat)?;
4551        let mut doc = DcMstring::new();
4552        for sh in shorthands {
4553            doc.push_char(DcChar::from_u128(sh.to_global_id()?));
4554        }
4555        Ok(doc)
4556    }
4557
4558    fn build_converter_emitting_constant_wasm_shorthands(
4559        target_wasm_doc: &DcMstr,
4560        spin_iters: u32,
4561    ) -> Result<Vec<DcShorthand>> {
4562        let dc_str = target_wasm_doc.to_dc_string()?;
4563        let raw_dctf = dc_str.as_bytes();
4564        let mut stores = String::new();
4565        for (idx, &b) in raw_dctf.iter().enumerate() {
4566            let addr = 512usize.saturating_add(idx);
4567            stores.push_str(&format!("    (i32.store8 {addr} {b})\n"));
4568        }
4569        let spin_wat = if spin_iters == 0 {
4570            String::new()
4571        } else {
4572            format!(
4573                "    (local $i i32)\n    (set $i {spin_iters})\n    (block $done (loop $lp (br_if $done (i32.eqz $i)) (set $i (i32.sub $i 1)) (br $lp)))\n"
4574            )
4575        };
4576        let wat = format!(
4577            r#"(module
4578  (memory (export "memory") 1)
4579  (func (export "step") (result i32)
4580{spin_wat}{stores}    (i32.store 8 512)
4581    (i32.store 12 {})
4582    (i32.const 0)))"#,
4583            raw_dctf.len()
4584        );
4585        ctb_formats_dcstring::wat_to_dc_shorthands(&wat)
4586    }
4587
4588    #[crate::ctb_test]
4589    fn test_dc_2608_convert_dc_string_to_wasm_and_dc_1938_resolve_to_pin()
4590    -> Result<()> {
4591        use ctb_formats_dcstring::syntax::DatasetRuleResolver;
4592
4593        let shared_sg = SeedGraphIndex::shared()?;
4594        let default_res = ctb_formats_dcstring::syntax::default_syntax_resolver();
4595
4596        // 1. `scan_first_pin_description` ignores Dc 641 inside comments and literals.
4597        let head_pin = shared_sg.system_block_most_recent_node_id().unwrap();
4598        let mut commented_doc = DcMstring::new();
4599        commented_doc.push_char(dc::DC_BEGIN_SINGLE_LINE_COMMENT);
4600        commented_doc
4601            .push_char(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
4602        commented_doc.push_char(DcChar::from_u128(head_pin));
4603        commented_doc.push_char(dc::DC_END_SINGLE_LINE_COMMENT);
4604        commented_doc.push_char(dc::DC_BEGIN_LITERAL);
4605        commented_doc.push_char(dc::DC_BEGIN_TYPE_DEF);
4606        commented_doc.push_char(dc::DC_TYPE_STRING);
4607        commented_doc.push_char(dc::DC_END_TYPE_DEF);
4608        commented_doc
4609            .push_char(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
4610        commented_doc.push_char(DcChar::from_u128(head_pin));
4611        commented_doc.push_char(dc::DC_END_LITERAL);
4612        assert_eq!(
4613            SystemSupervisorAdmission::scan_first_pin_description(
4614                &commented_doc,
4615                default_res.as_ref()
4616            )?,
4617            None
4618        );
4619
4620        // 2. Construct an in-memory graph snapshot extending `shared_sg` with two revisions
4621        //    of a standalone `[Dc 302 262 1927]` converter routine (`pin_v1 < pin_v2`).
4622        let mut nodes = shared_sg.nodes().to_vec();
4623        let mut next_id = head_pin.checked_add(1).unwrap();
4624        let mut alloc_node = |tokens: Vec<DcShorthand>| -> u128 {
4625            let id = next_id;
4626            next_id += 1;
4627            nodes.push(ctb_formats_dcstring::LedgerNode {
4628                id,
4629                tokens,
4630                comment: String::new(),
4631                created_ns: None,
4632            });
4633            id
4634        };
4635
4636        let wasm_v1 = build_minimal_constant_output_wasm_doc(b'A', 0)?;
4637        let wasm_v2 = build_minimal_constant_output_wasm_doc(b'B', 0)?;
4638        let conv_wasm_v1 =
4639            build_converter_emitting_constant_wasm_shorthands(&wasm_v1, 0)?;
4640        let conv_wasm_v2 =
4641            build_converter_emitting_constant_wasm_shorthands(&wasm_v2, 0)?;
4642
4643        let fmt_node_id = alloc_node(vec![
4644            DcShorthand::Short(302),
4645            DcShorthand::Short(262),
4646            DcShorthand::Short(1927),
4647        ]);
4648        let conv_ent_v1 = alloc_node(vec![
4649            DcShorthand::Short(586),
4650            DcShorthand::Short(615),
4651            DcShorthand::Short(280),
4652        ]);
4653        let fmt_has_a_v1 = alloc_node(vec![
4654            DcShorthand::Short(584),
4655            DcShorthand::Long(conv_ent_v1),
4656            DcShorthand::Short(595),
4657        ]);
4658        let _fmt_val_v1 = alloc_node(vec![
4659            DcShorthand::Short(610),
4660            DcShorthand::Long(fmt_has_a_v1),
4661            DcShorthand::Long(fmt_node_id),
4662        ]);
4663        let wasm_node_v1 = alloc_node(conv_wasm_v1);
4664        let decomp_has_a_v1 = alloc_node(vec![
4665            DcShorthand::Short(584),
4666            DcShorthand::Long(conv_ent_v1),
4667            DcShorthand::Short(611),
4668        ]);
4669        let decomp_val_v1 = alloc_node(vec![
4670            DcShorthand::Short(610),
4671            DcShorthand::Long(decomp_has_a_v1),
4672            DcShorthand::Long(wasm_node_v1),
4673        ]);
4674        let pin_v1 = decomp_val_v1;
4675
4676        // Revision 2 adds a Preferred (`Dc 570`) standalone converter routine for `262 -> 1927`.
4677        let conv_ent_v2 = alloc_node(vec![
4678            DcShorthand::Short(586),
4679            DcShorthand::Short(615),
4680            DcShorthand::Short(280),
4681        ]);
4682        let fmt_has_a_v2 = alloc_node(vec![
4683            DcShorthand::Short(584),
4684            DcShorthand::Long(conv_ent_v2),
4685            DcShorthand::Short(595),
4686        ]);
4687        let _fmt_val_v2 = alloc_node(vec![
4688            DcShorthand::Short(610),
4689            DcShorthand::Long(fmt_has_a_v2),
4690            DcShorthand::Long(fmt_node_id),
4691        ]);
4692        let wasm_node_v2 = alloc_node(conv_wasm_v2);
4693        let decomp_has_a_v2 = alloc_node(vec![
4694            DcShorthand::Short(584),
4695            DcShorthand::Long(conv_ent_v2),
4696            DcShorthand::Short(611),
4697        ]);
4698        let _decomp_val_v2 = alloc_node(vec![
4699            DcShorthand::Short(610),
4700            DcShorthand::Long(decomp_has_a_v2),
4701            DcShorthand::Long(wasm_node_v2),
4702        ]);
4703        let pref_v2 = alloc_node(vec![
4704            DcShorthand::Short(584),
4705            DcShorthand::Long(decomp_has_a_v2),
4706            DcShorthand::Short(570),
4707        ]);
4708        let pin_v2 = pref_v2;
4709
4710        let custom_sg = std::sync::Arc::new(SeedGraphIndex::from_nodes(nodes));
4711        let custom_res = DatasetRuleResolver::from_seed_graph(&custom_sg)?;
4712        let empty_in = DcMstring::new();
4713
4714        // Pinned to `pin_v1` -> executes converter V1 -> outputs "A"
4715        let mut doc_v1 = DcMstring::new();
4716        doc_v1.push_char(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
4717        doc_v1.push_char(DcChar::from_u128(pin_v1));
4718        doc_v1.push_char(dc::DC_BEGIN_TYPE_DEF);
4719        doc_v1.push_char(dc::DC_TYPE_STRING);
4720        doc_v1.push_char(dc::DC_END_TYPE_DEF);
4721        let mut env_v1 = ExecutionContext::new(false);
4722        let trace_v1 = env_v1.execute_dc_document_default_with_trace(
4723            &doc_v1,
4724            &empty_in,
4725            &custom_res,
4726        )?;
4727        assert_eq!(trace_v1.result.output.to_dc_string()?.to_string(), "A");
4728
4729        // Pinned to `pin_v2` (and unpinned) -> executes preferred converter V2 -> outputs "B"
4730        let mut doc_v2 = DcMstring::new();
4731        doc_v2.push_char(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
4732        doc_v2.push_char(DcChar::from_u128(pin_v2));
4733        doc_v2.push_char(dc::DC_BEGIN_TYPE_DEF);
4734        doc_v2.push_char(dc::DC_TYPE_STRING);
4735        doc_v2.push_char(dc::DC_END_TYPE_DEF);
4736        let mut env_v2 = ExecutionContext::new(false);
4737        let trace_v2 = env_v2.execute_dc_document_default_with_trace(
4738            &doc_v2,
4739            &empty_in,
4740            &custom_res,
4741        )?;
4742        assert_eq!(trace_v2.result.output.to_dc_string()?.to_string(), "B");
4743
4744        let mut doc_unpinned = DcMstring::new();
4745        doc_unpinned.push_char(dc::DC_BEGIN_TYPE_DEF);
4746        doc_unpinned.push_char(dc::DC_TYPE_STRING);
4747        doc_unpinned.push_char(dc::DC_END_TYPE_DEF);
4748        let mut env_unpinned = ExecutionContext::new(false);
4749        let trace_unpinned = env_unpinned
4750            .execute_dc_document_default_with_trace(
4751                &doc_unpinned,
4752                &empty_in,
4753                &custom_res,
4754            )?;
4755        assert_eq!(
4756            trace_unpinned.result.output.to_dc_string()?.to_string(),
4757            "B"
4758        );
4759
4760        // Future pin `pin_v2 + 1` -> rejected!
4761        let mut doc_future = DcMstring::new();
4762        doc_future
4763            .push_char(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
4764        doc_future.push_char(DcChar::from_u128(pin_v2 + 1));
4765        doc_future.push_char(dc::DC_BEGIN_TYPE_DEF);
4766        doc_future.push_char(dc::DC_TYPE_STRING);
4767        doc_future.push_char(dc::DC_END_TYPE_DEF);
4768        let mut env_future = ExecutionContext::new(false);
4769        assert!(
4770            env_future
4771                .execute_dc_document_default_with_trace(
4772                    &doc_future,
4773                    &empty_in,
4774                    &custom_res,
4775                )
4776                .is_err()
4777        );
4778        Ok(())
4779    }
4780
4781    #[crate::ctb_test]
4782    fn test_dc_1936_shared_quota_across_compilation_and_execution() -> Result<()>
4783    {
4784        use ctb_formats_dcstring::syntax::DatasetRuleResolver;
4785
4786        let shared_sg = SeedGraphIndex::shared()?;
4787        let head_pin = shared_sg.system_block_most_recent_node_id().unwrap();
4788        let mut nodes = shared_sg.nodes().to_vec();
4789        let mut next_id = head_pin.checked_add(1).unwrap();
4790        let mut alloc_node = |tokens: Vec<DcShorthand>| -> u128 {
4791            let id = next_id;
4792            next_id += 1;
4793            nodes.push(ctb_formats_dcstring::LedgerNode {
4794                id,
4795                tokens,
4796                comment: String::new(),
4797                created_ns: None,
4798            });
4799            id
4800        };
4801
4802        // Target WASM spins 120 iterations (> 100 V2 checkpoints); converter spins 80 iterations.
4803        let target_wasm = build_minimal_constant_output_wasm_doc(b'Q', 120)?;
4804        let conv_wasm = build_converter_emitting_constant_wasm_shorthands(
4805            &target_wasm,
4806            80,
4807        )?;
4808        let fmt_node_id = alloc_node(vec![
4809            DcShorthand::Short(302),
4810            DcShorthand::Short(262),
4811            DcShorthand::Short(1927),
4812        ]);
4813        let conv_ent = alloc_node(vec![
4814            DcShorthand::Short(586),
4815            DcShorthand::Short(615),
4816            DcShorthand::Short(280),
4817        ]);
4818        let fmt_has_a = alloc_node(vec![
4819            DcShorthand::Short(584),
4820            DcShorthand::Long(conv_ent),
4821            DcShorthand::Short(595),
4822        ]);
4823        let _fmt_val = alloc_node(vec![
4824            DcShorthand::Short(610),
4825            DcShorthand::Long(fmt_has_a),
4826            DcShorthand::Long(fmt_node_id),
4827        ]);
4828        let wasm_node = alloc_node(conv_wasm);
4829        let decomp_has_a = alloc_node(vec![
4830            DcShorthand::Short(584),
4831            DcShorthand::Long(conv_ent),
4832            DcShorthand::Short(611),
4833        ]);
4834        let decomp_val = alloc_node(vec![
4835            DcShorthand::Short(610),
4836            DcShorthand::Long(decomp_has_a),
4837            DcShorthand::Long(wasm_node),
4838        ]);
4839        let pin = decomp_val;
4840
4841        let custom_sg = std::sync::Arc::new(SeedGraphIndex::from_nodes(nodes));
4842        let custom_res = DatasetRuleResolver::from_seed_graph(&custom_sg)?;
4843        let empty_in = DcMstring::new();
4844
4845        let mut doc = DcMstring::new();
4846        doc.push_char(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
4847        doc.push_char(DcChar::from_u128(pin));
4848        doc.push_char(dc::DC_BEGIN_TYPE_DEF);
4849        doc.push_char(dc::DC_TYPE_STRING);
4850        doc.push_char(dc::DC_END_TYPE_DEF);
4851
4852        // Measure standalone target execution cost:
4853        let mut probe_session = DcWasmSession::from_dc_wasm_with_resolver(
4854            &target_wasm,
4855            &empty_in,
4856            Some(pin),
4857            &custom_res,
4858        )?;
4859        let _ = probe_session.step()?;
4860        let exec_cost = probe_session.total_instructions_executed();
4861        assert!(exec_cost > 100);
4862
4863        // Measure compilation cost via SharedWasmTaskQuota:
4864        let default_adm =
4865            SystemSupervisorAdmission::admit_execution_kernel_default()?;
4866        let probe_quota =
4867            ctb_formats_dcstring::converters::wasm::SharedWasmTaskQuota::new(
4868                DcWasmResourceLimits::default(),
4869            );
4870        let _ = default_adm.compile_dc_document_to_wasm_with_shared_quota(
4871            &doc,
4872            &custom_res,
4873            probe_quota.clone(),
4874        )?;
4875        let compile_cost = probe_quota.snapshot()?.total_instructions_executed;
4876        assert!(
4877            compile_cost > 200,
4878            "Both Dc 2608 unescaping and converter routine must consume metered quota (got {compile_cost})"
4879        );
4880
4881        // 1. Budget smaller than `compile_cost`: interrupts with ComputeQuotaExhausted during compilation!
4882        let mut tiny_limits = DcWasmResourceLimits::default();
4883        tiny_limits.max_instructions_per_step = compile_cost / 2;
4884        let tiny_adm = SystemSupervisorAdmission::admit_execution_kernel(
4885            tiny_limits,
4886            DcWasmWatchdogLimits::default(),
4887        )?;
4888        let mut env_compile_exhaust = ExecutionContext::new(false)
4889            .with_system_supervisor_admission(tiny_adm)
4890            .with_privilege_decision(
4891                Privilege::ExcessiveCompute,
4892                PermissionDecision::Deny,
4893            );
4894        let trace_compile_exhaust = env_compile_exhaust
4895            .execute_dc_document_default_with_trace(
4896                &doc,
4897                &empty_in,
4898                &custom_res,
4899            )?;
4900        assert!(trace_compile_exhaust.result.broke_out_early);
4901        assert!(matches!(
4902            trace_compile_exhaust.events.first(),
4903            Some(WasmTraceEvent::ResourceInterruption {
4904                interruption: Some(
4905                    WasmResourceInterruption::ComputeQuotaExhausted { .. }
4906                ),
4907                decision: PermissionDecision::Deny,
4908                ..
4909            })
4910        ));
4911
4912        // 2. Budget large enough for `compile_cost` OR `exec_cost` individually,
4913        //    but smaller than `compile_cost + exec_cost`: compilation succeeds, then
4914        //    target execution exhausts the shared remaining quota!
4915        let mid_budget = compile_cost + (exec_cost / 2);
4916        assert!(mid_budget > exec_cost);
4917        let mut mid_limits = DcWasmResourceLimits::default();
4918        mid_limits.max_instructions_per_step = mid_budget;
4919        let mid_adm = SystemSupervisorAdmission::admit_execution_kernel(
4920            mid_limits,
4921            DcWasmWatchdogLimits::default(),
4922        )?;
4923        let mut env_mid_deny = ExecutionContext::new(false)
4924            .with_system_supervisor_admission(mid_adm.clone())
4925            .with_privilege_decision(
4926                Privilege::ExcessiveCompute,
4927                PermissionDecision::Deny,
4928            );
4929        let trace_mid_deny = env_mid_deny
4930            .execute_dc_document_default_with_trace(
4931                &doc,
4932                &empty_in,
4933                &custom_res,
4934            )?;
4935        assert!(trace_mid_deny.result.broke_out_early);
4936
4937        // Granting `Allow` on `ExcessiveCompute` resumes and finishes cleanly!
4938        let mut env_mid_allow = ExecutionContext::new(false)
4939            .with_system_supervisor_admission(mid_adm)
4940            .with_compute_quota_grant(exec_cost)
4941            .with_privilege_decision(
4942                Privilege::ExcessiveCompute,
4943                PermissionDecision::Allow,
4944            );
4945        let trace_mid_allow = env_mid_allow
4946            .execute_dc_document_default_with_trace(
4947                &doc,
4948                &empty_in,
4949                &custom_res,
4950            )?;
4951        assert!(!trace_mid_allow.result.broke_out_early);
4952        assert_eq!(
4953            trace_mid_allow.result.output.to_dc_string()?.to_string(),
4954            "Q"
4955        );
4956        Ok(())
4957    }
4958
4959    fn sl3_source_to_dc_document(
4960        src: &str,
4961        sg: &SeedGraphIndex,
4962        pin: Option<u128>,
4963    ) -> Result<DcMstring> {
4964        let tokens =
4965            ctb_formats_dcstring::stagel3::seed_linker::sl3_to_dc_tokens_with_seed_graph(
4966                src, sg,
4967            )?;
4968        let mut dc_str = DcString::with_capacity(tokens.len().saturating_mul(4));
4969        if let Some(pin_id) = pin {
4970            dc_str.push(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
4971            dc_str.push(DcChar::from_u128(pin_id));
4972        }
4973        for tok in tokens {
4974            dc_str.push(tok);
4975        }
4976        DcMstring::from_dc_str(&dc_str)
4977    }
4978
4979    fn admit_high_budget_execution_kernel() -> Result<SystemSupervisorAdmission> {
4980        SystemSupervisorAdmission::admit_cli_execution_kernel()
4981    }
4982
4983    #[crate::ctb_test]
4984    fn test_dc_1936_executes_real_stagel3_via_pinned_self_hosted_wat_converter()
4985    -> Result<()> {
4986        use ctb_formats_dcstring::stagel_dc_alloc::{
4987            DiscoveredStagelFile, ImplStage, reconcile_stagel_and_csv_in_memory,
4988        };
4989        use ctb_formats_dcstring::syntax::DatasetRuleResolver;
4990        use std::collections::BTreeSet;
4991        use std::path::PathBuf;
4992
4993        // 1. Real StageL 3 document importing `std/bytes` & `std/math` and using n-ary tuples
4994        //    + positional `struct`s, compiled via `stagel3_to_wasm.wat` in `SeedGraphIndex::shared()`.
4995        let shared_sg = SeedGraphIndex::shared()?;
4996        let shared_res = DatasetRuleResolver::from_seed_graph(shared_sg)?;
4997        let head_pin = shared_sg.system_block_most_recent_node_id().unwrap();
4998        let high_adm = admit_high_budget_execution_kernel()?;
4999
5000        let std_app_src = r#"
5001use std/bytes: explode implode ::.
5002use std/math: canAdd ::.
5003
5004struct pairTag :: l/u8 u32.
5005
5006v/l/u8/step l/u8/input
5007    do
5008        let tup: l/l/u8 b ::/parts tupNew: explode b"," /input canAdd u32:10 u32:20 ::.
5009        if not field /parts u32:1 fault nop.
5010        let pairTag/pt structNew pairTag: implode b":" field /parts u32:0 u32:1 ::.
5011        let pairTag/pt2 with /pt u32:1 u32:2.
5012        if ne field /pt2 u32:1 u32:2 fault nop.
5013        concat field /pt2 u32:0 b"!ok".
5014    ::.
5015"#;
5016        let pinned_std_doc =
5017            sl3_source_to_dc_document(std_app_src, shared_sg, Some(head_pin))?;
5018        let unpinned_std_doc =
5019            sl3_source_to_dc_document(std_app_src, shared_sg, None)?;
5020        let mut std_in = DcMstring::new();
5021        for ch in "one,two,three".chars() {
5022            std_in.push_char(DcChar::from(ch));
5023        }
5024
5025        let mut env_std_pinned = ExecutionContext::new(false)
5026            .with_system_supervisor_admission(high_adm.clone());
5027        let trace_std_pinned = env_std_pinned
5028            .execute_dc_document_default_with_trace(
5029                &pinned_std_doc,
5030                &std_in,
5031                &shared_res,
5032            )?;
5033        assert!(
5034            !trace_std_pinned.result.broke_out_early,
5035            "unexpected early interruption on pinned std execution: {:?}",
5036            trace_std_pinned.events
5037        );
5038        assert_eq!(
5039            trace_std_pinned.result.output.to_dc_string()?.to_string(),
5040            "one:two:three!ok"
5041        );
5042
5043        let mut env_std_unpinned = ExecutionContext::new(false)
5044            .with_system_supervisor_admission(high_adm.clone());
5045        let trace_std_unpinned = env_std_unpinned
5046            .execute_dc_document_default_with_trace(
5047                &unpinned_std_doc,
5048                &std_in,
5049                &shared_res,
5050            )?;
5051        assert!(
5052            !trace_std_unpinned.result.broke_out_early,
5053            "unexpected early interruption on unpinned std execution: {:?}",
5054            trace_std_unpinned.events
5055        );
5056        assert_eq!(
5057            trace_std_unpinned.result.output.to_dc_string()?.to_string(),
5058            "one:two:three!ok"
5059        );
5060
5061        // 2. Multi-revision historical pin fidelity across StageL 3 dependencies (`Dc 591` & `Dc 592`):
5062        let dep_v1_src = "ns demo/ver.\n\npub v/l/u8/tag :: b\"v1:\".\npub v/l/u8/onlyInV1 :: b\"legacy:\".\n";
5063        let mut files_v1 = vec![DiscoveredStagelFile {
5064            stage: ImplStage::Stage1,
5065            disk_path: PathBuf::from("demo/ver.sl3"),
5066            repo_rel_path:
5067                "src/formats/dcdata/data-src/stage_1_impls/demo/ver.sl3"
5068                    .to_owned(),
5069            psr4_rel_path: "demo/ver.sl3".to_owned(),
5070            raw_bytes: dep_v1_src.as_bytes().to_vec(),
5071            source: dep_v1_src.to_owned(),
5072        }];
5073        let (v1_nodes, _, _) = reconcile_stagel_and_csv_in_memory(
5074            Vec::new(),
5075            &mut files_v1,
5076            &[],
5077            &[],
5078            &BTreeSet::new(),
5079            None,
5080        )?;
5081        let v1_len = v1_nodes.len();
5082        assert!(v1_len > 0);
5083
5084        // Revision 2 supersedes `tag` (`b"v1:"` -> `b"v2:"`) via `Dc 591` and retracts `onlyInV1` via `Dc 592`.
5085        let dep_v2_src = files_v1[0].source.replace("b\"v1:\"", "b\"v2:\"");
5086        let v2_lines: Vec<&str> = dep_v2_src.lines().collect();
5087        let only_idx = v2_lines
5088            .iter()
5089            .position(|l| l.contains("onlyInV1"))
5090            .expect("onlyInV1 line must exist");
5091        let dc_comment_idx = only_idx.checked_sub(1).unwrap();
5092        assert!(v2_lines[dc_comment_idx].trim_start().starts_with(": @dc "));
5093        let mut trimmed_v2 = String::new();
5094        for (i, line) in v2_lines.iter().enumerate() {
5095            if i != dc_comment_idx && i != only_idx {
5096                trimmed_v2.push_str(line);
5097                trimmed_v2.push('\n');
5098            }
5099        }
5100        let mut files_v2 = vec![DiscoveredStagelFile {
5101            stage: ImplStage::Stage1,
5102            disk_path: PathBuf::from("demo/ver.sl3"),
5103            repo_rel_path:
5104                "src/formats/dcdata/data-src/stage_1_impls/demo/ver.sl3"
5105                    .to_owned(),
5106            psr4_rel_path: "demo/ver.sl3".to_owned(),
5107            raw_bytes: trimmed_v2.as_bytes().to_vec(),
5108            source: trimmed_v2,
5109        }];
5110        let (v2_nodes, _, v2_stats) = reconcile_stagel_and_csv_in_memory(
5111            v1_nodes,
5112            &mut files_v2,
5113            &[],
5114            &[],
5115            &BTreeSet::new(),
5116            None,
5117        )?;
5118        assert!(v2_stats.nodes_superseded >= 1);
5119        assert!(v2_stats.nodes_retracted >= 1);
5120
5121        let sys_start =
5122            ctb_formats_dcstring::global_graph_layout::SYSTEM_REGION_START;
5123        let id_shift = (head_pin + 1) - sys_start;
5124        let mut combined_nodes = shared_sg.nodes().to_vec();
5125        let mut pin_v1 = 0u128;
5126        let mut pin_v2 = 0u128;
5127        for (idx, mut node) in v2_nodes.into_iter().enumerate() {
5128            node.id += id_shift;
5129            for tok in &mut node.tokens {
5130                if let DcShorthand::Long(lid) = tok
5131                    && *lid >= sys_start
5132                {
5133                    *lid += id_shift;
5134                }
5135            }
5136            if idx + 1 == v1_len {
5137                pin_v1 = node.id;
5138            }
5139            pin_v2 = node.id;
5140            combined_nodes.push(node);
5141        }
5142        assert!(pin_v1 > head_pin && pin_v2 > pin_v1);
5143
5144        let v1_only_nodes: Vec<ctb_formats_dcstring::LedgerNode> =
5145            combined_nodes
5146                .iter()
5147                .filter(|n| n.id <= pin_v1)
5148                .cloned()
5149                .collect();
5150        let snapshot_v1 = SeedGraphIndex::from_nodes(v1_only_nodes);
5151        let custom_sg =
5152            std::sync::Arc::new(SeedGraphIndex::from_nodes(combined_nodes));
5153        let custom_res = DatasetRuleResolver::from_seed_graph(&custom_sg)?;
5154
5155        let caller_tag_src =
5156            "use demo/ver: tag ::.\nv/l/u8/step l/u8/inp :: concat tag /inp.\n";
5157        let raw_tag_body =
5158            sl3_source_to_dc_document(caller_tag_src, &snapshot_v1, None)?;
5159
5160        let mut doc_tag_v1_str = DcString::new();
5161        doc_tag_v1_str
5162            .push(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
5163        doc_tag_v1_str.push(DcChar::from_u128(pin_v1));
5164        doc_tag_v1_str.push_dc_str(&raw_tag_body.to_dc_string()?);
5165        let doc_tag_v1 = DcMstring::from_dc_str(&doc_tag_v1_str)?;
5166
5167        let mut doc_tag_v2_str = DcString::new();
5168        doc_tag_v2_str
5169            .push(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
5170        doc_tag_v2_str.push(DcChar::from_u128(pin_v2));
5171        doc_tag_v2_str.push_dc_str(&raw_tag_body.to_dc_string()?);
5172        let doc_tag_v2 = DcMstring::from_dc_str(&doc_tag_v2_str)?;
5173
5174        let mut world_in = DcMstring::new();
5175        for ch in "world".chars() {
5176            world_in.push_char(DcChar::from(ch));
5177        }
5178
5179        let mut env_v1 = ExecutionContext::new(false)
5180            .with_system_supervisor_admission(high_adm.clone());
5181        let trace_v1 = env_v1.execute_dc_document_default_with_trace(
5182            &doc_tag_v1,
5183            &world_in,
5184            &custom_res,
5185        )?;
5186        assert_eq!(
5187            trace_v1.result.output.to_dc_string()?.to_string(),
5188            "v1:world"
5189        );
5190
5191        let mut env_v2 = ExecutionContext::new(false)
5192            .with_system_supervisor_admission(high_adm.clone());
5193        let trace_v2 = env_v2.execute_dc_document_default_with_trace(
5194            &doc_tag_v2,
5195            &world_in,
5196            &custom_res,
5197        )?;
5198        assert_eq!(
5199            trace_v2.result.output.to_dc_string()?.to_string(),
5200            "v2:world"
5201        );
5202
5203        // Calling `onlyInV1` succeeds when pinned to `pin_v1` and fails cleanly when pinned to `pin_v2`:
5204        let caller_legacy_src =
5205            "use demo/ver: onlyInV1 ::.\nv/l/u8/step l/u8/inp :: concat onlyInV1 /inp.\n";
5206        let raw_legacy_body =
5207            sl3_source_to_dc_document(caller_legacy_src, &snapshot_v1, None)?;
5208
5209        let mut doc_legacy_v1_str = DcString::new();
5210        doc_legacy_v1_str
5211            .push(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
5212        doc_legacy_v1_str.push(DcChar::from_u128(pin_v1));
5213        doc_legacy_v1_str.push_dc_str(&raw_legacy_body.to_dc_string()?);
5214        let doc_legacy_v1 = DcMstring::from_dc_str(&doc_legacy_v1_str)?;
5215
5216        let mut env_leg_v1 = ExecutionContext::new(false)
5217            .with_system_supervisor_admission(high_adm.clone());
5218        let trace_leg_v1 = env_leg_v1.execute_dc_document_default_with_trace(
5219            &doc_legacy_v1,
5220            &world_in,
5221            &custom_res,
5222        )?;
5223        assert_eq!(
5224            trace_leg_v1.result.output.to_dc_string()?.to_string(),
5225            "legacy:world"
5226        );
5227
5228        let mut doc_legacy_v2_str = DcString::new();
5229        doc_legacy_v2_str
5230            .push(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
5231        doc_legacy_v2_str.push(DcChar::from_u128(pin_v2));
5232        doc_legacy_v2_str.push_dc_str(&raw_legacy_body.to_dc_string()?);
5233        let doc_legacy_v2 = DcMstring::from_dc_str(&doc_legacy_v2_str)?;
5234
5235        let mut env_leg_v2 = ExecutionContext::new(false)
5236            .with_system_supervisor_admission(high_adm);
5237        assert!(
5238            env_leg_v2
5239                .execute_dc_document_default_with_trace(
5240                    &doc_legacy_v2,
5241                    &world_in,
5242                    &custom_res,
5243                )
5244                .is_err(),
5245            "Retracted StageL dependency routine must be rejected when pinned to pin_v2"
5246        );
5247        Ok(())
5248    }
5249
5250    #[crate::ctb_test]
5251    fn test_dc_1936_real_stagel3_shared_quota_across_compile_and_exec()
5252    -> Result<()> {
5253        use ctb_formats_dcstring::syntax::DatasetRuleResolver;
5254
5255        let shared_sg = SeedGraphIndex::shared()?;
5256        let shared_res = DatasetRuleResolver::from_seed_graph(shared_sg)?;
5257        let head_pin = shared_sg.system_block_most_recent_node_id().unwrap();
5258
5259        let spin_sl3 = r#"
5260v/l/u8/step l/u8/inp
5261    do
5262        let u32/i u32:0.
5263        let u64/acc u64:0.
5264        while lt /i u32:600 do
5265            set /acc wrapAdd /acc conv /i u64.
5266            set /i add /i u32:1.
5267        ::.
5268        if eq /acc u64:0 fault nop.
5269        concat /inp b":done".
5270    ::.
5271"#;
5272        let doc = sl3_source_to_dc_document(spin_sl3, shared_sg, Some(head_pin))?;
5273        let mut input = DcMstring::new();
5274        for ch in "quota".chars() {
5275            input.push_char(DcChar::from(ch));
5276        }
5277
5278        // Measure `stagel3_to_wasm.wat` compilation cost and resulting target `.WASM` execution cost:
5279        let high_adm = admit_high_budget_execution_kernel()?;
5280        let mut probe_limits = DcWasmResourceLimits::default();
5281        probe_limits.max_instructions_per_step = 100_000_000;
5282        let probe_quota =
5283            ctb_formats_dcstring::converters::wasm::SharedWasmTaskQuota::new(
5284                probe_limits,
5285            );
5286        let (compiled_wasm, compiled_pin) = high_adm
5287            .compile_dc_document_to_wasm_with_shared_quota(
5288                &doc,
5289                &shared_res,
5290                probe_quota.clone(),
5291            )?;
5292        assert_eq!(compiled_pin, Some(head_pin));
5293        let compile_cost = probe_quota.snapshot()?.total_instructions_executed;
5294        assert!(compile_cost > 10_000);
5295
5296        let mut probe_session = DcWasmSession::from_dc_wasm_with_resolver(
5297            &compiled_wasm,
5298            &input,
5299            Some(head_pin),
5300            &shared_res,
5301        )?;
5302        let _ = probe_session.step()?;
5303        let exec_cost = probe_session.total_instructions_executed();
5304        assert!(exec_cost > 1_000);
5305
5306        // 1. Budget smaller than `compile_cost`: interrupts with ComputeQuotaExhausted during compilation!
5307        let mut compile_cap_limits = DcWasmResourceLimits::default();
5308        compile_cap_limits.max_instructions_per_step = compile_cost / 2;
5309        let compile_cap_adm = SystemSupervisorAdmission::admit_execution_kernel(
5310            compile_cap_limits,
5311            DcWasmWatchdogLimits::default(),
5312        )?;
5313        let mut env_compile_deny = ExecutionContext::new(false)
5314            .with_system_supervisor_admission(compile_cap_adm)
5315            .with_privilege_decision(
5316                Privilege::ExcessiveCompute,
5317                PermissionDecision::Deny,
5318            );
5319        let trace_compile_deny = env_compile_deny
5320            .execute_dc_document_default_with_trace(&doc, &input, &shared_res)?;
5321        assert!(trace_compile_deny.result.broke_out_early);
5322        assert!(matches!(
5323            trace_compile_deny.events.first(),
5324            Some(WasmTraceEvent::ResourceInterruption {
5325                interruption: Some(
5326                    WasmResourceInterruption::ComputeQuotaExhausted { .. }
5327                ),
5328                decision: PermissionDecision::Deny,
5329                ..
5330            })
5331        ));
5332
5333        // 2. Budget covering compilation alone (`compile_cost + exec_cost / 2`), but less than
5334        //    `compile_cost + exec_cost`: compilation finishes, then target `.WASM` execution
5335        //    exhausts the shared remaining budget!
5336        let mid_budget = compile_cost + (exec_cost / 2);
5337        assert!(mid_budget > compile_cost && mid_budget > exec_cost);
5338        let mut mid_limits = DcWasmResourceLimits::default();
5339        mid_limits.max_instructions_per_step = mid_budget;
5340        let mid_adm = SystemSupervisorAdmission::admit_execution_kernel(
5341            mid_limits,
5342            DcWasmWatchdogLimits::default(),
5343        )?;
5344        let mut env_mid_deny = ExecutionContext::new(false)
5345            .with_system_supervisor_admission(mid_adm.clone())
5346            .with_privilege_decision(
5347                Privilege::ExcessiveCompute,
5348                PermissionDecision::Deny,
5349            );
5350        let trace_mid_deny = env_mid_deny
5351            .execute_dc_document_default_with_trace(&doc, &input, &shared_res)?;
5352        assert!(trace_mid_deny.result.broke_out_early);
5353
5354        // Granting `Allow` on `ExcessiveCompute` resumes and finishes target execution cleanly!
5355        let mut env_mid_allow = ExecutionContext::new(false)
5356            .with_system_supervisor_admission(mid_adm)
5357            .with_compute_quota_grant(exec_cost)
5358            .with_privilege_decision(
5359                Privilege::ExcessiveCompute,
5360                PermissionDecision::Allow,
5361            );
5362        let trace_mid_allow = env_mid_allow
5363            .execute_dc_document_default_with_trace(&doc, &input, &shared_res)?;
5364        assert!(!trace_mid_allow.result.broke_out_early);
5365        assert_eq!(
5366            trace_mid_allow.result.output.to_dc_string()?.to_string(),
5367            "quota:done"
5368        );
5369        Ok(())
5370    }
5371
5372    #[crate::ctb_test]
5373    fn test_dc_1936_executes_real_stager3_via_pinned_f1681_and_f1680_chain()
5374    -> Result<()> {
5375        use ctb_formats_dcstring::syntax::DatasetRuleResolver;
5376
5377        let shared_sg = SeedGraphIndex::shared()?;
5378        let shared_res = DatasetRuleResolver::from_seed_graph(shared_sg)?;
5379        let head_pin = shared_sg.system_block_most_recent_node_id().unwrap();
5380
5381        let stager_adm = admit_high_budget_execution_kernel()?;
5382
5383        let sr3_src = r#"ns app/kernel_stager.
5384
5385brand u32/tagId.
5386
5387struct jobSpec
5388    tagId/id.
5389    i32/offset.
5390
5391enum jobMode
5392    echo.
5393    i32/boost.
5394
5395v/result/i32/evalJob jobSpec/spec jobMode/mode
5396    const i32/base conv? unwrap field /spec id i32.
5397    const i32/sum add? /base field /spec offset.
5398    match /mode
5399        case echo result/i32:ok /sum.
5400        case boost i32/k add /sum /k.
5401    ::.
5402
5403pub v/l/u8/step l/u8/input
5404    const jobSpec/spec structNew jobSpec:
5405        offset i32:-3
5406        id wrap u32:40 tagId
5407    ::.
5408    const i32/score unwrapOr evalJob /spec jobMode:boost i32:5 i32:0.
5409    const s/joined implode ":" explode "," "left,right".
5410    if and eq /score i32:42 eq /joined "left:right"
5411        concat b"sr3:" /input
5412        b"bad".
5413"#;
5414        let sr_tokens =
5415            ctb_formats_dcstring::stagel3::seed_linker::sr3_to_dc_tokens_with_seed_graph(
5416                sr3_src, shared_sg,
5417            )?;
5418        let build_sr_doc = |pin: Option<u128>| -> Result<DcMstring> {
5419            let mut dc_str =
5420                DcString::with_capacity(sr_tokens.len().saturating_mul(4));
5421            if let Some(pin_id) = pin {
5422                dc_str.push(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
5423                dc_str.push(DcChar::from_u128(pin_id));
5424            }
5425            for &tok in &sr_tokens {
5426                dc_str.push(tok);
5427            }
5428            DcMstring::from_dc_str(&dc_str)
5429        };
5430        let pinned_sr_doc = build_sr_doc(Some(head_pin))?;
5431        let unpinned_sr_doc = build_sr_doc(None)?;
5432
5433        let mut in_doc = DcMstring::new();
5434        for ch in "payload".chars() {
5435            in_doc.push_char(DcChar::from(ch));
5436        }
5437
5438        let mut env_pinned = ExecutionContext::new(false)
5439            .with_system_supervisor_admission(stager_adm.clone());
5440        let trace_pinned = env_pinned.execute_dc_document_default_with_trace(
5441            &pinned_sr_doc,
5442            &in_doc,
5443            &shared_res,
5444        )?;
5445        assert!(
5446            !trace_pinned.result.broke_out_early,
5447            "pinned StageR 3 execution broke out early (op={:?}, req_cost={:?}); events: {:?}",
5448            trace_pinned.last_interrupted_op_ordinal,
5449            trace_pinned.last_interrupted_op_required_cost,
5450            trace_pinned.events,
5451        );
5452        assert_eq!(
5453            trace_pinned.result.output.to_dc_string()?.to_string(),
5454            "sr3:payload"
5455        );
5456
5457        // Second execution exercises unpinned head resolution (and verifies cached StageL
5458        // converter quota accounting under `stager_adm`).
5459        let mut env_unpinned = ExecutionContext::new(false)
5460            .with_system_supervisor_admission(stager_adm);
5461        let trace_unpinned = env_unpinned
5462            .execute_dc_document_default_with_trace(
5463                &unpinned_sr_doc,
5464                &in_doc,
5465                &shared_res,
5466            )?;
5467        assert!(
5468            !trace_unpinned.result.broke_out_early,
5469            "unpinned StageR 3 execution broke out early (op={:?}, req_cost={:?}); events: {:?}",
5470            trace_unpinned.last_interrupted_op_ordinal,
5471            trace_unpinned.last_interrupted_op_required_cost,
5472            trace_unpinned.events,
5473        );
5474        assert_eq!(
5475            trace_unpinned.result.output.to_dc_string()?.to_string(),
5476            "sr3:payload"
5477        );
5478        Ok(())
5479    }
5480
5481    #[crate::ctb_test]
5482    fn test_option_b_dc_1939_and_dc_1940_execution_context_policies()
5483    -> Result<()> {
5484        use ctb_formats_dcstring::converters::encode_dc_string_literal;
5485        use ctb_formats_dcstring::converters::wat::{
5486            wat_to_dcmstring, wat_to_wasm,
5487        };
5488        use ctb_formats_dcstring::syntax::default_syntax_resolver;
5489
5490        let resolver = default_syntax_resolver();
5491        let sg = resolver.seed_graph().context("Missing seed graph")?;
5492        let watermark = sg
5493            .system_block_most_recent_node_id()
5494            .context("Missing seed graph watermark")?;
5495
5496        let mut wm_req = DcMstring::new();
5497        wm_req.push_char(dc::DC_MINIMAL_SYSTEM_GRAPH_QUERY);
5498        wm_req.push_char(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
5499        wm_req.push_char(dc::DC_WILDCARD_PATTERN);
5500
5501        // Build a looping pure child WASM module so quota exhaustion deterministically occurs inside Dc 1940.
5502        let child_wat = r#"(module
5503          (memory (export "memory") 1)
5504          (func (export "step") (result i32)
5505            (local $i i32)
5506            (block $done
5507              (loop $lp
5508                (br_if $done (i32.ge_u (local.get $i) (i32.const 400)))
5509                (local.set $i (i32.add (local.get $i) (i32.const 1)))
5510                (br $lp)))
5511            (i32.store (i32.const 8) (i32.load (i32.const 0)))
5512            (i32.store (i32.const 12) (i32.load (i32.const 4)))
5513            (i32.const 0)))"#;
5514        let child_wasm_doc = wat_to_dcmstring(child_wat)?;
5515        let lit_in = encode_dc_string_literal(&[
5516            DcChar::from('H'),
5517            DcChar::from('i'),
5518        ]);
5519        let mut pure_req = DcMstring::new();
5520        pure_req.push_char(dc::DC_EXECUTE_PURE_WASM_PROGRAM);
5521        for ch in child_wasm_doc.to_dc_string()?.chars() {
5522            pure_req.push_char(ch);
5523        }
5524        for ch in lit_in.to_dc_string()?.chars() {
5525            pure_req.push_char(ch);
5526        }
5527
5528        let mut combined_input = wm_req.clone();
5529        let wm_len = combined_input.payload_bytes().len();
5530        for ch in pure_req.to_dc_string()?.chars() {
5531            combined_input.push_char(ch);
5532        }
5533        let pure_len =
5534            combined_input.payload_bytes().len().saturating_sub(wm_len);
5535
5536        let parent_wat = format!(
5537            r#"(module
5538              (memory (export "memory") 1)
5539              (global $__heap_ptr (mut i32) (i32.const 256))
5540              (export "__heap_ptr" (global $__heap_ptr))
5541              (func $__ctb_capability_yield (export "__ctb_capability_yield"))
5542              (func $copy (param $src i32) (param $dst i32) (param $len i32)
5543                (local $i i32)
5544                (block $done
5545                  (loop $lp
5546                    (br_if $done (i32.ge_u (local.get $i) (local.get $len)))
5547                    (i32.store8
5548                      (i32.add (local.get $dst) (local.get $i))
5549                      (i32.load8_u (i32.add (local.get $src) (local.get $i))))
5550                    (local.set $i (i32.add (local.get $i) (i32.const 1)))
5551                    (br $lp))))
5552              (func (export "step") (result i32)
5553                (local $in_ptr i32)
5554                (local $in_len i32)
5555                (local $p1 i32)
5556                (local $l1 i32)
5557                (local $p2 i32)
5558                (local $l2 i32)
5559                (local $out_ptr i32)
5560                (local.set $in_ptr (i32.load (i32.const 0)))
5561                (local.set $in_len (i32.load (i32.const 4)))
5562                (global.set $__heap_ptr
5563                  (i32.and
5564                    (i32.add (i32.add (local.get $in_ptr) (local.get $in_len)) (i32.const 63))
5565                    (i32.const -8)))
5566                (i32.store (i32.const 8) (local.get $in_ptr))
5567                (i32.store (i32.const 12) (i32.const {wm_len}))
5568                (call $__ctb_capability_yield)
5569                (local.set $p1 (i32.load (i32.const 0)))
5570                (local.set $l1 (i32.load (i32.const 4)))
5571                (i32.store (i32.const 8) (i32.add (local.get $in_ptr) (i32.const {wm_len})))
5572                (i32.store (i32.const 12) (i32.const {pure_len}))
5573                (call $__ctb_capability_yield)
5574                (local.set $p2 (i32.load (i32.const 0)))
5575                (local.set $l2 (i32.load (i32.const 4)))
5576                (local.set $out_ptr (global.get $__heap_ptr))
5577                (call $copy (local.get $p1) (local.get $out_ptr) (local.get $l1))
5578                (call $copy (local.get $p2) (i32.add (local.get $out_ptr) (local.get $l1)) (local.get $l2))
5579                (i32.store (i32.const 8) (local.get $out_ptr))
5580                (i32.store (i32.const 12) (i32.add (local.get $l1) (local.get $l2)))
5581                (i32.const 0)))"#,
5582        );
5583        let parent_wasm = wat_to_wasm(&parent_wat)?;
5584
5585        // 1. Default policy allows both Dc 1939 and Dc 1940.
5586        let mut expected_allow = DcMstring::new();
5587        expected_allow
5588            .push_char(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID);
5589        expected_allow.push_char(DcChar::from_u128(watermark));
5590        for ch in lit_in.to_dc_string()?.chars() {
5591            expected_allow.push_char(ch);
5592        }
5593        let mut s_ok = DcWasmSession::from_wasm_bytes_with_limits(
5594            &parent_wasm,
5595            &combined_input,
5596            Some(watermark),
5597            DcWasmResourceLimits::default(),
5598        )?;
5599        let mut ctx_ok = ExecutionContext::new(false);
5600        let tr_ok = ctx_ok
5601            .execute_wasm_session_default_with_resolver_and_trace(
5602                &mut s_ok,
5603                &combined_input,
5604                resolver.as_ref(),
5605            )?;
5606        assert!(!tr_ok.result.broke_out_early);
5607        assert_eq!(tr_ok.result.output, expected_allow);
5608        let cap_privs: Vec<(&Privilege, PermissionDecision)> = tr_ok
5609            .events
5610            .iter()
5611            .filter_map(|e| match e {
5612                WasmTraceEvent::CapabilityInteraction {
5613                    privilege,
5614                    decision,
5615                    ..
5616                } => Some((privilege, *decision)),
5617                _ => None,
5618            })
5619            .collect();
5620        assert_eq!(
5621            cap_privs,
5622            vec![
5623                (&Privilege::SystemGraphQuery, PermissionDecision::Allow),
5624                (&Privilege::ExecutePureWasm, PermissionDecision::Allow),
5625            ]
5626        );
5627
5628        // 2. Explicit Deny override on SystemGraphQuery returns Dc 518 without executing query.
5629        let mut s_deny = DcWasmSession::from_wasm_bytes_with_limits(
5630            &parent_wasm,
5631            &combined_input,
5632            Some(watermark),
5633            DcWasmResourceLimits::default(),
5634        )?;
5635        let mut ctx_deny = ExecutionContext::new(false)
5636            .with_privilege_decision(
5637                Privilege::SystemGraphQuery,
5638                PermissionDecision::Deny,
5639            );
5640        let tr_deny = ctx_deny
5641            .execute_wasm_session_default_with_resolver_and_trace(
5642                &mut s_deny,
5643                &combined_input,
5644                resolver.as_ref(),
5645            )?;
5646        let mut expected_deny = DcMstring::new();
5647        expected_deny.push_char(dc::DC_BOOLEAN_FALSE);
5648        for ch in lit_in.to_dc_string()?.chars() {
5649            expected_deny.push_char(ch);
5650        }
5651        assert_eq!(tr_deny.result.output, expected_deny);
5652
5653        // 3. Exhausting shared compute quota inside Dc 1940 child WASM records ResourceInterruption.
5654        let tiny_limits = DcWasmResourceLimits::default()
5655            .with_max_instructions_per_step(5);
5656        let tiny_quota =
5657            ctb_formats_dcstring::converters::wasm::SharedWasmTaskQuota::new(
5658                tiny_limits,
5659            );
5660        let mut s_quota = DcWasmSession::from_wasm_bytes_with_limits(
5661            &parent_wasm,
5662            &combined_input,
5663            Some(watermark),
5664            tiny_limits,
5665        )?;
5666        s_quota.set_shared_task_quota(tiny_quota)?;
5667        let mut ctx_quota = ExecutionContext::new(false)
5668            .with_privilege_decision(
5669                Privilege::ExcessiveCompute,
5670                PermissionDecision::Deny,
5671            );
5672        let tr_quota = ctx_quota
5673            .execute_wasm_session_default_with_resolver_and_trace(
5674                &mut s_quota,
5675                &combined_input,
5676                resolver.as_ref(),
5677            )?;
5678        assert!(tr_quota.result.broke_out_early);
5679        assert!(tr_quota.events.iter().any(|e| matches!(
5680            e,
5681            WasmTraceEvent::ResourceInterruption {
5682                decision: PermissionDecision::Deny,
5683                interruption: Some(_),
5684                ..
5685            }
5686        )));
5687        assert!(tr_quota.ensure_not_denied().is_err());
5688
5689        Ok(())
5690    }
5691
5692    #[crate::ctb_test]
5693    fn test_dc_2608_graph_stager_and_pre_migration_fallback() -> Result<()> {
5694        use ctb_formats_dcstring::converters::encode_dc_string_literal;
5695        use ctb_formats_dcstring::syntax::DatasetRuleResolver;
5696
5697        let shared_sg = SeedGraphIndex::shared()?;
5698        let dc2608_sh = DcShorthand::from_global_id(
5699            dc::DC_CONVERT_DC_STRING_TO_WASM.to_u128(),
5700        );
5701        let mut cur_sg = std::sync::Arc::clone(shared_sg);
5702        let mut pre_pin: Option<u128> = None;
5703        while let Some((val_id, _)) =
5704            cur_sg.resolve_stagel_decomposition_tokens(dc2608_sh)?
5705        {
5706            let mut min_id = val_id;
5707            for pred in [
5708                dc::DC_CANONICAL_DECOMPOSITION,
5709                dc::DC_DECOMPOSITION,
5710                dc::DC_SEMANTIC_DECOMPOSITION,
5711            ] {
5712                let pred_sh = DcShorthand::from_global_id(pred.to_u128());
5713                for entry in cur_sg.get_multi_properties(dc2608_sh, pred_sh) {
5714                    min_id = min_id.min(entry.has_a_id);
5715                }
5716            }
5717            let next_pin = min_id
5718                .checked_sub(1)
5719                .context("Dc 2608 pre-migration pin underflow")?;
5720            pre_pin = Some(next_pin);
5721            cur_sg = SeedGraphIndex::load_at_most_recent_from_asset_bundle(
5722                next_pin,
5723            )?;
5724        }
5725        let pre_pin = pre_pin.context(
5726            "Expected active StageR 3 decomposition on Dc 2608 at HEAD",
5727        )?;
5728        assert!(
5729            cur_sg
5730                .resolve_stagel_decomposition_tokens(dc2608_sh)?
5731                .is_none()
5732        );
5733
5734        let tiny_sl3 = "v/l/u8/step l/u8/input :: concat b\"ok:\" /input.\n";
5735        let doc_unpinned =
5736            sl3_source_to_dc_document(tiny_sl3, shared_sg, None)?;
5737        let doc_pre_pinned =
5738            sl3_source_to_dc_document(tiny_sl3, &cur_sg, Some(pre_pin))?;
5739        let doc_chars: Vec<DcChar> =
5740            doc_unpinned.to_dc_string()?.chars().collect();
5741        let encoded_doc_lit = encode_dc_string_literal(&doc_chars);
5742        let mut call_tokens = vec![dc::DC_CONVERT_DC_STRING_TO_WASM];
5743        for ch in encoded_doc_lit.to_dc_string()?.chars() {
5744            call_tokens.push(ch);
5745        }
5746
5747        let mut input_hi = DcMstring::new();
5748        for ch in "hi".chars() {
5749            input_hi.push_char(DcChar::from(ch));
5750        }
5751
5752        let high_adm = admit_high_budget_execution_kernel()?;
5753        assert!(
5754            std::ptr::eq(
5755                ctb_formats_dcstring::syntax::default_syntax_resolver()
5756                    .seed_graph()
5757                    .context("Missing default seed graph")?,
5758                shared_sg.as_ref(),
5759            ),
5760            "default_syntax_resolver() must share the process-wide SeedGraphIndex::shared() Arc without cloning"
5761        );
5762        let head_res = DatasetRuleResolver::from_seed_graph(shared_sg)?;
5763        let pre_res = DatasetRuleResolver::from_seed_graph(&cur_sg)?;
5764
5765        // 1. HEAD pin compiles Dc 2608 via its StageR 3 graph implementation.
5766        assert!(
5767            shared_sg
5768                .resolve_stagel_decomposition_tokens(dc2608_sh)?
5769                .is_some(),
5770            "HEAD pin must have an active StageR 3 decomposition on Dc 2608"
5771        );
5772        let mut env_head = ExecutionContext::new(false)
5773            .with_system_supervisor_admission(high_adm.clone());
5774        let trace_head = env_head.execute_dc_document_default_with_trace(
5775            &doc_unpinned,
5776            &input_hi,
5777            &head_res,
5778        )?;
5779        assert!(
5780            !trace_head.result.broke_out_early,
5781            "HEAD graph StageR 3 Dc 2608 execution broke out early: {:?}",
5782            trace_head.events
5783        );
5784        assert_eq!(
5785            trace_head.result.output.to_dc_string()?.to_string(),
5786            "ok:hi"
5787        );
5788
5789        // 2. Pre-migration pin returns None from graph StageR 3 lookup and
5790        //    succeeds through the historical host Rust fallback.
5791        assert!(
5792            ctb_formats_dcstring::converters::wasm::run_graph_stager_dc_2608_with_quota(
5793                &call_tokens,
5794                &pre_res,
5795                None,
5796            )?
5797            .is_none(),
5798            "Pre-migration pin must return None so historical Rust fallback handles Dc 2608"
5799        );
5800        let mut env_pre_res = ExecutionContext::new(false)
5801            .with_system_supervisor_admission(high_adm.clone());
5802        let trace_pre_res = env_pre_res
5803            .execute_dc_document_default_with_trace(
5804                &doc_unpinned,
5805                &input_hi,
5806                &pre_res,
5807            )?;
5808        assert!(
5809            !trace_pre_res.result.broke_out_early,
5810            "Pre-migration resolver execution broke out early: {:?}",
5811            trace_pre_res.events
5812        );
5813        assert_eq!(
5814            trace_pre_res.result.output.to_dc_string()?.to_string(),
5815            "ok:hi"
5816        );
5817
5818        let mut env_pre_doc = ExecutionContext::new(false)
5819            .with_system_supervisor_admission(high_adm.clone());
5820        let trace_pre_doc = env_pre_doc
5821            .execute_dc_document_default_with_trace(
5822                &doc_pre_pinned,
5823                &input_hi,
5824                &head_res,
5825            )?;
5826        assert!(
5827            !trace_pre_doc.result.broke_out_early,
5828            "Pre-migration Dc 641 pinned document execution broke out early: {:?}",
5829            trace_pre_doc.events
5830        );
5831        assert_eq!(
5832            trace_pre_doc.result.output.to_dc_string()?.to_string(),
5833            "ok:hi"
5834        );
5835
5836        let mut env_pre_doc_default = ExecutionContext::new(false)
5837            .with_system_supervisor_admission(high_adm);
5838        let trace_pre_doc_default = env_pre_doc_default
5839            .execute_dc_document_default_with_trace(
5840                &doc_pre_pinned,
5841                &input_hi,
5842                ctb_formats_dcstring::syntax::default_syntax_resolver()
5843                    .as_ref(),
5844            )?;
5845        assert!(
5846            !trace_pre_doc_default.result.broke_out_early,
5847            "Pre-migration Dc 641 pinned document execution against default_syntax_resolver broke out early: {:?}",
5848            trace_pre_doc_default.events
5849        );
5850        assert_eq!(
5851            trace_pre_doc_default.result.output.to_dc_string()?.to_string(),
5852            "ok:hi"
5853        );
5854
5855        Ok(())
5856    }
5857
5858    #[crate::ctb_test]
5859    fn test_wasm_substitute_cross_backend_trace_replay_parity() -> Result<()> {
5860        use ctb_formats_dcstring::converters::wasm::{
5861            DcWasmExecutionBackend, compile_system_subject_wasm_bytes,
5862        };
5863        use ctb_formats_dcstring::stagel3::seed_linker::{
5864            bundle_dc_module_for_wasm_converter,
5865            sl3_to_dc_tokens_with_seed_graph,
5866        };
5867        use ctb_formats_dcstring::syntax::default_syntax_resolver;
5868        use ctb_formats_dcstring::{DcWasmResourceLimits, WasmResourceInterruption};
5869
5870        ctb_wasm_substitutes::ensure_registered();
5871        let resolver = default_syntax_resolver();
5872        let sg = SeedGraphIndex::shared()?;
5873        let f1680_wasm = compile_system_subject_wasm_bytes(
5874            DcShorthand::Format(1680),
5875            resolver.as_ref(),
5876        )?;
5877
5878        let tiny_sl3 = "v/l/u8/step l/u8/input :: concat b\"ok:\" /input.\n";
5879        let entry_tokens = sl3_to_dc_tokens_with_seed_graph(tiny_sl3, sg)?;
5880        let bundled = bundle_dc_module_for_wasm_converter(
5881            &entry_tokens,
5882            sg,
5883            resolver.as_ref(),
5884        )?;
5885        let mut input_doc = DcMstring::new();
5886        for &tok in &bundled {
5887            input_doc.push_char(tok);
5888        }
5889
5890        let base_limits = DcWasmResourceLimits::default()
5891            .with_max_instructions_per_step(50_000_000)
5892            .with_max_memory_pages(512)
5893            .with_max_step_output_bytes(8 * 1024 * 1024)
5894            .with_max_session_output_bytes(16 * 1024 * 1024);
5895
5896        let mut measure_session =
5897            DcWasmSession::from_wasm_bytes_with_limits_and_backend(
5898                &f1680_wasm,
5899                &input_doc,
5900                None,
5901                base_limits,
5902                DcWasmExecutionBackend::Auto,
5903            )?;
5904        assert!(measure_session.used_native_substitute());
5905        let mut measure_ctx = ExecutionContext::new(false);
5906        let full_trace = measure_ctx.execute_wasm_session_default_with_trace(
5907            &mut measure_session,
5908            &input_doc,
5909        )?;
5910        let full_total = measure_session.total_instructions_executed();
5911        assert!(full_total > 10 && !full_trace.result.broke_out_early);
5912
5913        let tight_quota = (full_total / 2).max(1);
5914        let tight_limits =
5915            base_limits.with_max_instructions_per_step(tight_quota);
5916        let grant = full_total.saturating_mul(2);
5917
5918        // 1. Record trace on NativeSubstitute (`Auto`), then replay on `ForceTinyWasm`.
5919        let mut s_native =
5920            DcWasmSession::from_wasm_bytes_with_limits_and_backend(
5921                &f1680_wasm,
5922                &input_doc,
5923                None,
5924                tight_limits,
5925                DcWasmExecutionBackend::Auto,
5926            )?;
5927        assert!(s_native.used_native_substitute());
5928        let mut ctx_native = ExecutionContext::new(false)
5929            .with_compute_quota_grant(grant)
5930            .with_privilege_decision(
5931                Privilege::ExcessiveCompute,
5932                PermissionDecision::Allow,
5933            );
5934        let trace_native = ctx_native.execute_wasm_session_default_with_trace(
5935            &mut s_native,
5936            &input_doc,
5937        )?;
5938        assert!(!trace_native.result.broke_out_early);
5939        assert!(trace_native.events.iter().any(|ev| {
5940            matches!(
5941                ev,
5942                WasmTraceEvent::ResourceInterruption {
5943                    interruption: Some(
5944                        WasmResourceInterruption::ComputeQuotaExhausted { .. }
5945                    ),
5946                    decision: PermissionDecision::Allow,
5947                    ..
5948                }
5949            )
5950        }));
5951
5952        let mut s_replay_tw =
5953            DcWasmSession::from_wasm_bytes_with_limits_and_backend(
5954                &f1680_wasm,
5955                &input_doc,
5956                None,
5957                tight_limits,
5958                DcWasmExecutionBackend::ForceTinyWasm,
5959            )?;
5960        assert!(!s_replay_tw.used_native_substitute());
5961        let mut replay_tw_ctx =
5962            ExecutionContext::new(false).with_compute_quota_grant(grant);
5963        let replayed_on_tw = replay_tw_ctx.replay_wasm_session_trace(
5964            &mut s_replay_tw,
5965            &input_doc,
5966            &trace_native,
5967        )?;
5968        assert_eq!(replayed_on_tw, trace_native);
5969
5970        // 2. Record trace on `ForceTinyWasm`, verify equality, and replay on `Auto`.
5971        let mut s_tw = DcWasmSession::from_wasm_bytes_with_limits_and_backend(
5972            &f1680_wasm,
5973            &input_doc,
5974            None,
5975            tight_limits,
5976            DcWasmExecutionBackend::ForceTinyWasm,
5977        )?;
5978        assert!(!s_tw.used_native_substitute());
5979        let mut ctx_tw = ExecutionContext::new(false)
5980            .with_compute_quota_grant(grant)
5981            .with_privilege_decision(
5982                Privilege::ExcessiveCompute,
5983                PermissionDecision::Allow,
5984            );
5985        let trace_tw = ctx_tw.execute_wasm_session_default_with_trace(
5986            &mut s_tw,
5987            &input_doc,
5988        )?;
5989        assert_eq!(trace_tw, trace_native);
5990
5991        let mut s_replay_native =
5992            DcWasmSession::from_wasm_bytes_with_limits_and_backend(
5993                &f1680_wasm,
5994                &input_doc,
5995                None,
5996                tight_limits,
5997                DcWasmExecutionBackend::Auto,
5998            )?;
5999        assert!(s_replay_native.used_native_substitute());
6000        let mut replay_native_ctx =
6001            ExecutionContext::new(false).with_compute_quota_grant(grant);
6002        let replayed_on_native = replay_native_ctx.replay_wasm_session_trace(
6003            &mut s_replay_native,
6004            &input_doc,
6005            &trace_tw,
6006        )?;
6007        assert_eq!(replayed_on_native, trace_tw);
6008
6009        Ok(())
6010    }
6011}