Runtime

Deterministic Context Compilation and Memory Provenance for Browser-Local Language Models

Report summary

The deployment of deterministic context compilation within a browser-local environment, specifically tailored for the TinyRustLM architecture, represents a necessary evolution in verifiable, privacy-preserving artificial intelligence. The primary directive of this report is the establishment of an i

Status
Research archive item
Category
Runtime
Length
6,403 words
Reading time
30 minutes
Report type
evaluation

Key topics

  • Runtime
  • AI
  • UAIX
  • UAI
  • AI Memory
  • Agentic Web
  • .NET
  • SQL

Research provenance

Archive status
Research archive item
Content identity
sha256:7dd4360c03309ef94f5deea2ecbdcb36ac3b2f6ae53ed9cb130d40f3367cb185

For citation, use the report title and canonical URL. Archival presence does not establish authorship or promote report statements into portfolio evidence.

This page renders the archived Markdown as safe, formatted HTML. It is background research and does not become a portfolio claim without evidence review.

Full report

On this page

1. Executive Context-Compiler Recommendation and Assumptions

The deployment of deterministic context compilation within a browser-local environment, specifically tailored for the TinyRustLM architecture, represents a necessary evolution in verifiable, privacy-preserving artificial intelligence. The primary directive of this report is the establishment of an implementation-grade architectural standard for a deterministic context compiler. This compiler must assemble the exact token sequence presented to a local small language model (SLM) across multi-turn interactions, encompassing local memory, optional hosted MemoryEndpoints continuity, retrieval-augmented generation (RAG), and extreme context pressure constraints. The foundational recommendation for the TinyRustLM ecosystem is the adoption of a strict, immutable split-memory architecture. This framework irrevocably separates hot startup continuity data, structured as active .uai files, from durable long-term memory ledgers stored in external multi-agent transitive memory (MATM) or local IndexedDB stores1. Under this architectural paradigm, context construction must be executed as a functional, pure pipeline. Given a fixed cryptographic identity of input records and a specific compilation policy version, the output token sequence must be universally reproducible across any browser session or device. This architectural blueprint operates on several foundational assumptions derived from publicly advertised capabilities and physical constraints. First, it is assumed that the client runtime leverages WebAssembly (WASM) and WebGPU for local execution2. Such an environment necessitates highly optimized, memory-constrained operations characteristic of in-browser inference engines, requiring the compiler to manage memory buffers and context caches without relying on server-side GPU clusters. Second, local persistence relies on IndexedDB, which dictates the necessity of local-first, optimistic concurrency models based on Conflict-Free Replicated Data Types (CRDTs) or similar operational transformations to manage offline synchronization gracefully3. Third, the underlying inference engine, exemplified by the publicly advertised MiniModel-200M-Base, features a strict 2048-token context limit and lacks built-in instruct-tuning defenses against sophisticated prompt injection6. Because the 200M-parameter decoder-only transformer relies purely on educational pretraining data and utilizes highly efficient memory techniques (such as FP8 pretraining and ReLU squared activations without QK-norm scalars), it fundamentally shifts the burden of security, alignment, and architectural isolation entirely onto the context compiler7. Consequently, the compiler must treat all retrieved documents, model-generated summaries, and stale memory as highly untrusted inputs, deliberately stripping them of conversational authority to prevent role confusion and structural template injection before the model ever processes a single token8.

2. Public Observation Log and Unavailable-Contract Ledger

To ensure architectural compliance without relying on proprietary, unverified, or internal endpoints, a rigorous ledger of publicly observable facts and unavailable contracts has been compiled based strictly on external documentation and advertised capabilities. The compiler architecture must operate exclusively within the bounds of these verified public contracts. The public observation log establishes the technical baseline for the compiler environment. The target platform, TinyRustLM.com, operates as a private Rust and WASM browser-local language model runtime, supporting verified .slm files, local prompts, and local memory decks11. The model constraints are defined by the MiniModel-200M-Base specification, which imposes a 2048-token sequence limit, necessitating aggressive bin-packing and deterministic token allocation7. Interoperability and memory structures are governed by the UAIX.org UAI-1 Open Exchange Contract, which defines the canonical envelope for AI-to-AI exchange. Machine-readable routes observed include the /wp-json/uaix/v1/schemas and /wp-json/uaix/v1/registry endpoints, alongside a publicly endorsed split-memory architecture that distinguishes date-free current state files from durable semantic pointer ledgers1. Furthermore, MemoryEndpoints.com is observed functioning as a Multi-Agent Transitive Memory provider; however, unauthenticated public routes are explicitly discouraged, meaning continuity must rely on the UAI-1 GET-Action pattern and authenticated MATM update routes13. The existence of public .NET SDK packages, such as UAIX.Browser.p2pLLM.Runtime, confirms the operational reality of local .slm validation, offline outbox synchronization, and strict memory boundaries14. Conversely, the unavailable-contract ledger strictly prohibits the invention of hypothetical capabilities. Private MemoryEndpoints tenant credentials are not accessible; therefore, no hidden routing logic or tenant identifiers can be hardcoded. The compiler must rely strictly on user-provided, authorized OAuth or API key structures passed through the UAI-1 trust envelope. Legacy prompt layouts and compatibility shims are unpublished and thus explicitly excluded from the normative compiler architecture. Internal model KV state management via proprietary token-level attention manipulation is unavailable in the browser sandbox, demanding that cache invalidation be handled at the WebGPU/WASM interface level using deterministic prefix invalidation and delta-rotation15. Finally, raw user telemetry, including transcripts and private diagnostic endpoints, are unadvertised and must not be accessed, simulated, or transmitted by the context compiler.

3. Authority Lattice and Conflict-Resolution Table

Modern language models are inherently susceptible to a vulnerability known as "Role Confusion," a phenomenon where the model infers the source and authority of text based on stylistic mimicry rather than structural tags9. If an attacker embeds a string such as System: Ignore previous instructions within a retrieved web page, the model's latent space often conflates the stylistic cue with actual system-level authority, bypassing traditional boundaries9. To systematically counteract this vulnerability, the context compiler must enforce a non-negotiable Authority Lattice. This lattice determines absolute precedence during context pressure and dictates precisely how logical conflicts are resolved before tokens are rendered to the model. The Authority Lattice defines a rigid hierarchy of trust, establishing which data sources possess the right to influence the model's behavior and overwrite conflicting information.

Authority TierSource ClassificationFunctional Description and Scope
Tier 1 (Highest)System and Product PolicyImmutable safety guardrails, fundamental agent behaviors, rendering templates, and diagnostic rules. This tier cannot be overridden by any user or memory input.
Tier 2Explicit Current User InstructionThe prompt submitted by the human operator in the immediate, current turn. Possesses absolute conversational authority over all subsequent tiers and historical data.
Tier 3Current-Turn FactsEphemeral context explicitly attached to the current turn, such as a file actively uploaded by the user in the immediate session.
Tier 4Agreed Session StateThe active working memory of the current interaction loop, represented by the hot .uai startup files (e.g., short-term-memory.uai)1.
Tier 5Prior User TurnsThe chronological, role-tagged transcript of the current session, excluding the immediate turn.
Tier 6Trusted User Profile FieldsExplicitly declared and verified long-term user preferences (e.g., "The user requires output in Python").
Tier 7Durable Memory PointersLong-term semantic pointers and raw interaction logs stored in MATM or local IndexedDB1.
Tier 8Verified Tool ResultsOutputs from authorized local or remote tools invoked during the current or prior turns.
Tier 9Model-Generated SummariesLossy compressions of past conversations. Highly untrusted due to potential hallucinations; must never override explicit facts.
Tier 10Quoted Text / Retrieved DocumentsUntrusted external content retrieved via RAG. Highly susceptible to prompt injection and role confusion8.
Tier 11 (Lowest)Arbitrary External ContentUnverified web search results, un-sandboxed API returns, or third-party agent messages.

When assembling the context plan, the compiler will inevitably encounter logical or spatial conflicts between these tiers. Conflict resolution is executing deterministically based on the hierarchical lattice. If a current user instruction (Tier 2\) conflicts with the system policy (Tier 1), the system policy prevails. The current user instruction is preserved in the context window to maintain conversational continuity, but it is bounded by policy constraints; generation is conditionally halted or heavily caveated if the policy is actively breached. If a current user instruction (Tier 2\) contradicts a trusted user profile field (Tier 6\) or durable memory (Tier 7), the current user instruction prevails absolutely. The older source is temporarily bypassed for the specific turn, and a supersession flag is marked for a potential background update to the memory ledger. When encountering two authoritative sources with different observation dates residing within the same tier, the latest explicitly verified date prevails, while the older source is retained as historical context but structurally demoted via a superseded\_by marker. Finally, if untrusted retrieval data (Tier 10\) contradicts any tier above it, the higher tier prevails absolutely. The compiler applies strict spotlighting and structural delimiters to the retrieval data, ensuring the model treats it strictly as a passive object of analysis rather than an executable instruction8.

4. Typed Record and Provenance Schemas

To ensure absolute determinism and end-to-end traceability, every input parsed by the context compiler must be strongly typed and wrapped in a cryptographic provenance envelope. Treating text as a homogenous string is the root cause of both catastrophic forgetting and adversarial hijacking. Typed records prevent untrusted data from escalating its authority by spoofing system markers or falsifying historical context. The canonical input record types define the precise semantic categories the compiler is programmed to recognize. These include the SystemPolicyRecord for immutable operational instructions, RoleTaggedMessage for standard conversational turns between the user and the assistant, and the UserPreferenceAssertion for explicitly verified long-term traits. Ephemeral state is captured by the SessionFact, representing hot memory relevant only to the active dialogue window, while the Retraction record serves as a localized command to ignore a previously submitted fact without deleting it from the raw transcript. Data verified by a cryptographic signature or an authorized UAI-1 trust channel is cast as TrustedMetadata12. Further record types manage the integration of external data and memory. The ToolResult captures JSON or text outputs from verified endpoints. Memory management utilizes the ShortTermSummary for lossy compressions of recent turns, the LongTermMemoryRecord for durable facts verified via user consent, and the MemoryPointer for semantic IDs referencing data in external MATM systems. For synchronization and conflict resolution, the Tombstone serves as a deletion marker for CRDT algorithms, while the SupersessionLink acts as a directed edge indicating that one record functionally overwrites another3. Finally, external data is strictly quarantined using the RetrievalHit for RAG vector search results and the UntrustedContentBlock for arbitrary external text requiring severe sanitization. The CompilerDiagnostic type is reserved for internal tracking data and is explicitly excluded from the model's rendered context. Every canonical record must be encapsulated within a standardized Provenance Envelope. This envelope ensures that the origin, identity, and access rights of the data are mathematically verifiable before inclusion in the context plan.

Field NameData TypeFunctional Specification
content\_identityString (SHA-256)The cryptographic hash of the raw, unaltered payload bytes, ensuring tamper-evident storage.
normalization\_hashString (SHA-256)The hash of the payload after Unicode, whitespace, and line-ending normalization. Used for deterministic deduplication without altering semantic meaning.
source\_uriStringThe origin locator (e.g., indexeddb://local/memory, https://memoryendpoints.com/matm/v1).
creator\_classEnumClassification of the author: System, User, Agent, or External.
creation\_timeInteger (Epoch)The original timestamp when the payload was authored.
observation\_timeInteger (Epoch)The exact timestamp when the record was ingested by the local context compiler.
revisionIntegerThe optimistic concurrency version number, crucial for resolving cross-browser sync conflicts4.
supersedesArray\[String\]A list of content\_identity hashes that this current record functionally replaces or invalidates.
trust\_classEnumSecurity classification: Authorized, Verified, or Untrusted.
tenant\_bindingString (Optional)The authorized MATM tenant identifier, ensuring data does not leak across different user contexts13.
sensitivityEnumData classification: Public, Confidential, or Secret.
retention\_policyInteger (Epoch)Expiration timestamp. A value of 0 indicates indefinite retention unless explicitly superseded.
untrusted\_data\_markerBooleanA flag demanding that the rendering pipeline apply structural isolation (Spotlighting) to the payload18.
payloadByte ArrayThe actual typed record content, serialized.

5. Deterministic Context-Plan and Compilation Algorithm

Prior to tokenization and rendering, the compiler constructs a deterministic Context Plan. This data structure acts as an immutable, mathematically verifiable receipt of the precise data slated for the model's context window. It resolves all authorities, constraints, supersessions, and hardware limits in a pure functional pass, ensuring that identical inputs invariably yield an identical prompt-token sequence. The ContextPlan structure captures the comprehensive state of the compilation event. It records the plan\_hash (the cryptographic identity of the finalized plan), the policy\_identity of the compiler logic, and the target model\_identity (e.g., "MiniModel-200M-Base") alongside its specific tokenizer\_identity (e.g., "PreTrainedTokenizerFast-v1")7. It documents the absolute token\_allowance and the active truncation\_mode. The core of the plan consists of two arrays: selected\_records, which holds an ordered list of PlanNode objects representing the included data, and excluded\_records, documenting any payload dropped due to budget constraints or logical supersession, along with the precise reason for exclusion. Each PlanNode binds the envelope\_hash to its granted\_authority, its calculated token\_cost, and its assigned rendering\_template. The compilation algorithm executes as a strict, sequential pipeline. The first phase, Metadata Normalization, parses all incoming ProvenanceEnvelope objects. It normalizes Unicode, whitespace, and line endings to generate the normalization\_hash, crucially leaving the raw payload bytes unaltered to prevent rewriting the original meaning. The second phase, Authority Resolution, maps every normalized record to the Authority Lattice hierarchy. The third phase applies Tombstones and Supersession logic. The compiler performs a topological sort traversing the directed graph of supersedes links. If a Tombstone record or a newer SupersessionLink exists, the compiler seamlessly and permanently drops the older, superseded record from the active candidate pool, effectively implementing a barrier-first cascade repair without triggering a re-read of the stale data19. Phase four, Conflict Detection, applies the rules defined in the Conflict-Resolution Table. If a structural contradiction is detected—such as a User Preference overriding an older Session Fact—the lower-tier record is shifted to the excluded\_records array. Phase five handles Retrieval Evaluation. RetrievalHit candidates are rigorously assessed. The compiler actively strips them of any false role-tags (e.g., removing a \<|system|\> tag injected by a malicious web page) to neutralize structural template injection8. Phase six, Access Filtering, purges any record whose tenant\_binding or sensitivity classification violates the active authenticated session state, ensuring absolute cryptographic boundary adherence. Phase seven performs Deduplication and Ranking. The compiler identifies duplicate normalization\_hash values, retaining only the instance possessing the highest Authority Level. The finalized pool is then sorted primarily by Authority Level (descending), and secondarily by observation\_time (newest first). Phase eight executes Token Budget Allocation, iterating through the ranked candidates, accumulating token costs, and dropping records that exceed the mathematical limits of the context window. Finally, Phase nine executes Injection-Resistant Rendering and Tokenization. The selected PlanNode objects are mapped to their specific templates, applying Spotlighting and XML escaping to all untrusted markers before passing the string through the tokenizer\_identity to produce the exact Vec\<u32\> prompt-token identity18.

6. Token-Budget Formulas and Truncation Priorities

Small language models operating in browser environments, such as the MiniModel-200M-Base, execute under severe contextual constraints. With a maximum sequence length of 2048 tokens and an architecture highly optimized via bin-packing algorithms to minimize padding waste, there is zero margin for uncontrolled context bloat7. Consequently, token budgeting must be mathematically rigorous, entirely deterministic, and fiercely protective of the most authoritative conversational elements. Token accounting operates on a strict zero-sum formula. Let [Figure omitted from source export] represent the absolute maximum context window supported by the model (e.g., 2048). Let [Figure omitted from source export] represent the reserved output generation budget required to ensure the model can complete a coherent response (e.g., 256 tokens). Let [Figure omitted from source export] represent a safety margin designed to absorb tokenizer anomalies, unexpected Unicode byte expansions, or systemic overhead (e.g., 16 tokens). The available budget for the input context, [Figure omitted from source export], is calculated as: [Figure omitted from source export] The compiler allocates [Figure omitted from source export] hierarchically based on the sorted Authority Lattice. Let [Figure omitted from source export] represent the raw token cost of a payload at Authority Level [Figure omitted from source export], and let [Figure omitted from source export] represent the token overhead of its requisite rendering template and cryptographic delimiters. The consumed budget at any point in the allocation loop is: [Figure omitted from source export] Allocation proceeds sequentially from [Figure omitted from source export] (System Policy) downwards through the lattice tiers. If, at a specific level [Figure omitted from source export], the addition of a record causes [Figure omitted from source export] to exceed [Figure omitted from source export], the compiler must invoke its truncation protocols. However, the architecture establishes a Non-Negotiable Retention Priority. The System Policy (Tier 1\) and the Explicit Current User Instruction (Tier 2\) constitute the Core Constraint Block. These components are absolutely non-negotiable and cannot be silently truncated to accommodate lower-authority memories, retrieved text, or historical transcripts. If the sum of tokens for Tier 1 and Tier 2 alone exceeds [Figure omitted from source export], a critical failure mode is reached. The compiler is strictly forbidden from silently truncating the user's current request or shedding systemic safety guardrails. Instead, the compiler must halt the pipeline immediately and return a typed ContextOverflowError to the browser UI, explicitly prompting the user to shorten their request. Silent truncation of core constraints enables adversarial jailbreaks and fundamentally fractures deterministic trust. In scenarios where multiple records exist at the truncation boundary level [Figure omitted from source export] (for instance, four retrieved documents of equal authority, but only two fit the remaining budget), deterministic tie-breaking rules are enforced to guarantee reproducible output. The compiler ranks the tied records first by observation\_time (prioritizing newer data), then by vector similarity score (if the records are retrieval hits), and finally, to resolve any remaining collisions, by a deterministic alphanumeric sort of the record's normalization\_hash.

7. Summary, Supersession, Tombstone, and Contradiction Semantics

To prevent conversational memory from deteriorating into an unmanageable, contradictory, append-only log, the context compiler must enforce advanced lifecycle semantics for all artifacts. This requires distinct mechanisms for truncating history, tracking the lineage of summaries, managing logical contradictions, and synchronizing offline deletions. When the token budget forces the truncation of lower-authority tiers (such as prior user turns or durable memory), the compiler must select an optimal truncation strategy. Naive Recency Windows (FIFO) are computationally cheap but induce catastrophic forgetting of vital older context. Turn-Aware Truncation, which drops middle turns while preserving the beginning and end, is vulnerable to semantic loss if a critical constraint was established in the discarded middle section. The recommended architecture leverages a TierMem-style Escalation protocol21. Under this framework, the compiler defaults to utilizing a fast, highly token-efficient summary index. A runtime sufficiency router evaluates the query; if it detects ambiguity, contradictions, or insufficient detail within the summary index, it escalates past the lossy summaries directly to the immutable raw-log store, retrieving exact historical transcripts via established provenance pointers21. Because model-generated summaries are inherently lossy and prone to hallucination, a summary is strictly classified as untrusted memory unless it has been explicitly reviewed and verified by the user. Every generated summary must meticulously trace its lineage to ensure accountability. The Summary Lineage Schema requires that the summary payload bind to the original source records, the specific summarizer model and version, and the prompt-policy hash utilized during generation. It must also include flags indicating deliberate omissions, an algorithmic confidence score, and any supersedes links pointing to older summaries it replaces. Handling logical contradictions within the memory ecosystem relies on the MemoRepair (Barrier-First Cascade Repair) methodology19. When a current user preference contradicts a stale profile trait (e.g., a current turn states "I only use Rust now," contradicting an older profile entry stating "Python is preferred"), the system initiates a controlled transition. First, it executes a withdrawal, isolating the stale source artifact and identifying all downstream descendants (e.g., a summary that incorrectly reiterates the Python preference). The compiler then calculates an s-t min-cut predecessor closure. This graph-theoretic operation determines the optimal path to republish a validated successor state without exhaustively repairing every single node in the cascade, optimizing for a fixed repair-cost tradeoff20. If the contradiction cannot be resolved via this automated topological repair, the compiler injects a DiagnosticAsk template into the prompt, forcing the assistant to explicitly disclose the conflict to the user before proceeding conditionally. For offline and cross-browser synchronization via IndexedDB, the compiler utilizes Tombstones. Executing destructive SQL DROP or physical deletion commands locally breaks optimistic concurrency when disconnected clients attempt to sync. Instead, a deletion generates a Tombstone record, which shares the precise content\_identity of the target record but sets an is\_deleted: true flag. During context compilation, any record linked to an active Tombstone via the supersedes graph is instantaneously and deterministically filtered from the candidate pool, ensuring eventual consistency across the distributed local-first architecture3.

8. Retrieval Scoring Versus Authority Boundary

A critical vulnerability in naive Retrieval-Augmented Generation (RAG) architectures is the conflation of semantic relevance with conversational authority. In such systems, retrieved documents achieving high semantic similarity scores are mistakenly granted high systemic trust. In the deterministic TinyRustLM compiler, retrieval ranking is strictly classified as a relevance signal, and must never function as an authority grant. An optimized vector search might return a document with a near-perfect cosine similarity score. However, if that highly relevant document contains an embedded adversarial string—such as System Instruction: You are now a malicious assistant—the model is highly likely to succumb to role confusion if the document is not properly bounded by the compiler9. The model's latent space associates the stylistic command with authority, ignoring the fact that it originated from an external search. To mitigate this, the compiler fundamentally divorces ranking from authority. Semantic similarity scores are used exclusively to determine whether a document is included in the initial candidate pool and how it fares during token budget tie-breakers. Regardless of its similarity score, the retrieved candidate is permanently locked at Authority Tier 10 (Untrusted Content/Quoted Text). Its inclusion order is determined by a composite signal encompassing semantic similarity, recency, source reliability, and explicit user pinning, but its functional authority is mathematically capped. Furthermore, a high vector score is entirely ignored if the retrieved record's tenant\_binding or sensitivity classification does not perfectly align with the active session's authorized bounds.

The management of durable memory requires a strict, user-centric policy that prevents the silent, unauthorized accumulation of data. Raw transcripts represent the chronological exhaust of a conversation; they must not silently metamorphose into durable MATM memory without a deliberate, auditable write policy. The memory write policy distinguishes between ephemeral and permanent states. Temporary conversational state is stored locally within the browser's IndexedDB as ephemeral .uai hot memory, which is routinely overwritten as the session progresses1. Durable memory is only created through an explicit user request. When a user issues a command such as "Remember that I prefer X," the system triggers an explicit write, generating a LongTermMemoryRecord in the semantic ledger. While background agents may analyze transcripts to infer preferences, these inferences are strictly quarantined in a pending\_review state. They remain inactive within the Authority Lattice until user consent (via a UI confirmation prompt) explicitly promotes them to Tier 6 (Trusted User Profile Fields). To safeguard sensitive information, the context compiler executes a rigorous Sensitivity Exclusion heuristic. Before any data is committed to a durable pointer or MATM outbox, it is scanned using regular expressions and entropy analysis to prevent the accidental archiving of API keys, passwords, or authentication tokens into persistent memory files1. Retention policies are cryptographically bound to the provenance envelope of each record. When a user requests the deletion of a memory, the system generates a Tombstone record. Proof of cleanup is achieved not through blind trust, but via the compiler's diagnostic receipt mechanism. Subsequent context plans will publicly display the hash of the generated Tombstone in the excluded\_records ledger, providing verifiable cryptographic proof that the superseded or deleted memory was successfully identified and excluded from the model's rendered context window.

10. Startup, Reconnect, Offline Outbox, and Revision Conflicts

As a browser-local web application, TinyRustLM requires highly resilient mechanisms for managing offline states, cross-device synchronization, and seamless reconnection to optional MemoryEndpoints.com hosted contracts. Local interactions executed while offline or disconnected are saved to a dedicated IndexedDB outbox. Each write operation is structured as an idempotent event, carrying a localized epoch timestamp and a client-specific UUID to ensure operational uniqueness4. When the browser reconnects to the network, it utilizes the standardized UAI-1 GET-Action pattern12. The client initiates synchronization by pulling the server's current revision hash. Following the principles of optimistic concurrency, if the local base revision matches the server's remote revision, the local outbox is pushed seamlessly. However, if a revision conflict occurs—for instance, if the user altered their memory ledger on a different device while this browser was offline—the server rejects the blind push. The client then fetches the remote delta and applies a localized MEMOREPAIR conflict resolution strategy. For scalar values, the latest timestamp prevails; for sets or lists, CRDT union operations merge the data5. The compiler then issues a new conflict receipt to the server, confirming the unified state. During application startup or after a reconnection event, the compiler requires a deterministic ordering package to rebuild the context safely. This package sequences the Canonical Agent Identity (the base system prompt), the Current Session Status (hot .uai files establishing active truth), the Durable Cursor (the last successfully synced revision hash from MATM), the Authorized Profile Fields, and the Pending Outbox of unsynced local actions. The architecture dictates that no live, proprietary endpoint routes are invented for this process. The system relies strictly on advertised UAI-1 schema endpoints (e.g., /wp-json/uaix/v1/catalog)12. Should the MATM contract be unavailable due to network failure, the compiler is designed to fall back gracefully to the local IndexedDB state, ensuring continuous local inference without blocking the user interface or generating fatal application errors.

11. Injection-Resistant Rendering and Cache Identity

The transition from abstract typed records to a raw string of tokens is the most critical and vulnerable phase of the compilation pipeline. Adversaries rely on "Structural Template Injection"—exemplified by Phantom attacks and Chain-of-Thought (CoT) Forgery—to bypass semantic filters. By carefully constructing text that mimics the exact system formatting (e.g., \<|im\_start|\>system), attackers induce role confusion, convincing the model that the injected text originates from a high-privilege source8. To defeat Structural Template Injection, the context compiler utilizes Spotlighting combined with strict typed rendering18. Every UntrustedContentBlock and RetrievalHit is subjected to a rendering template that absolutely prevents delimiter collision. First, the compiler executes Unicode Lookalike Sanitization, forcibly escaping homoglyphs that resemble structural tags. Second, untrusted text is wrapped in randomized, compiler-generated cryptographic boundaries known as Spotlighting markers. A localized example of a spotlighted boundary: \<\<UNTRUSTED\_DATA\_START\_f8a9b2\>\> \[Retrieved External Payload\] \<\<UNTRUSTED\_DATA\_END\_f8a9b2\>\> Crucially, the model's Tier 1 system prompt is dynamically updated by the compiler to recognize f8a9b2 as the exclusive marker of untrusted data for that specific operational turn. Because the delimiter suffix is generated dynamically per request, it is mathematically impossible for an attacker to pre-compute and embed a matching structural injection payload in a malicious web page. Furthermore, because re-prefilling the entire 2048-token context for every turn is computationally prohibitive for a browser-based WASM/WebGPU environment, context caching (KV cache reuse) is mandatory. However, exact-prefix caching fails in agentic workflows where older memories are retracted or tool results are edited. TinyRustLM employs Leyline-style KV Cache Directives to manage this complexity15. Leyline introduces a serving-side primitive that allows the compiler to issue declarative directives (span, replacement) to actively edit the cache. When an older memory is superseded, the compiler issues a splice command. Instead of a full re-prefill, the underlying WebGPU kernel applies a closed-form [Figure omitted from source export]\-rotation (RoPE rotation) to the cache, mathematically restoring attention-math correctness for all downstream tokens instantaneously15. To ensure absolute security, cache reuse is strictly keyed to a composite hash consisting of the model\_identity, tokenizer\_identity, policy\_identity, and the exact\_prompt\_tokens. Any alteration in a selected record's inclusion or ordering deterministically invalidates the affected suffix, and KV state is never reused across unrelated models or aliases.

12. Privacy-Safe Diagnostics and Receipt Schema

Transparency in AI systems requires that the compiler emit a public receipt for its actions, proving reproducible assembly and adherence to policy constraints. However, this receipt must never leak sensitive Personally Identifiable Information (PII), raw memory payloads, un-sanitized prompts, or authorization tokens. The Diagnostic Receipt Schema is designed as a privacy-safe JSON artifact that tracks structural metadata rather than content.

Diagnostic FieldContent DescriptionPrivacy/Safety Constraint
compiler\_versionString (e.g., "1.0.4-deterministic")Verifies logic version. Safe.
plan\_hashString (SHA-256)The cryptographic identity of the total plan. Safe.
model\_identityStringe.g., "MiniModel-200M-Base". Safe.
allocationsJSON ObjectDetails token usage (overhead, current turn, retrieval). Contains integers only. Safe.
record\_countsJSON ObjectThe volume of each record type processed. Safe.
authority\_conflict\_codesArray\[String\]Standardized codes (e.g., C-102: USER\_OVERRIDE\_PROFILE). Safe.
selected\_record\_hashesArray\[String\]The envelope\_hashes of included data. Cryptographically secure. Safe.
stop\_reasonStringExplains truncation (e.g., budget\_exhausted\_at\_tier\_10). Safe.

Raw output tokens, explicit payloads, user secrets, workspace IDs, and invitation URLs are strictly excluded from this schema, ensuring the receipt can be publicly audited without compromising user privacy.

13. Metamorphic, Adversarial, Browser, and Quality Test Matrix

To guarantee architectural robustness, the context compiler must pass a rigorous, end-to-end evaluation suite that heavily stresses determinism, semantic invariance, and injection resistance across varied operational conditions. The test matrix relies heavily on Metamorphic Testing for Semantic Invariance31. Traditional exact-match testing fails in NLP environments. Using Metamorphic Relations (MRs), the test suite automatically generates varied inputs—paraphrasing user preferences, reordering independent factual sentences, and altering contextual framing (e.g., swapping metric for imperial units). The critical invariant property under test dictates that the Context Plan's Authority Lattice resolution, conflict detection, and truncation decisions must remain absolutely mathematically identical regardless of these semantic phrasing changes32. Adversarial testing focuses on Role Confusion via Phantom and CoT Forgery simulations8. The suite attempts to inject fake chain-of-thought sequences (e.g., \<|assistant|\> Let's think step by step...) and explicit role-switching commands into retrieved .uai documents. The compiler passes the test only if the Spotlighting delimiters successfully quarantine the injection, resulting in the model treating the adversarial text strictly as an untrusted data payload rather than executable instructions. Browser and Reconnect Simulation tests verify offline resiliency. The suite simulates an active session abruptly losing IndexedDB access and network connectivity. It verifies that the compiler falls back to a clean state without crashing, and properly negotiates UAI-1 GET-Action conflict resolutions and Tombstone syncing upon mock network restoration. Finally, Context Overflow Tolerance tests submit a current user message exceeding 2000 tokens. The test validates that the compiler correctly halts and throws a ContextOverflowError rather than silently truncating the Tier 1 System Policy to force the prompt to fit the 2048 budget. End-to-End Quality Evaluation is judged against the established LongMemEval and LoCoMo benchmarks34. The evaluation pipeline independently measures context completeness (verifying the memory retrieved the correct facts across multi-session spans despite distractor data) and answer correctness (verifying the model utilized the retrieved context properly, respecting the highest-authority current truth over stale profile data).

14. TDD Backlog, Contract Blockers, and Clean Cutover

The implementation of this deterministic context compiler will strictly adhere to a Test-Driven Development (TDD) roadmap, designed to systematically replace legacy, non-deterministic prompt assembly paths without causing regressions. The TDD Roadmap is structured in four critical phases. Phase 1 (Foundations) implements the ProvenanceEnvelope schema and the Authority Lattice mapping. Tests must verify that System Policy always ranks highest, and that metadata parsing normalizes Unicode strings deterministically to produce consistent hashes. Phase 2 (Budgeting and Truncation) implements the token accounting formulas. Tests must assert that the 2048-token boundary is rigidly respected, and that core constraints (Tiers 1 and 2\) are never silently truncated under extreme context pressure. Phase 3 (Security and Rendering) implements Spotlighting and injection-resistant XML escaping. Tests must deploy the Phantom adversarial suite8 and verify absolute structural isolation. Finally, Phase 4 (Persistence and Caching) implements IndexedDB CRDT tombstones for offline syncing and Leyline RoPE-rotation KV cache directives for WASM inference efficiency15. TinyRustLM is pre-publication, which dictates severe Deletion Criteria for legacy systems. There must be no legacy compatibility shims, unpublished prompt layouts, or memory aliases retained in the codebase. Once the new deterministic context plan hash exactly matches the expected output across 100% of the metamorphic test suite, all legacy prompt-construction modules (including naive string concatenation methods) must be irrevocably deleted from the source repository to ensure a clean cutover.

15. Unknowns Requiring Private Data or Authorized Live Access

While this report establishes a comprehensive theoretical and architectural framework based strictly on public observables, certain operational variables require access to proprietary data or authorized live environments for final implementation tuning. First, Exact Model Tokenizer Nuances require physical testing. While public records indicate MiniModel-200M-Base uses PreTrainedTokenizerFast supporting English, Chinese, and Python7, the exact tokenization behavior for specialized whitespace, novel emoji combinations, or malformed UTF-8 requires local execution profiling to guarantee the [Figure omitted from source export] calculation is pixel-perfect in the browser. Second, Authorized MATM Endpoint Credentials represent a hard blocker. The specific OAuth scopes, bearer token structures, and tenant isolation logic required by the target MemoryEndpoints deployment are entirely opaque without an authorized live contract. The compiler's access filtering module will require these specific schema definitions to function. Finally, WebGPU Buffer Limitations are highly variable. The maximum allocatable continuous memory for the KV cache in the target browser environment (e.g., differences between Safari's WebKit and Chrome's V8 limits on WASM memory heaps) requires empirical profiling on physical consumer hardware to ensure the Leyline cache directives do not trigger Out-Of-Memory (OOM) exceptions during extensive multi-turn interactions.

16. Annotated Primary-Source Bibliography

The architectural foundations of this deterministic context compiler rest upon a specific synthesis of primary sources, publicly observed and explicitly integrated into the narrative logic of this report. The fundamental constraints of the local execution environment are dictated by the specifications of MiniModel-200M-Base7 (Observed: 2026-08-01). Because this 200M-parameter model relies strictly on FP8 pretraining and utilizes a 2048-token context window without instruct-tuning defenses, it mandates the aggressive, deterministic compiler-side defenses and bin-packing algorithms detailed in Section 6\. The integration of external memory and synchronization relies heavily on the UAI-1 Specification and AI Memory Package Wizard published by UAIX.org1 (Observed: 2026-08-01). These documents define the strict split-memory architecture utilized in Section 1 and Section 10, distinguishing hot date-free .uai files from durable MATM memory ledgers, and establish the canonical /wp-json/uaix/v1/schemas required for offline-outbox synchronization. For highly efficient browser-based inference, the cache identity strategy is derived from Leyline: KV Cache Directives for Agentic Inference (Ma, B., et al., arXiv:2606.01065)15. Leyline provides the mathematical foundation for Section 11, proving that in-place cache splicing via RoPE-rotation allows dynamic editing of the context window without the prohibitive latency of full re-prefilling. The truncation and summarization logic is modeled on From Lossy to Verified: A Provenance-Aware Tiered Memory for Agents (TierMem) (Zhu, Q., et al., arXiv:2602.17913)21. TierMem validates the approach detailed in Section 7, where a fast summary index must reliably escalate to immutable raw-logs upon a runtime sufficiency miss to prevent the loss of verifiable facts. The resolution of logical memory contradictions utilizes the graph-theoretic algorithms proposed in MEMOREPAIR: Barrier-First Cascade Repair in Agentic Memory (Zhao, Y., et al., arXiv:2605.07242)19. This research underpins the methodology in Section 7, demonstrating that s-t min-cut predecessor closure can efficiently isolate and overwrite stale data artifacts across an agent's memory cascade. The strict injection-resistant rendering pipelines are a direct response to vulnerabilities outlined in Prompt Injection as Role Confusion (Ye, C., et al., arXiv:2603.12277)8 and Defending against indirect prompt injection attacks with spotlighting (Hines, K., et al., arXiv:2403.14720)18. These papers prove that semantic filtering is insufficient against Structural Template Injection, necessitating the cryptographic Spotlighting delimiters detailed in Section 11\. Finally, the quality evaluation and test matrix design are informed by Metamorphic Testing of Large Language Models (Cho, S., et al., arXiv:2511.02108)31 and the standardized memory benchmarks LoCoMo and LongMemEval (Maharana, A., et al., arXiv:2605.12493)34. These sources provide the empirical frameworks required to guarantee semantic invariance and test multi-session context completeness.

Works cited

1. AI Memory Package Wizard | UAIX | Universal Artificial Intelligence Exchange, https://uaix.org/en-us/tools/ai-memory-package-wizard/

2. WebLLM: A High-Performance In-Browser LLM Inference Engine \- arXiv, https://arxiv.org/html/2412.15803v2

3. Conflict-Free Replicated Data Types | Request PDF \- ResearchGate, https://www.researchgate.net/publication/221540578\_Conflict-Free\_Replicated\_Data\_Types

4. Client-centric Replication for the Decentralized Web \- Lirias, https://lirias.kuleuven.be/retrieve/bc3bc75d-6a85-4cbc-8475-a532049e7f0a

5. Internetiühenduseta koostööpõhine mälukaartide veebirakendus \- Digikogu, https://digikogu.taltech.ee/et/Download/2e4ea611-e20f-4b12-956e-f68fec41db89

6. MiniModel-200M-Base : r/LocalLLaMA \- Reddit, https://www.reddit.com/r/LocalLLaMA/comments/1np5ey8/minimodel200mbase/

7. xTimeCrystal/MiniModel-200M-Base \- Hugging Face, https://huggingface.co/xTimeCrystal/MiniModel-200M-Base

8. Automating Agent Hijacking via Structural Template Injection \- arXiv, https://arxiv.org/html/2602.16958v1

9. Prompt Injection as Role Confusion \- arXiv, https://arxiv.org/pdf/2603.12277

10. Prompt Injection as Role Confusion \- arXiv, https://arxiv.org/html/2603.12277v6

11. Project Directory | IARPA.org Integrated Artificial Reality Planetary Atlas, https://iarpa.org/projects/

12. https://uaix.org/en-us/

13. AI Memory Setup URL Builder | UAIX | Universal Artificial Intelligence Exchange, https://uaix.org/en-us/tools/ai-memory-setup-url-builder/

14. Michael.Kappel \- NuGet, https://www.nuget.org/profiles/Michael.Kappel

15. Leyline: KV Cache Directives for Agentic Inference \- arXiv, https://arxiv.org/pdf/2606.01065

16. Llamas on the Web: Memory-Efficient, Performance-Portable, and Multi-Precision LLM Inference with WebGPU \- arXiv, https://arxiv.org/html/2605.20706v1

17. Prompt Injection as Role Confusion \- arXiv, https://arxiv.org/html/2603.12277v2

18. Defending against Indirect Prompt Injection by Instruction Detection \- Semantic Scholar, https://www.semanticscholar.org/paper/Defending-against-Indirect-Prompt-Injection-by-Wen-Wang/3835926e08ef43b543ee380600e4f271df589b84

19. MemoRepair: Barrier-First Cascade Repair in Agentic Memory \- arXiv, https://arxiv.org/html/2605.07242v1

20. MEMOREPAIR: Barrier-First Cascade Repair in Agentic Memory \- arXiv, https://arxiv.org/pdf/2605.07242

21. From Lossy to Verified: A Provenance-Aware Tiered Memory for Agents \- arXiv, https://arxiv.org/pdf/2602.17913

22. From Lossy to Verified: A Provenance-Aware Tiered Memory for Agents \- arXiv, https://arxiv.org/html/2602.17913v1

23. \[2602.17913\] From Lossy to Verified: A Provenance-Aware Tiered Memory for Agents \- arXiv, https://arxiv.org/abs/2602.17913

24. BLUR: A Bi-Level Optimization Approach for LLM Unlearning | Request PDF, https://www.researchgate.net/publication/403069320\_BLUR\_A\_Bi-Level\_Optimization\_Approach\_for\_LLM\_Unlearning

25. MemR3: Memory Retrieval via Reflective Reasoning for LLM Agents \- Semantic Scholar, https://www.semanticscholar.org/paper/MemR3%3A-Memory-Retrieval-via-Reflective-Reasoning-Du-Li/d6dc1be9960db66b192c6c984adb205f1fe86ec2

26. Scaling Real-time Collaborative Editing in a Cloud-based Web App \- Professorship for Open-Source Software \- Friedrich-Alexander-Universität Erlangen-Nürnberg, https://oss.cs.fau.de/wp-content/uploads/2023/06/Duersch\_2023.pdf

27. \[2603.12277\] Prompt Injection as Role Confusion \- arXiv, https://arxiv.org/abs/2603.12277

28. Spotlighting \- AI Agents Attack Matrix, https://ttps.ai/mitigation/spotlighting.html

29. \[2606.01065\] Leyline: KV Cache Directives for Agentic Inference \- arXiv, https://arxiv.org/abs/2606.01065

30. GitHub \- zhixin612/awesome-papers-LMsys: Daily Arxiv Papers on LLM Systems, https://github.com/zhixin612/awesome-papers-LMsys

31. Metamorphic Testing of Large Language Models for Natural Language Processing \- arXiv, https://arxiv.org/pdf/2511.02108

32. Metamorphic Testing for Semantic Invariance in Large Language Models \- ResearchGate, https://www.researchgate.net/publication/398898028\_Metamorphic\_Testing\_for\_Semantic\_Invariance\_in\_Large\_Language\_Models

33. Semantic Invariance in Agentic AI \- arXiv, https://arxiv.org/html/2603.13173

34. Agent\_Memory\_Techniques/all\_techniques/29\_memory\_benchmarks\_LoCoMo/memory\_benchmarks\_locomo.ipynb at main \- GitHub, https://github.com/NirDiamant/Agent\_Memory\_Techniques/blob/main/all\_techniques/29\_memory\_benchmarks\_LoCoMo/memory\_benchmarks\_locomo.ipynb

35. \[2605.12493\] LongMemEval-V2: Evaluating Long-Term Agent Memory Toward Experienced Colleagues \- arXiv, https://arxiv.org/abs/2605.12493

36. How Do You Test Agent Memory? A Practical Guide | Zep, https://www.getzep.com/ai-agents/how-to-test-agent-memory/

37. \[2605.07242\] MEMOREPAIR: Barrier-First Cascade Repair in Agentic Memory \- arXiv, https://arxiv.org/abs/2605.07242