This guide is intentionally written in Brazilian Portuguese. The header Headers
When to UseandLimitationsremain in English only for compatibility with catalog discovery and automatic validation.
[!WARNING] This skill creates snapshots and may remove them during pruning. Confirm the data directory, keep a backup and obtain explicit approval before running
saveorprune; never assume authorization to modifyMEMORY.mdor other user context files.
Overview
Context guardian that preserves critical data before automatic compaction. Snapshots, integrity verification and zero information loss.
When to Use This Skill
- When the user mentions "context compaction" or related topics
- When the user mentions "context loss" or related topics
- When the user mentions "context snapshot" or related topics
- When the user mentions "preserve context" or related topics
- When the user mentions "critical context" or related topics
- When the user mentions "before compacting" or related topics
When Not to Use This Skill
- The task is not related to context preservation
- A simpler and more specific tool can fulfill the request
- The user only needs general assistance, without this specialization
How It Works
Context integrity system that protects complex technical projects against
information loss during Claude Code automatic compaction. While
context-agent acts AFTER sessions (save/load), context-guardian acts DURING
the session, detecting when compaction is near and running preservation
protocols with redundant verification.
Why This Exists
Claude Code automatically compacts old messages when the context approaches the window limit. This compaction is heuristic — it summarizes messages to free up space, but inevitably loses details. For simple projects, this works well. But for heavyweight technical projects (such as ecosystems with 21+ skills, security audits, architecture refactorings), the loss of a single detail can cause regressions, rework or serious inconsistencies.
The context-guardian solves this by creating a PRE-compaction protection layer: it extracts, classifies, verifies and persists all critical information BEFORE automatic compaction destroys it.
Location
C:\Users\renat\skills\context-guardian\
├── SKILL.md # Este arquivo
├── references/
│ ├── extraction-protocol.md # Protocolo detalhado de extracao
│ └── verification-checklist.md # Checklist de verificacao e redundancia
└── scripts/
└── context_snapshot.py # Script de snapshot automatico
Integration With The Ecosystem
context-guardian (PRE-compactacao) context-agent (POS-sessao)
│ │
├── Detecta contexto grande ├── Salva resumo ao final
├── Extrai dados criticos ├── Atualiza ACTIVE_CONTEXT.md
├── Verifica integridade ├── Sincroniza MEMORY.md
├── Salva snapshot verificado ├── Indexa busca FTS5
└── Gera briefing de transicao └── Arquiva sessoes antigas
context-guardian and context-agent are complementary:
- context-guardian: real-time protection, DURING the session
- context-agent: persistence between sessions, AFTER the session
Automatic Activation (Claude Should Start It On Its Own)
- Context limit: when you notice that you have already consumed ~60-70% of the context window (indicators: messages starting to be summarized, compaction warning)
- Heavy projects: sessions with many files edited, many tool calls, or projects with complex dependencies between components
- Before long tasks: when a next task may generate extensive output that would push the context beyond the limit
Manual Activation (User Requests)
- "save the state before compacting"
- "do a checkpoint"
- "snapshot the context"
- "I don't want to lose anything from this session"
- "prepare for compaction"
- "the context is big, protect it"
Phase 1: Structured Extraction
Go through the entire conversation up to this point and extract critical categories. For each category, classify by priority (P0 = fatal loss, P1 = severe loss, P2 = tolerable loss).
P0 — Fatal Loss (preserve with triple redundancy)
| Category | What to extract | Example |
|---|---|---|
| Technical decisions | Architecture, pattern, technology choices AND reason | "We use parameterized queries because f-strings cause SQL injection" |
| Task status | What was done, what is left, dependencies | "18/18 match OK, ZIP missing" |
| Fixes applied | Bug, root cause, exact solution, affected files | "instagram/db.py: SQL injection via f-string → ? placeholders" |
| Code generated/modified | Exact path, changed lines, nature of the change | "match_skills.py:40-119: added 5 categories" |
| Errors encountered | Exact message, relevant stack trace, how it was resolved | "TypeError at line 45 → cast to int" |
| Commands that worked | Complete command that produced the correct result | "python verify_zips.py → 22/22 OK" |
P1 — Severe Loss (preserve with verification)
| Category | What to extract |
|---|---|
| Discovered patterns | Conventions, observed code patterns |
| Dependencies between components | "scan_registry.py AND match_skills.py must have identical categories" |
| User preferences | Language, style, level of detail, preferred workflow |
| Project context | Directory structure, key files, purpose |
| Open questions | Unanswered questions, unresolved ambiguities |
P2 — Tolerable Loss (compact summary)
| Category | What to extract |
|---|---|
| History of attempts | "I tried X, it didn't work because of Y, so Z" |
| Progress metrics | Counters, times, sizes |
| Exploratory discussions | Brainstorm, options considered and discarded |
Phase 2: Integrity Verification
After extracting, verify that NOTHING critical was omitted.
Verification Checklist (run mentally for each item):
□ Cada arquivo modificado tem: caminho, natureza da mudanca, motivo
□ Cada bug corrigido tem: sintoma, causa raiz, solucao, arquivo
□ Cada decisao tem: o que, por que, alternativas descartadas
□ Cada tarefa pendente tem: descricao, prioridade, dependencias
□ Cada padrao/convencao tem: regra, motivo, exemplos
□ Nenhuma informacao de uma secao contradiz outra
□ Referencias cruzadas estao consistentes (ex: "18 queries testadas" aparece em
multiplos lugares com o mesmo numero)
□ Caminhos de arquivo estao completos (absolutos, nao relativos)
If any item fails, go back to Phase 1 and re-extract the missing information.
For details on advanced verification, read references/verification-checklist.md.
Phase 3: Redundant Persistence
Save the extracted information in 3 layers of redundancy:
Layer 1 — Structured snapshot (.md file)
python C:\Users\renat\skills\context-guardian\scripts\context_snapshot.py save
Generate C:\Users\renat\skills\context-guardian\data\snapshot-YYYYMMDD-HHMMSS.md with
all the extracted information in structured format.
If the script is not available, create the file manually following the format
described in references/extraction-protocol.md.
Layer 2 — MEMORY.md updated
Update C:\Users\renat\.claude\projects\C--Users-renat-Skill-JUD\memory\MEMORY.md
with the most critical P0 information in ultra-compact format. MEMORY.md is loaded
automatically in every new session, so it is the last line of defense.
Layer 3 — Context-agent save
python C:\Users\renat\skills\context-agent\scripts\context_manager.py save
Trigger the context-agent to save the complete session with FTS5 indexing.
Phase 4: Transition Briefing
Generate a formatted text block that serves as a "business card" for the Claude that will continue after compaction. This briefing should be the LAST thing written before compaction, so that it stays at the top of the compacted context.
Briefing format:
## Estado Atual
- Projeto: [nome]
- Fase: [fase atual]
- Progresso: [X/Y tarefas completas]
## O Que Foi Feito Nesta Sessao
1. [tarefa 1 — resultado]
2. [tarefa 2 — resultado]
...
## O Que Falta Fazer
1. [tarefa pendente — prioridade] [dependencia se houver]
2. ...
## Decisoes Criticas (Nao Alterar Sem Motivo)
- [decisao 1]: [motivo]
- [decisao 2]: [motivo]
## Correcoes Aplicadas (Nao Reverter)
- [arquivo]: [correcao] — [motivo]
## Caminhos Importantes
- [caminho 1]: [proposito]
- [caminho 2]: [proposito]
## Alertas
- [qualquer armadilha, edge case, ou cuidado especial]
## Onde Recuperar Mais Informacoes
- Snapshot: C:\Users\renat\skills\context-guardian\data\snapshot-[timestamp].md
- MEMORY.md: carregado automaticamente
- Context-agent: `python context_manager.py load`
- Busca historica: `python context_manager.py search "termo"`
Quick Protocol (When Time Is Short)
If compaction is imminent and there is no time for the complete 4-phase protocol:
- 30 seconds — Write a mini-briefing with: pending tasks, critical decisions, modified file paths
- 1 minute — Update MEMORY.md with P0 information
- 2 minutes — Run context-agent save
Even the quick protocol is better than no protection.
Post-Compaction Completeness Detection
When a session continues after compaction, verify whether the preserved context is complete:
- Read MEMORY.md (it will already be loaded automatically)
- If available, read the most recent snapshot in
data/ - Compare with the transition briefing (if visible in the compacted context)
- If you find gaps, run:
python C:\Users\renat\skills\context-agent\scripts\context_manager.py load - If gaps still remain, search by term:
python C:\Users\renat\skills\context-agent\scripts\context_manager.py search "termo"
Real Usage Example
Scenario: Long session creating advogado-especialista (46KB), fixing match_skills (5 new categories), auditing security (10 vulnerabilities), generating 22 ZIPs.
Without context-guardian: Compaction summarizes everything as "created legal skill, fixed bugs, generated zips". The next Claude does not know which categories were added, which vulnerabilities were fixed, what the state of each ZIP is, or why certain decisions were made. Result: rework, inconsistencies, regressions.
With context-guardian: Before compaction, run the complete protocol:
- Snapshot with 5 new categories listed (legal, auction, security, image-generation, monitoring)
- 10 vulnerabilities cataloged with file, type, and exact fix
- 22 ZIPs verified with checksums
- Documented decisions ("removed 'health' from monitoring because it caused a false positive")
- Transition briefing at the top of the context Next Claude continues with full precision, zero rework.
Performance Considerations
- The full protocol takes 2-5 minutes of Claude's work
- For simple projects, use only the quick protocol
- Do not activate for short sessions or casual conversations
- The 3-layer persistence (snapshot + MEMORY.md + context-agent) ensures that even if one layer fails, the other two preserve the information
- Old snapshots (>10) can be pruned manually
Best Practices
- Provide clear and specific context about the project and its requirements
- Review all suggestions before applying them to production code
- Combine this skill with other complementary skills when necessary
Common Pitfalls
- Using this skill on tasks outside its domain
- Applying recommendations without understanding the specific context
- Providing insufficient context for an accurate analysis
Related Skills
context-agent- Complementary skill for persistence between sessions
Limitations
- Use this skill only when the task clearly matches the scope above.
- The integration examples use absolute paths specific to Windows and the author; adapt and validate all paths before any execution.
- The script creates files and the operation
pruneremoves old snapshots; require approval for the exact path and preserve a recoverable backup. - Stop and ask for clarification when inputs, permissions, security limits, or success criteria are missing.