/loxihart-ai:managing-agent-contextfrom loxihart-ai
Manages context windows in long-running AI agent loops — deciding when to summarize vs. truncate, implementing rolling window patterns, preserving critical context while shedding stale state, and budgeting tokens across multi-turn agent interactions. Use when an agent is running out of context, building autonomous loops that run many turns, experiencing context window errors, trying to keep agents focused across long sessions, managing token costs in multi-turn interactions, or designing agents that need to maintain state across hours or days. Also triggers on: context limit, token limit, context window full, agent loses track, agent forgets, long-running agent, context overflow, too many tokens, context management, rolling summary, compaction, context pruning.
Ships in loxihart-ai. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
The context window is the agent's working memory. When it fills up, the agent loses access to its own history. This skill covers architectural patterns for managing that constraint in production agent loops.
Distinct from ecc:strategic-compact which handles Claude Code session
compaction for interactive developer sessions. This skill covers autonomous
agent loops that accumulate context across hundreds of tool calls.
Every turn of an agent loop adds tokens:
At some point: context limit reached → agent fails or must be restarted. Solution: proactive context management before the limit is hit.
What's your situation?
│
├─ Agent is hitting context limits in production
│ → Section 1: Emergency Reduction Patterns
│
├─ Designing a new multi-turn agent
│ → Section 2: Context Budget Planning
│
├─ Building an autonomous loop (many tool calls)
│ → Section 3: Rolling Window Architecture
│
└─ Agent loses important context mid-session
→ Section 4: Critical Context Preservation
If an agent is hitting context limits in production now:
Option A: Truncate oldest messages (fastest fix) Drop the oldest user/assistant turns while keeping:
def truncate_to_fit(messages: list, max_tokens: int, keep_last_n: int = 10) -> list:
system = [m for m in messages if m["role"] == "system"]
turns = [m for m in messages if m["role"] != "system"]
# Keep last N turns
trimmed = system + turns[-keep_last_n * 2:] # *2 for user+assistant pairs
# If still too long, reduce N
if estimate_tokens(trimmed) > max_tokens:
trimmed = system + turns[-6:]
return trimmed
Option B: Summarize and replace (better quality) Have the model summarize the conversation history before it exceeds the limit, then replace the raw history with the summary.
See Section 3 for the full rolling window implementation.
Before building a multi-turn agent, define a context budget.
Context budget formula:
Total window (e.g., 200K tokens)
- System prompt: ~2K tokens (reserve)
- Task description: ~1K tokens (reserve)
- Tool definitions: ~3K tokens per 10 tools (reserve)
- Buffer (15%): ~30K tokens (safety margin)
────────────────────────────────────────────────
Available for turns: ~164K tokens
Typical turn cost: ~500-2K tokens per turn
Max turns before management required: ~80-300 turns
Design rule: trigger context management at 70% of the window, not 95%. Waiting until the window is nearly full means you're already in a degraded state before you start managing.
CONTEXT_MANAGEMENT_THRESHOLD = 0.70 # 70% of max context
def needs_context_management(messages: list, model_max_tokens: int) -> bool:
current_tokens = estimate_tokens(messages)
return current_tokens > (model_max_tokens * CONTEXT_MANAGEMENT_THRESHOLD)
The standard architecture for long-running agents.
Pattern: maintain a rolling summary that replaces accumulated history, keeping only the summary + recent turns in the active context.
SUMMARY_TRIGGER_TOKENS = 100_000 # adjust based on model max
TURNS_TO_KEEP_AFTER_SUMMARY = 6 # keep recent turns verbatim
async def manage_context(
messages: list,
model_max_tokens: int,
anthropic_client
) -> list:
if not needs_context_management(messages, model_max_tokens):
return messages
system_msgs = [m for m in messages if m["role"] == "system"]
turns = [m for m in messages if m["role"] != "system"]
# Split: turns to summarize vs. turns to keep verbatim
turns_to_summarize = turns[:-TURNS_TO_KEEP_AFTER_SUMMARY * 2]
turns_to_keep = turns[-TURNS_TO_KEEP_AFTER_SUMMARY * 2:]
if not turns_to_summarize:
return messages # nothing to compress yet
# Generate a summary of the portion being discarded
summary_response = await anthropic_client.messages.create(
model="claude-haiku-4-5-20251001", # use cheaper model for summarization
max_tokens=1000,
messages=[
{
"role": "user",
"content": f"""Summarize this agent conversation history concisely.
Preserve: decisions made, actions taken, data discovered, any blockers.
Discard: conversational filler, intermediate reasoning that led to decisions.
History:
{format_turns_for_summary(turns_to_summarize)}
Produce a structured summary under 800 tokens."""
}
]
)
summary_text = summary_response.content[0].text
# Replace history with summary injection
summary_msg = {
"role": "user",
"content": f"[CONTEXT SUMMARY — earlier conversation compressed]\n{summary_text}"
}
summary_ack = {
"role": "assistant",
"content": "Understood. I have the context from earlier in the conversation."
}
return system_msgs + [summary_msg, summary_ack] + turns_to_keep
Cost note: Use claude-haiku for summarization — it's 10-20x cheaper
than Sonnet for this task and adequate for compressing agent history.
Some context must survive summarization. Before compressing, extract and preserve:
CRITICAL_CONTEXT_FIELDS = [
"task_objective", # The original task the agent is solving
"decisions_made", # Key choices that constrain future actions
"data_discovered", # Facts found that will be needed later
"actions_completed", # What has already been done (avoid repetition)
"active_constraints", # Rules or limits in effect
"current_blockers", # Issues that still need resolution
]
Store critical context separately from the message history. Inject it into the context at each turn as a structured header:
def build_context_header(critical_context: dict) -> str:
return f"""
[PERSISTENT CONTEXT]
Objective: {critical_context.get('task_objective', 'None set')}
Decisions made: {'; '.join(critical_context.get('decisions_made', []))}
Completed actions: {'; '.join(critical_context.get('actions_completed', []))}
Active constraints: {'; '.join(critical_context.get('active_constraints', []))}
[END PERSISTENT CONTEXT]
"""
This ensures that even after aggressive context compression, the agent retains the information it needs to continue correctly.
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub krosebrook/loxihart-skills --plugin loxihart-ai37 skills in this plugin
/ai-agents-workflowBuilds and implements AI agents, automation workflows, and tool integrations — MCP servers (2025 async, OAuth, stateless spec), LangChain and CrewAI agents, multi-LLM orchestration, and no-code platforms. Use when the user mentions: MCP server, build an agent, tool integration, API orchestration, multi-LLM routing, OAuth flow, webhook, connect services, deploy a workflow, integrate external APIs. Not for conceptual architecture overviews (use orchestrating-ai- agents), not for production n8n incident ops (use operating-n8n-production), and not for pure no-code platform wiring (use workflow-automation).
/ai-solution-architectureDesign pre-sales technical architectures for AI/ML solutions targeting B2B enterprise clients. Use when scoping AI implementations, designing reference architectures, mapping integration patterns, estimating infrastructure requirements, or preparing technical proposals. Triggers on solution design, AI architecture, technical scoping, integration mapping, infrastructure sizing, pre-sales engineering for AI projects./applying-adversarial-reviewApplies Kyle's adversarial review methodology to consequential outputs. Forces every recommendation, audit, plan, or claim through three checks before shipping: a CLAIMS / COUNTEREXAMPLE / CONTRADICTIONS footer, [SOURCED] vs [GENERATED] provenance labeling, and an agreement-streak flag at three consecutive consequential agreements. Use when finishing an audit, writing a recommendation, delivering a plan, drafting a decision memo, or producing any high-stakes deliverable. Also triggers when explicitly asked to pressure-test, stress-test, steelman, play devil's advocate, fight an idea, or check for blind spots. Triggers on: adversarial review, anti-sycophancy, claims footer, stress test this, steelman this, pressure test, devil's advocate, am I missing anything, what could go wrong, sourced vs generated, agreement streak, push back on this, where am I wrong, review this PR, pull request review, code review, PR feedback.
/auditing-agent-securityApplies the Agent Security framework to autonomous AI systems and ghost-team architectures — permission and blast-radius mapping, prompt-injection and context-poisoning review, MCP bridge security, and quarterly cleanses. Use when the user mentions: agent security audit, permission stack review, agent hygiene, context window poisoning, prompt injection defense, MCP security, ghost team security, agent-to-agent trust, blast radius test, permission escalation risk. Not for application or codebase vulnerability review and not for building the agent itself (use orchestrating-ai-agents or building-langgraph-agents).
/auditing-cross-lane-routine-artifactsAdversarially audits multi-routine automation artifacts (cron/API routine libraries, scheduled-task decks, "routine cards") for cross-lane contamination, scheduled-task governance violations, and the structurally-empty-at-runtime defect — then splits them into lane-clean artifacts and rebuilds them from a single-source generator. Use whenever Kyle hands over a routine/automation artifact and says "audit this", "fresh adversarial pass", "keep them lane-specific", "make these lane-clean", "split by lane", "apply all fixes", or "rebuild the artifact" — even if he doesn't say "lane" or "governance". Also triggers on: routine cards audit, cron library review, automation deck audit, scheduled-task governance check, Loxihart vs FlashFusion bleed, lane contamination, n8n tenant collision, pipeline-vs-recognized-revenue, data-source guard, count-bug, generator rebuild, lane separation. PERSONAL/Loxihart context. NOT for app/codebase security audits (use code-auditor) and NOT for building a single new routine.
/avoiding-ai-slopDetects and eliminates AI-slop from text, prose, and image prompts using a 76-rule structural pattern corpus, a 237-term tiered ban lexicon, and an image-slop negative-prompt pack, with a slopcheck.py linter for scan, calibrate, and allowlist workflows. Use when the user mentions: de-slop this, deslop, anti-slop, AI slop, sounds like AI, reads like ChatGPT, AI tells, humanize this, make this sound human, remove AI words, overused AI words, banned words check, slop scan, slopcheck, cliché check, AI writing check, delve, tapestry, em-dash overuse, negative parallelism, it's not X it's Y, image slop, negative prompts for AI images, calibrate slop thresholds, refresh the slop list. Also applies silently as writing constraints when drafting outward-facing prose — blog posts, LinkedIn, newsletters, docs, marketing copy. NOT for attributing third-party text to AI (no authorship claims) and NOT for icon slop (use purging-icon-slop).