Kanji
・Cloud engineer / freelance ・Born in 1993 ・From Ehime / Living in Shibuya, Tokyo ・5 years AWS experience Profile details
Table of Contents
In my daily workflow pairing with autonomous AI coding agents (Google Antigravity, Anthropic Claude Code, and AWS Kiro), the single most persistent bottleneck I repeatedly ran into was “the degradation of long-term memory and the compounding waste of context window tokens.”
Initially, like many developers, I assumed that simply introducing a local vector database such as LanceDB or Chroma—and letting the agent stash past decisions, incident notes, and terminal outputs into it—would solve the problem. However, once our knowledge base surpassed several hundred records, critical failure modes began emerging in real-world agent operations:
In this article, I walk through the complete architecture of our Gen 3 Long-Term Memory Hub designed to overcome these pitfalls: combining Git-managed Markdown SSOT (Single Source of Truth) with Hybrid GraphRAG (LanceDB + SQLite FTS5 Trigram BM25 + WikiLink CTE Graph Traversal + Local Cross-Encoder Reranking) .
Furthermore, I examine the mechanics of halving token consumption by maintaining system prompts and operational rules in English , while leveraging multilingual embeddings to orchestrate seamless bilingual retrieval from natural Japanese developer prompts, supported by empirical 554-chunk benchmarks on an Apple M5 Mac.
AI agent memory architectures have evolved through three distinct generations:
.md
memory_save
When agents write unstructured summaries directly to binary storage via internal APIs, developers cannot review those memories in Git diffs. Outdated workarounds and hallucinated parameters persist invisibly, continuously re-infecting subsequent coding loops with legacy bugs.
Vector similarity is suited for broad thematic proximity, but notoriously frail when dealing with strict technical identifiers like port: 30001 or AUTH_TIMEOUT_504 . Beyond 500 documents, semantic drift pulls hundreds of unrelated task logs to the top, pushing the real configuration file down below rank 20.
port: 30001
AUTH_TIMEOUT_504
Engineering knowledge is inherently relational. An outage post-mortem ( incident-passkey-timeout.md ) directly motivates a permanent design choice ( adr-port-lock.md ), which then dictates a strict system rule ( rule-auth.md ). Flat vector tables discard these graph edges entirely, leaving the agent blind to why a policy exists.
incident-passkey-timeout.md
adr-port-lock.md
rule-auth.md
Because Bi-Encoder vector similarity cannot guarantee strict relevance, developers routinely inject 10 to 15 raw chunks into the prompt. At 400 tokens per chunk, this consumes 4,000 to 6,000 tokens before work even begins, dramatically increasing API overhead while diluting the LLM’s focus on user instructions.
One of the most effective yet frequently overlooked optimizations in agent design lies in the language used for internal system prompts and operational rules: English-first authoring .
Modern LLM tokenizers (such as those used by Claude 3.5 Sonnet / Opus, GPT-4o, and Gemini 1.5 Pro) are built on Byte-Pair Encoding (BPE) vocabularies heavily skewed toward English phonemes and morphology.
[Comparative Tokenizer Efficiency: Japanese vs English] ● Japanese Formulation: 「エージェント長期記憶の運用ルールとナレッジ昇格ゲート」 ➔ ~28 characters / 22 to 26 tokens (0.8 to 1.5 tokens per character across kanji/hiragana) ● English Formulation: "Operational rules for Agent Memory Hub and knowledge promotion barrier" ➔ 74 characters / 11 tokens (1.1 to 1.2 tokens per whole word)
For identical semantic specifications and architectural guidelines, English representations require 40% to 55% fewer tokens than Japanese .
Rather than forcing users to prompt in English, we decouple human communication from internal agent memory:
┌─────────────────────────────────────────────────────────────┐ │ Human Developer (Japanese Chat) │ │ "Tell me the fix for passkey authentication timeout." │ └──────────────────────────────┬──────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ AI Agent Orchestrator │ │ - Output to User: Natural, polite Japanese │ │ - Internal Chain-of-Thought: English / Concise Japanese │ │ - Operational Rules & SSOT Docs: English (~50% token cut) │ └──────────────────────────────┬──────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Multilingual Embedding (multilingual-e5-small) │ │ Maps Japanese query to English ADR / Incident docs │ │ across language spaces with zero translation latency │ └─────────────────────────────────────────────────────────────┘
By deploying Xenova/multilingual-e5-small , a natural Japanese developer query reliably retrieves English ADRs and incident analyses with high cosine similarity. The agent reasons over concise English rules, and articulates its recommendations in natural Japanese, preserving the developer experience while slashing token costs by half.
Xenova/multilingual-e5-small
To overcome these structural hurdles, we engineered the following multi-tiered Gen 3 memory pipeline:
AND
UI
DB
PR
LIKE
Cosine similarities and BM25 scores operate on entirely different scales and cannot be combined via simple linear weighted averages. Instead, we use RRF based strictly on rank position:
R R F _ S c o r e ( d ) = 1 60 + R a n k v e c ( d ) + 1 60 + R a n k b m 25 ( d ) RRF\_Score(d) = \frac{1}{60 + Rank_{vec}(d)} + \frac{1}{60 + Rank_{bm25}(d)}
This algorithm guarantees that documents ranking high across both modalities—or holding a dominant #1 position in either—reliably surface in the top 15 candidate set.
From the top 15 candidates, SQLite’s recursive Common Table Expression (CTE) traverses the graph_edges table to identify directly linked documents:
graph_edges
WITH RECURSIVE graph_cte(source, target, depth) AS ( SELECT source_file, target_link, 1 FROM graph_edges WHERE source_file IN ('incident-20261014-passkey-timeout') UNION SELECT e.source_file, e.target_link, g.depth + 1 FROM graph_edges e JOIN graph_cte g ON e.source_file = g.target WHERE g.depth < 2 ) SELECT DISTINCT source, target, depth FROM graph_cte;
If an incident post-mortem contains a WikiLink [[adr-20261015-agent-memory-hub-gen3]] , the summary chunk of that ADR is automatically retrieved and merged into the candidate pool (measured latency: 0.19 ms).
[[adr-20261015-agent-memory-hub-gen3]]
All 15 to 20 candidate pairs (Query, Candidate Document) are fed into hotchpotch/japanese-reranker-xsmall-v2 (ONNX INT8 arm64, 37 MB). Unlike Bi-Encoders, the Cross-Encoder computes full cross-attention over query-document pairs, generating calibrated relevance probabilities between 0.0 and 1.0.
(Query, Candidate Document)
hotchpotch/japanese-reranker-xsmall-v2
Only the top 3 to 5 highest-scoring chunks are injected into the agent prompt.
A sophisticated memory system quickly degrades into digital clutter without an explicit barrier governing what gets committed:
┌─────────────────────────────────────────────────────────────┐ │ ① Ephemeral Scratch: brain/<conversation-id>/ │ │ - Agent thinking traces & terminal execution logs │ │ - Temporary debug scripts (/scratch/) │ │ - Disposable drafts (implementation_plan.md) │ └──────────────────────────────┬──────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ ② Knowledge Promotion Barrier (Session Completion / Review) │ │ [Evaluation Criteria] │ │ - Ephemeral working log? ➔ Discard upon session end │ │ - Permanent architecture decision? ➔ Promote to docs/adrs │ │ - Post-mortem prevention lesson? ➔ Promote to docs/incid. │ └──────────────────────────────┬──────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ ③ Permanent Markdown SSOT (Git-Managed Vault) │ │ - docs/adrs/adr-YYYYMMDD-xxx.md │ │ - docs/incidents/incident-YYYYMMDD-xxx.md │ │ - docs/rules/rule-xxx.md │ │ * Automatically indexed into SQLite & LanceDB on commit │ └─────────────────────────────────────────────────────────────┘
README.md
brain/<conversation-id>/
docs/adrs/
docs/incidents/
To validate production viability, we executed comprehensive benchmarks against 554 production chunks across historical ADRs, incident reports, and system rules on an Apple M5 Mac (32 GB unified memory).
Rules for promoting temporary scratch memory to long-term SSOT
rules/rule-agent-memory.md#1
agent-memory_JP.md#3
port 30001 passkey authentication
incidents/incident-20261014-passkey-timeout.md#2
WebAuthn passkey timeout root cause and permanent remediation
incidents/incident-20261014-passkey-timeout.md#0
DB schema and UI design
incident
adr
rule
bge-reranker-v2-m3
During initial prototyping, we evaluated bge-reranker-v2-m3 (588 MB), a popular multi-lingual reranking model. However, on our Apple M5 testbed, reranking 15 candidate chunks took 2,480 ms (nearly 2.5 seconds) while peak resident memory spiked to 2.6 GB .
In contrast, our production model hotchpotch/japanese-reranker-xsmall-v2 (ONNX INT8 arm64): - Model Footprint : 37 MB ( 1/15th the memory size ) - Inference Latency : 213 ms ( 11.6x faster ) - Resident Working Set : 648 MB
It demonstrated exceptional discriminative precision on technical bilingual text (reliably separating top candidates with scores above 0.7 from irrelevant noise), delivering interactive responsiveness without noticeable latency lag.
Discussions surrounding AI agent memory have all too often focused on superficial tooling debates—which vector database to pick. In production, however, three architectural foundations matter far more:
Adopting this Gen 3 architecture has allowed my coding agents to reliably build upon historical architecture decisions and incident lessons while slashing daily token costs.
Questions certainly remain—such as managing Cross-Encoder latency scaling across tens of thousands of chunks, and orchestrating conflict-free concurrent commits across multiple subagents. For engineers looking to push AI pair programming into true autonomous co-working, I hope these real-world findings serve as a dependable blueprint.
Get the complete configuration pack featured in this article: universal AGENTS.md, deterministic hooks.json, Git safety guardrails, and validation scripts tested across Antigravity, Kiro, Claude Code, and Codex.
Powered by the frontier LLM orchestration and automated pipelines featured on this blog. Daily quantitative scoring, macro signals, and market analytics.
Hands-on engineering advisory for AI coding agent standardization, hybrid LanceDB/SQLite memory hubs, and AWS / Google Cloud infrastructure modernization.