Skill: relunctance/context-hawk (version 1.0.1)

# 🦅 Context-Hawk — AI 记忆守护者 > **纯 Python 记忆包，零外部依赖，零 API Key，直接 import 就能用** *让任何 Python 项目或 AI Agent 拥有记忆能力——跨会话、跨话题、跨时间。* --- ## 定位 **纯 Python 包，可独立使用** - 不需要 OpenClaw，不需要 API Key - `pip install` 后直接 `from hawk.memory import MemoryManager` - 可嵌入任何 Python 项目（AI Agent、脚本、爬虫等） **配合 hawk-bridge 使用时**，hawk-bridge 负责 autoCapture/autoRecall Hook，context-hawk 提供底层 Python 核心。 --- ## 核心模块 | 模块 | 功能 | API Key | |------|------|---------| | `MemoryManager` | 四层记忆衰减（Working/Short/Long/Archive） | ❌ | | `ContextCompressor` | 上下文压缩，按 token 限制 | ❌ | | `Config` | 配置管理 | ❌ | | `SelfImproving` | 自我反思，错误模式学习 | ❌ | | `VectorRetriever` | 向量语义检索（LanceDB） | ❌* | | `MarkdownImporter` | 导入 .md 记忆文件 | ❌* | | `Extractor` | 记忆提取（6类分类） | ⚠️ 可选 | | `Governance` | 系统巡检指标 | ❌ | *VectorRetriever 和 MarkdownImporter 需要 LanceDB（免费本地）* --- ## 安装 ```bash pip install lancedb ``` 不需要任何 API Key，纯本地运行。 --- ## 快速开始 ```python from hawk.memory import MemoryManager # 创建记忆管理器 mm = MemoryManager() # 存入记忆 mm.store("用户喜欢简洁的回复风格", category="preference") mm.store("公司叫趣近团队", category="entity") mm.store("老板决定用Go语言重构", category="decision") # 检索记忆 results = mm.recall("老板的风格偏好") for r in results: print(f"{r.layer}: {r.text}") # 查看统计 print(mm.get_stats()) # {'working': 2, 'short': 1, 'long': 0, 'archive': 0, 'total': 3, 'avg_importance': 0.65} ``` --- ## MemoryManager — 四层记忆 ``` Working → Short → Long → Archive ↑ ↓ ←──── Weibull 衰减 ←←← ``` ```python from hawk.memory import MemoryManager mm = MemoryManager() # 存入，指定重要程度（0.0-1.0） mm.store("这是重要决策", category="decision", importance=0.9) mm.store("普通信息", category="fact", importance=0.4) # 触发衰减（清理低价值记忆） mm.decay() # 访问记忆（更新计数器，可能触发层级升级） item = mm.access("memory_id") print(f"访问次数: {item.access_count}") ``` --- ## VectorRetriever — 向量语义检索 需要先设置 `OPENAI_API_KEY`（可选，用于 embedding） ```python from hawk.vector_retriever import VectorRetriever retriever = VectorRetriever(top_k=5, min_score=0.6) # 检索相关记忆 chunks = retriever.recall("老板之前部署过哪些服务") print(retriever.format_for_context(chunks)) ``` **输出：** ``` 🦅 [记忆检索结果] [entity] (85%相关): 趣近团队的服务器部署在阿里云 [fact] (72%相关): 生产环境用 Docker Compose 管理 ``` --- ## MarkdownImporter — 导入 .md 记忆文件 一键把已有的 `.md` 记忆文件导入向量库： ```python from hawk.markdown_importer import MarkdownImporter importer = MarkdownImporter(memory_dir="~/.openclaw/memory") # 扫描预览 chunks = importer.scan() print(f"发现 {len(chunks)} 个记忆块") # 一键导入（增量，已导入的打标签跳过） result = importer.import_all() print(f"导入完成: {result['files']} 个文件, {result['chunks']} 个块") ``` **CLI：** ```bash python3.12 -m hawk.markdown_importer --dry-run # 预览 python3.12 -m hawk.markdown_importer # 实际导入 ``` --- ## ContextCompressor — 上下文压缩 按 token 限制压缩对话历史： ```python from hawk.compressor import ContextCompressor compressor = ContextCompressor(max_tokens=4000) conversation = [ {"role": "user", "content": "我们要做XX项目"}, {"role": "assistant", "content": "好的，我来规划"}, # ... 100 轮对话 ] result = compressor.compress(conversation) print(f"压缩率: {result['compression_ratio']}") print(result['compressed']) ``` --- ## Extractor — 记忆提取 **零 API 模式（关键词提取，完全离线）：** ```python from hawk.extractor import extract_memories text = "用户说他喜欢用Go语言，公司叫趣近团队，决定用Docker部署" memories = extract_memories(text, provider="keyword") # 不需要任何 API Key ``` **有 API Key 时（LLM 6类分类，更精准）：** ```python # 设置环境变量 import os os.environ["OPENAI_API_KEY"] = "sk-xxx" # 或 os.environ["MINIMAX_API_KEY"] = "sk-cp-xxx" memories = extract_memories(text, provider="openai") # 或 memories = extract_memories(text, provider="minimax", [REDACTED_SECRET]", model="MiniMax-M2.7", base_url="https://api.minimaxi.com/anthropic") ``` **输出示例：** ```python [ {"text": "喜欢用Go语言", "category": "preference", "importance": 0.8, "abstract": "用户偏好Go", "overview": "[preference] 喜欢用Go语言"}, {"text": "公司叫趣近团队", "category": "entity", "importance": 0.9, "abstract": "公司名称", "overview": "[entity] 公司叫趣近团队"}, {"text": "决定用Docker部署", "category": "decision", "importance": 0.95, "abstract": "部署决策", "overview": "[decision] 决定用Docker部署"} ] ``` --- ## SelfImproving — 自我反思 ```python from hawk.self_improving import SelfImproving si = SelfImproving() # 记录错误 si.learn_from_error( error_type="recall_miss", context={"query": "老板上次说的项目", "results": []}, correction="改进了检索关键词策略" ) # 获取统计 print(si.get_stats()) # {'total': 1, 'resolved': 0, 'unresolved': 1, 'by_type': {'recall_miss': 1}} # 获取未解决的问题 unresolved = si.get_unresolved() for u in unresolved: print(f"待解决: {u.error_type} - {u.context}") ``` --- ## Governance — 系统巡检 ```python from hawk.governance import Governance gov = Governance() # 记录指标 gov.log_extraction(total=10, stored=3, skipped=7) gov.log_noise_filter(filtered_count=2, total=10) gov.log_recall(hits=2, total=5) # 查看24小时统计 stats = gov.get_stats(hours=24) print(stats) # {'extractions': 10, 'noise_filtered': 2, 'recalls': 5, 'recall_hits': 2, ...} ``` --- ## HawkContext — autoCapture + autoRecall 包装器 HawkContext 是一个 Python 上下文管理器，包装 LLM 调用，自动实现： - **autoRecall**：对话开始时自动检索相关记忆并注入上下文 - **autoCapture**：对话结束时自动提取记忆存入 LanceDB ```python from hawk import HawkContext # 初始化（自动从环境变量读取配置） hawk = HawkContext( provider="minimax", # minimax | openai | groq | ollama | keyword [REDACTED_SECRET]", model="MiniMax-M2.7" ) # 对话开始时自动 recall # 对话结束时（with 块退出时）自动 capture with hawk: response = hawk.chat( "老板之前用什么技术栈？", system_prompt="你是一个助手" ) print(response) # 也可以手动控制 hawk.recall("用户的项目偏好") hawk.capture() ``` **自动 recall 机制：** - `hawk.recall()` 在 `hawk.chat()` 内部被调用 - 检索当前用户消息相关的记忆 - 结果自动插入 LLM 消息中 **支持 provider：** | provider | API Key | 说明 | |----------|---------|------| | minimax | 需要 | MiniMax-M2.7（推荐） | | openai | 需要 | GPT-4o 等 | | groq | 不需要 | 免费 Llama-3 | | ollama | 不需要 | 本地模型 | | keyword | 不需要 | 纯规则提取 | **配置优先级：** 1. 显式传参 > 环境变量 > 默认值 --- ## 与 hawk-bridge 的关系 | | context-hawk | hawk-bridge | |---|---|---| | **定位** | 纯 Python 包 | OpenClaw Hook 插件 | | **触发方式** | 手动调用 / 脚本 | 自动 Hook | | **API Key** | 可选（keyword模式不需要） | 需要 | | **用途** | 任何 Python 项目 | OpenClaw 用户 | **推荐组合：** - 独立 Python 项目 → 只装 context-hawk - OpenClaw 用户 → 装 hawk-bridge（内置 context-hawk 核心） --- ## 目录结构 ``` context-hawk/ ├── SKILL.md ← 本文档 ├── hawk/ │ ├── __init__.py │ ├── memory.py ← 四层记忆 + 衰减 │ ├── compressor.py ← 上下文压缩 │ ├── config.py ← 配置管理 │ ├── self_improving.py ← 自我反思 │ ├── vector_retriever.py ← 向量检索 │ ├── markdown_importer.py ← .md 导入 │ ├── extractor.py ← 记忆提取（keyword / LLM） │ └── governance.py ← 巡检指标 └── scripts/ └── install.sh ← 一键安装脚本 ```

path: README.de.md
content: # 🦅 Context-Hawk

> **KI-Kontext-Gedächtnis-Wächter** — Hör auf, den Faden zu verlieren, und fang an, dich an das Wichtige zu erinnern.

*Gib jedem KI-Agenten ein Gedächtnis, das wirklich funktioniert — über Sessions, Themen und Zeit hinweg.*

[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![OpenClaw Compatible](https://img.shields.io/badge/OpenClaw-2026.3%2B-brightgreen)](https://github.com/openclaw/openclaw)
[![ClawHub](https://img.shields.io/badge/ClawHub-context--hawk-blue)](https://clawhub.com)

**English** | [中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Français](README.fr.md) | [Español](README.es.md) | [Deutsch](README.de.md) | [Italiano](README.it.md) | [Русский](README.ru.md) | [Português (Brasil)](README.pt-BR.md)

---

## Was es macht

Die meisten KI-Agenten leiden an **Amnesie** — jede neue Sitzung beginnt bei Null. Context-Hawk löst das mit einem produktionsreifen Gedächtnisverwaltungssystem, das automatisch erfasst, was wichtig ist, Rauschen verblassen lässt und die richtige Erinnerung zum richtigen Zeitpunkt abruft.

**Ohne Context-Hawk:**
> "Ich habe es dir schon gesagt — ich mag kurze Antworten!"
> (nächste Sitzung, der Agent vergisst es wieder)

**Mit Context-Hawk:**
> (wendet stillschweigend deine Kommunikationspräferenzen aus Sitzung 1 an)
> ✅ Liefert jedes Mal eine präzise, direkte Antwort

---

## ❌ Without vs ✅ With Context-Hawk (TODO: translate)

| Scenario | ❌ Without Context-Hawk | ✅ With Context-Hawk |
|----------|------------------------|---------------------|
| **New session starts** | Blank — knows nothing about you | ✅ Injects relevant memories automatically |
| **User repeats a preference** | "I told you before..." | Remembers from day 1 |
| **Long task runs for days** | Restart = start over | Task state persists via `hawk resume` |
| **Context gets large** | Token bill skyrockets | 5 compression strategies keep it lean |
| **Duplicate info** | Same fact stored 10 times | SimHash dedup — stored once |
| **Memory recall** | All similar, redundant injection | MMR diverse recall — no repetition |
| **Memory management** | Everything piles up forever | 4-tier decay — noise fades, signal stays |
| **Self-improvement** | Repeats the same mistakes | importance + access_count tracking → smart promotion |
| **Multi-agent team** | Each agent starts fresh | Shared memory via LanceDB |

---

## 😰 Pain Points & Solutions (TODO: translate)

| Pain Point | Impact | Context-Hawk Solution |
|------------|--------|----------------------|
| AI forgets every session | Users repeat themselves | 4-tier memory decay |
| Long tasks lost on restart | Work wasted | `hawk resume` |
| Context overflow | Token costs spike | 5 injection + 5 compression strategies |
| Memory noise | Important info buried | AI importance scoring |
| Preferences ignored | User re-explains rules | importance ≥ 0.9 = permanent |

---

## 🎯 5 Core Problems (TODO: translate)

**Problem 1: Session context window limits**
Context has token limit (e.g. 32k). Long history crowds out important content.
→ Context-Hawk compresses/archives, injects only the most relevant.

**Problem 2: AI forgets across sessions**
Session ends → context disappears. Next conversation starts fresh.
→ `hawk recall` retrieves relevant memories for the next session.

**Problem 3: Multiple agents share nothing**
Agent A doesn't know Agent B's context.
→ Shared LanceDB (with hawk-bridge): all agents read/write the same store.

**Problem 4: Context grows too large before LLM**
Recall without optimization = large, repetitive context.
→ Compression + SimHash dedup + MMR: context is much smaller before LLM.

**Problem 5: Memory never self-manages**
No management: messages pile up until overflow.
→ Auto-extraction → importance scoring → 4-tier decay.

---

## ✨ 12 Kernfunktionen

---

## ✨ 12 Kernfunktionen

| # | Funktion | Beschreibung |
|---|---------|-------|
| 1 | **Aufgabenstatus-Persistenz** | `hawk resume` — Status speichern, nach Neustart fortsetzen |
| 2 | **4-stufiges Gedächtnis** | Working → Short → Long → Archive mit Weibull-Abfall |
| 3 | **Strukturiertes JSON** | Wichtigkeitsbewertung (0-10), Kategorie, Ebene, L0/L1/L2-Schichten |
| 4 | **KI-Wichtigkeitsbewertung** | Erinnerungen automatisch bewerten, minderwertige Inhalte verwerfen |
| 5 | **5 Injektionsstrategien** | A(high-imp) / B(aufgabenbezogen) / C(rezent) / D(top5) / E(voll) |
| 6 | **5 Kompressionsstrategien** | summarize / extract / delete / promote / archive |
| 7 | **Selbst-Introspektion** | Prüft Aufgabenklarheit, fehlende Informationen, Schleifenerkennung |
| 8 | **LanceDB-Vektorsuche** | Optional — hybride Vektor + BM25-Suche |
| 9 | **Reines Gedächtnis-Fallback** | Funktioniert ohne LanceDB, JSONL-Datei-Persistenz |
| 10 | **Auto-Deduplizierung** | Führt doppelte Erinnerungen automatisch zusammen |
| 11 | **MMR-Abruf** | Maximale Randrelevanz — vielfältiger Abruf, keine Wiederholung |
| 12 | **6-Kategorie-Extraktion** | KI-gestützte Kategorisierung: Tatsache / Präferenz / Entscheidung / Entität / Aufgabe / Sonstiges |

---

## 🚀 Schnellstart

```bash
# Einzeilige Installation (empfohlen)
bash <(curl -fsSL https://raw.githubusercontent.com/relunctance/context-hawk/master/install.sh)

# Oder direkt via pip
pip install context-hawk

# Mit allen Funktionen (inkl. sentence-transformers)
pip install "context-hawk[all]"
```

---

## 🏗️ Architektur

```
┌──────────────────────────────────────────────────────────────┐
│                      Context-Hawk                              │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  Working Memory  ←── Aktuelle Sitzung (letzte 5-10 Runden)  │
│       ↓ Weibull-Abfall                                        │
│  Short-term      ←── 24h Inhalt, zusammengefasst            │
│       ↓ access_count ≥ 10 + Wichtigkeit ≥ 0.7             │
│  Long-term       ←── Permanentes Wissen, vektorindiziert   │
│       ↓ >90 Tage oder decay_score < 0.15                    │
│  Archive          ←── Historie, bei Bedarf geladen         │
│                                                              │
├──────────────────────────────────────────────────────────────┤
│  Task State Memory  ←── Über Neustarts hinweg persistent (Schlüssel!)│
│  - Aktuelle Aufgabe / nächste Schritte / Fortschritt / Ausgaben│
├──────────────────────────────────────────────────────────────┤
│  Injektions-Engine  ←── Strategie A/B/C/D/E bestimmt Abruf │
│  Selbst-Introspektion ←── Jede Antwort prüft Kontext       │
│  Auto-Trigger        ←── Alle 10 Runden (konfigurierbar)    │
└──────────────────────────────────────────────────────────────┘
```

---

## 📦 Aufgabenstatus-Gedächtnis (Wertvollste Funktion)

Selbst nach Neustart, Stromausfall oder Sitzungswechsel setzt Context-Hawk genau dort fort, wo es aufgehört hat.

```json
// memory/.hawk/task_state.jsonl
{
  "task_id": "task_20260329_001",
  "description": "API-Dokumentation abschließen",
  "status": "in_progress",
  "progress": 65,
  "next_steps": ["Architekturvorlage überprüfen", "Benutzer Bericht erstatten"],
  "outputs": ["SKILL.md", "constitution.md"],
  "constraints": ["Abdeckung muss 98% erreichen", "APIs müssen versioniert sein"],
  "resumed_count": 3
}
```

```bash
hawk task "Dokumentation abschließen"  # Aufgabe erstellen
hawk task --step 1 done             # Schritt als erledigt markieren
hawk resume                           # Nach Neustart fortsetzen ← KERN!
```

---

## 🧠 Strukturiertes Gedächtnis

```json
{
  "id": "mem_20260329_001",
  "type": "task|knowledge|conversation|document|preference|decision",
  "content": "Vollständiger Originalinhalt",
  "summary": "Einzeilige Zusammenfassung",
  "importance": 0.85,
  "tier": "working|short|long|archive",
  "created_at": "2026-03-29T00:00:00+08:00",
  "access_count": 3,
  "decay_score": 0.92
}
```

### Wichtigkeitsbewertung

| Bewertung | Typ | Aktion |
|-------|------|--------|
| 0.9-1.0 | Entscheidungen/Regeln/Fehler | Permanent, langsamster Abfall |
| 0.7-0.9 | Aufgaben/Präferenzen/Wissen | Langzeitgedächtnis |
| 0.4-0.7 | Dialog/Diskussion | Kurzzeit, Abfall zu Archiv |
| 0.0-0.4 | Chat/Begrüßungen | **Verwerfen, niemals speichern** |

---

## 🎯 5 Kontextinjektionsstrategien

| Strategie | Auslöser | Einsparung |
|----------|---------|-----------|
| **A: Hohe Wichtigkeit** | `Wichtigkeit ≥ 0.7` | 60-70% |
| **B: Aufgabenbezogen** | Scope-Treffer | 30-40% ← Standard |
| **C: Aktuell** | letzte 10 Runden | 50% |
| **D: Top5 Abruf** | Top 5 `access_count` | 70% |
| **E: Voll** | kein Filter | 100% |

---

## 🗜️ 5 Kompressionsstrategien

`summarize` · `extract` · `delete` · `promote` · `archive`

---

## 🔔 4-stufiges Alarm-System

| Stufe | Schwellenwert | Aktion |
|-------|---------|--------|
| ✅ Normal | < 60% | Still |
| 🟡 Beobachten | 60-79% | Kompression vorschlagen |
| 🔴 Kritisch | 80-94% | Auto-Schreiben pausieren, Vorschlag erzwingen |
| 🚨 Gefahr | ≥ 95% | Schreiben blockieren, Kompression Pflicht |

---

## 🚀 Schnellstart

```bash
# LanceDB-Plugin installieren (empfohlen)
openclaw plugins install memory-lancedb-pro@beta

# Skill aktivieren
openclaw skills install ./context-hawk.skill

# Initialisieren
hawk init

# Kernbefehle
hawk task "Meine Aufgabe"    # Aufgabe erstellen
hawk resume             # Letzte Aufgabe fortsetzen ← SEHR WICHTIG
hawk status            # Kontextnutzung anzeigen
hawk compress          # Gedächtnis komprimieren
hawk strategy B        # Zum aufgabenbezogenen Modus wechseln
hawk introspect         # Selbst-Introspektionsbericht
```

---

## Auto-Trigger: Alle N Runden

Alle **10 Runden** (Standard, konfigurierbar) führt Context-Hawk automatisch aus:

1. Kontext-Wasserstand prüfen
2. Gedächtniswichtigkeit bewerten
3. Status an Benutzer melden
4. Kompression vorschlagen, wenn nötig

```bash
# Konfiguration (memory/.hawk/config.json)
{
  "auto_check_rounds": 10,          # alle N Runden prüfen
  "keep_recent": 5,                 # letzte N Runden bewahren
  "auto_compress_threshold": 70      # komprimieren wenn > 70%
}
```

---

## Dateistruktur

```
context-hawk/
├── SKILL.md
├── README.md
├── LICENSE
├── scripts/
│   └── hawk               # Python CLI-Werkzeug
└── references/
    ├── memory-system.md           # 4-Ebenen-Architektur
    ├── structured-memory.md      # Gedächtnisformat und Wichtigkeit
    ├── task-state.md           # Aufgabenstatus-Persistenz
    ├── injection-strategies.md  # 5 Injektionsstrategien
    ├── compression-strategies.md # 5 Kompressionsstrategien
    ├── alerting.md             # Alarmsystem
    ├── self-introspection.md   # Selbst-Introspektion
    ├── lancedb-integration.md  # LanceDB-Integration
    └── cli.md                  # CLI-Referenz
```

---

## Technische Daten

| | |
|---|---|
| **Persistenz** | JSONL lokale Dateien, keine Datenbank erforderlich |
| **Vektorsuche** | LanceDB (optional) + sentence-transformers local embedding, automatisches Fallback auf Dateien |
| **Suche** | BM25 + ANN Vektorsuche + RRF-Fusion |
| **Embedding-Anbieter** | Ollama / sentence-transformers / Jina AI / Minimax / OpenAI |
| **Cross-Agent** | Universell, keine Geschäftslogik, funktioniert mit jedem KI-Agenten |
| **Null-Konfiguration** | Sofort einsatzbereit mit intelligenten Standardwerten (BM25-only Modus) |
| **Python** | 3.12+ |

---

## Lizenz

MIT — frei verwendbar, änderbar und verteilbar.


path: README.es.md
content: # 🦅 Context-Hawk

> **Guardián de Memoria Contextual para IA** — Deja de perder el hilo, empieza a recordar lo que importa.

*Dale a cualquier agente de IA una memoria que realmente funciona — a través de sesiones, temas y tiempo.*

[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![OpenClaw Compatible](https://img.shields.io/badge/OpenClaw-2026.3%2B-brightgreen)](https://github.com/openclaw/openclaw)
[![ClawHub](https://img.shields.io/badge/ClawHub-context--hawk-blue)](https://clawhub.com)

**English** | [中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Français](README.fr.md) | [Español](README.es.md) | [Deutsch](README.de.md) | [Italiano](README.it.md) | [Русский](README.ru.md) | [Português (Brasil)](README.pt-BR.md)

---

## ¿Qué hace?

La mayoría de los agentes de IA sufren de **amnesia** — cada nueva sesión comienza desde cero. Context-Hawk lo resuelve con un sistema de gestión de memoria de grado de producción que captura automáticamente lo que importa, deja que el ruido se disipe, y recupera el recuerdo correcto en el momento correcto.

**Sin Context-Hawk:**
> "¡Ya te lo dije — prefiero respuestas concisas!"
> (próxima sesión, el agente olvida otra vez)

**Con Context-Hawk:**
> (aplca silenciosamente tus preferencias de comunicación desde la sesión 1)
> ✅ Entrega respuesta concisa y directa cada vez

---

## ❌ Without vs ✅ With Context-Hawk (TODO: translate)

| Scenario | ❌ Without Context-Hawk | ✅ With Context-Hawk |
|----------|------------------------|---------------------|
| **New session starts** | Blank — knows nothing about you | ✅ Injects relevant memories automatically |
| **User repeats a preference** | "I told you before..." | Remembers from day 1 |
| **Long task runs for days** | Restart = start over | Task state persists via `hawk resume` |
| **Context gets large** | Token bill skyrockets | 5 compression strategies keep it lean |
| **Duplicate info** | Same fact stored 10 times | SimHash dedup — stored once |
| **Memory recall** | All similar, redundant injection | MMR diverse recall — no repetition |
| **Memory management** | Everything piles up forever | 4-tier decay — noise fades, signal stays |
| **Self-improvement** | Repeats the same mistakes | importance + access_count tracking → smart promotion |
| **Multi-agent team** | Each agent starts fresh | Shared memory via LanceDB |

---

## ✨ 12 Funcionalidades Principales

---

## ✨ 12 Funcionalidades Principales

| # | Funcionalidad | Descripción |
|---|---------|-------|
| 1 | **Persistencia de Estado de Tarea** | `hawk resume` — persiste el estado, recupera tras reinicio |
| 2 | **Memoria de 4 Niveles** | Working → Short → Long → Archive con decaimiento Weibull |
| 3 | **JSON Estructurado** | Puntuación de importancia (0-10), categoría, nivel, capas L0/L1/L2 |
| 4 | **Puntuación de Importancia IA** | Puntuación automática de recuerdos, descarta contenido de bajo valor |
| 5 | **5 Estrategias de Inyección** | A(alta-imp) / B(tarea) / C(reciente) / D(top5) / E(completo) |
| 6 | **5 Estrategias de Compresión** | summarize / extract / delete / promote / archive |
| 7 | **Auto-Introspección** | Verifica claridad de tarea, info faltante, detección de bucle |
| 8 | **Búsqueda Vectorial LanceDB** | Opcional — búsqueda híbrida vectorial + BM25 |
| 9 | **Fallback de Memoria Pura** | Funciona sin LanceDB, persistencia JSONL |
| 10 | **Autodeduplicación** | Fusiona automáticamente recuerdos duplicados |
| 11 | **MMR Recall** | Maximal Marginal Relevance — diverse recall, no repetition |
| 12 | **6-Category Extraction** | LLM-powered: fact / preference / decision / entity / task / other |

---

## 🚀 Instalación Rápida

```bash
# Instalación en una línea (recomendado)
bash <(curl -fsSL https://raw.githubusercontent.com/relunctance/context-hawk/master/install.sh)

# O directamente via pip
pip install context-hawk

# Con todas las funciones (incluyendo sentence-transformers)
pip install "context-hawk[all]"
```

---

## 🏗️ Arquitectura

```
┌──────────────────────────────────────────────────────────────┐
│                      Context-Hawk                              │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  Working Memory  ←── Sesión actual (últimos 5-10 turnos)     │
│       ↓ Decaimiento Weibull                                   │
│  Short-term      ←── Contenido 24h, resumido               │
│       ↓ access_count ≥ 10 + importancia ≥ 0.7             │
│  Long-term       ←── Conocimiento permanente, indexado vectorial│
│       ↓ >90 días o decay_score < 0.15                        │
│  Archive          ←── Histórico, cargado bajo demanda          │
│                                                              │
├──────────────────────────────────────────────────────────────┤
│  Task State Memory  ←── Persistente entre reinicios (¡clave!)│
│  - Tarea actual / siguientes pasos / progreso / salidas        │
├──────────────────────────────────────────────────────────────┤
│  Motor de Inyección  ←── Estrategia A/B/C/D/E decide el recall│
│  Auto-Introspección ←── Cada respuesta verifica el contexto   │
│  Auto-Trigger        ←── Cada 10 turnos (configurable)       │
└──────────────────────────────────────────────────────────────┘
```

---

## 📦 Memoria de Estado de Tarea (Característica Más Valiosa)

Incluso después de reinicio, corte de energía o cambio de sesión, Context-Hawk continúa exactamente donde lo dejó.

```json
// memory/.hawk/task_state.jsonl
{
  "task_id": "task_20260329_001",
  "description": "Completar la documentación de la API",
  "status": "in_progress",
  "progress": 65,
  "next_steps": ["Revisar plantilla de arquitectura", "Informar al usuario"],
  "outputs": ["SKILL.md", "constitution.md"],
  "constraints": ["La cobertura debe alcanzar el 98%", "Las APIs deben estar versionadas"],
  "resumed_count": 3
}
```

```bash
hawk task "Completar la documentación"  # Crear tarea
hawk task --step 1 done             # Marcar paso completado
hawk resume                           # Recuperar tras reinicio ← ¡CLAVE!
```

---

## 🧠 Memoria Estructurada

```json
{
  "id": "mem_20260329_001",
  "type": "task|knowledge|conversation|document|preference|decision",
  "content": "Contenido original completo",
  "summary": "Resumen en una línea",
  "importance": 0.85,
  "tier": "working|short|long|archive",
  "created_at": "2026-03-29T00:00:00+08:00",
  "access_count": 3,
  "decay_score": 0.92
}
```

### Puntuación de Importancia

| Puntuación | Tipo | Acción |
|-------|------|--------|
| 0.9-1.0 | Decisiones/reglas/errores | Permanente, decaimiento más lento |
| 0.7-0.9 | Tareas/preferencias/conocimiento | Memoria largo plazo |
| 0.4-0.7 | Diálogo/discusión | Corto plazo, decaimiento a archivo |
| 0.0-0.4 | Chat/saludos | **Descartar, nunca almacenar** |

---

## 🎯 5 Estrategias de Inyección de Contexto

| Estrategia | Disparador | Ahorro |
|----------|-----------|--------|
| **A: Alta Importancia** | `importancia ≥ 0.7` | 60-70% |
| **B: Relacionada con Tarea** | scope coincide | 30-40% ← por defecto |
| **C: Reciente** | últimos 10 turnos | 50% |
| **D: Top5 Recall** | top 5 `access_count` | 70% |
| **E: Completo** | sin filtro | 100% |

---

## 🗜️ 5 Estrategias de Compresión

`summarize` · `extract` · `delete` · `promote` · `archive`

---

## 🔔 Sistema de Alerta de 4 Niveles

| Nivel | Umbral | Acción |
|-------|--------|--------|
| ✅ Normal | < 60% | Silencioso |
| 🟡 Vigilancia | 60-79% | Sugerir compresión |
| 🔴 Crítico | 80-94% | Pausar escritura auto, forzar sugerencia |
| 🚨 Peligro | ≥ 95% | Bloquear escrituras, comprimir obligatorio |

---

## 🚀 Inicio Rápido

```bash
# Instalar plugin LanceDB (recomendado)
openclaw plugins install memory-lancedb-pro@beta

# Activar skill
openclaw skills install ./context-hawk.skill

# Inicializar
hawk init

# Comandos esenciales
hawk task "Mi tarea"    # Crear tarea
hawk resume             # Recuperar última tarea ← MUY IMPORTANTE
hawk status            # Ver uso de contexto
hawk compress          # Comprimir memoria
hawk strategy B        # Cambiar a modo relacionado con tarea
hawk introspect         # Informe de auto-introspección
```

---

## Auto-Trigger: Cada N Turnos

Cada **10 turnos** (por defecto, configurable), Context-Hawk automáticamente:

1. Verifica nivel de contexto
2. Evalúa importancia de recuerdos
3. Te reporta el estado
4. Sugiere compresión si es necesario

```bash
# Config (memory/.hawk/config.json)
{
  "auto_check_rounds": 10,          # verificar cada N turnos
  "keep_recent": 5,                 # preservar últimos N turnos
  "auto_compress_threshold": 70      # comprimir cuando > 70%
}
```

---

## Estructura de Archivos

```
context-hawk/
├── SKILL.md
├── README.md
├── LICENSE
├── scripts/
│   └── hawk               # Herramienta CLI Python
└── references/
    ├── memory-system.md           # Arquitectura de 4 niveles
    ├── structured-memory.md      # Formato de memoria e importancia
    ├── task-state.md           # Persistencia de estado de tarea
    ├── injection-strategies.md  # 5 estrategias de inyección
    ├── compression-strategies.md # 5 estrategias de compresión
    ├── alerting.md             # Sistema de alerta
    ├── self-introspection.md   # Auto-introspección
    ├── lancedb-integration.md  # Integración LanceDB
    └── cli.md                  # Referencia CLI
```

---

## Especificaciones Técnicas

| | |
|---|---|
| **Persistencia** | Archivos JSONL locales, sin base de datos |
| **Búsqueda Vectorial** | LanceDB (opcional) + sentence-transformers embedding local, fallback automático a archivos |
| **Búsqueda** | BM25 + búsqueda vectorial ANN + fusión RRF |
| **Proveedores de Embedding** | Ollama / sentence-transformers / Jina AI / Minimax / OpenAI |
| **Cross-Agent** | Universal, sin lógica de negocio, funciona con cualquier agente IA |
| **Cero Configuración** | Funciona listo para usar (modo BM25-only) |
| **Python** | 3.12+ |

---

## Licencia

MIT — libre para usar, modificar y distribuir.


path: README.fr.md
content: # 🦅 Context-Hawk

> **Gardien de Mémoire Contextuelle pour l'IA** — Arrêtez de perdre le fil, commencez à retenir ce qui compte.

*Donnez à n'importe quel agent IA une mémoire qui fonctionne vraiment — à travers les sessions, les sujets, le temps.*

[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![OpenClaw Compatible](https://img.shields.io/badge/OpenClaw-2026.3%2B-brightgreen)](https://github.com/openclaw/openclaw)
[![ClawHub](https://img.shields.io/badge/ClawHub-context--hawk-blue)](https://clawhub.com)

**English** | [中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Français](README.fr.md) | [Español](README.es.md) | [Deutsch](README.de.md) | [Italiano](README.it.md) | [Русский](README.ru.md) | [Português (Brasil)](README.pt-BR.md)

---

## Ce qu'il fait

La plupart des agents IA souffrent d'**amnésie** — chaque nouvelle session part de zéro. Context-Hawk résout cela avec un système de gestion de mémoire de qualité production qui capture automatiquement ce qui compte, laisse le bruit se dissiper, et rappelle la bonne mémoire au bon moment.

**Sans Context-Hawk :**
> "Je t'ai déjà dit — je préfère les réponses concises !"
> (session suivante, l'agent oublie encore)

**Avec Context-Hawk :**
> (applique silencieusement vos préférences de communication depuis la session 1)
> ✅ Réponse concise et directe à chaque fois

---

## ❌ Without vs ✅ With Context-Hawk (TODO: translate)

| Scenario | ❌ Without Context-Hawk | ✅ With Context-Hawk |
|----------|------------------------|---------------------|
| **New session starts** | Blank — knows nothing about you | ✅ Injects relevant memories automatically |
| **User repeats a preference** | "I told you before..." | Remembers from day 1 |
| **Long task runs for days** | Restart = start over | Task state persists via `hawk resume` |
| **Context gets large** | Token bill skyrockets | 5 compression strategies keep it lean |
| **Duplicate info** | Same fact stored 10 times | SimHash dedup — stored once |
| **Memory recall** | All similar, redundant injection | MMR diverse recall — no repetition |
| **Memory management** | Everything piles up forever | 4-tier decay — noise fades, signal stays |
| **Self-improvement** | Repeats the same mistakes | importance + access_count tracking → smart promotion |
| **Multi-agent team** | Each agent starts fresh | Shared memory via LanceDB |

---

## ✨ 12 Fonctionnalités Principales

---

## ✨ 12 Fonctionnalités Principales

| # | Fonctionnalité | Description |
|---|---------|-------|
| 1 | **Persistance de l'État des Tâches** | `hawk resume` — persiste l'état, reprend après redémarrage |
| 2 | **Mémoire à 4 Niveaux** | Working → Short → Long → Archive avec décroissance Weibull |
| 3 | **JSON Structuré** | Score d'importance (0-10), catégorie, niveau, couches L0/L1/L2 |
| 4 | **Score d'Importance IA** | Auto-score les souvenirs, élimine le contenu à faible valeur |
| 5 | **5 Stratégies d'Injection** | A(high-imp) / B(task) / C(recent) / D(top5) / E(full) |
| 6 | **5 Stratégies de Compression** | summarize / extract / delete / promote / archive |
| 7 | **Auto-Introspection** | Vérifie la clarté de la tâche, infos manquantes, détection de boucle |
| 8 | **Recherche Vectorielle LanceDB** | Optionnel — recherche hybride vectorielle + BM25 |
| 9 | **Fallback Mémoire Pure** | Fonctionne sans LanceDB, persistance JSONL |
| 10 | **Déduplication Auto** | Fusionne automatiquement les souvenirs en double |
| 11 | **MMR Recall** | Maximal Marginal Relevance — diverse recall, no repetition |
| 12 | **6-Category Extraction** | LLM-powered: fact / preference / decision / entity / task / other |

---

## 🚀 Installation Rapide

```bash
# Installation en une ligne (recommandé)
bash <(curl -fsSL https://raw.githubusercontent.com/relunctance/context-hawk/master/install.sh)

# Ou directement via pip
pip install context-hawk

# Avec toutes les fonctionnalités (y compris sentence-transformers)
pip install "context-hawk[all]"
```

---

## 🏗️ Architecture

```
┌──────────────────────────────────────────────────────────────┐
│                      Context-Hawk                              │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  Working Memory  ←── Session actuelle (5-10 derniers tours)  │
│       ↓ Décroissance Weibull                                  │
│  Short-term      ←── Contenu 24h, résumé                    │
│       ↓ access_count ≥ 10 + importance ≥ 0.7               │
│  Long-term       ←── Connaissance permanente, indexée        │
│       ↓ >90 jours ou decay_score < 0.15                    │
│  Archive          ←── Historique, chargé à la demande       │
│                                                              │
├──────────────────────────────────────────────────────────────┤
│  Task State Memory  ←── Persistant à travers les redémarrages│
│  - Tâche actuelle / étapes suivantes / progression / sorties  │
├──────────────────────────────────────────────────────────────┤
│  Moteur d'Injection  ←── Stratégie A/B/C/D/E décide le rappel│
│  Auto-Introspection ←── Chaque réponse vérifie le contexte    │
│  Déclenchement Auto ←── Tous les 10 tours (configurable)    │
└──────────────────────────────────────────────────────────────┘
```

---

## 📦 Mémoire d'État de Tâche (Fonctionnalité la Plus Précieuse)

Même après redémarrage, coupure de courant ou changement de session, Context-Hawk reprend exactement où il s'était arrêté.

```json
// memory/.hawk/task_state.jsonl
{
  "task_id": "task_20260329_001",
  "description": "Compléter la documentation API",
  "status": "in_progress",
  "progress": 65,
  "next_steps": ["Revoir le modèle d'architecture", "Rapport à l'utilisateur"],
  "outputs": ["SKILL.md", "constitution.md"],
  "constraints": ["La couverture doit atteindre 98%", "Les API doivent être versionnées"],
  "resumed_count": 3
}
```

```bash
hawk task "Compléter la documentation"  # Créer une tâche
hawk task --step 1 done             # Marquer étape terminée
hawk resume                           # Reprendre après redémarrage ← ESSENTIEL !
```

---

## 🧠 Mémoire Structurée

```json
{
  "id": "mem_20260329_001",
  "type": "task|knowledge|conversation|document|preference|decision",
  "content": "Contenu original complet",
  "summary": "Résumé en une ligne",
  "importance": 0.85,
  "tier": "working|short|long|archive",
  "created_at": "2026-03-29T00:00:00+08:00",
  "access_count": 3,
  "decay_score": 0.92
}
```

### Score d'Importance

| Score | Type | Action |
|-------|------|--------|
| 0.9-1.0 | Décisions/règles/erreurs | Permanent, décroissance la plus lente |
| 0.7-0.9 | Tâches/préférences/connaissances | Mémoire long terme |
| 0.4-0.7 | Dialogue/discussion | Court terme, décroissance vers archive |
| 0.0-0.4 | Chat/_messages de salutation | **Éliminer, ne jamais stocker** |

---

## 🎯 5 Stratégies d'Injection de Contexte

| Stratégie | Déclencheur | Économie |
|----------|-----------|----------|
| **A: Haute Importance** | `importance ≥ 0.7` | 60-70% |
| **B: Liée à la Tâche** | scope correspond | 30-40% ← défaut |
| **C: Récente** | 10 derniers tours | 50% |
| **D: Top5 Rappel** | top 5 `access_count` | 70% |
| **E: Complète** | pas de filtre | 100% |

---

## 🗜️ 5 Stratégies de Compression

`summarize` · `extract` · `delete` · `promote` · `archive`

---

## 🔔 Système d'Alerte à 4 Niveaux

| Niveau | Seuil | Action |
|-------|-------|--------|
| ✅ Normal | < 60% | Silencieux |
| 🟡 Surveiller | 60-79% | Suggestion de compression |
| 🔴 Critique | 80-94% | Pause écriture auto, forcer suggestion |
| 🚨 Danger | ≥ 95% | Bloquer écritures, compression obligatoire |

---

## 🚀 Démarrage Rapide

```bash
# Installer le plugin LanceDB (recommandé)
openclaw plugins install memory-lancedb-pro@beta

# Activer le skill
openclaw skills install ./context-hawk.skill

# Initialiser
hawk init

# Commandes essentielles
hawk task "Ma tâche"    # Créer une tâche
hawk resume             # Reprendre la dernière tâche ← TRÈS IMPORTANT
hawk status            # Voir l'utilisation du contexte
hawk compress          # Compresser la mémoire
hawk strategy B        # Passer en mode lié à la tâche
hawk introspect         # Rapport d'auto-introspection
```

---

## Déclenchement Auto : Tous les N Tours

Tous les **10 tours** (défaut, configurable), Context-Hawk automatiquement :

1. Vérifie le niveau d'eau du contexte
2. Évalue l'importance des souvenirs
3. Vous rapporte le statut
4. Suggère une compression si nécessaire

```bash
# Config (memory/.hawk/config.json)
{
  "auto_check_rounds": 10,
  "keep_recent": 5,
  "auto_compress_threshold": 70
}
```

---

## Structure des Fichiers

```
context-hawk/
├── SKILL.md
├── README.md
├── LICENSE
├── scripts/
│   └── hawk               # Outil CLI Python
└── references/
    ├── memory-system.md           # Architecture 4 niveaux
    ├── structured-memory.md      # Format mémoire et importance
    ├── task-state.md           # Persistance état de tâche
    ├── injection-strategies.md  # 5 stratégies d'injection
    ├── compression-strategies.md # 5 stratégies de compression
    ├── alerting.md             # Système d'alerte
    ├── self-introspection.md   # Auto-introspection
    ├── lancedb-integration.md  # Intégration LanceDB
    └── cli.md                  # Référence CLI
```

---

## Spécifications Techniques

| | |
|---|---|
| **Persistance** | Fichiers JSONL locaux, pas de base de données |
| **Recherche Vectorielle** | LanceDB (optionnel) + sentence-transformers embedding local, repli automatique vers fichiers |
| **Recherche** | BM25 + recherche vectorielle ANN + fusion RRF |
| **Fournisseurs d'Embedding** | Ollama / sentence-transformers / Jina AI / Minimax / OpenAI |
| **Cross-Agent** | Universel, sans logique métier, fonctionne avec n'importe quel agent IA |
| **Zéro Config** | Fonctionne prêt à l'emploi (mode BM25-only) |
| **Python** | 3.12+ |

---

## Licence

MIT — libre d'utilisation, modification et distribution.


path: README.it.md
content: # 🦅 Context-Hawk

> **Guardiano della Memoria Contestuale IA** — Smetti di perdere il filo, inizia a ricordare ciò che conta.

*Dai a qualsiasi agente IA una memoria che funziona davvero — attraverso sessioni, argomenti e tempo.*

[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![OpenClaw Compatible](https://img.shields.io/badge/OpenClaw-2026.3%2B-brightgreen)](https://github.com/openclaw/openclaw)
[![ClawHub](https://img.shields.io/badge/ClawHub-context--hawk-blue)](https://clawhub.com)

**English** | [中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Français](README.fr.md) | [Español](README.es.md) | [Deutsch](README.de.md) | [Italiano](README.it.md) | [Русский](README.ru.md) | [Português (Brasil)](README.pt-BR.md)

---

## Cosa fa

La maggior parte degli agenti IA soffre di **amnesia** — ogni nuova sessione parte da zero. Context-Hawk risolve questo con un sistema di gestione della memoria di livello produzione che cattura automaticamente ciò che conta, fa svanire il rumore e richiama il ricordo giusto al momento giusto.

**Senza Context-Hawk:**
> "Te l'ho già detto — preferisco risposte concise!"
> (sessione successiva, l'agente dimentica di nuovo)

**Con Context-Hawk:**
> (applica silenziosamente le tue preferenze di comunicazione dalla sessione 1)
> ✅ Risposta concisa e diretta ogni volta

---

## ❌ Without vs ✅ With Context-Hawk (TODO: translate)

| Scenario | ❌ Without Context-Hawk | ✅ With Context-Hawk |
|----------|------------------------|---------------------|
| **New session starts** | Blank — knows nothing about you | ✅ Injects relevant memories automatically |
| **User repeats a preference** | "I told you before..." | Remembers from day 1 |
| **Long task runs for days** | Restart = start over | Task state persists via `hawk resume` |
| **Context gets large** | Token bill skyrockets | 5 compression strategies keep it lean |
| **Duplicate info** | Same fact stored 10 times | SimHash dedup — stored once |
| **Memory recall** | All similar, redundant injection | MMR diverse recall — no repetition |
| **Memory management** | Everything piles up forever | 4-tier decay — noise fades, signal stays |
| **Self-improvement** | Repeats the same mistakes | importance + access_count tracking → smart promotion |
| **Multi-agent team** | Each agent starts fresh | Shared memory via LanceDB |

---

## ✨ 12 Funzionalità Principali

---

## ✨ 12 Funzionalità Principali

| # | Funzionalità | Descrizione |
|---|---------|-------|
| 1 | **Persistenza Stato Attività** | `hawk resume` — persiste lo stato, riprendi dopo riavvio |
| 2 | **Memoria a 4 Livelli** | Working → Short → Long → Archive con decadimento Weibull |
| 3 | **JSON Strutturato** | Punteggio di importanza (0-10), categoria, livello, strati L0/L1/L2 |
| 4 | **Punteggio Importanza IA** | Assegna automaticamente punteggio ai ricordi, scarta contenuto a basso valore |
| 5 | **5 Strategie di Iniezione** | A(alta-imp) / B(collegata attività) / C(recente) / D(top5) / E(completa) |
| 6 | **5 Strategie di Compressione** | summarize / extract / delete / promote / archive |
| 7 | **Auto-Introspezione** | Verifica chiarezza attività, info mancanti, rilevamento loop |
| 8 | **Ricerca Vettoriale LanceDB** | Opzionale — ricerca ibrida vettoriale + BM25 |
| 9 | **Fallback Memoria Pura** | Funziona senza LanceDB, persistenza JSONL |
| 10 | **Auto-Deduplicazione** | Unisce automaticamente i ricordi duplicati |
| 11 | **MMR Recall** | Maximal Marginal Relevance — diverse recall, no repetition |
| 12 | **6-Category Extraction** | LLM-powered: fact / preference / decision / entity / task / other |

---

## 🚀 Avvio Rapido

```bash
# Installazione in una riga (consigliata)
bash <(curl -fsSL https://raw.githubusercontent.com/relunctance/context-hawk/master/install.sh)

# Oppure direttamente via pip
pip install context-hawk

# Con tutte le funzionalità (inclusi sentence-transformers)
pip install "context-hawk[all]"
```

---

## 📦 Memoria Stato Attività (Funzionalità Più Preziosa)

Anche dopo riavvio, interruzione di corrente o cambio sessione, Context-Hawk riprende esattamente da dove aveva lasciato.

```json
// memory/.hawk/task_state.jsonl
{
  "task_id": "task_20260329_001",
  "description": "Completare la documentazione API",
  "status": "in_progress",
  "progress": 65,
  "next_steps": ["Rivedi template architettura", "Riporta all'utente"],
  "outputs": ["SKILL.md", "constitution.md"],
  "constraints": ["Copertura deve raggiungere il 98%", "Le API devono essere versionate"],
  "resumed_count": 3
}
```

```bash
hawk task "Completa la documentazione"  # Crea attività
hawk task --step 1 done             # Segna passo completato
hawk resume                           # Riprendi dopo riavvio ← FONDAMENTALE!
```

---

## 🧠 Memoria Strutturata

```json
{
  "id": "mem_20260329_001",
  "type": "task|knowledge|conversation|document|preference|decision",
  "content": "Contenuto originale completo",
  "summary": "Riepilogo in una riga",
  "importance": 0.85,
  "tier": "working|short|long|archive",
  "created_at": "2026-03-29T00:00:00+08:00",
  "access_count": 3,
  "decay_score": 0.92
}
```

### Punteggio di Importanza

| Punteggio | Tipo | Azione |
|-------|------|--------|
| 0.9-1.0 | Decisioni/regole/errori | Permanente, decadimento più lento |
| 0.7-0.9 | Attività/preferenze/conoscenze | Memoria a lungo termine |
| 0.4-0.7 | Dialogo/discussione | Breve termine, decadimento verso archivio |
| 0.0-0.4 | Chat/saluti | **Scartare, mai memorizzare** |

---

## 🎯 5 Strategie di Iniezione Contestuale

| Strategia | Trigger | Risparmio |
|----------|---------|--------|
| **A: Alta Importanza** | `importanza ≥ 0.7` | 60-70% |
| **B: Collegata all'Attività** | scope corrisponde | 30-40% ← predefinito |
| **C: Recente** | ultimi 10 turni | 50% |
| **D: Top5 Richiamo** | top 5 `access_count` | 70% |
| **E: Completa** | nessun filtro | 100% |

---

## 🗜️ 5 Strategie di Compressione

`summarize` · `extract` · `delete` · `promote` · `archive`

---

## 🔔 Sistema di Avviso a 4 Livelli

| Livello | Soglia | Azione |
|-------|--------|--------|
| ✅ Normale | < 60% | Silenzioso |
| 🟡 Osservazione | 60-79% | Suggerisci compressione |
| 🔴 Critico | 80-94% | Metti in pausa scrittura auto, forza suggerimento |
| 🚨 Pericolo | ≥ 95% | Blocca scritture, compressione obbligatoria |

---

## 🚀 Avvio Rapido

```bash
# Installa plugin LanceDB (consigliato)
openclaw plugins install memory-lancedb-pro@beta

# Attiva skill
openclaw skills install ./context-hawk.skill

# Inizializza
hawk init

# Comandi essenziali
hawk task "La mia attività"    # Crea attività
hawk resume             # Riprendi ultima attività ← MOLTO IMPORTANTE
hawk status            # Visualizza utilizzo contesto
hawk compress          # Comprimi memoria
hawk strategy B        # Passa a modo collegato all'attività
hawk introspect         # Report di auto-introspezione
```

---

## Auto-Trigger: Ogni N Turni

Ogni **10 turni** (predefinito, configurabile), Context-Hawk automaticamente:

1. Controlla livello contesto
2. Valuta importanza dei ricordi
3. Ti riporta lo stato
4. Suggerisce compressione se necessario

```bash
# Configurazione (memory/.hawk/config.json)
{
  "auto_check_rounds": 10,          # controlla ogni N turni
  "keep_recent": 5,                 # preserva ultimi N turni
  "auto_compress_threshold": 70      # comprimi quando > 70%
}
```

---

## Struttura File

```
context-hawk/
├── SKILL.md
├── README.md
├── LICENSE
├── scripts/
│   └── hawk               # Strumento CLI Python
└── references/
    ├── memory-system.md           # Architettura a 4 livelli
    ├── structured-memory.md      # Formato memoria e importanza
    ├── task-state.md           # Persistenza stato attività
    ├── injection-strategies.md  # 5 strategie di iniezione
    ├── compression-strategies.md # 5 strategie di compressione
    ├── alerting.md             # Sistema di avviso
    ├── self-introspection.md   # Auto-introspezione
    ├── lancedb-integration.md  # Integrazione LanceDB
    └── cli.md                  # Riferimento CLI
```

---

## Specifiche Tecniche

| | |
|---|---|
| **Persistenza** | File JSONL locali, nessun database richiesto |
| **Ricerca vettoriale** | LanceDB (opzionale) + sentence-transformers embedding locale, fallback automatico su file |
| **Ricerca** | BM25 + ricerca vettoriale ANN + fusione RRF |
| **Provider di Embedding** | Ollama / sentence-transformers / Jina AI / Minimax / OpenAI |
| **Cross-Agent** | Universale, nessuna logica di business, funziona con qualsiasi agente IA |
| **Zero-Config** | Funziona out-of-the-box (modalità BM25-only) |
| **Python** | 3.12+ |

---

## Licenza

MIT — libero di utilizzare, modificare e distribuire.


path: README.ja.md
content: # 🦅 Context-Hawk

> **AI コンテキスト記憶ガーディアン** — 追跡を失うことをやめ、重要ことを記憶し始める。

*どの AI agent にも、session をまたぎ、トピックをまたぎ、時間を超えて実際に機能する記憶を。*

[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![OpenClaw Compatible](https://img.shields.io/badge/OpenClaw-2026.3%2B-brightgreen)](https://github.com/openclaw/openclaw)
[![ClawHub](https://img.shields.io/badge/ClawHub-context--hawk-blue)](https://clawhub.com)

**English** | [中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Français](README.fr.md) | [Español](README.es.md) | [Deutsch](README.de.md) | [Italiano](README.it.md) | [Русский](README.ru.md) | [Português (Brasil)](README.pt-BR.md)

---

## 何をするのか？

ほとんどの AI agent は**健忘症**に苦しんでいます — 新しい session が開始されるたびにゼロから始まります。Context-Hawk は、本番対応の記憶管理システムでこれ問題を解決します。重要なことを自動的に捕捉し、ノイズを忘れさせ、正しい時間に正しい記憶を思い出させます。

**Context-Hawk なし：**
> "もう言いましたよね — 簡潔な返信が好きだって！"
>（次の session、agent はまた忘れる）

**Context-Hawk あり：**
>（session 1 から静かにコミュニケーションの好みを適用）
> ✅ 毎回簡潔で直接的な回答を配信

---

## ❌ Context-Hawk なし vs ✅ Context-Hawk あり

| シナリオ | ❌ Context-Hawk なし | ✅ Context-Hawk あり |
|----------|------------------------|---------------------|
| **新しい session の開始** | 空白 — あなたについて何も知らない | ✅ 関連する記憶を自動注入 |
| **ユーザーが好みを繰り返す** | "前に言ったよね..." | 初日から記憶 |
| **長期間のタスクが数日間実行** | 再起動 = 最初から | Task State 持続化、`hawk resume` でシームレス |
| **コンテキストが肥大化** | Token 料金急騰、パフォーマンス低下 | 5つの圧縮戦略で軽量維持 |
| **重複情報** | 同じ事実が10回保存される | SimHash 重複排除 — 1回だけ保存 |
| **記憶のリコール** | 全て類似、繰り返し注入 | MMR 多様なリコール — 繰り返しなし |
| **記憶管理** | 全てが永久に蓄積 | 4層崩壊 — ノイズは消え、 сигナルは残る |
| **自己改善** | 同じミスを繰り返す | importance + access_count 追跡 → スマート促進 |
| **マルチエージェントチーム** | 各エージェントが最初から開始、共有コンテキストなし | 共有記憶（ LanceDB 経由）— 全エージェントが互いに学習 |

---

## 😰 痛点 & 解決策

| 痛点 | 影響 | Context-Hawk 解決策 |
|------|------|----------------------|
| **AI が各 session で忘れる** | ユーザーが同じことを何度も言う必要がある | 4層記憶崩壊 — 重要なコンテンツが自動的に保持 |
| **長時間タスクが再起動後に丢失** | 作業が無駄に、コンテキストが完全に消える | `hawk resume` — タスク状態が再起動を跨いで持続 |
| **コンテキストの膨張** | Token 料金急騰、応答が低速化 | 5つの注入戦略 + 5つの圧縮戦略 |
| **記憶ノイズ** | 重要な情報がチャット履歴に埋もれる | AI 重要度スコアリング — 低価値コンテンツを自動破棄 |
| **好みが忘れられる** | ユーザーが毎回ルールを説明し直す必要がある | 重要度 ≥ 0.9 = 永久記憶 |

**コアバリュー：** Context-Hawk は、AI agent に実際に機能する記憶を付与します — 何もかも保存するのではなく、重要なことをインテリジェントに保持し、重要でないことを忘れます。

---

## 🎯 5つのコア問題を解決

**問題 1：セッションコンテキストウィンドウの制限**
コンテキストにはトークン上限があります（例：32k）。長い履歴は重要なコンテンツを押し出します。
→ Context-Hawk は古いコンテンツを圧縮/アーカイブし、最も関連する記憶だけを注入します。

**問題 2：セッションをまたいだ記憶の消失**
セッションが終了すると、コンテキストが消えます。、次の会話はゼロから始まります。
→ 記憶は永続的に保存されます。`hawk recall` は次のセッションで関連する記憶を取得します。

**問題 3：複数のエージェントが互いに情報を共有しない**
Agent A は Agent B のコンテキストをしません。ある agent が行った決定は他の agent には見えません。
→ 共有 LanceDB 記憶庫（hawk-bridge と組み合わせて使用）：全 agent が同じ記憶を読み書き。サイロなし。

**問題 4：LLM に送信する前のコンテキストの肥大化**
最適化のないリコール = 大規模で繰り返しコンテキスト。
→ 圧縮 + SimHash 重複排除 + MMR リコール後：LLM に送信されるコンテキストは**大幅に縮小**され、token とコストを節約。

**問題 5：記憶が自ら管理しない**
管理メカニズムなし：全メッセージが堆積し、コンテキストがオーバーフローするまで蓄積。
→ 自動抽出 → 重要度スコアリング → 4層崩壊。不重要 → 削除。重要 → 長期記憶に昇格。

---

## ✨ 12 のコア機能

| # | 機能 | 説明 |
|---|---------|-------|
| 1 | **タスク状態持続性** | `hawk resume` — タスク状態を保持、再起動後も再開可能 |
| 2 | **4層記憶** | Working → Short → Long → Archive（Weibull 崩壊付） |
| 3 | **構造化 JSON** | 重要度スコア（0-10）、カテゴリ、ティア、L0/L1/L2 レイヤー |
| 4 | **AI 重要度スコアリング** | 記憶に自動スコア、低価値コンテンツは破棄 |
| 5 | **5つの注入戦略** | A(高重要度) / B(タスク関連) / C(最近) / D(Top5) / E(フル) |
| 6 | **5つの圧縮戦略** | summarize / extract / delete / promote / archive |
| 7 | **自己内省** | タスクの明確さ、欠落情報、ループ検出をチェック |
| 8 | **LanceDB ベクトル検索** | オプション — ハイブリッド vector + BM25 検索 |
| 9 | **Pure-Memory フォールバック** | LanceDB なしでも動作、JSONL ファイル永続化 |
| 10 | **自動重複排除** | SimHash 重複排除、重複記憶を削除 |
| 11 | **MMR リコール** | 最大辺縁関連性 — 多様なリコール、繰り返しなし |
| 12 | **6カテゴリ抽出** | LLM 駆動の分類抽出：事実 / 好み / 決定 / エンティティ / タスク / その他 |

---

## 🚀 クイックインストール

```bash
# ワンラインインストール（推奨）
bash <(curl -fsSL https://raw.githubusercontent.com/relunctance/context-hawk/master/install.sh)

# またはpipで直接
pip install context-hawk

# 全機能インストール（含 sentence-transformers）
pip install "context-hawk[all]"
```

---

## 🏗️ アーキテクチャ

```
┌──────────────────────────────────────────────────────────────┐
│                      Context-Hawk                              │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  Working Memory  ←── 現在の session（最近 5-10 ターン）    │
│       ↓ Weibull 崩壊                                        │
│  Short-term      ←── 24時間コンテンツ、要約済み             │
│       ↓ access_count ≥ 10 + 重要度 ≥ 0.7                │
│  Long-term       ←── 永続的知識、ベクトルインデックス        │
│       ↓ >90 日または decay_score < 0.15                      │
│  Archive          ←── 履歴、オンデマンドでロード           │
│                                                              │
├──────────────────────────────────────────────────────────────┤
│  Task State Memory  ←── 再起動間を永続化（重要！）          │
│  - 現在のタスク / 次のステップ / 進捗 / 出力             │
├──────────────────────────────────────────────────────────────┤
│  注入エンジン       ←── 戦略 A/B/C/D/E が検索を決定       │
│  自己内省            ←── 毎回答がコンテキストをチェック     │
│  自動トリガー        ←── 毎 10 ターン（設定可能）        │
└──────────────────────────────────────────────────────────────┘
```

---

## 📦 タスク状態記憶（最も価値のある機能）

再起動、電源障害、session 切替後も、Context-Hawk は中断した正確な位置から再開します。

```json
// memory/.hawk/task_state.jsonl
{
  "task_id": "task_20260329_001",
  "description": "API 文書を完成させる",
  "status": "in_progress",
  "progress": 65,
  "next_steps": ["アーキテクチャテンプレートをレビュー", "ユーザーに報告"],
  "outputs": ["SKILL.md", "constitution.md"],
  "constraints": ["カバー率は98%必須", "APIはバージョン化管理"],
  "resumed_count": 3
}
```

```bash
hawk task "文書を完成させる"  # タスク作成
hawk task --step 1 done     # ステップ完了をマーク
hawk resume                   # 再起動後に再開 ← コア機能！
```

---

## 🧠 構造化記憶

```json
{
  "id": "mem_20260329_001",
  "type": "task|knowledge|conversation|document|preference|decision",
  "content": "完全な元のコンテンツ",
  "summary": "1行サマリー",
  "importance": 0.85,
  "tier": "working|short|long|archive",
  "created_at": "2026-03-29T00:00:00+08:00",
  "access_count": 3,
  "decay_score": 0.92
}
```

### 重要度スコアリング

| スコア | タイプ | アクション |
|-------|------|--------|
| 0.9-1.0 | 決定/規則/エラー | 永久、最も遅い崩壊 |
| 0.7-0.9 | タスク/好み/知識 | 長期記憶 |
| 0.4-0.7 | 対話/議論 | 短期、アーカイブへ崩壊 |
| 0.0-0.4 | チャット/挨拶 | **破棄、決して格納しない** |

---

## 🎯 5 つのコンテキスト注入戦略

| 戦略 | トリガー | 節約量 |
|------|---------|--------|
| **A: 高重要性** | `重要度 ≥ 0.7` | 60-70% |
| **B: タスク関連** | スコープ一致 | 30-40% ← デフォルト |
| **C: 最近** | 最後 10 ターン | 50% |
| **D: Top5 リコール** | `access_count` Top 5 | 70% |
| **E: フル** | フィルターなし | 100% |

---

## 🗜️ 5 つの圧縮戦略

`summarize` · `extract` · `delete` · `promote` · `archive`

---

## 🔔 4段階アラートシステム

| レベル | 閾値 | アクション |
|-------|---------|------|
| ✅ Normal | < 60% | サイレント |
| 🟡 Watch | 60-79% | 圧縮を提案 |
| 🔴 Critical | 80-94% | 自動書き込みを一時停止、強制提案 |
| 🚨 Danger | ≥ 95% | 書き込みをブロック、圧縮必須 |

---

## 🚀 クイックスタート

```bash
# LanceDB プラグインをインストール（推奨）
openclaw plugins install memory-lancedb-pro@beta

# スキルを有効化
openclaw skills install ./context-hawk.skill

# 初期化
hawk init

# コアコマンド
hawk task "私のタスク"    # タスク作成
hawk resume             # 最後のタスクを再開 ← 最も重要
hawk status            # コンテキスト使用状況を查看
hawk compress          # 記憶を圧縮
hawk strategy B        # タスク関連モードに切替
hawk introspect         # 自己内省レポート
```

---

## 自動トリガー：毎 N ターン

毎 **10 ターン**（デフォルト、設定可能）、Context-Hawk は自動的に：

1. コンテキスト水位を確認
2. 記憶の重要度を評価
3. ユーザーに状況を報告
4. 必要に応じて圧縮を提案

```bash
# 設定（memory/.hawk/config.json）
{
  "auto_check_rounds": 10,          # 毎 N ターン確認
  "keep_recent": 5,                 # 最後の N ターンを保持
  "auto_compress_threshold": 70      # 70% を超えたら圧縮
}
```

---

## ファイル構造

```
context-hawk/
├── SKILL.md
├── README.md
├── LICENSE
├── scripts/
│   └── hawk               # Python CLI ツール
└── references/
    ├── memory-system.md           # 4層アーキテクチャ
    ├── structured-memory.md      # 記憶フォーマットと重要度
    ├── task-state.md           # タスク状態持続性
    ├── injection-strategies.md  # 5つの注入戦略
    ├── compression-strategies.md # 5つの圧縮戦略
    ├── alerting.md             # アラートシステム
    ├── self-introspection.md   # 自己内省
    ├── lancedb-integration.md  # LanceDB 統合
    └── cli.md                  # CLI リファレンス
```

---

## 🔌 技術仕様

| | |
|---|---|
| **永続化** | JSONL ローカルファイル、データベース不要 |
| **ベクトル検索** | LanceDB（オプション）+ sentence-transformers ローカルベクトル、ファイルへの自動フォールバック |
| **検索** | BM25 + ANN ベクトル検索 + RRF フュージョン |
| **Embedding プロバイダー** | Ollama / sentence-transformers / Jina AI / Minimax / OpenAI |
| **Cross-Agent** | 汎用、ビジネスロジックなし、任意の AI agent で動作 |
| **ゼロ設定** | 優れたデフォルトで箱から出してすぐ動作（BM25-only モード） |
| **Python** | 3.12+ |

---

## ライセンス

MIT — 無償で可以使用、修正、配布できます。


path: README.ko.md
content: # 🦅 Context-Hawk

> **AI 컨텍스트 메모리 가디언** — 추적을 잃는 것을 멈추고, 중요한 것을 기억하기 시작하세요.

*어떤 AI 에이전트에게도 session을 넘어, 주제를 넘어, 시간을超越하여 실제로 작동하는 기억을 제공하세요.*

[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![OpenClaw Compatible](https://img.shields.io/badge/OpenClaw-2026.3%2B-brightgreen)](https://github.com/openclaw/openclaw)
[![ClawHub](https://img.shields.io/badge/ClawHub-context--hawk-blue)](https://clawhub.com)

**English** | [中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Français](README.fr.md) | [Español](README.es.md) | [Deutsch](README.de.md) | [Italiano](README.it.md) | [Русский](README.ru.md) | [Português (Brasil)](README.pt-BR.md)

---

## 무엇을 하나요?

대부분의 AI 에이전트는 **건망증**으로 고통받습니다 — 새로운 session이 시작될 때마다零에서 시작합니다. Context-Hawk는 생산グレード 메모리 관리 시스템으로 이것을 해결합니다. 중요한 것을 자동으로 캡처하고, 노이즈를 희석시키며, 올바른 시간에 올바른 기억을思い出します.

**Context-Hawk 없이:**
> "이미 말했잖아요 — 간결한 답장을 좋아한다고!"
> (다음 session, 에이전트가 다시 잊어버림)

**Context-Hawk 사용 시:**
> (session 1에서 자동으로 커뮤니케이션 선호도를 적용)
> ✅ 매번 간결하고 직접적인 응답을 제공

---

## ❌ Context-Hawk 없음 vs ✅ Context-Hawk 있음

| 시나리오 | ❌ Context-Hawk 없음 | ✅ Context-Hawk 있음 |
|----------|------------------------|---------------------|
| **새 session 시작** |空白 — 당신에 대해 아무것도 모름 | ✅ 관련 기억을 자동으로 주입 |
| **사용자가 선호도를 반복** | "전에 말했잖아..." | 첫날부터 기억 |
| **며칠 동안 장기 작업 실행** | 재시작 = 처음부터 | Task State 지속화, `hawk resume`으로 완벽 연결 |
| **컨텍스트가 커짐** | Token 비용 급등, 성능 저하 | 5가지 압축 전략으로 가벼움 유지 |
| **중복 정보** | 같은 사실이 10번 저장됨 | SimHash 중복 제거 — 1번만 저장 |
| **기억 리콜** | 모두 유사, 반복 주입 | MMR 다양한 리콜 — 반복 없음 |
| **기억 관리** | 모든 것이 영구적으로 누적 | 4계층衰减 — 노이즈는 사라지고, 시그널은 유지 |
| **자기 개선** | 같은 실수를 반복 | importance + access_count 추적 → 스마트 승격 |
| **멀티 에이전트 팀** | 각 에이전트가 처음부터 시작, 공유 컨텍스트 없음 | 공유 기억 (LanceDB 통해) — 모든 에이전트가 서로 학습 |

---

## 😰 문제점 & 해결책

| 문제점 | 영향 | Context-Hawk 해결책 |
|------|------|----------------------|
| **AI가 각 session마다 기억을 잃음** | 사용자가 같은 말을 반복해서 해야 함 | 4계층 기억衰减 — 중요한 콘텐츠가 자동으로 유지 |
| **장기 작업이 재시작 후丢失** | 작업이 낭비되고, 컨텍스트가 완전히 사라짐 | `hawk resume` — 작업 상태가 재시작을 넘어 지속 |
| **컨텍스트膨胀** | Token 비용이 급등하고, 응답이 느려짐 | 5가지 주입 전략 + 5가지 압축 전략 |
| **기억 노이즈** | 중요한 정보가 채팅 이력에 묻힘 | AI 중요도 점수화 — 저가치 콘텐츠를 자동으로 폐기 |
| **선호도가 잊혀짐** | 사용자가 매번 규칙을 다시 설명해야 함 | 중요도 ≥ 0.9 = 영구 기억 |

**핵심 가치:** Context-Hawk는 AI 에이전트에 실제로 작동하는 기억을 제공합니다 — 모든 것을 저장하는 것이 아니라, 중요한 것을 지능적으로 유지하고 중요하지 않은 것은 잊어버립니다.

---

## 🎯 5가지 핵심 문제를 해결

**문제 1: 세션 컨텍스트 창 제한**
컨텍스트에는 토큰 제한이 있습니다(예: 32k). 긴 이력은 중요한 콘텐츠를 밀어냅니다.
→ Context-Hawk는古い 콘텐츠를 압축/보관하고 가장 관련된 기억만 주입합니다.

**문제 2: 세션을またいだ기억 상실**
세션이 종료되면 컨텍스트가 사라집니다. 다음 대화는零から始まります。
→ 기억은 영구적으로 저장됩니다. `hawk recall`은 다음 세션에서 관련된 기억을 검색합니다.

**문제 3: 여러 에이전트가 서로 정보를 공유하지 않음**
Agent A는 Agent B의 컨텍스트를 모릅니다. 한 에이전트가 내린 결정은 다른 에이전트에게 보이지 않습니다.
→ 공유 LanceDB 기억소( hawk-bridge와 함께 사용): 모든 에이전트가 같은 기억을 읽고 씁니다. 사일로 없음.

**문제 4: LLM에送信前 컨텍스트가 이미膨胀함**
최적화 없는 리콜 = 크고 반복적인 컨텍스트.
→ 압축 + SimHash 중복 제거 + MMR 리콜 후: LLM에送信される 컨텍스트는**대폭缩小**되어 토큰과 비용을 절약합니다.

**문제 5: 기억이 스스로管理하지 않음**
관리 메커니즘 없음: 모든 메시지가 쌓여서 컨텍스트가 overflow될 때까지.
→ 자동 추출 → 중요도 점수화 → 4계층衰减. 중요하지 않음 → 삭제. 중요함 → 장기 기억으로 승격.

---

## ✨ 12가지 핵심 기능

| # | 기능 | 설명 |
|---|---------|-------|
| 1 | **작업 상태 지속성** | `hawk resume` — 작업 상태 보존, 재시작 후 계속 |
| 2 | **4계층 메모리** | Working → Short → Long → Archive, Weibull衰减 적용 |
| 3 | **구조화된 JSON** | 중요도 점수(0-10), 카테고리, 티어, L0/L1/L2 레이어 |
| 4 | **AI 중요도 점수화** | 기억에 자동 점수 부여, 저가치 콘텐츠 폐기 |
| 5 | **5가지 주입 전략** | A(높은 중요도) / B(작업 관련) / C(최근) / D(Top5) / E(전체) |
| 6 | **5가지 압축 전략** | summarize / extract / delete / promote / archive |
| 7 | **자기 성찰** | 작업 명확성, 누락된 정보, 루프 감지 확인 |
| 8 | **LanceDB 벡터 검색** | 선택 사항 — 하이브리드 vector + BM25 검색 |
| 9 | **순수 메모리 폴백** | LanceDB 없이 동작, JSONL 파일 지속성 |
| 10 | **자동 중복 제거** | SimHash 중복 제거, 중복 기억을 제거 |
| 11 | **MMR 리콜** | 최대 한계 관련성 — 다양한 리콜, 반복 없음 |
| 12 | **6카테고리 추출** | LLM 기반 분류 추출: 사실 / 선호도 / 결정 / 엔티티 / 작업 / 기타 |

---

## 🚀 빠른 설치

```bash
# 원라인 설치 (권장)
bash <(curl -fsSL https://raw.githubusercontent.com/relunctance/context-hawk/master/install.sh)

# 또는 pip로 직접
pip install context-hawk

# 전체 기능 설치 (sentence-transformers 포함)
pip install "context-hawk[all]"
```

---

## 🏗️ 아키텍처

```
┌──────────────────────────────────────────────────────────────┐
│                      Context-Hawk                              │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  Working Memory  ←── 현재 session (최근 5-10턴)           │
│       ↓ Weibull衰减                                         │
│  Short-term      ←── 24시간 콘텐츠, 요약됨               │
│       ↓ access_count ≥ 10 + 중요도 ≥ 0.7                │
│  Long-term       ←── 영구 지식, 벡터 인덱싱               │
│       ↓ >90일 또는 decay_score < 0.15                     │
│  Archive          ←── 이력, 요청 시 로드                   │
│                                                              │
├──────────────────────────────────────────────────────────────┤
│  Task State Memory  ←── 재시작 간 지속 (핵심!)            │
│  - 현재 작업 / 다음 단계 / 진행률 / 출력물                  │
├──────────────────────────────────────────────────────────────┤
│  주입 엔진       ←── 전략 A/B/C/D/E가 리콜 결정           │
│  자기 성찰        ←── 매 답변 시 컨텍스트 확인              │
│  자동 트리거      ←── 매 10턴 (설정 가능)                │
└──────────────────────────────────────────────────────────────┘
```

---

## 📦 작업 상태 메모리 (가장 가치 있는 기능)

재시작, 정전 또는 session 전환 후에도 Context-Hawk는 정확한 중단 지점에서 재개합니다.

```json
// memory/.hawk/task_state.jsonl
{
  "task_id": "task_20260329_001",
  "description": "API 문서 완료",
  "status": "in_progress",
  "progress": 65,
  "next_steps": ["아키텍처 템플릿 검토", "사용자에게 보고"],
  "outputs": ["SKILL.md", "constitution.md"],
  "constraints": ["커버율 98% 필수", "API는 버전化管理"],
  "resumed_count": 3
}
```

```bash
hawk task "문서 완료"        # 작업 생성
hawk task --step 1 done  # 단계 완료 표시
hawk resume               # 재시작 후 재개 ← 핵심!
```

---

## 🧠 구조화된 메모리

```json
{
  "id": "mem_20260329_001",
  "type": "task|knowledge|conversation|document|preference|decision",
  "content": "완전한 원본 콘텐츠",
  "summary": "한 줄 요약",
  "importance": 0.85,
  "tier": "working|short|long|archive",
  "created_at": "2026-03-29T00:00:00+08:00",
  "access_count": 3,
  "decay_score": 0.92
}
```

### 중요도 점수화

| 점수 | 유형 | 행동 |
|-------|------|------|
| 0.9-1.0 | 결정/규칙/오류 | 영구, 가장 느린衰减 |
| 0.7-0.9 | 작업/선호도/지식 | 장기 기억 |
| 0.4-0.7 | 대화/논의 | 단기, archive로衰减 |
| 0.0-0.4 | 채팅/인사 | **폐기, 절대 저장 안 함** |

---

## 🎯 5가지 컨텍스트 주입 전략

| 전략 | 트리거 | 절약 |
|------|---------|------|
| **A: 높은 중요도** | `중요도 ≥ 0.7` | 60-70% |
| **B: 작업 관련** | scope 일치 | 30-40% ← 기본값 |
| **C: 최근** | 마지막 10턴 | 50% |
| **D: Top5 리콜** | `access_count` Top 5 | 70% |
| **E: 전체** | 필터 없음 | 100% |

---

## 🗜️ 5가지 압축 전략

`summarize` · `extract` · `delete` · `promote` · `archive`

---

## 🔔 4단계 알림 시스템

| 레벨 | 임계값 | 행동 |
|-------|---------|------|
| ✅ Normal | < 60% | 자동 |
| 🟡 Watch | 60-79% | 압축 제안 |
| 🔴 Critical | 80-94% | 자동 쓰기 일시 중지, 강제 제안 |
| 🚨 Danger | ≥ 95% | 쓰기 차단, 압축 필수 |

---

## 🚀 빠른 시작

```bash
# LanceDB 플러그인 설치 (권장)
openclaw plugins install memory-lancedb-pro@beta

# 스킬 활성화
openclaw skills install ./context-hawk.skill

# 초기화
hawk init

# 핵심 명령
hawk task "내 작업"    # 작업 생성
hawk resume             # 마지막 작업 재개 ← 가장 중요
hawk status            # 컨텍스트 사용량 확인
hawk compress          # 메모리 압축
hawk strategy B        # 작업 관련 모드로 전환
hawk introspect         # 자기 성찰 보고서
```

---

## 자동 트리거: 매 N턴

매 **10턴** (기본값, 설정 가능), Context-Hawk가 자동으로:

1. 컨텍스트 수위 확인
2. 기억 중요도 평가
3. 사용자에게 상태 보고
4. 필요 시 압축 제안

```bash
# 설정 (memory/.hawk/config.json)
{
  "auto_check_rounds": 10,          # 매 N턴 확인
  "keep_recent": 5,                 # 마지막 N턴 보존
  "auto_compress_threshold": 70      # 70% 초과 시 압축
}
```

---

## 파일 구조

```
context-hawk/
├── SKILL.md
├── README.md
├── LICENSE
├── scripts/
│   └── hawk               # Python CLI 도구
└── references/
    ├── memory-system.md           # 4계층 아키텍처
    ├── structured-memory.md      # 메모리 형식 및 중요도
    ├── task-state.md           # 작업 상태 지속성
    ├── injection-strategies.md  # 5가지 주입 전략
    ├── compression-strategies.md # 5가지 압축 전략
    ├── alerting.md             # 알림 시스템
    ├── self-introspection.md   # 자기 성찰
    ├── lancedb-integration.md  # LanceDB 통합
    └── cli.md                  # CLI 참조
```

---

## 🔌 기술 사양

| | |
|---|---|
| **지속성** | JSONL 로컬 파일, 데이터베이스 불필요 |
| **벡터 검색** | LanceDB (선택) + sentence-transformers 로컬 벡터, 파일로 자동 폴백 |
| **검색** | BM25 + ANN 벡터 검색 + RRF 퓨전 |
| **Embedding 제공자** | Ollama / sentence-transformers / Jina AI / Minimax / OpenAI |
| **Cross-Agent** | 범용, 비지니스 로직 없음, 모든 AI 에이전트와 동작 |
| **제로 설정** | 스마트 기본값, 즉시 사용 가능 (BM25-only 모드) |
| **Python** | 3.12+ |

---

## 라이선스

MIT — 무료로 사용, 수정, 배포 가능.


path: README.pt-BR.md
content: # 🦅 Context-Hawk

> **Guardião de Memória Contextual de IA** — Pare de perder o fio, comece a lembrar o que importa.

*Dê a qualquer agente de IA uma memória que realmente funciona — através de sessões, tópicos e tempo.*

[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![OpenClaw Compatible](https://img.shields.io/badge/OpenClaw-2026.3%2B-brightgreen)](https://github.com/openclaw/openclaw)
[![ClawHub](https://img.shields.io/badge/ClawHub-context--hawk-blue)](https://clawhub.com)

**English** | [中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Français](README.fr.md) | [Español](README.es.md) | [Deutsch](README.de.md) | [Italiano](README.it.md) | [Русский](README.ru.md) | [Português (Brasil)](README.pt-BR.md)

---

## O que ele faz

A maioria dos agentes de IA sofrem de **amnésia** — cada nova sessão começa do zero. O Context-Hawk resolve isso com um sistema de gerenciamento de memória de nível de produção que captura automaticamente o que importa, deixa o ruído sumir e lembra o que é certo na hora certa.

**Sem Context-Hawk:**
> "Eu já te disse — prefiro respostas concisas!"
> (próxima sessão, o agente esquece de novo)

**Com Context-Hawk:**
> (aplica silenciosamente suas preferências de comunicação desde a sessão 1)
> ✅ Entrega resposta concisa e direta toda vez

---

## ❌ Without vs ✅ With Context-Hawk (TODO: translate)

| Scenario | ❌ Without Context-Hawk | ✅ With Context-Hawk |
|----------|------------------------|---------------------|
| **New session starts** | Blank — knows nothing about you | ✅ Injects relevant memories automatically |
| **User repeats a preference** | "I told you before..." | Remembers from day 1 |
| **Long task runs for days** | Restart = start over | Task state persists via `hawk resume` |
| **Context gets large** | Token bill skyrockets | 5 compression strategies keep it lean |
| **Duplicate info** | Same fact stored 10 times | SimHash dedup — stored once |
| **Memory recall** | All similar, redundant injection | MMR diverse recall — no repetition |
| **Memory management** | Everything piles up forever | 4-tier decay — noise fades, signal stays |
| **Self-improvement** | Repeats the same mistakes | importance + access_count tracking → smart promotion |
| **Multi-agent team** | Each agent starts fresh | Shared memory via LanceDB |

---

## ✨ 12 Funcionalidades Principais

---

## ✨ 12 Funcionalidades Principais

| # | Funcionalidade | Descrição |
|---|---------|-------|
| 1 | **Persistência de Estado de Tarefa** | `hawk resume` — persiste o estado, retoma após reinício |
| 2 | **Memória de 4 Camadas** | Working → Short → Long → Archive com decaimento Weibull |
| 3 | **JSON Estruturado** | Pontuação de importância (0-10), categoria, camada, camadas L0/L1/L2 |
| 4 | **Pontuação de Importância IA** | Pontua automaticamente as memórias, descarta conteúdo de baixo valor |
| 5 | **5 Estratégias de Injeção** | A(alta-imp) / B(relacionada à tarefa) / C(recente) / D(top5) / E(completa) |
| 6 | **5 Estratégias de Compressão** | summarize / extract / delete / promote / archive |
| 7 | **Auto-Introspecção** | Verifica clareza da tarefa, informações faltantes, detecção de loop |
| 8 | **Busca Vetorial LanceDB** | Opcional — busca híbrida vetorial + BM25 |
| 9 | **Fallback Memória Pura** | Funciona sem LanceDB, persistência JSONL |
| 10 | **Autodeduplicação** | Mescla automaticamente memórias duplicadas |
| 11 | **MMR Recall** | Maximal Marginal Relevance — diverse recall, no repetition |
| 12 | **6-Category Extraction** | LLM-powered: fact / preference / decision / entity / task / other |

---

## 🚀 Instalação Rápida

```bash
# Instalação em uma linha (recomendado)
bash <(curl -fsSL https://raw.githubusercontent.com/relunctance/context-hawk/master/install.sh)

# Ou diretamente via pip
pip install context-hawk

# Com todas as funcionalidades (incluindo sentence-transformers)
pip install "context-hawk[all]"
```

---

## 📦 Memória de Estado de Tarefa (Funcionalidade Mais Valiosa)

Mesmo após reinício, queda de energia ou troca de sessão, Context-Hawk continua exatamente de onde parou.

```json
// memory/.hawk/task_state.jsonl
{
  "task_id": "task_20260329_001",
  "description": "Completar a documentação da API",
  "status": "in_progress",
  "progress": 65,
  "next_steps": ["Revisar template de arquitetura", "Relatar ao usuário"],
  "outputs": ["SKILL.md", "constitution.md"],
  "constraints": ["Cobertura deve alcançar 98%", "APIs devem ser versionadas"],
  "resumed_count": 3
}
```

```bash
hawk task "Completar a documentação"  # Criar tarefa
hawk task --step 1 done             # Marcar passo concluído
hawk resume                           # Retomar após reinício ← ESSENCIAL!
```

---

## 🧠 Memória Estruturada

```json
{
  "id": "mem_20260329_001",
  "type": "task|knowledge|conversation|document|preference|decision",
  "content": "Conteúdo original completo",
  "summary": "Resumo em uma linha",
  "importance": 0.85,
  "tier": "working|short|long|archive",
  "created_at": "2026-03-29T00:00:00+08:00",
  "access_count": 3,
  "decay_score": 0.92
}
```

### Pontuação de Importância

| Pontuação | Tipo | Ação |
|-------|------|--------|
| 0.9-1.0 | Decisões/regras/erros | Permanente, decaimento mais lento |
| 0.7-0.9 | Tarefas/preferências/conhecimento | Memória de longo prazo |
| 0.4-0.7 | Diálogo/discussão | Curto prazo, decaimento para arquivo |
| 0.0-0.4 | Chat/mensagens de saudação | **Descartar, nunca armazenar** |

---

## 🎯 5 Estratégias de Injeção de Contexto

| Estratégia | Gatilho | Economia |
|----------|---------|---------|
| **A: Alta Importância** | `importância ≥ 0.7` | 60-70% |
| **B: Relacionada à Tarefa** | scope coincide | 30-40% ← padrão |
| **C: Recente** | últimos 10 turnos | 50% |
| **D: Top5 Recall** | top 5 `access_count` | 70% |
| **E: Completa** | sem filtro | 100% |

---

## 🗜️ 5 Estratégias de Compressão

`summarize` · `extract` · `delete` · `promote` · `archive`

---

## 🔔 Sistema de Alerta de 4 Níveis

| Nível | Limiar | Ação |
|-------|--------|--------|
| ✅ Normal | < 60% | Silencioso |
| 🟡 Observação | 60-79% | Sugerir compressão |
| 🔴 Crítico | 80-94% | Pausar escrita automática, forçar sugestão |
| 🚨 Perigo | ≥ 95% | Bloquear escritas, compressão obrigatória |

---

## 🚀 Início Rápido

```bash
# Instalar plugin LanceDB (recomendado)
openclaw plugins install memory-lancedb-pro@beta

# Ativar skill
openclaw skills install ./context-hawk.skill

# Inicializar
hawk init

# Comandos essenciais
hawk task "Minha tarefa"    # Criar tarefa
hawk resume             # Retomar última tarefa ← MUITO IMPORTANTE
hawk status            # Ver uso de contexto
hawk compress          # Comprimir memória
hawk strategy B        # Mudar para modo relacionado à tarefa
hawk introspect         # Relatório de auto-introspecção
```

---

## Auto-Trigger: A Cada N Turnos

A cada **10 turnos** (padrão, configurável), Context-Hawk automaticamente:

1. Verifica nível de contexto
2. Avalia importância das memórias
3. Relata status ao usuário
4. Sugere compressão se necessário

```bash
# Configuração (memory/.hawk/config.json)
{
  "auto_check_rounds": 10,          # verificar a cada N turnos
  "keep_recent": 5,                 # preservar últimos N turnos
  "auto_compress_threshold": 70      # comprimir quando > 70%
}
```

---

## Estrutura de Arquivos

```
context-hawk/
├── SKILL.md
├── README.md
├── LICENSE
├── scripts/
│   └── hawk               # Ferramenta CLI Python
└── references/
    ├── memory-system.md           # Arquitetura de 4 camadas
    ├── structured-memory.md      # Formato de memória e importância
    ├── task-state.md           # Persistência de estado de tarefa
    ├── injection-strategies.md  # 5 estratégias de injeção
    ├── compression-strategies.md # 5 estratégias de compressão
    ├── alerting.md             # Sistema de alerta
    ├── self-introspection.md   # Auto-introspecção
    ├── lancedb-integration.md  # Integração LanceDB
    └── cli.md                  # Referência CLI
```

---

## Especificações Técnicas

| | |
|---|---|
| **Persistência** | Arquivos JSONL locais, sem banco de dados |
| **Busca vetorial** | LanceDB (opcional) + sentence-transformers embedding local, fallback automático para arquivos |
| **Busca** | BM25 + busca vetorial ANN + fusão RRF |
| **Provedores de Embedding** | Ollama / sentence-transformers / Jina AI / Minimax / OpenAI |
| **Cross-Agent** | Universal, sem lógica de negócio, funciona com qualquer agente de IA |
| **Zero-Config** | Funciona pronto para uso (modo BM25-only) |
| **Python** | 3.12+ |

---

## Licença

MIT — livre para usar, modificar e distribuir.


path: hawk/__init__.py
content: """
hawk — context-hawk core modules

Pure Python memory package:
- MemoryManager: 四层记忆 + Weibull衰减
- ContextCompressor: 上下文压缩
- Config: 配置管理
- SelfImproving: 自我反思学习
- VectorRetriever: 向量检索
- MarkdownImporter: Markdown导入
- Extractor: LLM记忆提取（支持keyword/llm模式）
- Governance: 治理指标
- HawkContext: LLM wrapper with autoCapture + autoRecall
"""

from .memory import MemoryManager
from .compressor import ContextCompressor
from .config import Config
from .self_improving import SelfImproving
from .vector_retriever import VectorRetriever, RetrievedChunk
from .markdown_importer import MarkdownImporter
from .governance import Governance
from .extractor import extract_memories
from .wrapper import HawkContext

__all__ = [
    "MemoryManager",
    "ContextCompressor",
    "Config",
    "SelfImproving",
    "VectorRetriever",
    "RetrievedChunk",
    "MarkdownImporter",
    "Governance",
    "extract_memories",
    "HawkContext",
]


path: scripts/cron_health_check.sh
content: #!/bin/bash
# context-hawk 定时健康检查
# 发现 bug 或改进点则自动 commit + push

REPO="$HOME/.openclaw/workspace/context-hawk"
cd "$REPO"

LOG="$REPO/tests/health_check.log"
DATE=$(date "+%Y-%m-%d %H:%M:%S")

echo "[$DATE] Running health check..." >> "$LOG"

# 运行健康检查，捕获退出码
OUTPUT=$(python3 "$REPO/tests/health_check.py" 2>&1)
EXIT=$?

echo "$OUTPUT" >> "$LOG"

if [ $EXIT -ne 0 ]; then
    echo "[$DATE] ❌ Tests failed, committing fixes..." >> "$LOG"
    # 有测试失败，尝试自动修复
    git add -A
    git commit -m "fix: auto-fix from health check cron [$DATE]"
    git push >> "$LOG" 2>&1
    echo "[$DATE] ✅ Fixes committed and pushed" >> "$LOG"
else
    echo "[$DATE] ✅ All tests passed, no changes needed" >> "$LOG"
fi


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)