# build_context URL: /api/utils/build_context/ Section: utils -------------------------------------------------------------------------------- build_context - Bengal window.BENGAL_THEME_DEFAULTS = { appearance: 'dark', palette: 'snow-lynx' }; // Progressive Enhancement System Configuration window.Bengal = window.Bengal || {}; window.Bengal.enhanceBaseUrl = '/bengal/assets/js/enhancements'; window.Bengal.watchDom = true; window.Bengal.debug = false; (function () { try { var defaults = window.BENGAL_THEME_DEFAULTS || { appearance: 'system', palette: '' }; var defaultAppearance = defaults.appearance; if (defaultAppearance === 'system') { defaultAppearance = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; } var storedTheme = localStorage.getItem('bengal-theme'); var storedPalette = localStorage.getItem('bengal-palette'); var theme = storedTheme ? (storedTheme === 'system' ? defaultAppearance : storedTheme) : defaultAppearance; var palette = storedPalette ?? defaults.palette; document.documentElement.setAttribute('data-theme', theme); if (palette) { document.documentElement.setAttribute('data-palette', palette); } } catch (e) { document.documentElement.setAttribute('data-theme', 'light'); } })(); Skip to main content Magnifying Glass ESC Recent Clear Magnifying Glass No results for "" Try different keywords or check your spelling Start typing to search... ↑↓ Navigate ↵ Open ESC Close Powered by Lunr ᓚᘏᗢ Documentation Info About Arrow Clockwise Get Started Note Tutorials File Text Content Palette Theming Settings Building Starburst Extending Bookmark Reference Learning Tracks Releases Dev GitHub API Reference bengal CLI Magnifying Glass Search ⌘K Palette Appearance Chevron Down Mode Monitor System Sun Light Moon Dark Palette Snow Lynx Brown Bengal Silver Bengal Charcoal Bengal Blue Bengal List ᓚᘏᗢ Magnifying Glass Search X Close Documentation Info About Arrow Clockwise Get Started Note Tutorials File Text Content Palette Theming Settings Building Starburst Extending Bookmark Reference Learning Tracks Releases Dev GitHub API Reference bengal CLI Palette Appearance Chevron Down Mode Monitor System Sun Light Moon Dark Palette Snow Lynx Brown Bengal Silver Bengal Charcoal Bengal Blue Bengal API Reference __main__ bengal Caret Right Folder Analysis community_detection graph_analysis graph_reporting graph_visualizer knowledge_graph link_suggestions link_types page_rank path_analysis performance_advisor results Caret Right Folder Assets manifest pipeline Caret Right Folder Autodoc base config docstring_parser utils virtual_orchestrator Caret Right Folder Extractors cli openapi python Caret Right Folder Models cli common openapi python Caret Right Folder Cache asset_dependency_map cache_store cacheable compression dependency_tracker page_discovery_cache query_index query_index_registry taxonomy_index utils Caret Right Folder Build Cache autodoc_tracking core file_tracking fingerprint parsed_content_cache rendered_output_cache taxonomy_index_mixin validation_cache Caret Right Folder Indexes author_index category_index date_range_index section_index Caret Right Folder Cli __main__ base site_templates utils Caret Right Folder Commands assets build clean collections config debug explain fix health init perf project serve site skeleton sources theme utils validate Caret Right Folder Graph __main__ bridges communities orphans pagerank report suggest Caret Right Folder New config presets scaffolds site wizard Caret Right Folder Helpers cli_app_loader cli_output config_validation error_handling menu_config metadata progress site_loader traceback validation Caret Right Folder Skeleton hydrator schema Caret Right Folder Templates base registry Caret Right Folder Blog template Caret Right Folder Changelog template Caret Right Folder Default template Caret Right Folder Docs template Caret Right Folder Landing template Caret Right Folder Portfolio template Caret Right Folder Resume template Caret Right Folder Collections errors loader schemas validator Caret Right Folder Config defaults deprecation directory_loader env_overrides environment feature_mappings hash loader merge origin_tracker validators Caret Right Folder Content Layer entry loaders manager source Caret Right Folder Sources github local notion rest Caret Right Folder Content Types base registry strategies Caret Right Folder Core build_context cascade_engine menu section theme Caret Right Folder Asset asset_core css_transforms Caret Right Folder Page computed content metadata navigation operations page_core proxy relationships utils Caret Right Folder Site core data discovery factories page_caches properties section_registry theme Caret Right Folder Debug base config_inspector content_migrator delta_analyzer dependency_visualizer explainer incremental_debugger models reporter shortcode_sandbox Caret Right Folder Discovery asset_discovery content_discovery Caret Right Folder Fonts downloader generator Caret Right Folder Health autofix base health_check report Caret Right Folder Linkcheck async_checker ignore_policy internal_checker models orchestrator Caret Right Folder Validators anchors assets cache config connectivity cross_ref fonts links menu navigation output performance rendering rss sitemap taxonomy tracks Caret Right Folder Directives analysis checkers constants Caret Right Folder Orchestration asset content full_to_incremental incremental menu postprocess related_posts render section static streaming taxonomy Caret Right Folder Postprocess html_output redirects rss sitemap special_pages Caret Right Folder Output Formats index_generator json_generator llm_generator lunr_index_generator txt_generator utils Caret Right Folder Rendering api_doc_enhancer asset_extractor errors jinja_utils link_transformer link_validator pygments_cache renderer template_context template_profiler validator Caret Right Folder Parsers base factory mistune native_html pygments_patch python_markdown Caret Right Folder Pipeline core output thread_local toc transforms Caret Right Folder Plugins badges cross_references inline_icon term variable_substitution Caret Right Folder Directives _icons admonitions badge base button cache cards checklist code_tabs container contracts data_table dropdown embed errors example_label fenced figure glossary icon include list_table literalinclude marimo navigation options rubric steps tabs target term terminal tokens utils validator video Caret Right Folder Template Engine asset_url core environment manifest menu url_helpers Caret Right Folder Template Functions advanced_collections advanced_strings autodoc collections content crossref data dates debug files get_page i18n icons images math_functions navigation pagination_helpers seo strings tables taxonomies theme urls Caret Right Folder Server build_handler component_preview constants dev_server live_reload pid_manager reload_controller request_handler request_logger resource_manager utils Caret Right Folder Services validation Caret Right Folder Themes config Caret Right Folder Utils atomic_write autodoc build_context build_stats build_summary cli_output css_minifier dates dotdict error_handlers file_io file_lock hashing incremental_constants js_bundler live_progress logger metadata observability page_initializer pagination path_resolver paths performance_collector performance_report profile progress retry rich_console sections swizzle text theme_registry theme_resolution thread_local traceback_config traceback_renderer url_normalization url_strategy API Reference Utils ᗢ Caret Down Link Copy URL External Open LLM text Copy Copy LLM text Share with AI Ask Claude Ask ChatGPT Ask Gemini Ask Copilot Module utils.build_context Build context for sharing state across build phases. Provides BuildContext dataclass for passing shared state between build phases, replacing scattered local variables. Created at build start and populated incrementally as phases execute. Key Concepts: Shared context: Single context object passed to all build phases Phase coordination: Enables phase-to-phase communication State management: Centralized build state management Lifecycle: Created at build start, populated during phases Lazy artifacts: Expensive computations cached on first access Related Modules: bengal.orchestration.build: Build orchestration using BuildContext bengal.utils.build_stats: Build statistics collection bengal.utils.progress: Progress reporting See Also: bengal/utils/build_context.py: BuildContext for context structure plan/active/rfc-build-pipeline.md: Build pipeline design plan/active/rfc-lazy-build-artifacts.md: Lazy artifact design View source 1 Class Classes BuildContext dataclass Shared build context passed across build phases. This context is created at the start of build() a… 13 Caret Right Shared build context passed across build phases. This context is created at the start of build() and passed to all phase* methods. It replaces local variables that were scattered throughout the 894-line build() method. Lifecycle: 1. Created in _setup_build_context() at build start 2. Populated incrementally as phases execute 3. Used by all _phase_* methods for shared state Categories: Core: site, stats, profile (required) Cache: cache, tracker (initialized in Phase 0) Build mode: incremental, verbose, quiet, strict, parallel Work items: pages_to_build, assets_to_process (determined in Phase 2) Incremental state: affected_tags, affected_sections, changed_page_paths Output: cli, progress_manager, reporter Attributes Name Type Description site Site | None stats BuildStats | None profile BuildProfile | None cache BuildCache | None tracker DependencyTracker | None incremental bool verbose bool quiet bool strict bool parallel bool memory_optimized bool full_output bool profile_templates bool pages list[Page] | None pages_to_build list[Page] | None assets list[Asset] | None assets_to_process list[Asset] | None affected_tags set[str] affected_sections set[str] | None changed_page_paths set[Path] config_changed bool cli CLIOutput | None progress_manager LiveProgressManager | None reporter ProgressReporter | None build_start float _knowledge_graph Any _knowledge_graph_enabled bool _page_contents dict[str, str] _content_cache_lock Lock _accumulated_page_json list[tuple[Any, dict[str, Any]]] _accumulated_json_lock Lock Methods 12 Tag knowledge_graph property Get knowledge graph (built lazily, cached for build duration). The knowledge g… KnowledgeGraph | None Caret Right def knowledge_graph(self) -> KnowledgeGraph | None Get knowledge graph (built lazily, cached for build duration). The knowledge graph is expensive to build (~200-500ms for 773 pages). By caching it here, we avoid rebuilding it 3 times per build (post-processing, special pages, health check). Returns KnowledgeGraph | None — Built KnowledgeGraph instance, or None if disabled/unavailable Tag content_cache_size property Get number of cached content entries. int Caret Right def content_cache_size(self) -> int Get number of cached content entries. Returns int — Number of files with cached content Tag has_cached_content property Check if content cache has any entries. Validators can use this to decide whet… bool Caret Right def has_cached_content(self) -> bool Check if content cache has any entries. Validators can use this to decide whether to use cache or fallback. Returns bool — True if cache has content Tag has_accumulated_json property Check if accumulated JSON data exists. Post-processing can use this to decide … bool Caret Right def has_accumulated_json(self) -> bool Check if accumulated JSON data exists. Post-processing can use this to decide whether to use accumulated data or fall back to computing from pages. Returns bool — True if accumulated JSON data exists clear_lazy_artifacts Clear lazy-computed artifacts to free memory. Call this at the end of a build … 0 None Caret Right def clear_lazy_artifacts(self) -> None Clear lazy-computed artifacts to free memory. Call this at the end of a build to release memory used by cached artifacts like the knowledge graph and content cache. cache_content Cache raw content during discovery phase (thread-safe). Call this during conte… 2 None Caret Right def cache_content(self, source_path: Path, content: str) -> None Cache raw content during discovery phase (thread-safe). Call this during content discovery to store file content for later use by validators. This eliminates redundant disk I/O during health checks. Parameters 2 source_path Path Path to source file (used as cache key) content str Raw file content to cache get_content Get cached content without disk I/O. 1 str | None Caret Right def get_content(self, source_path: Path) -> str | None Get cached content without disk I/O. Parameters 1 source_path Path Path to source file Returns str | None — Cached content string, or None if not cached get_all_cached_contents Get a copy of all cached contents for batch processing. Returns a copy to avoi… 0 dict[str, str] Caret Right def get_all_cached_contents(self) -> dict[str, str] Get a copy of all cached contents for batch processing. Returns a copy to avoid thread safety issues when iterating. Returns dict[str, str] — Dictionary mapping source path strings to content clear_content_cache Clear content cache to free memory. Call this after validation phase completes… 0 None Caret Right def clear_content_cache(self) -> None Clear content cache to free memory. Call this after validation phase completes to release memory used by cached file contents. accumulate_page_json Accumulate JSON data for a page during rendering (thread-safe). Call this duri… 2 None Caret Right def accumulate_page_json(self, json_path: Any, page_data: dict[str, Any]) -> None Accumulate JSON data for a page during rendering (thread-safe). Call this during rendering phase to store JSON data for later use in post-processing. This eliminates redundant computation and double iteration of pages. Parameters 2 json_path Any Path where JSON file should be written page_data dict[str, Any] Pre-computed JSON data dictionary get_accumulated_json Get all accumulated JSON data for post-processing. Returns a copy to avoid thr… 0 list[tuple[Any, dic… Caret Right def get_accumulated_json(self) -> list[tuple[Any, dict[str, Any]]] Get all accumulated JSON data for post-processing. Returns a copy to avoid thread safety issues when iterating. Returns list[tuple[Any, dict[str, Any]]] — List of (json_path, page_data) tuples clear_accumulated_json Clear accumulated JSON data to free memory. Call this after post-processing ph… 0 None Caret Right def clear_accumulated_json(self) -> None Clear accumulated JSON data to free memory. Call this after post-processing phase completes to release memory used by accumulated JSON data. Internal Methods 1 Caret Right _build_knowledge_graph Build and cache knowledge graph. 0 KnowledgeGraph | None Caret Right def _build_knowledge_graph(self) -> KnowledgeGraph | None Build and cache knowledge graph. Returns KnowledgeGraph | None — Built KnowledgeGraph instance, or None if disabled/unavailable ← Previous autodoc Next → build_stats List © 2025 Bengal ᓚᘏᗢ window.BENGAL_LAZY_ASSETS = { tabulator: '/bengal/assets/js/tabulator.min.js', dataTable: '/bengal/assets/js/data-table.js', mermaidToolbar: '/bengal/assets/js/mermaid-toolbar.9de5abba.js', mermaidTheme: '/bengal/assets/js/mermaid-theme.344822c5.js', graphMinimap: '/bengal/assets/js/graph-minimap.cc7e42e3.js', graphContextual: '/bengal/assets/js/graph-contextual.440e59c6.js' }; window.BENGAL_ICONS = { close: '/bengal/assets/icons/close.911d4fe1.svg', enlarge: '/bengal/assets/icons/enlarge.652035e5.svg', copy: '/bengal/assets/icons/copy.3d56e945.svg', 'download-svg': '/bengal/assets/icons/download.04f07e1b.svg', 'download-png': '/bengal/assets/icons/image.c34dfd40.svg', 'zoom-in': '/bengal/assets/icons/zoom-in.237b4a83.svg', 'zoom-out': '/bengal/assets/icons/zoom-out.38857c77.svg', reset: '/bengal/assets/icons/reset.d26dba29.svg' }; Arrow Up X -------------------------------------------------------------------------------- Metadata: - Author: lbliii - Word Count: 1931 - Reading Time: 10 minutes