Skip to main content

5. BSG Compression & LLM Injection

5.1 Dual-Mode Rendering​

Batho Structured Graph (BSG) outputs support dual-mode rendering to align database footprint and ingestion latency with downstream use cases:

View ModeTarget AudienceKey CharacteristicsEmits SYNTAX_GLUE?
storageDownstream parsers, recovery scriptsFull-fidelity representation. Includes raw source text, byte offsets, and syntactic gaps.Yes
agentLLM prompts, context providersHighly compressed representation. Includes structural definitions and signatures only.No

View Selection Guidelines​

  • Storage View: Used when you need complete codebase context, cross-file references, or 100% byte-for-byte source reconstruction. It guarantees a lossless round trip.
  • Agent View: Used when presenting the codebase structure to a Large Language Model (LLM). It filters out comment blocks, whitespace, and formatting anomalies, reducing token footprints by up to 10x.

5.2 Token Budget Algorithm​

To prevent LLM context windows from being overwhelmed, the agent view supports token budgeting. When exporting, the engine filters and prioritizes entities using an importance-based scoring mechanism:

Figure 7: Token Budget Algorithm - Flowchart showing how the compressed agent rendering mode prioritizes entities within token constraints.

Priority Scoring Factors​

Entities are scored for the agent view using the following criteria:

FactorWeightDescription
Public API30%Functions, methods, and classes not prefixed with _.
Import Fan-in25%How many other modules reference this entity.
Semantic Tags25%Annotations from rule plugins (e.g. api, auth, db).
Complexity10%Cyclomatic complexity estimate of the AST node.
Recency10%Node changed in recent patch cycles.

5.3 Arrow IPC Serialization​

Both storage and agent views are serialized and stored inside the .batho database. To ensure high-speed reads and minimize memory overhead when downstream tools consume these graphs:

  • Arrow IPC Format: Relational data (such as entity adjacency indices and dependencies) are mapped directly to Arrow IPC table schemas, permitting memory-mapped reads without full JSON deserialization overhead.
  • Binary Blobs: Compression-friendly chunks (such as individual file BSGs and relationship graphs) are compressed using zstd and stored as binary blobs in Arrow files, loaded on-demand.

5.4 BSG Plugin Catalog​

Batho ships 51 declarative YAML plugins in two packs, plus 5 built-in pipeline hooks. The engine owns algorithms and identity; the plugin SDK (batho_plugin) owns the knowledge — detection rules, classification, language data, and enrichment. All matching is deterministic; no LLM calls at index time.

PackCountLoadingContents
Core pack38Mandatory, auto-loaded (plugins.core.required)Detection, classification, bidirectional integrity, token optimization, language packs, policies
External pack13Config-gated (plugins.external.enabled, default off; allowlist via plugins.external.select)9 security/quality/optimization interceptors + reconstruction integrity, domain taxonomy, quarantine, service tags
Pipeline hooks5Auto-loadedlanguage_detect, stamp_language, comment_classify, property_classify, prune_stub

Plugin Schema Versions​

SchemaStatus
bsg-plugin-schema-v1Legacy (backward compatible)
bsg-plugin-schema-v2Current (supports bidirectional, ast_edges, depends_on)

Core Pack — Detection & Categorization​

Core plugins run during graph construction to detect languages, frameworks, and file categories, and to apply baseline semantic tags.

Plugin IDNameDescription
batho_plugin.core.file_detectionFile DetectionExtension-to-language detection data with multi-strategy fallbacks
bsg_detection_foundationDetection FoundationPackage-manager, manifest, and infrastructure detection
bsg_file_categorizationFile CategorizationCategorize files into TEST, DOCS, CONFIG, SOURCE by path patterns and extensions
bsg_graph_foundationGraph FoundationBaseline deterministic node tagging for category, scope, and service metadata
bsg_token_optimizationToken OptimizationDocstring truncation, test fixture detection, entry point normalization, metadata cleanup (60–80% token reduction)
bsg_bidirectional_foundationBidirectional FoundationGap coverage validation, file integrity verification, reconstruction flagging
bsg_detection_cicdCI/CD DetectionDetect CI/CD pipeline configurations (GitHub Actions, GitLab CI, Jenkins)
bsg_detection_cloud_providersCloud Provider DetectionDetect cloud provider SDKs (AWS, GCP, Azure)
bsg_detection_test_frameworksTest Framework DetectionDetect test frameworks (pytest, Jest, JUnit, Go testing)

Core Pack — Language & Framework Detection​

Plugin IDScopeDescription
bsg_detection_cppC/C++Detect C/C++ projects from source files and build configs
bsg_detection_csharpC#Detect C#/.NET projects from .csproj, .sln files
bsg_detection_dartDartDetect Dart/Flutter projects from pubspec.yaml
bsg_detection_elixirElixirDetect Elixir projects from mix.exs
bsg_detection_kotlinKotlinDetect Kotlin/JVM projects from build.gradle.kts
bsg_detection_phpPHPDetect PHP projects from composer.json
bsg_detection_rubyRubyDetect Ruby projects from Gemfile
bsg_detection_scalaScalaDetect Scala projects from build.sbt
bsg_detection_swiftSwiftDetect Swift/iOS projects from Package.swift
bsg_framework_angularAngularDetect Angular components, services, and modules
bsg_framework_djangoDjangoDetect Django views, models, and middleware
bsg_framework_flaskFlaskDetect Flask routes, blueprints, and decorators
bsg_framework_nodejsNode.jsDetect Node.js patterns: Express, Fastify, middleware chains
bsg_framework_pythonPythonDetect Python-specific patterns: dataclasses, Pydantic, async
bsg_framework_reactReactDetect React components, hooks, and contexts
bsg_framework_vueVueDetect Vue components, composables, and stores
bsg_framework_otherOtherDetect patterns for Spring, Rails, Laravel, Gin, and more

Core Pack — Data Packs & Bidirectional Tests​

Plugin IDDescription
language-ecosystemsPer-language package-manager ecosystem knowledge
noise-pathsGenerated/vendored path data for quarantine rules
pruning-policyWhich entity kinds to prune per language
resolution-policyCross-file resolution strategy data
lang-python / lang-typescript / lang-javascript / lang-go / lang-rustPer-language data packs: builtins, comment syntax
test_bidirectional_gapValidate gap entity coverage for bidirectional reconstruction
test_bidirectional_integrityVerify content hash consistency for bidirectional mode
test_bidirectional_reconstructionEnd-to-end reconstruction verification tests

External Pack — Interceptors (config-gated)​

Interceptor plugins run as a non-blocking enricher pipeline during graph construction. Detections are tagged, not blocked, allowing the build to continue while surfacing issues. Enable the pack via plugins.external.enabled: true, or allowlist specific plugins with plugins.external.select.

Plugin IDNameSeverityDetects
bsg_hardcoded_secret_catcherHardcoded Secret CatcherblockAPI keys, tokens in string literals
bsg_auth_boundary_shieldAuth Boundary ShieldblockMissing auth decorators on API route handlers
bsg_api_contract_guardianAPI Contract GuardianblockBackend API contract changes with downstream dependents
bsg_schema_migration_enforcerSchema Migration EnforcerblockORM/schema changes requiring migration companions
bsg_silent_failure_catcherSilent Failure CatcherwarningBare except:, swallowed exceptions
bsg_dependency_blast_radiusDependency Blast RadiuswarningHigh fan-out modules (>N dependents)
bsg_iac_drift_sentinelIaC Drift SentinelwarningConfig drift between app env references and IaC definitions
bsg_nplus1_query_catcherN+1 Query CatcherwarningDatabase execution patterns inside loop structures
bsg_resource_leak_preventerResource Leak PreventerwarningResource allocations without cleanup paths
bsg_reconstruction_interceptorsReconstruction Interceptorsblock/warningCoverage gap detection and reconstruction integrity verification

Plus three enrichment plugins: gen_domain_taxonomy (domain tier derivation), gen_quarantine_unresolved (quarantine unresolved stubs), and gen_service_tag (service attribution).

Plugin Dependency Graph​

Foundation plugins declare dependencies via depends_on:

Figure 32: Plugin Dependency Graph — Bidirectional foundation and reconstruction interceptors depend on the graph foundation plugin.