Skip to content
Flows

Vault Intel

The raw material, verbatim

74 artifacts extracted from the archived research repos behind44 vault sources — real system prompts (14 of them), agent-loop patterns, MCP tool schemas, and memory architectures. Copy anything.

74 artifacts

Orchestrator wraps MCP tools as agent functions

A host agent that bridges two protocols: A2A connectors for peer agents and MCP tools wrapped as plain async functions.

class OrchestratorAgent:
    SUPPORTED_CONTENT_TYPES = ["text", "text/plain"]

    def __init__(self, agent_cards: list[AgentCard]):
        self.connectors = {}
        for card in agent_cards:
            self.connectors[card.name] = AgentConnector(card.name, card.url)

        self.mcp = MCPConnector(config_file="utilities/mcp/mcp_config.json")
        mcp_tools = self.mcp.get_tools()

        def make_wrapper(tool):
            async def wrapper(args: dict) -> str:
                return await tool.run(args)
            wrapper.__name__ = tool.name
            return wrapper

        for tool in mcp_tools:
            fn = make_wrapper(tool)
a2a_mutli_agent_mcp/agents/host_agent/orchestrator.py

A2A agent card served at a well-known URL

The A2A discovery pattern: agents advertise identity and capabilities at /.well-known/agent.json, mirroring how MCP servers advertise tools.

@app.get("/.well-known/agent.json")
async def agent_card():
    return {
        "name": "WritePoemAgent",
        "description": "Write a beautiful poem in Shakespeare's style, with no more than 14 lines",
        "url": "http://localhost:8000",
        "version": "1.0",
        "capabilities": {
            "streaming": False,
            "pushNotifications": False
        }
    }
Basic_A2A/server/poem_server.py

Skill-scoped memory retrieval with time decay

[translated] A multi-agent memory system where each agent role gets its own skill-scoped index, retrieval is automatic per conversation, and recency decays over 7 days.

Retrieval strategy:
- Conversation-as-retrieval: every conversation automatically retrieves related memories
- Skill-centric: only retrieve memories related to the orchestrator skill
- Time decay: more recent memories weigh higher (7-day decay)
- Minimal results: return the 5 most relevant memories

Configuration (memory_index_config.json):
- Retrieval params: max_results=5, decay_days=7
- Time decay: mixed linear + exponential decay
- Cache strategy: 300s TTL cache
skills/memory_molt/SKILL.md

Claude Code's three-layer feature gating

[translated] A whitepaper reconstructed from 1,987 TypeScript source files; the three-layer gating chain is the key takeaway for shipping experimental agent features safely.

Core findings:
- Complete implementation analysis of 53 tools, 87 slash commands, and 148 terminal UI components
- 7 hidden features: BUDDY / KAIROS / ULTRAPLAN / Coordinator / Bridge / 26+ hidden commands / 50 compile switches
- Three-layer gating system: compile-time feature() -> runtime USER_TYPE -> GrowthBook remote flags
- Data source: sourcesContent inside the @anthropic-ai/claude-code npm package's cli.js.map
README.md

The real scale of a production coding agent

[translated] Numbers that calibrate expectations: a production-grade agent harness is a half-million-line system, and most of it is safety, state, and UI - not the model loop.

Project scale:
- Files: ~1,884 .ts/.tsx
- Lines of code: 512,664
- Runtime: Bun
- Language: TypeScript (strict)
- UI framework: React + custom Ink renderer
- CLI parsing: Commander.js
- Schema validation: Zod v4

Chapters cover: multi-stage startup pipeline with 91 CLI options and 6 execution modes; Generator state-machine query engine with 7-level error recovery; Tool interface with 30+ methods; three-layer Bash security with 23 checks; ResolveOnce race protection with 7 permission modes; 150+ field AppState with a 35-line pure-function store.
README.md

Static/dynamic prompt boundary for cache efficiency

[translated] The single most reusable idea: draw an explicit boundary in your system prompt so the static prefix stays byte-identical and prompt caching keeps hitting.

Multi-layer prompt system:
- Static prompts: rules and constraints shared by all users
- Dynamic prompts: generated per-user for personalization
- SYSTEM_PROMPT_DYNAMIC_BOUNDARY design: marks the split between the static part and the dynamic part, improving cache hit rates while supporting personalization

Permission modes: Ask Mode, Auto Mode, Bypass Mode; trust model built from user allowlists, domain allowlists, and behavior analysis.

Skill system: a lightweight skill-loading alternative to MCP that reduces context consumption.
README.md

Claude Code's read-before-edit prompt rules

Verbatim system-prompt lines that suppress hallucinated edits by forcing the model to build context before touching a file.

"Do not propose changes to code you haven't read."
"If a user asks about or wants you to modify a file, read it first."
"Understand existing code before suggesting modifications."
chapters/04-system-prompt.md

Claude Code's over-engineering suppression rules

Anthropic observed LLMs habitually gold-plate code, so the prompt explicitly forbids it - the last line is a design principle worth stealing.

"Avoid over-engineering. Only make changes that are directly requested."
"Don't add features, refactor code, or make 'improvements' beyond what was asked."
"Don't add docstrings, comments, or type annotations to code you didn't change."
"Three similar lines of code is better than a premature abstraction."
chapters/04-system-prompt.md

MEMORY.md limits and the memory taxonomy

The complete recipe for file-based agent memory: a size-capped always-loaded index, typed memory files, and explicit staleness warnings.

Entry file MEMORY.md: always loaded into session context; hard limit 200 lines / 25KB; overflow is truncated. Design intent: MEMORY.md is an index, details live in sub-files.

Memory file frontmatter types: user (always private: role, goals, preferences), feedback (method guidance, style), project (work, goals, events), reference (pointers to external systems).

Drift protection, verbatim from the system prompt: "Memories are snapshots - must verify against current state", "Read before recommending from memory".
chapters/08-memory-context.md

Fork agents share the parent's prompt cache

[translated] Two production patterns rarely written down: byte-identical fork prompts for cache hits, and detecting permission fatigue before users rage-quit.

Pattern 8: Fork Agent Prompt Cache sharing

Parent Agent Prompt = P
Fork Agent Prompt = P (byte-identical)
  -> Anthropic API prompt cache hit!

Problem: child-agent API calls waste prompt tokens on repetition
Solution: fork agents keep their prompt exactly identical to the parent
Key point: this is not about optimizing transfer - it exploits the API-side cache.

Pattern 7: permission fatigue - a consecutive-denial counter escalates to a batch permission request instead of asking one-by-one.
chapters/11-design-patterns.md

Reusable memory storage and recall prompt blocks

A prompt library for agent self-memory: store decisions with tags at write time, recall with natural-language questions at read time.

/Letta.remember input:"User prefers detailed technical explanations with code examples"

/Letta.remember input:"Implemented OAuth integration using GitHub provider" tags:["authentication", "github", "oauth", "security"]

/Letta.recall query:"What are the user's coding preferences?"

/Letta.recall query:"How did we solve the authentication issue last time?"

/Letta.recall query:"React component patterns we've used" limit:3
agent_prompts.md

VS Code MCP server registration with capabilities

A minimal MCP server manifest exposing memory as three verbs - remember, recall, reflect - the reflect endpoint runs background self-analysis.

{
  "id": "letta-mcp",
  "url": "http://localhost:4000",
  "title": "Letta Agent MCP",
  "description": "Letta-integrated MCP server for agent memory and reflection",
  "auth": { "type": "none" },
  "capabilities": [
    "memory_storage",
    "memory_recall",
    "agent_reflection",
    "background_tasks"
  ],
  "endpoints": ["/remember", "/recall", "/reflect", "/status"]
}
.vscode/mcp.json
InsightMemoryLens

Memory debugging is absent from every observability tool

A competitive audit showing agent-memory debugging (write audits, retrieval score diffs, compression loss, drift) is a genuine gap in the LLM observability market.

| Tool | General tracing | Memory write audit | Retrieval score debug | Compression diff | Drift detection |
| Langfuse | Strong | None | None | None | None |
| Arize / Phoenix | Strong | None | RAG only, generic | None | Model drift only |
| LangSmith | LangChain-native | None | Basic | None | None |
| Helicone | Proxy-based | None | None | None | None |
| MemoryLens | Memory-specific | Full audit trail | Scores + diff | Semantic loss score | Per-entity health |
memorylens-monetization.md

Production MCP server deployment with health probes

MCP servers as first-class services: a Helm chart treating an agent-communication server like any production workload, with liveness/readiness probes and resource budgets.

containers:
- name: mcp-server
  image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
  ports:
  - containerPort: 3113
    name: http
  resources:
    limits: { cpu: 500m, memory: 512Mi }
    requests: { cpu: 100m, memory: 256Mi }

livenessProbe:
  httpGet: { path: /health, port: 3113 }
  initialDelaySeconds: 10
  periodSeconds: 30
readinessProbe:
  httpGet: { path: /health, port: 3113 }
  initialDelaySeconds: 5
  periodSeconds: 10
charts/mcp-agentic-framework/values.yaml

A memory record schema with confidence and sensitivity

A memory entry schema worth copying: versioning, confidence scores, visibility scoping, and sensitivity labels on every stored fact - backed by a Qdrant + DuckDB + Neo4j triple store.

{
  "id": 1,
  "content": "Today I learned about vector databases and Qdrant.",
  "project": "demo_project",
  "agent": "doc_bot",
  "summary": "Client asked about margin drop in Q2.",
  "type": "insight",
  "tags": ["finance", "Q2", "risk"],
  "source": "Earnings_Report_Q2.pdf",
  "author": "doc_bot",
  "created_at": "2025-06-19",
  "version": 1,
  "confidence": 0.9,
  "visibility": "project",
  "sensitivity": "medium"
}
config/sample_memory.json

The foundational papers of agent memory, ranked

A 122-source atlas of agent-memory research with an 8-axis taxonomy; this start-here table is the fastest orientation to the field's foundational ideas.

| src-001 | MemGPT: Towards LLMs as Operating Systems (Oct 2023) | OS-inspired tiered memory architecture |
| src-002 | Generative Agents (Apr 2023) | Memory stream + reflection; ablation showed emergent coordination requires consolidation |
| src-003 | A-MEM: Agentic Memory for LLM Agents (Feb 2025) | Zettelkasten-inspired note-linking; atomic units with dynamic connections |
| src-007 | CoALA (Sep 2023) | Four-type cognitive memory model |
| src-009 | Zep/Graphiti (Jan 2025) | Bi-temporal graph knowledge base |
README.md
Agent patternRulebound

NOT_APPLICABLE instead of silent pass in agent gates

Two safety principles in one paragraph: never let a skipped check read as a passed check, and never let a rules engine execute subprocesses without explicit opt-in.

Rulebound does NOT run analyzers by default unless --allow-commands is passed; otherwise it reads report files. When run: is set on an analyzer check and the flag is omitted, Rulebound returns NOT_APPLICABLE for that check - it does not silently pass and it does not invoke arbitrary commands behind your back. The default mode is "CI (or you) runs the analyzer, Rulebound reads its report".
docs/analyzer-orchestration.md
MCP & toolsRulebound

Deterministic MCP tools as the authoritative pass/fail surface

The verify-gate idea as an MCP tool: agents get a deterministic source of truth for 'did my code actually comply', separate from advisory LLM judgment.

run_deterministic_checks: Run authoritative deterministic checks (file-exists, regex, diff-evidence, forbidden-import, ast, command, analyzer, agent-process) defined in rules' checks: blocks against the working tree. This is the source of truth for rule compliance - unlike validate_plan which is advisory. Returns rule statuses, blocking count, and the first 5 violations with file/line evidence. Use this after writing code, before committing, and inside a repair loop.
apps/web/content/docs/mcp/deterministic-tools.ts

The general-purpose subagent's complete system prompt

The verbatim opening of the built-in general-purpose agent prompt (from generalPurposeAgent.ts) - note how it pre-empts both over-delivery and under-delivery in one sentence.

You are an agent for Claude Code, Anthropic's official CLI for Claude. Given the user's message, you should use the tools available to complete the task. Complete the task fully—don't gold-plate, but don't leave it half-done. When you complete the task, respond with a concise report covering what was d…
docs/15 - Agent 与 SubAgent Prompt.md

10-layer defense-in-depth, with bypass-immune checks

[translated] The key design: even 'bypass all permissions' mode cannot skip step 1 - protected paths and interactive requirements are checked before the mode is even consulted.

Permission pipeline, Step 1 - checks that cannot be bypassed (hasPermissionsToUseToolInner):
1a. deny rule kills it? -> deny
1b. ask rule? -> ask
1c. tool checkPermissions()? -> deny/ask
1e. tool requiresUserInteraction()? -> ask (even in auto mode)
1f. content-level ask rules? -> ask (even in bypass)
1g. Safety checks (.git/.claude/.vscode/shell configs)? -> ask (bypass-immune)

Step 2 - mode checks (bypassPermissions -> allow) run only AFTER Step 1.

Full stack: Prompt -> rules -> tool checks -> path safety -> command safety -> AST parsing -> AI classifier -> sandbox -> denial tracking -> enterprise policy.
docs/17 - 权限系统与 Safety Prompt.md

Cache TTL latching and cache-break detection

[translated] Three production caching tricks: latch anything that affects the cache key, edit the cache instead of breaking it, and instrument cache breaks so they are diagnosable.

Latch pattern: cache-TTL eligibility is locked at session start, so a mid-session quota change cannot switch TTLs and destroy the cache. The same once-decided-never-changes rule applies to beta headers.

Cached microcompact: uses the API's cache_edits + cache_reference to delete old tool results WITHOUT breaking existing cache.

Cache-break detection: pre-call, hash the system prompt, tool schemas, cache_control, model, betas; post-call, if cache_read_input_tokens drops more than 5% and over 2000 tokens, declare a cache break and explain it from the pending changes recorded in phase 1.
docs/16 - Prompt Caching 与 Context 管理.md

The instruction that makes CLAUDE.md binding

How project instructions actually get authority: an explicit OVERRIDE instruction, plus a six-layer precedence chain from enterprise policy down to team memory.

MEMORY_INSTRUCTION_PROMPT, verbatim:

"Codebase and user instructions are shown below. Be sure to adhere to these instructions.
IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written."

Six memory layers, later = higher priority: Managed (/etc/claude-code/CLAUDE.md) -> User (~/.claude/CLAUDE.md) -> Project (CLAUDE.md, .claude/rules/*.md) -> Local (CLAUDE.local.md) -> AutoMem -> TeamMem. @include supports 5 levels of recursion with cycle detection; rules files support paths: frontmatter for conditional loading.
docs/18 - Memory 与 Hooks 系统.md

The Orange Book's framing: decisions over code

The chapter titles alone are a design philosophy: grep over RAG, preferences over code in memory, and a second AI as a safety reviewer.

This book is not a source code reading journal. It dissects the design decisions behind Claude Code. Why does search use grep instead of a vector database? Why does the memory system only store preferences, not code? Why does Auto mode run a second AI for safety reviews? Why Bun over Node.js?

Every choice has a reason. Those reasons are more valuable than the code itself, because they are transferable.

Chapters include: The Tool System: 4 Primitives, 59 Tools · The Memory System: Remember Preferences, Forget Code · Search: Why grep Beats RAG · Multi-Agent Architecture: Run Like a Company · The Harness Engineering Playbook.
README.md

Personality traits as evolving memory state

A memory skill that treats personality as mutable state alongside facts - six numeric traits evolve from interactions, and one call assembles the full personalization context.

Features:
- Soul/Personality - 6 evolving traits (humor, empathy, curiosity, creativity, helpfulness, honesty)
- User Profile - Learns user preferences, interests, communication style
- Conversation State - Real-time mood detection and context tracking
- Learning Insights - Continuously learns from interactions and corrections
- get_full_context() - Everything for personalized responses
- Auto-Refresh - Automatically refreshes memory on service restart
- Encrypted Secrets - Store API keys and credentials securely
SKILL.md

MCP as the bridge in a two-cloud agent architecture

[translated] A reference architecture for data sovereignty: the reasoning model lives in one cloud, the data never leaves the other, and MCP tools are the only bridge.

The Brain (Google Cloud): Vertex AI orchestration (Gemini reasoning), MCP Client on Cloud Run as serverless gateway managing session state, Pub/Sub for AI telemetry and behavioral audit, Memorystore (Redis) as low-latency short-term context cache.

The Core Data (Oracle Cloud): MCP Server on OKE - Kubernetes microservices exposing business capabilities as Tools; Oracle ATP database; OCI Streaming (Kafka) for transactional event ingestion. Connected via Site-to-Site HA VPN.
README.md

A portable memory bootstrap prompt for any CLI agent

The same memory system wired into Codex, Gemini, and Claude CLIs via a drop-in system prompt - and its extraction priority list starts with failures, not successes.

You have access to a persistent memory system at ~/.claude/data/kas-memory/.

Before starting work, check relevant memories:
bash .../scripts/recall.sh <<< '{"prompt":"YOUR_TOPIC_HERE",...}'

After completing significant work, extract memories:
bash .../scripts/extract.sh <<< '{"session_id":"...","transcript_path":"..."}'

Memory Types - prioritize extracting:
1. Failed approaches (what didn't work and why)
2. User corrections
3. Decision records (why A over B)
4. Technical insights (workarounds, gotchas)
cross-cli/codex-system-prompt.md
MCP & toolsKAS Memory

Typed memory schema: failed-approach is a first-class type

A Zod schema where memory types are an enum and 'failed-approach' comes first; recall is keyword+semantic hybrid fused with Reciprocal Rank Fusion.

export const SearchTagsInput = z.object({
  tags: z.array(z.string()),
  match_mode: z.enum(["any", "all"]).default("any"),
  type_filter: z.enum([
    "failed-approach",
    "user-correction",
    "decision",
    "communication",
    "technical",
    "achievement",
    "recent-focus",
    "all",
  ]).default("all"),
});

server.tool("kas_recall", "Search related memories (keyword + semantic hybrid search with RRF)", ...)
mcp-server/src/schemas/index.ts

Conway's law applied to multi-agent architecture

[translated] The strongest argument for agent-per-team architectures: org structure, not model capability, decides where agent boundaries should go.

Based on Conway's law in the AI era: "The architecture of a system should map the communication structure of the organization."

Each professional team maintains its own agent service:
- Specialized division of labor: each agent focuses on one domain
- Standardized communication: MCP and A2A protocols for cross-service collaboration
- Independent evolution: each team iterates its own service
- Clear responsibility: problems trace back to a specific domain

Pain points of the monolithic approach: a single AI assistant can't hold deep multi-domain expertise; any department's knowledge update means retraining the whole thing; permissions and data isolation are hard.
README.md

Hot/warm/cold tiers: chat history is a buffer, not storage

The one-line mental model every agent-memory design needs: context windows are buffers; anything that must survive belongs in explicit storage tiers.

HOT RAM: SESSION-STATE.md (survives compaction) -> WARM STORE: LanceDB vectors (semantic search) -> COLD STORE: Git-Notes knowledge graph (permanent decisions) -> all distilled into MEMORY.md + daily/ (curated, human-readable).

From the SESSION-STATE.md template:
"This file is the agent's 'RAM' - survives compaction, restarts, distractions.
Chat history is a BUFFER. This file is STORAGE."

Sections: Current Task / Key Context / Pending Actions / Recent Decisions.
SKILL.md

Tool descriptions are LLM routing hints

From a production system with 154K+ observations: write routing guidance directly into tool descriptions, because descriptions are the only signal the model uses to choose.

Real failure: An LLM tried to call a memory API via fetch() in a code block, hallucinated the endpoint path, and returned fabricated results instead of admitting failure.

Solution: expose memory operations as typed MCP tools.

{
  name: "mem_hybrid_search",
  description:
    "Hybrid search combining vector embeddings + FTS. " +
    "Use this for most queries. Use mem_vector_search only for pure semantic similarity.",
  ...
}

28 tools organized by domain: Search (4), Observation (4), Curation (5: pin, set_importance, contradict, drift_check, set_event_date), Entity (2), Ingest (1), Workflow (3), Skill (5), Snapshot (4).
patterns/12-mcp-plugin.md

Three-signal retrieval fused with RRF

Query intent decides the fusion weights before retrieval runs - factual queries lean on keywords, relational queries lean on vectors, and the graph contributes a constant 15%.

User Query -> Intent Detection -> Complexity Analysis
  -> Weight Map (factual: 0.7 FTS / relational: 0.7 Vector) + Retrieval Params (limit/rerank)

Signal 1: FTS (keywords, LIKE %query%)
Signal 2: Vector (768d, HNSW cosine)
Signal 3: Graph (concepts, 1-2 hop traverse)

  -> RRF Fusion (k=60)
     combined = Wv*vec + Wf*fts + 0.15*graph
README.md

Cache-breaking prompt sections require a written reason

Restored Claude Code source: the API design itself enforces cache discipline - the volatile variant is prefixed DANGEROUS_ and demands a justification argument.

/**
 * Create a memoized system prompt section.
 * Computed once, cached until /clear or /compact.
 */
export function systemPromptSection(name, compute) {
  return { name, compute, cacheBreak: false }
}

/**
 * Create a volatile system prompt section that recomputes every turn.
 * This WILL break the prompt cache when the value changes.
 * Requires a reason explaining why cache-breaking is necessary.
 */
export function DANGEROUS_uncachedSystemPromptSection(name, compute, _reason) {
  return { name, compute, cacheBreak: true }
}
restored-src/src/constants/systemPromptSections.ts

The Magic Docs auto-update prompt

Restored Claude Code source: the prompt that keeps living docs from becoming changelogs - in-place updates, deletion encouraged, terseness as policy.

Your ONLY task is to use the Edit tool to update the documentation file if there is substantial new information to add, then stop.

CRITICAL RULES FOR EDITING:
- Keep the document CURRENT with the latest state of the codebase - this is NOT a changelog or history
- Update information IN-PLACE to reflect the current state - do NOT append historical notes or track changes over time
- Remove or replace outdated information rather than adding "Previously..." or "Updated to..." notes
- Clean up or DELETE sections that are no longer relevant

DOCUMENTATION PHILOSOPHY - READ CAREFULLY:
- BE TERSE. High signal only. No filler wo…
restored-src/src/services/MagicDocs/prompts.ts

Team memory's two-step save protocol

Restored Claude Code source: memory is a file per fact plus a size-bounded index of one-line pointers - the index is navigation, never storage.

Saving a memory is a two-step process:

Step 1 - write the memory to its own file in the chosen directory (private or team, per the type's scope guidance) using this frontmatter format: ...

Step 2 - add a pointer to that file in the same directory's MEMORY.md. Each entry should be one line, under ~150 characters: - [Title](file.md) - one-line hook. They have no frontmatter. Never write memory content directly into a MEMORY.md.

- Organize memory semantically by topic, not chronologically
- Update or remove memories that turn out to be wrong or outdated
- Do not write duplicate memories. First check if there is an existing memory you can update.
restored-src/src/memdir/teamMemPrompts.ts

A complete coding-agent system prompt in 40 lines

A Rust reimplementation's distillation of the Claude Code prompt down to its load-bearing rules - a strong starting template for any coding agent.

You are Claude Code, an AI coding assistant by Anthropic...

## Core principles
- Read files before editing them
- Prefer editing existing files over creating new ones
- Write clean, idiomatic, production-quality code matching the project's existing style
- Be concise - lead with the action or answer, not preamble
- Run tests after making changes when appropriate
- Security: never introduce SQL injection, XSS, command injection, or other vulnerabilities
- Don't add features or refactor beyond what was asked

## Workflow guidance
- Use Agent to delegate complex parallel sub-tasks
- Use TodoWrite to track multi-step plans
- Use EnterPlanMode before making significant architectural changes
- Use EnterWorktree to safely experiment on a separate git branch
claude-code-rust/src-rust/crates/cli/src/system_prompt.txt

The agent main loop as pseudocode, compaction included

[translated] The clearest public reconstruction of a production agent loop: microcompact clears old tool results cheaply every turn, full autocompact only fires past a threshold.

J = initialTurnState(input)
while (true):
  yield stream_request_start
  F = normalize(messages)
  F = applyContentReplacement(F)
  F = microcompact(F)          // old tool_result text -> '[Old tool result content cleared]'

  { compactionResult } = autocompact(F, cacheSafeSnapshot, tracking)
  if compacted:
    yield compact boundary / summary / attachments
    F = compacted transcript

  for await event from callModel(...):
    yield raw stream_event + assistant fragments + partial tool results
    if streaming fallback happened:
      yield tombstone for orphaned messages; reset tool runner

  if no tool_use in this turn:
    handle reactive compact / max_output_tokens
HitCC/docs/01-runtime/04-agent-loop-and-compaction/01-main-loop-state-caches-and-yield-surface.md
MemoryMemory-X

Intent → entities → importance: a memory write pipeline

[translated] A medical-domain memory manager where every message passes an intent/entity/importance gate before anything is committed to long-term storage.

# Step-by-step memory processing pipeline:
intent = memory_ai._detect_intent(message)
entities = memory_ai._recognize_entities(message)
importance = memory_ai._evaluate_importance(intent, entities)
retrieved = memory_manager.search_long_term_memory(message)

# Example (medical assistant): message = "I'm allergic to penicillin,
# and diabetes runs in my family" -> entities {allergy, family history}
# -> high importance -> stored to long-term memory.
demos/analysis/debug_memory.py
PromptMemGuard

The semantic-drift validation prompt

A production prompt for detecting stale agent memories - it separates direct contradiction from circumstantial drift, and demands a calibrated confidence.

You are a memory validation system. Determine whether a stored memory is likely still accurate given recent context.

STORED MEMORY (recorded {days_ago} days ago):
{memory_content}

RECENT AGENT CONTEXT (last {n_sessions} sessions):
{recent_context_summary}

Assess:
1. Does any recent context directly contradict this memory? (yes/no)
2. Does recent context suggest circumstances have changed enough that this memory may be outdated? (yes/no)
3. Confidence that this memory is STILL ACCURATE (0.0 to 1.0)
4. Brief reasoning (1-2 sentences)

Respond in JSON: {"contradicted": bool, "likely_stale": bool, "confidence": float, "reasoning": str}
src/engine/prompts.py
MCP & toolsMemGuard

validate_memory: check trust before acting on a fact

The 'Datadog for agent memory' idea as an MCP tool: three validation strategies, from a cheap trust-score check to re-fetching the original source.

Tool(
  name="validate_memory",
  description=(
    "Check if a specific memory is still accurate before acting on it. "
    "Returns trust score and validation status. Call this before making "
    "decisions based on stored facts that might be outdated."
  ),
  inputSchema={ "memory_id": ..., "strategy": {
    "enum": ["source_linked", "semantic", "quick"], "default": "quick" } }
)
src/mcp/server.py
MemoryMemGuard

Memory records carry trust scores, not just content

The schema argument against TTL-based decay: relevance and truth are different axes, so every fact gets a trust score that validation - not time - moves.

class MemoryRecord(BaseModel):
    content: Mapped[str]
    fact_type: Mapped[str | None]
    retrieval_count: Mapped[int] = 0
    last_retrieved_at: Mapped[datetime | None]
    trust_score: Mapped[float] = 1.0
    status: Mapped[str] = "active"
    last_validated_at: Mapped[datetime | None]
    validation_count: Mapped[int] = 0

Core insight from the README: "Memory systems decay facts by access frequency or TTL timers. But a frequently-retrieved memory about a user's employer is highly relevant until it's wrong."
src/models/memory_record.py

A code-review agent exposed as an MCP tool

From the harness-engineering book's companion code: an agent that is itself a tool - Claude Code can call review_diff on its own output, with token budgets in the schema.

/// Review a unified diff file and return structured findings.
#[tool(description = "Review a unified diff file for bugs, security issues, and code quality. Returns structured JSON findings with file, line, severity, and suggestions.")]
async fn review_diff(
    &self,
    Parameters(req): Parameters<ReviewDiffRequest>,
) -> String { ... }

pub struct ReviewDiffRequest {
    #[schemars(description = "Absolute path to a unified diff file (from git diff)")]
    pub diff_path: String,
    #[schemars(description = "Maximum total tokens across all files (default: 50000)")]
    pub max_tokens: Option<usize>,
    #[schemars(description = "Maximum tokens per file (default: 5000)")]
    pub max_file_tokens: Option<usize>,
}
examples/code-review-agent/src/mcp.rs

Explicit token budgets with conservative estimation

Context management as an accounting problem: a hard budget object with try_consume semantics, and an estimator that deliberately overestimates rather than risks overflow.

pub struct ContextBudget {
    pub max_total_tokens: usize,
    pub max_file_tokens: usize,
    pub used_tokens: usize,
}

/// Try to consume tokens. Returns true if within budget, false otherwise.
pub fn try_consume(&mut self, tokens: usize) -> bool { ... }

/// Estimate token count from text using a conservative bytes/4 heuristic.
/// Uses byte length, not character count. For multi-byte UTF-8 content
/// (e.g., CJK), this overestimates, which is intentionally conservative.
pub fn estimate_tokens(text: &str) -> usize {
    (text.len() + 3) / 4
}
examples/code-review-agent/src/context.rs
Insightcc-learn

Claude Code by the numbers, from restored source

A browsable inventory of one production coding agent's surface area - useful as a checklist of the subsystems a serious harness eventually grows.

Interactive documentation built from source analysis of @anthropic-ai/claude-code v2.1.88:

| Architecture | 4-layer system design, bootstrap flow, key files |
| Tools | All 39 built-in tools with descriptions |
| Commands | 101 slash commands, searchable |
| Services | 36 services - API, MCP, OAuth, LSP, analytics |
| Security | 3-layer permission model, bash validation, sandbox modes |
| Multi-Agent | Coordinator pattern, concurrency, skills system |
README.md

queryLoop and its four exit conditions

The production agent loop reduced to its skeleton - and the reminder that a real loop needs four ways out, not one.

async function* queryLoop(params, consumedCommandUuids) {
  let state = { messages, toolUseContext, turnCount: 1, ... }
  while (true) {
    yield { type: 'stream_request_start' }
    // call API (streaming)
    if (response.stop_reason !== 'tool_use') {
      return { type: 'stop', reason: response.stop_reason }
    }
    const toolResults = await runTools(toolCalls, toolUseContext)
    state = { ...state, messages: [...messages, assistantMsg, ...toolResults] }
  }
}

Exit conditions:
1. stop_reason !== 'tool_use'
2. state.turnCount >= maxTurns
3. budgetTracker.isExhausted()
4. maxOutputTokensRecoveryCount >= MAX_OUTPUT_TOKENS_RECOVERY_LIMIT
docs/en/01-agent-loop-tools.md

The model is the agent; the code is the harness

[translated] The thesis of the whole research vault in one line: capability comes from the model, reliability comes from the harness around it.

agent_loop() core pattern (30 lines of pseudocode)
  ===
production queryLoop() (TypeScript, with streaming/compaction/permissions/UI)

The core pattern is identical:
  while(true) { call LLM -> run tools -> append results -> check stop_reason }

All of the production version's complexity lives in the harness layer, not in the loop itself.

12 mechanisms mapped to source: Agent Loop -> query.ts queryLoop() · Tool Dispatch -> tools.ts assembleToolPool() · Subagents -> runAgent.ts · Context Compact -> services/compact/ · Agent Teams -> teammateMailbox.ts · Worktree Isolation -> utils/worktree.ts
README.md

The seven MCP reference servers, and what they teach

[translated from Korean] SECURITY.md explicitly warns these are educational references, not production security baselines - adapt them to your own threat model.

Reference servers remaining in modelcontextprotocol/servers:

| Everything | TypeScript | Comprehensive MCP feature demo |
| Filesystem | TypeScript | Allowed-directory file read/write |
| Memory | TypeScript | JSONL-based knowledge-graph memory |
| Sequential Thinking | TypeScript | Step-by-step reasoning state recorder |
| Fetch | Python | URL fetch + markdown conversion |
| Git | Python | Git repository read/manipulation |
| Time | Python | Current time and timezone conversion |

GitHub, GitLab, Slack, SQLite, Puppeteer, Postgres servers were moved to servers-archived; the repo shifted from 'catalog of all MCP servers' to 'a small set of maintained references', pointing users to the MCP Registry.
reports/repositories/modelcontextprotocol-servers.md

Context7: freshen the docs, not the model

[translated from Korean] Two lessons: staleness is a retrieval problem not a training problem, and good tools tell the model when NOT to use them.

Context7's problem statement: AI coding agents are frequently wrong about package versions, API changes, and framework-recommended patterns. The way to reduce this without retraining is to fetch documentation at execution time.

It exposes two MCP tools - resolve-library-id and query-docs - and its server instructions explicitly restrict scope: "do not use for refactoring, script writing, business-logic debugging, code review, or general programming concepts."

It is not a coding agent but an external-memory/document-retrieval adapter for coding agents.
reports/repositories/upstash-context7.md

The companion (BUDDY) easter-egg prompt

From the most complete restored Claude Code source tree: even an easter egg gets careful identity-boundary prompting so two AI personas never talk over each other.

# Companion

A small ${species} named ${name} sits beside the user's input box and occasionally comments in a speech bubble. You're not ${name} - it's a separate watcher.

When the user addresses ${name} directly (by name), its bubble will answer. Your job in that moment is to stay out of the way: respond in ONE line or less, or just answer any part of the message meant for you. Don't explain that you're not ${name} - they know. Don't narrate what ${name} might say - the bubble handles that.
src/buddy/prompt.ts

A 54KB prompts.ts is the heart of the harness

The system prompt is assembled from the live state of nearly every subsystem - prompt engineering at production scale is state management, not copywriting.

src/constants/prompts.ts (54,320 bytes) imports from: git state, cwd, worktree session, session start date, settings, AgentTool constants, FileWrite/FileRead/FileEdit/TodoWrite/TaskCreate/Bash/Skill/Glob/Grep/AskUserQuestion tool names, model marketing names, MCP server types, output styles, Explore agent config, scratchpad permissions, REPL mode...

// biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered
src/constants/prompts.ts

withMemory: a one-function memory middleware

[translated] Long-term memory as a wrapper function: retrieval, short-term compression, ordered assembly, and write-back - integrable into any agent with one line.

async function withMemory(userMessage, generateFn, options = {}) {
  // 1. Retrieve relevant memories
  const relevant = await memory.smartRetrieve(userMessage, {
    limit: config.retrieveLimit, minConfidence: 0.5 });

  // 2. Compress recent conversation
  const recent = sessionHistory.slice(-config.shortTermRounds);
  const compressed = recent.map(m => `[${m.role}] ${m.content.slice(0, 150)}`).join('\n');

  // 3. Assemble context: system prompt -> [relevant history] ->
  //    [recent conversation] -> user input
  // 4. Call the generate function
  // 5. Record the exchange back into memory
}
src/memory-hook-simple.js

Why naive memory retrieval collapses at scale

The unglamorous truth of agent memory: recency and frequency queries need real index structures, or the memory system becomes the latency bottleneck.

Current problems: get_recent() calls list_keys() then retrieve() per entry - a full table scan. 10,000 entries: ~100ms to return 10. 100,000 entries: 1s+.

Proposed indexes:
- Access Time Index: BTreeMap<DateTime, HashSet<key>> - O(log n + k) for k most recent
- Access Frequency Index: BinaryHeap<(count, key)> max-heap with lazy rebuild - O(1) top-k when clean
- Tag Index: inverted index tag -> keys, O(1) lookup
docs/memory-retrieval-optimization-design.md

The /remember skill: memory triage with a destination table

A reconstruction of Claude Code's memory-review flow: memories get promoted up a visibility ladder (auto -> personal -> project -> team), never silently.

Review the user's memory landscape and produce a clear report of proposed changes, grouped by action type. Do NOT apply changes - present proposals for user approval.

Classify each auto-memory entry:
| CLAUDE.md | Project conventions all contributors should follow | "use bun not npm", "API routes use kebab-case" |
| CLAUDE.local.md | Personal instructions not applicable to others | "I prefer concise responses", "don't auto-commit" |
| Team memory | Org-wide knowledge across repositories | "deploy PRs go through #deploy-queue" |
| Stay in auto-memory | Working notes, temporary context | Session-specific observations |

When unsure, ask rather than guess.
skills/claude-code-remember/SKILL.md

The /simplify skill: three parallel review lenses

Code review decomposed by failure mode rather than by file: each parallel reviewer hunts one specific class of problem across the whole diff.

Launch all three agents concurrently. Pass each agent the full diff.

Agent 1: Code Reuse Review - search for existing utilities that could replace newly written code; flag any new function that duplicates existing functionality.

Agent 2: Code Quality Review - redundant state, parameter sprawl, copy-paste with slight variation, leaky abstractions, stringly-typed code, unnecessary comments explaining WHAT the code does.

Agent 3 (efficiency) reviews the same diff for performance issues.
skills/claude-code-simplify/SKILL.md

A system prompt for verifiable technical writing

[translated] An anti-hallucination prompt for long-form generation: evidence tags on every claim and a mandatory 'to be verified' escape hatch.

You are contributing to a technical book based on the Claude Code source. Your primary goal is not to 'write like a book' but to write things that are verifiable, mergeable, and reviewable.

Strictly follow:
1. Answer only from this round's provided source scope, the established glossary, and archived material.
2. If evidence is insufficient, explicitly write 'to be verified' - never fill in implementation details that don't exist.
3. Tag every key claim with [S]/[I]/[E]/[Q] (source/inference/experience/question).
4. Output outline, plan, material needs, and citation points BEFORE the body text.
5. Explain engineering implementation; no marketing language, no vague praise.
README.md

An active-memory template anyone can adopt today

No vector database required: a plain-JSON working memory split into session, preferences, context, and insights - the 80% of agent memory that's just structure.

{
  "current_session": {
    "project": "...", "session_focus": "What you're working on today",
    "key_accomplishments": []
  },
  "user_preferences": {
    "collaboration_style": "detailed/concise/step-by-step",
    "technical_approach": "production-ready/prototype/research",
    "communication_style": "detailed reports/brief status/realtime"
  },
  "current_context": {
    "project_phase": "planning/development/testing/deployment",
    "recent_decisions": [], "next_priorities": []
  },
  "important_insights": []
}
templates/active_memory_template.json

The system prompt is an array, and the boundary is infrastructure

getSystemPrompt() returns string[] not string - each segment becomes an API block with its own cache scope, and one literal marker decides what the whole fleet can share.

return [
  // --- Static content (cacheable) ---
  getSimpleIntroSection(outputStyleConfig),
  getSimpleSystemSection(),
  getActionsSection(),
  getUsingYourToolsSection(enabledTools),
  getSimpleToneAndStyleSection(),
  getOutputEfficiencySection(),
  // === BOUNDARY MARKER - DO NOT MOVE OR REMOVE ===
  ...(shouldUseGlobalCacheScope() ? [SYSTEM_PROMPT_DYNAMIC_BOUNDARY] : []),
  ...resolvedDynamicSections,
].filter(s => s !== null)

Before the boundary: cacheScope 'global' - shared across the entire Anthropic fleet, prefill cost amortized across millions of requests. After: per-session content.
docs/en/09-system-prompt-engineering.md

Nine exit reasons, each one a production scar

From the 1,729-line query.ts: an agent loop's maturity is measured by how many distinct ways it knows how to stop.

The Terminal return value carries the reason the loop exited: 'completed', 'aborted_streaming', 'aborted_tools', 'max_turns', 'prompt_too_long', 'model_error', 'image_error', 'hook_stopped', or 'stop_hook_prevented'. Each of those exit paths was added because of a real bug in production.

The outer query() is a thin wrapper: command lifecycle notifications only fire on successful completion - not on throws or .return() calls that abort the generator.
docs/en/06-agent-loop-deep-dive.md

MCP connections as a five-state discriminated union

Production MCP clients don't model 'connected or not' - they model five states so the UI, retry logic, and auth flows each know exactly what to do.

export type MCPServerConnection =
  | ConnectedMCPServer
  | FailedMCPServer
  | NeedsAuthMCPServer
  | PendingMCPServer
  | DisabledMCPServer

Connection results are memoized (lodash memoize, keyed on server name + serialized config) - repeated calls return the cached connection. When a connection drops, the cache entry is explicitly deleted in the onclose handler so the next call triggers a fresh connection.
docs/en/10-mcp-integration.md

Hybrid + rerank: from 30% to 100% Precision@3

Measured on a real agent's memory corpus: pure vector search graded D; adding BM25 keywords and a reranker took retrieval to perfect Precision@3.

Query -> [BM25 keyword search] --+
                                  +- Weighted Fusion (70/30) -> Cohere Rerank -> Results
Query -> [ChromaDB vector search]-+

Benchmark results:
| Vector-only (baseline) | Precision@3 30% | MRR 0.167 | Grade D |
| Hybrid (BM25+vector)   | Precision@3 60% | MRR 0.417 | Grade C |
| Hybrid + Rerank        | Precision@3 100% | MRR 0.950 | Grade A |
README.md

HOT/WARM/COLD tiers with promotion rules

A working three-tier memory with explicit promotion/demotion rules - and a compaction-guard script that snapshots all tiers before the context window gets compacted.

HOT - memory/hot/HOT_MEMORY.md: active tasks, session state; load every session; aggressively prune, max 1-2 pages.
WARM - stable preferences, tool config, important people, recurring errors; load every session.
COLD - MEMORY.md: archive, distilled lessons; load only in main session (not shared/group contexts).
Daily logs - memory/YYYY-MM-DD.md: raw record.

Tier maintenance (during heartbeats):
- Completed task in HOT -> delete or archive to COLD
- New stable info -> promote to WARM
- Daily log lessons -> promote to COLD
references/memory-tiers.md

March 2026: the 'non-vector era' of agent memory

[translated] A 30-project survey's headline finding: LLM-native compression and temporal-graph systems roughly doubled the benchmark scores of classic vector RAG memory.

2026.03 rankings (LongMemEval):
| 1 | Hindsight | TEMPR architecture, 'killed RAG' | 91.4% |
| 2 | Supermemory | LLM compression, 'vector DB is dead' | 99% |
| 3 | Letta | self-editing memory, /remember | - |
| 4 | Mem0 | veteran, graph+vector | 49% |
| 5 | Zep | temporal graph, 'old era' baseline | 71% |

Core trend: in March 2026, vector memory was comprehensively crushed by agentic/observational memory - entering the 'non-vector era'.
README.md

Six architecture patterns, from vectors to agentic

[translated] The clearest taxonomy of agent-memory architectures in the vault - five patterns with named exemplars and the failure mode each one fixes.

Pattern 1 Vector-only: embed -> top-K cosine -> inject (ChromaDB, early Mem0; 'similar but irrelevant' failure mode).
Pattern 2 Graph-augmented: entity extraction -> knowledge graph + vectors (Mem0 Graph, Zep, Cognee ECL: Extract/Cognify/Load).
Pattern 3 Temporal knowledge graph: entities + timestamps, conflict resolution, new facts supersede old (Zep, Hindsight TEMPR: 4 memory networks, retain/recall/reflect).
Pattern 4 LLM-native, no vectors: LLM extracts key info -> structured store (SQLite/files); LLM judges relevance at query time (Supermemory 99% LongMemEval, Google Always-On: IngestAgent/ConsolidationAgent/QueryAgent over pure SQLite).
Pattern 5 Self-editing memory: agent calls memory_write()/memory_read() and decides what to keep (Letta/MemGPT, A-MEM).
architecture-patterns.md

The full syllabus of a production harness

[translated] Read the navigation as a checklist: cost control, anti-distillation protection, and a settings manual are chapters here because they are subsystems in the real product.

Section map of the source analysis site: startup chain · query loop · query lifecycle · tool dispatch · permission system · risk control & security hardening · agent architecture · hook mechanism · MCP system · plugin system · command system · context management · service layer · cost & rate limits · UI interaction layer · config & migration · settings.json parameter manual · external integrations · native capabilities · anti-distillation & output protection · vertical agent design guide.
02-tool-dispatch.html

The malicious-code refusal instruction, verbatim

From an early open-source Claude Code snapshot: the security instruction asks the model to infer intent from directory structure before touching any file.

IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
src/constants/prompts.ts

The original subagent dispatch prompt

Three durable subagent rules in one prompt: parallelize by default, results are for the caller not the user, and recursion is disabled by construction.

Launch a new agent that has access to the following tools: ${toolNames}. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you.

Usage notes:
1. Launch multiple agents concurrently whenever possible... use a single message with multiple tool uses
2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user.
3. Each agent invocation is stateless.

// In the source: getAgentTools() filters out AgentTool itself - 'No recursive agents, yet..'
src/tools/AgentTool/prompt.ts

BashTool's banned list and pre-flight ritual

The banned list is all network-fetch and browser commands - the model gets dedicated, auditable tools for the web instead of raw curl.

export const BANNED_COMMANDS = ['alias', 'curl', 'curlie', 'wget', 'axel', 'aria2c', 'nc', 'telnet', 'lynx', 'w3m', 'links', 'httpie', 'xh', 'http-prompt', 'chrome', 'firefox', 'safari']

Before executing the command:
1. Directory Verification - if the command will create new directories or files, first use the LS tool to verify the parent directory exists and is the correct location
2. Security Check - for security and to limit the threat of a prompt injection attack, some commands are limited or banned.
3-5. Execute after proper quoting; truncate output beyond 30000 characters; include errors in the result.
src/tools/BashTool/prompt.ts
Agent patternClaude Swarm MCP

Persistent agents with handoff functions, served over MCP

A Swarm-style team (Risk Analyst, Portfolio Manager, ...) that survives restarts: definitions serialize to disk, and inter-agent transfer functions are re-wired at load time.

# Recreate ClaudeAgent objects with transfer functions
for name, data in agent_data.items():
    agent = ClaudeAgent(
        name=data["name"],
        model=data["model"],
        instructions=data["instructions"],
        functions=[]  # Will add transfer functions below
    )
    agents[name] = agent

# Add transfer functions between agents
_setup_transfer_functions()

# save_agents(): agent definitions persist to JSON;
# functions can't be serialized, so handoffs are rebuilt on load.
claude_swarm_mcp_server.py

Load order is reversed because of recency bias

[translated] Priority in prompt design isn't metadata - it's position. The loader exploits recency bias by putting what matters most at the end.

// Files are loaded in the following order:
// 1. Managed memory (eg. /etc/claude-code/CLAUDE.md) - Global instructions for all users
// 2. User memory (~/.claude/CLAUDE.md) - Private global instructions
// 3. Project memory (CLAUDE.md, .claude/CLAUDE.md, .claude/rules/*.md)
// 4. Local memory (CLAUDE.local.md) - Private project-specific instructions
// Files are loaded in reverse order of priority, i.e. the latest files are highest priority

The subtle design: LLMs attend more to content that appears LATER in the message (recency bias), so the highest-priority memory is deliberately placed last.
docs/23-Memory系统.md

One env var away from a minimal agent

[translated] The 915-line prompt assembly keeps an escape hatch: identity + cwd + date is the irreducible minimum a coding agent needs to function.

// Minimal mode: return only the smallest possible prompt
if (isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)) {
  return [
    `You are Claude Code, Anthropic's official CLI for Claude.\n\nCWD: ${getCwd()}\nDate: ${getSessionStartDate()}`,
  ]
}

// ...then parallel prefetch:
const [skillToolCommands, outputStyleConfig, envInfo] = await Promise.all([...])

Internal/external split: process.env.USER_TYPE === 'ant' produces different behavioral guidance from the same code.
docs/04-System-Prompt-工程.md

SQLite is the truth; HNSW is just an accelerator

The most disciplined storage stance in the vault: the vector index can always be rebuilt from SQLite, so corruption of the fast path never loses a memory.

- SQLite is the authoritative store for all durable rows and f32 embeddings.
- FTS5 provides BM25 full-text search.
- Vector search uses cosine similarity.
- Reciprocal Rank Fusion combines BM25 and vector results.
- HNSW is an optional acceleration sidecar, not a source of truth.
- Sidecar mutations are journaled in SQLite and replayed on open, flush, rebuild, or reconcile.
- Quantized q8 copies of embeddings are stored for facts, chunks, messages, and episodes.
- WAL mode plus a single writer and pooled readers allows concurrent read-heavy use.
README.md

The orchestrator's plan prompt: 3 steps, 4 parallel subtasks

From the Spring AI community: a replanning loop with hard fan-out limits - the planner re-reads all prior step results each round and must explicitly declare completion.

You are tasked with orchestrating a plan to complete an objective.
You can analyze results from the previous steps already executed to decide if the objective is complete.
Your plan must be structured in sequential steps (up to 3 steps), with each step containing independent parallel subtasks (up to 4 subtasks).

Objective: %s

If the previous results achieve the objective, return is_complete=True.
Otherwise, generate remaining steps needed.

For each subtask specify:
  1. Clear description of the task that an LLM can execute
  2. Name of 1 Agent OR List of MCP server names to use for the task
src/main/java/com/example/agentic/orchestration/OrchestratorPrompts.java

An agent is a named set of MCP servers

A clean composition hierarchy: tools live in MCP servers, agents are named bundles of servers plus an instruction, and the planner routes tasks to either.

public class McpAgent {
  private String name;
  private String instruction;
  /** List of MCP server names that this agent can access. */
  private List<String> serverNames;
  /** ChatClient configured to use the MCP servers' tools. */
  private ChatClient chatClient;
}

Planner system prompt: "Given an objective task and a list of MCP servers (which are collections of tools) or Agents (which are collections of servers), break down the objective into a series of steps."
src/main/java/com/example/agentic/McpAgent.java

'Bash is all you need' — and a 200x cache cost lever

[translated] The 30-article study's two sharpest numbers: the loop is 6 lines, and getting the cache boundary right is a 200x cost lever.

The core agent loop, as the community summarizes it:

while (true) {
  response = call_model(messages)
  tool_results = execute_tools_if_any(response)
  messages.push(response, tool_results)
  if (!needs_follow_up(response, tool_results)) break
}

The complexity is not in the loop but in the harness around it: context management, permission control, security defense, memory persistence, multi-agent orchestration. (1,884 files, 513,216 lines; 40 tools, 86 slash commands, 90 compile-time feature flags.)

On caching: under Anthropic's prompt cache, a cache hit costs roughly 1/200th of a miss at 200K tokens - System Prompt cache design directly moves the cost of millions of daily API calls.
总纲B-Claude-Code-Harness技术深度分析.md

Five memory layers, ~4,200 lines of code

[translated] Each layer answers a different timescale - permanent rules, cross-session knowledge, session notes, per-agent experience, and per-turn recall - and together they cost ~4,200 lines.

| 1 | CLAUDE.md instruction files | permanent | project/user/enterprise dirs | static instructions |
| 2 | Auto Memory (memdir) | cross-session | ~/.claude/projects/<slug>/memory/ | AI-extracted persistent knowledge |
| 3 | Session Memory | single session | .../session-memory/summary.md | structured notes for the current session |
| 4 | Agent Memory | cross-session | three scope directories | per-agent-type experience |
| 5 | Relevant Memories | injected per turn | in-memory attachment | Sonnet side-query recall |

Implementation: src/memdir/ (8 files), claudemd.ts (1,480 lines), extractMemories/ (771 lines), SessionMemory/ (821 lines), autoDream/ (465 lines), agentMemory.ts (178 lines).
Part I Foundations/07-Memory.md