updated 2026-11-26·6 min read
Multi-Language AST & Regex Analysis Engine
Reference Tree-sitter S-expression queries, default zero-dependency regex fallback, and boundary digest normalization across SQL, Protobuf, Python, and Rust.
sqlfluff, protoc, mypy, and rustc only check syntax and types inside their own language boundaries. Stokes crosses them by extracting producer counts and downstream buffer capacities into one Boundary Intermediate Representation (BIR) and walking a directed compatibility graph.
One practical shortcut up front: contracts/ast_queries/ holds reference Tree-sitter .scm queries for SQL, Protobuf, Python, and Rust, albeit in the standalone Python package _query_tree_sitter delegates straight to compiled Python regex rules (_PATTERNS) unless compiled .so language grammars are installed. Requiring a C toolchain just to run a CLI lint check on a stripped Alpine runner wasn’t going to happen.
- Multi-Language Inputs
Reads SQL DDL/queries (001_bot_signals.sql), Protobuf schemas (signals.proto), Python ETL workers (extractor.py), and Rust edge proxies (feature_ingest.rs).
- Tree-sitter Hook & Regex Fallback
Probes for tree_sitter Python bindings at startup and falls back to deterministic compiled regexes (_PATTERNS) out of the box.
- Reference S-Expression Queries
Ships sql_catalog_query.scm, proto_repeated_query.scm, python_extractor_query.scm, and rust_slice_unwrap_query.scm alongside the regex rules.
- Boundary IR & Reachability Graph
Normalizes canonical primitive types, computes SHA-256 digests, and checks upstream counts against downstream buffer limits.
Tree-sitter Hook vs. Default Regex Engine
TreeSitterLoader checks whether tree_sitter is importable on startup, though _query_tree_sitter still delegates to _query_regex when compiled .so grammars aren’t provided. That keeps stokes verify working anywhere Python 3.11+ runs without native build failures:
Tree-sitter Interface & .scm Queries
Provides the tree_sitter probe hook and reference .scm S-expression queries for SQL, Protobuf, Python, and Rust when native compiled .so grammars are supplied.
Compiled Regex Engine (Default Runtime)
Runs compiled regex rules out of the box across SQL (unqualified_catalog_violation), Protobuf (unbounded_repeated_field), Python (unbounded_shadow_admission, unsliced_payload_expansion), Rust (fatal_slice_unwrap_violation, fixed_buffer_allocation), and Go (unbuffered_channel).
TreeSitterLoader & Reference S-Expression Queries (.scm)
# stokes/subagents/ast_engine/tree_sitter_loader.py
class TreeSitterLoader:
"""Unified AST analysis engine with native tree-sitter hook and regex extraction."""
_PATTERNS = {
"sql": [
(
"unqualified_catalog_violation",
"select_statement",
re.compile(r"(?i)FROM\s+system\.columns\b(?!.*database\s*=\s*currentDatabase)", re.MULTILINE | re.DOTALL),
),
(
"unqualified_catalog_violation",
"select_statement",
re.compile(r"(?i)FROM\s+system\.tables\b(?!.*database\s*=\s*currentDatabase)", re.MULTILINE | re.DOTALL),
),
],
"proto": [(
"unbounded_repeated_field",
"field",
re.compile(r"\brepeated\s+\w+\s+\w+\s*=\s*\d+(?!\s*\[.*stokes\.max_items)", re.MULTILINE),
)],
"python": [
(
"unbounded_shadow_admission",
"function_definition",
re.compile(r"def\s+(resolve_feature_cardinality|extract_features)\b", re.MULTILINE),
),
(
"unsliced_payload_expansion",
"assignment",
re.compile(r"features\s*=\s*\[.*\](?!\[:\s*MAX_CANONICAL\])", re.MULTILINE),
),
],
"rust": [
(
"fatal_slice_unwrap_violation",
"call_expression",
re.compile(r"\.try_into\(\)\s*\.(unwrap|expect)\s*\(", re.MULTILINE),
),
(
"fixed_buffer_allocation",
"let_declaration",
re.compile(r"let\s+\w+\s*:\s*\[[\w:]+;\s*\d+\]\s*=", re.MULTILINE),
),
],
"go": [(
"unbuffered_channel",
"make_call",
re.compile(r"make\s*\(\s*chan\s+\w+\s*\)", re.MULTILINE),
)],
};; contracts/ast_queries/sql_catalog_query.scm
(select_statement
(from_clause
(table_expression
(table_identifier) @catalog_table
(#match? @catalog_table "^(system\\.)?(columns|tables)$")))
(where_clause
(binary_expression
left: (column_identifier) @filter_col
operator: "="
right: (string_literal) @table_name
(#match? @filter_col "^(table|name)$"))) @where_predicate
(#not-has-child? @where_predicate
(binary_expression
left: (column_identifier) @db_col
(#match? @db_col "^database$")))) @unqualified_catalog_violation;; contracts/ast_queries/proto_repeated_query.scm
(field
(field_options)? @options
type: (_) @field_type
name: (field_name) @field_name
(#match? @options "repeated")
(#not-match? @options "stokes\\.max_items")) @unbounded_repeated_field;; contracts/ast_queries/python_extractor_query.scm
(function_definition
name: (identifier) @fn_name
(#match? @fn_name "resolve_feature_cardinality|extract_features")
body: (block
(for_statement
left: (identifier) @item_var
right: (identifier) @collection_var
body: (block
(if_statement
alternative: (else_clause
(expression_statement
(call
function: (attribute
object: (identifier) @target_list
attribute: (identifier) @append_method
(#eq? @append_method "append"))
arguments: (argument_list
(dictionary
(pair
key: (string) @prio_key
value: (integer) @prio_val
(#match? @prio_key "priority")
(#eq? @prio_val "0")))))))))))) @unbounded_shadow_admission;; contracts/ast_queries/rust_slice_unwrap_query.scm
(call_expression
function: (field_expression
value: (call_expression
function: (field_expression
value: (_) @source_slice
field: (field_identifier) @try_into_fn
(#eq? @try_into_fn "try_into")))
field: (field_identifier) @unwrap_fn
(#match? @unwrap_fn "^(unwrap|expect)$"))
arguments: (arg_list)) @fatal_slice_unwrap_violationNormalizing Contracts to Language-Agnostic Digests
The engine translates extracted fields into Boundary Intermediate Representation (BIR) by normalizing primitive widths across SQL, Protobuf, Python, and Rust:
| Canonical Type | ClickHouse SQL | Protocol Buffers | Python Hint | Rust Type | Memory Width |
|---|---|---|---|---|---|
U8 | UInt8 | uint32 (varint) | int | u8 | 1 byte |
U16 | UInt16 | uint32 (varint) | int | u16 | 2 bytes |
U32 | UInt32 | uint32 | int | u32 | 4 bytes |
U64 | UInt64 | uint64 | int | u64 | 8 bytes |
F32 | Float32 | float | float | f32 | 4 bytes (IEEE-754) |
F64 | Float64 | double | float | f64 | 8 bytes (IEEE-754) |
BOOL | UInt8 / Bool | bool | bool | bool | 1 byte |
BYTES | String / FixedString | bytes | bytes | [u8; N] / &[u8] | Variable / Fixed |
BoundaryInterfaceIR & ReachabilityGraph Implementation (Python)
# stokes/subagents/ast_engine/boundary_ir.py
from dataclasses import dataclass
from enum import Enum
import hashlib
import json
class CanonicalType(Enum):
U8 = "U8"
U16 = "U16"
U32 = "U32"
U64 = "U64"
F32 = "F32"
F64 = "F64"
BOOL = "BOOL"
BYTES = "BYTES"
@dataclass
class BoundaryField:
name: str
canonical_type: CanonicalType
ordinal: int
is_nullable: bool = False
@dataclass
class BoundaryInterfaceIR:
interface_id: str
direction: str # "upstream_producer" | "downstream_consumer"
fields: list[BoundaryField]
capacity_bound: int
is_bounded: bool
def compute_ast_digest(self) -> str:
normalized_repr = {
"interface_id": self.interface_id,
"fields": [
{
"name": f.name.lower().strip(),
"type": f.canonical_type.value,
"ordinal": f.ordinal,
"nullable": f.is_nullable,
}
for f in sorted(self.fields, key=lambda x: x.ordinal)
],
"capacity_bound": self.capacity_bound,
"is_bounded": self.is_bounded,
}
serialized = json.dumps(normalized_repr, sort_keys=True, separators=(",", ":"))
return "sha256:" + hashlib.sha256(serialized.encode("utf-8")).hexdigest()# stokes/subagents/ast_engine/reachability_graph.py
class ReachabilityGraph:
def evaluate_cardinality_invariants(self) -> list[ContractViolation]:
violations = []
for edge in self.edges:
src = self.nodes[edge.source]
tgt = self.nodes[edge.target]
if src.is_upstream and tgt.is_downstream:
if src.cardinality is None or tgt.cardinality is None:
continue
risk_ratio = src.cardinality / tgt.cardinality
if risk_ratio > 1.0:
violations.append(ContractViolation(
rule_id="LINT-004",
severity="FATAL",
source_file=src.file,
target_file=tgt.file,
risk_ratio=risk_ratio,
message=(
f"Cardinality inequality detected: Upstream emits {src.cardinality} "
f"features > Downstream buffer capacity {tgt.cardinality} (Risk: {risk_ratio:.2f})"
),
))
return violationsWhy It Stays Cheap in CI
| Characteristic | Stokes Boundary Scanner | Monolithic Compilers (rustc + mypy + sqlfluff) |
|---|---|---|
| What It Skips | No LLVM codegen, no database containers | Full typechecking and compilation |
| Directory Scan Cap | Walks up to 500 source files by default | Entire dependency graph |
| Cross-Boundary Visibility | Unified BIR reachability graph | Single-language files |
| External Dependencies | Zero (built-in regex fallback) | Python, Cargo, Rustc, LLVM |
Explore how the five language workers stream findings in Parallel Language Workers & Event Bus and how patches are stress-tested in Verification, Fuzzing & Simulation Harness.