Abstract Syntax Tree

3 posts

line4 min readCurated summary

Designing a Semantic Context OS: Beyond Token Stuffing in Agent Systems

The article argues that larger LLM context windows do not automatically produce better software-engineering agents. In long-running workflows, indiscriminately filling the context window can cause attention dilution, context rot, reasoning failures, and potential data exposure. It proposes a “Semantic Context OS,” a local runtime layer that actively governs context as a finite, structured system resource rather than treating it as an unmanaged text stream. ## The Context Window Is Not RAM - The article uses the “Karpathy metaphor”: - The LLM acts like a CPU: a largely stateless inference engine driven by pretrained parameters. - The context window acts like RAM: volatile working memory containing current state, instructions, telemetry, and runtime data. - Unlike physical RAM, LLM context is probabilistic rather than deterministic: - Traditional RAM provides precise address-based retrieval with predictable performance. - LLM retrieval depends on attention weights across Q, K, and V matrices. - Increasing capacity from 32K tokens to 1M or 2M tokens therefore does not guarantee proportionally better retrieval. Larger sequences also increase computational cost and structural noise. ## Attention Dilution and Long-Context Failure - Large codebases and logs contain substantial irrelevant material, including: - Boilerplate definitions - Unused imports - Duplicate syntax - Repeated utilities and naming patterns - As sequence length grows, the attention calculation `QKᵀ` accumulates entropy and background noise. - Softmax then spreads attention energy across more tokens, weakening the sharp attention peaks needed to retrieve important facts. - This contributes to the “lost in the middle” effect: - Information near the beginning and end of a prompt is often retrieved more reliably. - Retrieval accuracy can fall sharply across the middle portion of the context. - The article considers relying on massive, unmanaged contexts an architectural anti-pattern for tasks such as large-scale code review, dependency tracing, and automated refactoring. ## Context Rot in Long-Running Agents The article defines “context rot” as the degradation of an agent’s working context during extended autonomous tasks. - **Context poisoning** - Raw logs, obsolete errors, and previous execution data accumulate over multiple turns. - The model may treat temporary historical failures as current architectural constraints. - **Context distraction** - Monorepos often contain similar names, overloaded methods, and duplicated helper code. - Broad retrieval can overwhelm the model with structurally similar but logically irrelevant code. - **Context clash** - Old instructions may remain after the plan has evolved. - Contradictory directives can cause indecision, infinite reasoning loops, timeouts, or hallucinations. - The article claims that, without active management, failure rates increase nonlinearly with context depth and may reach roughly 40% in deeply nested codebases. ## Semantic Context OS as an AI Kernel The proposed Semantic Context OS sits between agent application logic and external foundation-model APIs, operating as a localhost loopback proxy at `localhost:8080`. Its responsibilities include: - Treating context as a finite hardware-like resource. - Tracking token lifecycles and state access. - Filtering and isolating data before it reaches the model. - Separating physical token limits from semantic governance. - Protecting downstream inference engines from structural noise and helping prevent intellectual-property leakage. The architecture includes: - A POSIX-like virtual file system for managing state topology. - A proprietary “PathAlign” stage for AST-based code-tree pruning. - An asynchronous “sawtooth” memory model for runtime token optimization. ## MVC: Minimum Viable Context The core MVC pipeline—described as “minimum viable context”—aims to provide only the smallest dense set of information required for the agent’s current reasoning step. Its processing stages include: - **Collection and token mapping** - Gather source files, dependency graphs, and runtime logs. - Map them using the target model’s tokenizer, such as `cl100k_base` or `o200k_base`. - **Structural pruning** - Use static analysis and structural rules to remove compiler comments, unused imports, boilerplate, and unrelated utilities. - The broader design replaces passive string concatenation with active context selection, lifecycle management, and bounded transmission policies. The article concludes that reliable enterprise agents require active context orchestration rather than larger prompts alone. A dedicated governance layer should prune, isolate, and refresh context throughout execution so that models receive minimal, relevant, and internally consistent information.

Read original(opens in new tab)
cloudflare3 min readCurated summary

Cloudflare Client-Side Security: smarter detection, now open to everyone

Cloudflare is making its Client-Side Security Advanced product self-serve and offering domain-based threat intelligence free to users of its basic bundle. The service detects malicious browser-side JavaScript through browser reporting, AST-based behavioral analysis, and a new LLM review layer. Its goal is to catch sophisticated skimming attacks while reducing false positives and avoiding performance impacts on customer applications. ## Growing Threat of Client-Side Attacks - Browser skimmers can steal credentials, payment data, and personal information without disrupting page loads or checkout flows. - Recent examples include: - A browser keylogger placed on a major U.S. bank’s employee merchandise store. - Malicious npm package releases capable of enabling browser-based crypto theft when bundled into front-end applications. - These attacks often exploit trusted first-party or third-party scripts rather than obvious server vulnerabilities. ## Broader Access to Client-Side Security - Client-Side Security Advanced, formerly the Page Shield add-on, is now available to self-serve customers. - Domain-based threat intelligence is complimentary for customers using the free Client-Side Security bundle. - Advanced capabilities include: - Machine-learning and LLM-assisted malicious script detection. - Continuous code-change monitoring for compliance requirements such as PCI DSS v4.0 requirement 11.6.1. - Proactive positive security rules maintained through ongoing monitoring. ## Browser-Based Monitoring Without Application Changes - Cloudflare evaluates approximately 3.5 billion scripts per day, with enterprise zones averaging about 2,200 scripts. - The system gathers signals through browser reporting mechanisms such as Content Security Policy. - Customers do not need scanners or application instrumentation. - Traffic must be proxied through Cloudflare. - The approach adds no latency to web applications. ## Detecting Script Intent - Enterprise sites may contain thousands of scripts, and roughly one-third change within a 30-day period. - Manually approving every DOM interaction or outbound connection would create excessive operational overhead. - Cloudflare instead analyzes what scripts are attempting to do. - JavaScript is represented as an Abstract Syntax Tree (AST), allowing the system to identify behavioral patterns even when code is minified, renamed, or obfuscated. ## Reducing False Positives - Client-side compromises are relatively rare but potentially severe, unlike the high-volume attacks typically handled by a WAF. - Because genuine incidents are uncommon, even accurate detection systems can produce more false alarms than real alerts. - False positives contribute to security-team fatigue and can obscure actual compromises. - Legitimate but heavily obfuscated code—such as bot challenges, tracking pixels, advertising bundles, and minified frameworks—can resemble malicious code structurally. ## GNN and LLM Detection Pipeline - Cloudflare’s primary detector is a Graph Neural Network (GNN) operating on JavaScript ASTs. - The GNN learns structural representations of code and can recognize similar behavior despite syntactic changes. - It is optimized for high recall to detect novel and zero-day threats. - Although fewer than 0.3% of analyzed traffic is incorrectly flagged, Cloudflare’s scale makes that percentage a significant number of alerts. - An LLM provides semantic context, recognizing common JavaScript frameworks, domain-specific coding patterns, and benign forms of suspicious-looking obfuscation. - The LLM complements rather than replaces the GNN: - Scripts classified as benign stop after the fast GNN evaluation. - Scripts exceeding the GNN’s risk threshold are sent to an open-source LLM hosted on Cloudflare Workers AI for a second opinion. Cloudflare’s approach combines low-overhead browser telemetry, structural machine learning, and semantic LLM review. For organizations handling payments or sensitive user data, enabling these controls can improve visibility into third-party scripts, detect unexpected code changes, and reduce the chance that false alarms overwhelm security teams.

Read original(opens in new tab)
tossOriginal article

Creating Always-Up-To (opens in new tab)

Managing complex multi-page onboarding funnels often leads to documentation that quickly becomes decoupled from the actual codebase, creating confusion for developers. To solve this, the Toss team developed an automated system that uses static code analysis to generate funnel flowcharts that are never outdated. By treating the source code as the "Source of Truth," they successfully transformed hard-to-track navigation logic into a synchronized, visual map. ### The Limitations of Manual Documentation * Manual diagrams fail to scale when a funnel contains high-frequency branching, such as the 82 distinct conditions found across 39 onboarding pages. * Traditional documentation becomes obsolete within days of a code change because developers rarely prioritize updating external diagrams during rapid feature iterations. * Complex conditional logic (e.g., branching based on whether a user is a representative or an agent) makes manual flowcharts cluttered and difficult to read. ### Static Analysis via AST * The team chose static analysis over runtime analysis to capture all possible navigation paths simultaneously without the need to execute every branch of the code. * They utilized the `ts-morph` library to parse TypeScript source code into an Abstract Syntax Tree (AST), which represents the code structure in a way the compiler understands. * This method allows for a comprehensive scan of the project to identify every instance of navigation calls like `router.push()` or `router.replace()`. ### Engineering the Navigation Edge Data Structure * A "Navigation Edge" data structure was designed to capture more than just the destination; it includes the navigation method, query parameters, and the exact line number in the source code. * The system records the "context" of a transition by traversing the AST upwards from a navigation call to find the parent `if` statements or ternary operators, effectively documenting the business logic behind the path. * By distinguishing between `push` (which adds to browser history) and `replace` (which does not), the documentation provides insights into the intended user experience and "back button" behavior. ### Tracking Hidden Navigation and Constants * **Custom Hook Analysis:** Since navigation logic is often abstracted into hooks, the tool scans `import` declarations to follow and analyze logic within external hook files. * **Constant Resolution:** Because developers use constants (e.g., `URLS.PAYMENT_METHOD`) rather than raw strings, the system parses the project's constant definition files to map these variables back to their actual URL paths. * **Source Attribution:** The system flags whether a transition originated directly from a page component or an internal hook, making it easier for developers to locate the source of a specific funnel behavior. ### Conclusion For teams managing complex user journeys, automating documentation through static analysis is a powerful way to eliminate technical debt and synchronization errors. By integrating this extraction logic into the development workflow, the codebase remains the definitive reference point while providing stakeholders with a clear, automated visual of the user experience.