Architectural standards, schemas, and production patterns.
A collection of 35 verified patterns from enterprise systems, agent orchestration, and high-accuracy retrieval pipelines. Formatted for systems engineers and AI crawlers.
All 35 entries have matching raw Markdown specs in llms.txt
Showing 35 of 35 resources
Retrieval & PipelinesPython 3.11
Enterprise RAG Hygiene & Verification
Eliminating tabular data hallucinations in financial and regulatory documents through Markdown ingestion and deterministic regex assertions.
The Problem
Flattening tabular data into raw text strings causes language models to misassociate headers and hallucinate metrics when retrieving complex financial or regulatory documents.
Production Rule
Extract tables directly as Markdown tables or structured JSON. Enforce an automated regex-based verification step between context retrieval and final generation to flag unsupported numbers.
The 8 Production RAG Architectures & Level 7 Ingestion
Systematic breakdown of Naive, Multimodal, HyDE, Corrective (CRAG), Graph, Hybrid, Adaptive, and Agentic RAG tiers, and when to stop at Level 4.
The Problem
Defaulting to agentic ReAct loops for every retrieval query causes severe cost inflation (500 to 5,000+ tokens) and 15-30s latencies where simple vector or hybrid search suffices.
Production Rule
Match retrieval architecture to query complexity. Reserve Agentic RAG for multi-step reasoning across decoupled systems. Use data normalization and content hashes for idempotent processing.
rag_decision_matrix.md
| Architecture | Core Mechanism | Use Case |
|---|---|---|
| Naive RAG | Query -> embed -> vector DB -> LLM | Single-turn Q&A, clean homogeneous docs |
| Multimodal RAG | Shared embedding space text/images | Visual charts, scanned PDFs |
| HyDE | LLM generates hypothetical doc first | Vocabulary mismatch between user & corpus |
| Corrective (CRAG) | Evaluates retrieved docs; web fallback | High precision; internal data has gaps |
| Graph RAG | Entity relationship graph | Entity connections (legal, corporate structures) |
| Hybrid RAG | Vector + keyword (BM25) | Exact terminology AND semantic meaning |
| Adaptive RAG | Query analyzer routes retrieval mode | Diverse user question patterns |
| Agentic RAG | Multi-agent ReAct cycles with memory | Multi-step cross-system investigations |
Retrieval & PipelinesData Ingestion
High-Precision PDF Extraction without OCR Artifacts
Converting complex documents into clean markdown tables while preserving column alignment and eliminating PDF control characters.
The Problem
Standard PDF parsers output unformatted strings that strip column groupings, creating broken tables and numeric errors in downstream vector retrieval.
Production Rule
Use specialized structural parsers that output native Markdown tables. Tag chunks with source, date, author, and content hashes at ingest for idempotent pipeline updates.
ingest_pdf_markdown.py
from llama_parse import LlamaParse
parser = LlamaParse(
result_type="markdown",
verbose=True,
language="en",
split_by_page=True,
)
# Returns page chunks formatted strictly as markdown with preserved tables
documents = parser.load_data("financial_report.pdf")
for doc in documents:
assert "| --- |" in doc.text or len(doc.text) < 100 # Verify tabular preservation
Retrieval & PipelinesModel Architecture
Sparse Attention & Efficiency in Long-Context LLMs
Understanding O(N^2) memory bottlenecks in 1M+ token windows and selecting subquadratic architectures for enterprise ingestion.
The Problem
Standard quadratic self-attention scales quadratically with context length, creating prohibitive GPU VRAM costs and latency degradation during large-document processing.
Production Rule
Evaluate subquadratic attention layers (such as state-space models and block-sparse attention) when building high-throughput document processing pipelines exceeding 128k context.
attention_complexity.md
Full Self-Attention: O(N^2) time & memory
Block-Sparse / Subquadratic: O(N * sqrt(N)) or O(N log N)
State-Space / Recurrent Models: O(N) linear time during inference
Pipeline guideline:
1. Use 1M+ token context windows for low-frequency synthesis tasks.
2. Use chunked vector index + reranking for high-concurrency Q&A to avoid quadratic VRAM spikes.
Retrieval & PipelinesArchitecture Pattern
Long Context vs Vector Retrieval: The Production Trade-off
Balancing raw context window brute-forcing against chunked vector retrieval based on query latency, token budgets, and cache hit rates.
The Problem
Dumping complete multi-megabyte documents into raw context windows costs significant token spend and introduces attention degradation ('needle-in-a-haystack' drop-off) in middle tokens.
Production Rule
Combine prompt caching with targeted retrieval. Use vector or hybrid search to retrieve relevant chapters, then feed structured sections into the cached model prompt.
hybrid_context_strategy.md
Production Heuristic:
1. File size < 50 pages: Direct prompt with prompt caching enabled (90% cost reduction on subsequent calls).
2. File size > 50 pages: Hybrid search (BM25 + Dense Vector) -> Top 10 chunks -> Re-ranker -> Filtered context window.
3. Tabular / Structured: SQL extraction first, never raw context dumping.
Retrieval & PipelinesEvaluation Suite
Enterprise Research Model Evaluation Framework
Benchmarking commercial and open-weight models across government policy corpora with deterministic factual assertions.
The Problem
Comparing language models using qualitative chat impressions fails to catch subtle hallucinations, reasoning drift, and citation errors.
Production Rule
Build an automated evaluation suite with at least 50 golden question-answer pairs. Score candidate models on schema validity, source attribution, and numeric faithfulness.
eval_framework.py
def evaluate_model_turn(prediction: str, golden_record: dict) -> dict:
has_valid_citations = all(c in prediction for c in golden_record['expected_citations'])
exact_match_score = 1.0 if golden_record['target_answer'] in prediction else 0.0
return {
'citation_precision': 1.0 if has_valid_citations else 0.0,
'exact_match': exact_match_score,
'passed': has_valid_citations and (exact_match_score > 0.8)
}
Agent OrchestrationTool Schema
Autonomous Agents: Terminal Execution over Vector DBs
Providing autonomous coding and data agents with native shell execution environments rather than fragmented text embeddings.
The Problem
Treating codebases as vector chunks floods agent contexts with fragmented snippets. Agents cannot inspect file trees or verify that generated changes pass tests.
Production Rule
Provide autonomous agents with an isolated terminal execution container. Equip the agent with direct shell commands (inspection, execution, diffing) rather than passive text search.
agent_terminal_tool.json
{
"name": "execute_command",
"description": "Run a shell command inside the sandboxed container. Returns stdout and stderr.",
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The exact shell command line string to run."
},
"timeout_seconds": {
"type": "integer",
"default": 30,
"description": "Maximum execution duration before process cancellation."
}
},
"required": ["command"]
}
}
How autonomous agents discover services, prove machine identity, exchange tokens, and call APIs without human captchas.
The Problem
Traditional SaaS onboarding relies on interactive browser forms, captchas, and manual credit card inputs, preventing autonomous agents from consuming services independently.
Production Rule
Implement machine-readable discovery files (auth.md) and scoped service tokens. Structure agent systems across five explicit layers: Runtime, Tools, Context, Feedback Loops, and Human Review.
agent_harness_architecture.md
The 5 Layers of Autonomous Agent Systems:
1. Runtime: Sandboxed container, execution permissions, scoped credentials.
2. Tools: MCP servers, database connectors, issue tracker APIs.
3. Context: Codebase index, PRDs, database schemas, persistent rules.
4. Feedback Loops: Automated linting, test runners, assertion gates.
5. Human Review: Strategic intent check and production deployment sign-off.
Architecting local and browser-native agents using declarative SOUL.md rules, skill directories, and step-by-step task decomposition.
The Problem
Single monolithic prompts fail on multi-tab web workflows like automated invoice extraction, competitive research, and calendar alignment.
Production Rule
Break complex workflows into subtask queues. Maintain agent state in a declarative SOUL.md file and load specialized tool skills only when triggered.
soul_configuration_sample.md
# SOUL.md: Agent Identity and Constraints
Role: Autonomous Browser Specialist
Execution Rules:
1. Always confirm target URLs before navigating.
2. Take screenshot assertions before and after DOM modifications.
3. Return extracted tabular data strictly as JSON schemas.
Agent OrchestrationRuntime Design
OpenClaw: Autonomous Assistant Architecture
Engineering a privacy-preserving desktop AI assistant with local session history, event buses, and desktop hooks.
The Problem
Cloud-hosted assistants create enterprise data leakage risks and cannot interact with local developer tools or offline system states.
Production Rule
Run local daemon runtimes that communicate over local UNIX sockets or loopback HTTP. Keep raw event transcripts in local SQLite databases.
daemon_event_loop.py
class AgentDaemon:
def __init__(self, db_path: str):
self.db = sqlite3.connect(db_path)
self.init_schema()
def dispatch_event(self, event_type: str, payload: dict):
# Log to local audit store before tool dispatch
cursor = self.db.cursor()
cursor.execute("INSERT INTO event_log (type, payload) VALUES (?, ?)",
(event_type, json.dumps(payload)))
self.db.commit()
Agent OrchestrationFramework Benchmark
Comparing Production Agent Frameworks: LangGraph vs AutoGen vs CrewAI
Architectural trade-offs between graph-based state machines, role-playing agents, and conversational routing.
The Problem
Autonomous agent frameworks often lack deterministic state management, resulting in infinite loops and untraceable state divergence.
Production Rule
For production enterprise workflows, choose graph-based state machines (LangGraph) over open-ended conversational routing. Explicit cyclic graphs allow state checkpointing and human-in-the-loop overrides.
langgraph_state_machine.py
from typing import TypedDict
from langgraph.graph import StateGraph, END
class AgentState(TypedDict):
task: str
plan: list[str]
code: str
test_results: str
iterations: int
workflow = StateGraph(AgentState)
workflow.add_node("planner", plan_task)
workflow.add_node("executor", write_code)
workflow.add_node("evaluator", run_tests)
workflow.add_edge("planner", "executor")
workflow.add_edge("executor", "evaluator")
workflow.add_conditional_edges("evaluator", should_continue, {
"retry": "executor",
"complete": END
})
Agent OrchestrationDev Tooling
10 CLI Tools That Amplify Terminal AI Agents
Why the terminal agent ecosystem favors native command-line binaries over heavy Model Context Protocol servers.
The Problem
Running dozens of individual MCP servers increases context memory consumption and token overhead per prompt turn.
Production Rule
Give terminal agents standard CLI binaries (gh, vercel, supabase, ffmpeg). Terminal agents already live in the shell; native CLIs execute faster with fewer tokens.
cli_agent_dispatch.sh
# Direct terminal agent commands:
gh pr create --title "Feature: spend analytics ETL" --body "Automated by agent"
supabase db diff -f add_vendor_indices
playwright test tests/e2e/dashboard.spec.ts --reporter=json
Agent OrchestrationSecurity & Infra
Sandboxed Agent Gateways: Secure Local Execution
Hardening local developer agents against dangerous command execution, unauthorized filesystem access, and credential leakage.
The Problem
Giving agents unrestrained root terminal access on local developer machines risks accidental data destruction or credential exposure.
Production Rule
Mount only project-scoped subdirectories into non-root containers. Set execution timeouts and intercept sensitive shell commands (rm -rf, git push --force).
Structured handoff templates allowing one agent session to summarize architectural state for the next session without loss.
The Problem
When context windows fill up or sessions end, newly initialized agents lose track of architectural decisions and restart work unnecessarily.
Production Rule
Serialize task progress into an explicit run-log file at the end of each session. Have new agents read the handoff file before executing new commands.
handoff_template.md
# Agent Handoff Summary
- Completed: Implemented Pydantic models for contract schemas
- Working File: app/schemas/contract.py
- Failing Test: tests/test_validation.py::test_date_overlap
- Next Immediate Step: Update regex parser to handle Q3 fiscal year notation
- Git Branch: feature/contract-schemas
Agent OrchestrationAutonomous Research
Automated Experimentation Loops: The Autoresearch Pattern
Structuring autonomous trial-and-error loops where agents propose hypotheses, run benchmarks, and record parameter sweeps.
The Problem
Human engineers spend hours manually adjusting hyper-parameters, prompt phrases, and regex patterns to optimize accuracy.
Production Rule
Define an immutable evaluation function. Let the agent iterate over code variations, keeping only changes that score higher on the benchmark suite.
autoresearch_loop.py
best_score = baseline_evaluation()
for iteration in range(max_trials):
patch = agent.propose_improvement()
apply_patch(patch)
score = run_test_suite()
if score > best_score:
best_score = score
git_commit(f"Improved benchmark to {score}")
else:
git_revert()
Agent OrchestrationSystems Architecture
Production Task Decomposition: Multi-Agent Software Pipelines
Separating responsibilities across planner, builder, and critic agents to deliver multi-service web platforms without hallucinated specifications.
The Problem
Single-agent pipelines attempt to design, code, and test simultaneously, resulting in incomplete implementations and neglected edge cases.
Production Rule
Strictly separate Planner, Builder, and Critic agents. The Critic must have access to independent test suites and veto authority over deployments.
agent_decomposition.md
Agent 1 (Planner): Generates task specification and API interface definitions.
Agent 2 (Builder): Implements code matching the specification.
Agent 3 (Critic): Executes linter, type-checker, and automated tests. Rejects PR on any failure.
Agent OrchestrationIndustry Analysis
Direct Corpus Interaction: Agents Need a Terminal, Not Just a Vector DB
Why the industry is shifting from static embedding queries to active command execution against data repositories.
The Problem
Vector search treats repositories as passive text chunks, unable to query schemas, inspect metadata, or run SQL transformations.
Production Rule
Equip data agents with direct query terminals and database clients. Let them inspect catalog tables and test SQL queries iteratively before returning answers.
dci_concept.md
Vector Retrieval (Passive):
Query -> Top 5 document chunks -> Probabilistic text answer
Direct Corpus Interaction (Active):
Query -> Inspect database schema -> Generate SQL -> Execute query -> Validate output -> Answer with source proof
Context & ConfigTemplate
Declarative Context Management (Karpathy Method)
Maintaining repository-level declarative configuration files that eliminate clarification loops and drop coding error rates from 41% to 11%.
The Problem
Conversational chat prompting repeats basic project conventions each session and omits negative constraints, keeping error rates high across developer sessions.
Production Rule
Maintain a single declarative configuration file at the repository root. State the primary objective on line 1, specify explicit negative constraints, and log session state in a continuity run-log.
CLAUDE.md
# Project Overview
Goal: Production API service for real-time spend analytics and contract optimization.
# Tech Stack & Standards
- Language: Python 3.11
- Web: FastAPI + Pydantic v2
- Database: PostgreSQL with SQLAlchemy (async)
- Testing: pytest with pytest-asyncio
# Coding Conventions
- Use explicit type annotations for all function signatures.
- Prefer pure functions for business calculations.
- Store database models in `app/models/` and schemas in `app/schemas/`.
# Negative Constraints
- Never run unmigrated database queries against production.
- Do not add external dependencies without explicit user confirmation.
- Do not edit files inside `migrations/` directly.
Context & ConfigPrompt Engineering
The 12 Enterprise System Prompt Packs
A proven collection of structured prompt packs spanning technical architecture, schema extraction, business logic audits, and adversarial testing.
The Problem
Vague, conversational prompts produce generic answers with unpredictable output shapes and missing boundary checks.
Production Rule
Structure every system prompt using the strict sequence: Role -> Objective -> Context -> Constraints -> Output Schema. Include explicit negative rules.
system_prompt_structure.md
# SYSTEM ROLE
You are a Principal AI Systems Engineer specializing in high-throughput data pipelines.
# OBJECTIVE
Audit the provided Python ETL pipeline for concurrency bottlenecks and memory leaks.
# CONSTRAINTS
- Propose changes only in standard library Python or existing project dependencies.
- Do not modify database schema definitions.
- Return findings categorized strictly by Severity: High, Medium, Low.
# OUTPUT FORMAT
Return a valid JSON object matching the AuditReport schema.
Context & ConfigToken Economics
Token Efficiency & Context Budgeting Strategies
Cutting production token usage by 70% using prompt caching, stripped conversational padding, and aggressive system prompt compression.
The Problem
Unmanaged system prompts and conversational filler blow up LLM token budgets and drive up operational inference costs.
Production Rule
Structure static instructions at the beginning of the prompt to maximize cache hit rates (90% discount). Strip boilerplate greetings and conversational padding.
caching_ordering_rule.md
Prompt Assembly Sequence for Optimal Cache Hit:
1. Static System Rules (Cached - 90% cost savings)
2. Project Conventions & Schemas (Cached)
3. Retrieved Context Documents (Cached across multi-turn queries)
4. Dynamic User Request & Turn History (Uncached)
Context & ConfigDeveloper Workflow
Claude Code Fundamentals: Features + Tests Discipline
Turning vague feature requests into shippable code through Plan Mode, test-first specifications, and clarifying interview loops.
The Problem
Jumping directly into code generation from a short prompt causes agents to guess architectural trade-offs and build the wrong feature.
Production Rule
Force the agent into Plan Mode before code generation. Use clarifying questions to pin down edge cases, interfaces, and constraints before touching files.
features_and_tests_spec.md
Feature Specification Protocol:
1. Clarification: Ask 2-3 specific questions regarding UI/UX and database constraints.
2. Plan: Draft an implementation plan covering files to create, edit, and test.
3. Tests First: Write failing pytest / vitest cases capturing expected behavior.
4. Implementation: Write minimal code required to pass the test suite.
Context & ConfigShortcuts & Macros
Slash Commands for Deterministic Developer Workflows
Manually retyping multi-paragraph instructions for code reviews, architectural planning, and deep research wastes developer focus.
Production Rule
Encapsulate complex multi-step prompting strategies into slash command shortcuts. Use /plan for multi-step breakdowns and /grill-me to stress-test designs.
slash_command_patterns.md
/plan: Freeze code writing. Outline step-by-step implementation dependencies.
/grill-me: Interview the engineer with 3 tough questions before finalizing architecture.
/boost: Deploy multi-perspective verification agents across the code changes.
Context & ConfigSystem Prompts
Hermes Agent Prompt Cheatsheet & System Patterns
Core prompting conventions for guiding open-weight models (DeepSeek, GLM, Llama 3) through multi-tool execution pipelines.
The Problem
Open-weight models often struggle with tool-calling precision if prompt formats deviate from expected JSON or XML structures.
Production Rule
Wrap tool schemas in explicit XML boundaries with typed parameter examples. Require models to output thought reasoning before emitting tool calls.
hermes_tool_calling.xml
<tool_call>
<thought>Need to verify if table 'vendors' exists before running ETL.</thought>
<function_call name="execute_sql">
<parameter name="query">SELECT table_name FROM information_schema.tables WHERE table_schema='public';</parameter>
</function_call>
</tool_call>
Context & ConfigWorkflow Automation
Automating Context Injection across Workflows
Eliminating manual copy-pasting of context by scripting dynamic context injection directly into agent CLI sessions.
The Problem
Engineers lose productivity manually copying project background, user stories, and logs into chat windows.
Production Rule
Automate context ingestion via shell piping and CLI commands. Pre-load relevant context files dynamically into the agent runtime.
inject_context.sh
# Pipe git diff and active ticket directly into agent session:
(cat context/project_overview.md; git diff main) | claude "Review these changes for security vulnerabilities"
Context & ConfigPrompt Technique
The Interview-Then-Spar Prompting Pattern
A two-phase technique where the model first interviews the engineer to uncover hidden requirements, then aggressively pressure-tests the proposal.
The Problem
Standard LLM prompting produces sycophantic praise for flawed system designs instead of exposing architectural edge cases.
Production Rule
Instruct the model to act as a skeptic. Command it to interview you on trade-offs first, then challenge every assumption before approving the architecture.
spar_prompt.md
Do not answer immediately.
Ask me 3 penetrating questions about concurrency limits, failure recovery, and data isolation in this design.
Once I answer, point out the weakest assumption in my architecture.
Memory & StorageSQL DDL
Open Brain: Vendor-Agnostic Memory Architecture
Treating raw text as permanent relational records and vector embeddings as disposable derivatives, enabling zero-loss re-indexing.
The Problem
SaaS second-brain systems bind raw content directly to vendor-specific embedding models. Upgrading embedding models requires destructive re-architecting or lock-in.
Production Rule
Treat raw text as permanent and embeddings as disposable. Store raw notes in relational tables and vector embeddings in a secondary table linked by foreign keys, enabling zero-loss re-indexing.
schema_open_brain.sql
-- Source records: Permanent relational store
CREATE TABLE documents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL,
content TEXT NOT NULL,
source_url TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Embeddings store: Disposable and regeneratable
CREATE TABLE document_embeddings (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
document_id UUID REFERENCES documents(id) ON DELETE CASCADE,
chunk_index INT NOT NULL,
chunk_content TEXT NOT NULL,
embedding vector(1536),
embedding_model TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX ON document_embeddings USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);
Memory & StorageKnowledge Graph
Obsidian Link Graphs as Agent Memory Layers
Using interlinked markdown files as a zero-cost knowledge graph that allows terminal agents to traverse concept relationships.
The Problem
Embedding-based vector search retrieves chunks by semantic similarity, missing structured hierarchical relationships and conceptual links.
Production Rule
Let the agent read markdown links directly. The link graph in a well-curated vault serves as the retrieval index without requiring vector databases.
link_graph_query.sh
# Agent traverses backlinks directly:
grep -rn "\[\[Spend Analytics\]\]" vault/
# Agent follows concept threads through explicit relationships rather than fuzzy cosine distances
Memory & StorageSystem Review
Persistent AI Memory Systems: Comparative Breakdown
Comparing dedicated memory servers, graph-based local memory, and file-based state logs across multi-turn agent sessions.
The Problem
Agents reset to zero context between sessions, requiring users to repeatedly explain preferences and project architecture.
Production Rule
Select memory architecture based on scope. Use file-based logs for single projects; use decoupled vector/graph memory for cross-project enterprise agents.
memory_architecture_matrix.md
1. Ephemeral Memory: Context window turn history (lost on restart)
2. File-Based State: run-log.md / CLAUDE.md (zero cost, high persistence)
3. Graph Memory: Graphify / Neo4j (tracks entity relationships across sessions)
4. Vector Memory: pgvector / Mem0 (fuzzy semantic retrieval of past conversations)
Memory & StorageGraph Architecture
Graphify: Knowledge Graphs for 70x Token Reduction
Extracting entities and relationships into structured graphs so agents query specific entity trees with 70x fewer tokens than raw vector dumping.
The Problem
Vector search often pulls large redundant text chunks into the prompt, burning tokens and diluting context.
Production Rule
Extract structured entity relationships during ingestion. Let agents query specific relational subgraphs to drastically reduce context token spend.
graph_query_concept.md
Entity: Vendor_A
-> Contract: Software_License_2026 ($1.2M)
-> Owner: Dept_DOE
-> Status: Under Review
Querying the entity subgraph retrieves exact facts in 150 tokens vs 10,000 tokens of raw PDF chunks.
Memory & StorageRAG Engine
NotebookLM & Grounded PRD Blueprint Workflows
Using Google's NotebookLM to ingest raw requirement specifications and generate verified PRD blueprints for agentic coding execution.
The Problem
Handing raw, ambiguous requirement PDFs directly to autonomous coding agents leads to drifted implementations.
Production Rule
Ingest source documents into NotebookLM first to generate a 'Grounded Blueprint' with explicit citations. Pass that verified blueprint to coding agents.
grounded_workflow.md
Step 1: Ingest contract & RFP documents into NotebookLM.
Step 2: Generate Grounded Blueprint (functional specs + exact numbers + source citations).
Step 3: Feed Grounded Blueprint to Antigravity / Claude Code agent for implementation.
Memory & StorageData Architecture
PKM Strategy: Markdown vs HTML Second Brain Architecture
The trade-offs between pure markdown notes for future-proof portability and interactive HTML for dynamic enterprise dashboards.
The Problem
Markdown is static and cannot render interactive calculators or dynamic KPI filters; pure HTML is verbose and hard for agents to parse.
Production Rule
Adopt a hybrid architecture: plain Markdown for knowledge capture and reference specs; interactive HTML/JS for executive client dashboards.
hybrid_pkm_spec.md
Markdown Layer:
- Journaling, architectural field notes, reference specs
- Consumed by LLMs and terminal agents without layout noise
HTML/JS Layer:
- Interactive financial models, covenant calculators, executive KPI views
- Consumed by human stakeholders for decision-making
Memory & StorageLocal Database
SQLite Integration for Long-Term Agent Memory
Giving autonomous agents their own dedicated SQLite database to store structured facts, user preferences, and project states across sessions.
The Problem
Agents lack structured relational memory, leading to repeated queries and lost historical insights across multi-day tasks.
Production Rule
Equip coding agents with SQL read and write tools pointing to a local project database. Let the agent store findings in relational tables.
Deterministic Document Generation via Template Engines
Strict separation of concerns: language models output validated JSON schemas while template engines compile formal enterprise documents.
The Problem
Prompting models to write full formal documents (RFPs, legal contracts, executive summaries) introduces formatting volatility, missing disclosures, and unvalidated outputs.
Production Rule
Separate business logic from presentation. Restrict language models to structured JSON outputs conforming to strict Pydantic schemas. Use deterministic Jinja2 templates to compile final artifacts.
template_compiler.py
from pydantic import BaseModel, Field
from jinja2 import Template
class SectionContent(BaseModel):
title: str = Field(description="Section heading")
summary: str = Field(description="Executive summary in 2 sentences")
key_metrics: list[str] = Field(description="Bullet points with quantitative findings")
DOCUMENT_TEMPLATE = """
# {{ data.title }}
## Executive Summary
{{ data.summary }}
## Key Findings
{% for metric in data.key_metrics %}
- {{ metric }}
{% endfor %}
"""
def render_document(extracted_json: dict) -> str:
validated = SectionContent.model_validate(extracted_json)
template = Template(DOCUMENT_TEMPLATE)
return template.render(data=validated)
Document GenerationSkill Library
Curated Claude Code Skills & Starter Plugins
Production starter skill set: Frontend Design, Simplify (multi-agent review), Skill Creator, and Webapp Testing.
The Problem
Default coding models produce generic 'AI-slop' designs with clunky color schemes and unverified component layouts.
Production Rule
Install specialized review and design skills. Run an automated Simplify pass with multi-agent reviewers before committing any production code.
skills_manifest.md
Core Recommended Skills:
1. frontend-design: Enforces clean typographic hierarchy and removes AI-style gradients.
2. simplify: Spawns 3 review subagents to audit code complexity and redundant abstractions.
3. webapp-testing: Headless browser automation that clicks through and tests generated UI flows.
4. skill-creator: Converts validated multi-step terminal workflows into reusable agent skills.