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 with 38 declarative YAML plugin files. Plugins are divided into two categories: foundation plugins (detection, categorization, and tagging) and interceptor plugins (security, reliability, and architectural risk detection).

Plugin Schema Versions​

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

Foundation Plugins (28 files)​

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

Core Detection & Categorization​

Plugin IDNameDescription
bsg_detection_foundationBSG Detection FoundationLanguage, framework, package manager, and infrastructure detection
bsg_file_categorizationBSG File CategorizationCategorize files into TEST, DOCS, CONFIG, SOURCE by path patterns and extensions
bsg_graph_foundationBSG Graph FoundationBaseline deterministic node tagging for category, scope, and service metadata
bsg_token_optimizationBSG Token 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

Language-Specific Detection​

Plugin IDLanguageDescription
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

Framework Detection​

Plugin IDFrameworkDescription
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

Specialized Detection​

Plugin IDDescription
bsg_detection_cicdDetect CI/CD pipeline configurations (GitHub Actions, GitLab CI, Jenkins)
bsg_detection_cloud_providersDetect cloud provider SDKs (AWS, GCP, Azure)
bsg_detection_test_frameworksDetect test frameworks (pytest, Jest, JUnit, Go testing)

Test Plugins (Bidirectional)​

Plugin IDDescription
test_bidirectional_gap_coverageValidate gap entity coverage for bidirectional reconstruction
test_bidirectional_integrityVerify content hash consistency for bidirectional mode
test_bidirectional_reconstructionEnd-to-end reconstruction verification tests

Interceptor Plugins (10 files)​

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.

Plugin IDNameSeverityDetects
bsg_hardcoded_secret_catcherHardcoded Secret CatcherHighAPI keys, tokens in string literals
bsg_auth_boundary_shieldAuth Boundary ShieldHighMissing auth decorators on API route handlers
bsg_silent_failure_catcherSilent Failure CatcherMediumBare except:, swallowed exceptions
bsg_dependency_blast_radiusDependency Blast RadiusLowHigh fan-out modules (>N dependents)
bsg_api_contract_guardianAPI Contract GuardianBlockBackend API contract changes with downstream 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_schema_migration_enforcerSchema Migration EnforcerBlockORM/schema changes requiring migration companions
bsg_reconstruction_interceptorsReconstruction InterceptorsWarning/BlockCoverage gap detection and reconstruction integrity verification

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.