Architecture & Engine Internals (கட்டமைப்பு மற்றும் பொறி உள்ளமைப்புகள்)
1. Concurrency Model & File Ingestion
urai-ecma processes large enterprise monorepos (10,000+ files) without thread contention or memory exhaustion.
1.1 Git-Aware Pruning Traversal (collect_source_files)
Standard directory traversals choke on node_modules, .next, or build artifacts. urai-ecma uses ignore::WalkBuilder with early prefix pruning:
- Early Branch Termination: By returning
falseinsidefilter_entry, the directory tree traversal avoids callingstat()or descending into tens of thousands of nested dependencies. - Extension Matching:
is_supported_extensionbounds AST ingestion to valid ECMAScript/TypeScript MIME signatures:js,jsx,ts,tsx,mjs, andcjs.
1.2 Rayon Parallelism and Thread Safety
File processing runs inside a fork-join work-stealing pool using rayon::prelude::*:
- Thread Confinement: Each worker thread maintains its own independent AST traversal instance, avoiding mutex contention during parsing.
- Safe Context Sharing:
UraiContextis wrapped in anArc<UraiContext>. Read-only properties (thresholds, modes, endpoint paths) are accessed concurrently across CPU cores without locking.
2. The SWC Parser & AST Ingestion Engine
Rather than relying on brittle regex matching, urai-ecma parses full Abstract Syntax Trees using SWC (swc_ecma_parser).
Memory Layout and Comment Attachment
When SWC parses a module, it yields a three-part tuple:
swc_ecma_ast::Module: The root AST node representing statements, imports, exports, and declarations.SingleThreadedComments: A two-tiered comment map separating leading and trailing trivia tokens indexed byBytePos.Lrc<SourceMap>: An atomic reference-counted source map linking internal byte offsets (lo,hi) to concrete file line numbers and character positions.
3. The AST Visitor Pipeline
urai-ecma sequences AST visitors in a specific order: extraction occurs before destructive pruning.
3.1 Structural Stub Retention (is_structural_stub_stmt)
The core innovation of urai-ecma is Structural Stub Retention. When collapsing multi-line function bodies, removing all statements blinds the downstream LLM to component lifecycle and reactive event flows.
urai-ecma solves this with is_structural_stub_stmt:
Why This Works
- Hooks Kept Intact:
useEffect(() => { ... }, [dep])is preserved, signaling side-effect dependencies to the LLM. - JSX Output Preserved: The return structure (
<div ...><Child /></div>) remains visible. - Dead Logic Discarded: Intermediate loops, data sanitization, and variable assignments are stripped and replaced with a single synthetic expression comment:
3.2 JSDoc Extraction with Distance-Based Fallback
Before querying an LLM, FunctionSummarizerVisitor checks for human-written documentation using the jsdoc crate:
- Export Anchor Matching: When functions are wrapped in export statements (e.g.,
export default function ...), comments attach to theExportDeclspan rather than the innerFnDecl. Trackingcurrent_export_locaptures these comments. - Proximity Scan Fallback: If exact span alignment fails, the engine scans all comments within a 300-byte window (
distance <= 300) to associate detached comments with their respective declarations.
3.3 The 4-Mode JSX Tailwind Pruner (ReactJsxPruner)
Modern utility-first CSS causes significant token bloat in LLM contexts. ReactJsxPruner intercepts JSX attributes via visit_mut_jsx_opening_element:
- Dynamic Code Preservation: By filtering on
JSXAttrValue::JSXExprContainer, patterns likeclassName={clsx("base", isActive && "active")}remain untouched, preserving conditional UI logic for the LLM.
3.4 Backend API Route Extraction (RouteVisitor)
RouteVisitor parses endpoint declarations across major backend frameworks:
1. Next.js App Router
Inspects exported functions within file paths containing route.ts, route.js, or /api/:
2. NestJS Controllers
Inspects AST decorators on classes and methods:
- Identifies
@Controller(prefix)to establish the base route. - Matches method decorators (
@Get,@Post,@Put, etc.) and joins subpaths to produce full URI endpoints.
3. Express & Fastify
Detects Member Expression calls on common server variables (app, router, fastify, server):
- Handles both string literals and template literals:
Resolves route patterns like
app.get(`/users/${id}`)into/users/${...}.
3.5 React Introspection (ReactComponentAnalyzer)
ReactComponentAnalyzer identifies components by PascalCase naming (name.chars().next().is_some_and(|c| c.is_uppercase())) across function declarations and arrow expressions:
- TypeScript Prop Extraction: Resolves explicit type annotations (
resolve_ts_type) and object destructuring patterns (ObjectPatProp::KeyValue). - Hook Inspection: Tracks hook invocations prefixed with
use*, increments side-effect counters onuseEffect/useLayoutEffect, and matchesuseStatevariable/setter pairs. - JSX Element Scanning: Walks the internal JSX element tree and records rendered child elements (e.g.,
<Button>,<ModalHeader>).
4. The Storage Engine: foyer Hybrid Cache
When function summarization or Tailwind style summarization is enabled, sending duplicate requests to an LLM slows down processing. urai-ecma integrates foyer, a hybrid memory and disk caching engine written in Rust.
4.1 Cryptographic Cache Keys
Cache keys are computed using Sha512_256:
- No Truncation Collisions:
Sha512_256produces a 256-bit digest resistant to collision attacks, making it safe across thousands of distinct code snippets. - Zero-Allocation Hex Formatting:
const_hexserializes raw bytes into ASCII hex strings with SIMD optimizations.
4.2 Storage and Eviction Policies
- Two-Tier Architecture: Hits resolve directly from memory in nanoseconds. When memory fills, entries spill over to disk.
- Zstd Compression: Compresses cached LLM response text by ~70%, fitting more entries within disk allocations.
- Graceful Shutdown: Implements
DropforOllamaUraito flush in-flight disk writes before the process exits:
5. Dependency Graph Construction
urai-ecma builds both directory trees and module dependency graphs without external runtime tooling.
5.1 ASCII Tree Generation
Recursively reads project directories while filtering out hidden entries and build output folders (target, dist, node_modules). Connectors (├── and └── ) are assigned using lookahead counters based on remaining path entries.
5.2 petgraph Directed Module Graph
Scans source files for relative import declarations (import ... from './component') and tracks them using petgraph::graph::UnGraph:
- Resolves relative paths against the project root.
- Emits a standard Mermaid.js diagram (
graph LR;) embedded directly into the generated prompt context, allowing the LLM to inspect project topology.
6. Token Telemetry & Context Optimization
6.1 tiktoken Integration (o200k_base)
At the end of an optimization run, urai-ecma benchmarks raw source tokens against the final output:
- Native GPT-4o Tokenizer: Uses the
o200k_basevocabulary matching OpenAI's flagship models, ensuring token calculations reflect actual API billing and context usage. - Accurate Source Counting:
calculate_raw_project_tokenscounts all supported source files, including file name token overhead.
