hAIve — Camada de Política de Contexto para Agentes de IA
Doucs91/hAIve
Contexto de equipe auditável e executável para agentes de codificação
Ver no GitHubMCP server que implementa um sistema de memória e política de contexto nativo do repositório para agentes de IA em tarefas de código. Fornece briefing antes da execução, valida mudanças contra decisões da equipe e bloqueia alterações que violam políticas de repositório através de gates em Git, CI e MCP.
Instalação
npx convez-ai Doucs91/hAIve1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Garantir que agentes de IA respeitem decisões arquiteturais da equipe
- Prevenir violações de padrões e anti-padrões conhecidos em mudanças de código
- Capturar e reutilizar conhecimento de repositório específico em sessões de agentes
- Validar mudanças contra políticas de negócio (ex: formato de IDs, campos obrigatórios)
Veredito

Solução madura e bem arquitetada para o problema real de agentes de IA perderem contexto crítico do repositório. Essencial para times que usam agentes de código em produção; implementação clara com bom ciclo de feedback (briefing → execução → enforcement).
README
A tradução para o português deste README ainda está na fila.
hAIve is the team-knowledge layer inside an AI coding-agent harness. It gives agents a feedforward briefing before work starts, then adds feedback gates in MCP, Git hooks, CI, and wrappers so changes cannot quietly bypass repo policy.
A capable model already knows generic best practice. What it cannot guess is your team's arbitrary, repo-specific knowledge: that public ids are id + 100000 prefixed AC-, that the status field must be "OK"/"KO", that you never edit an applied migration. Left to itself, a confident agent invents a plausible answer - clean, tested, green, and wrong by policy. hAIve carries that unguessable knowledge into the task and blocks the change that's about to violate it.
hAIve's job is not to replace tests, linters, or observability. It makes the repo-specific knowledge those tools cannot infer available, auditable, and enforceable.
The problem
AI coding agents are powerful, but they often act with incomplete repo context. Compaction, parallel sessions, agent switches, and stale advisory docs all create the same failure mode: the agent changes code without carrying the team's current decisions into the work.
Most teams work around this with instructions and hope:
- "Please read our architecture decisions first."
- "Don't repeat the migration mistake from last sprint."
- "Remember to capture what you learned."
- "Don't merge code that invalidates a team decision."
Those rules are easy to skip. hAIve turns them into repo-native context policy.
How it works
AI agent ──▶ hAIve briefing ──▶ code change ──▶ hAIve policy gate ──▶ merge
▲ │
└── context breadcrumbs · decisions · gotchas · anchors
haive initcreates a.ai/context policy layer in your repo.- Agents start every session with
get_briefing— one MCP call that returns small default context plus deeper breadcrumbs ranked by task relevance. - Decisions, gotchas, failed attempts, and session recaps live as Markdown files anchored to the code paths they describe. When code moves, hAIve detects stale anchors.
haive enforce checkand CI enforcement block unsafe states: missing briefing, stale critical decisions, an anchored anti-pattern your diff is about to repeat, or uncaptured session knowledge.
Memory is the substrate. Context enforcement is the product promise. AI changes should not enter the codebase without consulting the team's current knowledge.
Where hAIve fits in the harness
Harness engineering is about the environment around the model: feedforward guidance before it acts, feedback sensors after it acts, and workflow gates that keep bad states from landing. hAIve owns the repo-specific context policy part of that harness.
| Harness concern | hAIve role |
|---|---|
| Feedforward guidance | get_briefing, module context, skills, decisions, gotchas, failed attempts |
| Feedback and gates | MCP ordering policy, pre_commit_check, Git hooks, CI enforcement, stale-anchor detection |
| Knowledge lifecycle | Git-native Markdown records, path/symbol anchors, confidence, retirement, linting |
| Boundaries | hAIve complements unit/e2e tests, type checks, runtime traces, security scanners, and LLM evals; it does not try to replace them |
The narrow positioning is intentional: hAIve is not a general memory database or an agent dashboard. It is the control layer that helps coding agents act with the validated, non-obvious knowledge of the team.
Executable memory sensors
Some gotcha and attempt memories can now carry a sensor block: a deterministic regex guardrail
that scans the added lines of a diff. Sensors turn a documented lesson into a repeatable feedback
signal, independent of embeddings or model judgment. Autogenerated sensors start as warn; humans can
promote high-confidence ones to block.
haive sensors list
haive sensors check # scans git diff --cached
haive sensors promote <id> --yes # promote a vetted sensor to block
haive sensors export --format grep
Install
npm install -g @hiveai/cli
# Optional: local semantic search (downloads ~110MB model once)
npm install -g @hiveai/embeddings
Quick start
1. Initialize your project
cd my-project
haive init # Creates .ai/, bridge files, MCP config, hooks, CI template
haive init now also runs agent setup. It writes project-level MCP configs, records the best available mode, and asks before changing user-level client configs. In non-interactive shells it skips global config and tells you how to finish setup.
2. Connect your AI client
Claude Code (~/.claude.json):
{
"mcpServers": {
"haive": {
"command": "haive",
"args": ["mcp", "--stdio", "--root", "/absolute/path/to/my-project"]
}
}
}
Cursor (~/.cursor/mcp.json):
{
"mcpServers": {
"haive": {
"command": "haive",
"args": ["mcp", "--stdio", "--root", "/absolute/path/to/my-project"]
}
}
}
VS Code:
code --add-mcp '{"name":"haive","command":"haive","args":["mcp","--stdio","--root","/path/to/project"]}'
3. Bootstrap your project context
In your AI client, invoke the bootstrap_project MCP prompt. The agent analyzes your codebase and writes .ai/project-context.md automatically.
4. Start work through hAIve
Every session starts with one call:
get_briefing(task: "add a Stripe payment integration", files: ["src/payments/PaymentService.ts"])
The agent gets project context + relevant module contexts + ranked context breadcrumbs in one shot — no more grepping to rediscover what the team already knows.
For CLI agents without native MCP, wrap them:
haive run -- claude --dangerously-skip-permissions -p "$(cat task.md)"
Check the selected mode any time:
haive agent status
haive agent setup # re-run setup later
haive agent setup --yes # approve user-level MCP config without prompting
5. Gate commits and pull requests
haive enforce install # Installs Git hooks + CI enforcement template
haive enforce status # Current enforcement posture
haive enforce check # Pre-commit policy gate
haive enforce ci # CI entrypoint (exits 1 on violations)
CLI at a glance — the golden path
haive --help shows only the commands you use day to day. Everything else (review, import,
diagnostics, benchmarks) is one haive --advanced --help away — the focused surface is deliberate,
not a missing feature.
| Stage | Command | What it does |
|---|---|---|
| Set up | haive init | Create .ai/, bridge files, MCP config, hooks, CI |
haive doctor | Check the install is healthy | |
haive agent setup | Wire your AI client (MCP, hooks) | |
| Before editing | haive briefing | Feedforward context — the CLI mirror of get_briefing |
| Capture knowledge | haive memory save | Record a decision / convention / gotcha |
haive memory tried | Record a failed approach so it isn't repeated | |
| Retrieve | haive memory search · get | Find, then read a record |
| Feedback | haive sensors check | Scan the diff against documented lessons |
| Gate | haive enforce finish | Exit gate before you call the task done |
| Sync | haive sync | Re-check stale anchors, refresh bridge files |
| Close | haive session end | Save a recap for the next session |
One vocabulary across CLI and MCP. The memory verbs mirror the MCP tool names, so an agent learns
them once: haive memory save/search/get/delete ↔ mem_save/mem_search/mem_get/mem_delete
(the older add/query/show/rm still work as aliases).
What hAIve enforces
| Gate | What it checks |
|---|---|
| First-agent bootstrap | On a cold corpus, the first agent is forced to fill the knowledge layer before its commit/finish can pass: a filled project-context, a module context per component, an anchored memory per main code area, and a sensor per main code area. The trigger is corpus state — once the baseline exists the gate is silent for every later agent. Tunable via enforcement.bootstrapGate (off · warn · block (default)); only bites when production code is in play |
| Briefing loaded | Agent loaded fresh context breadcrumbs before editing |
| Decision coverage | Changed files are covered by relevant anchored decisions in the last briefing |
| Anti-pattern matching | Anti-patterns relevant to the diff are surfaced; an anchored, diff-corroborated, high-confidence match blocks the commit. Hardness is tunable via enforcement.antiPatternGate (off · review · anchored (default) · strict) |
| Stale anchors | Memories anchored to deleted/moved paths are flagged |
| Session recap | Agent captured what changed and what remains before closing |
| CI enforcement | Required check blocks merge on any gate failure |
What "block" means here. hAIve's gate is high-precision by design: it hard-blocks the case that is almost always a real mistake — an
attempt/gotchaanchored to the exact file you are editing, whose warning the diff corroborates. Looser, token-only matches are surfaced for review rather than blocked, so config/doc commits don't trip on incidental keyword overlap. Tighten or loosen this withenforcement.antiPatternGate; everything else is enforced as process (was the context loaded, were decisions surfaced, is the recap present).
Cold start — value in session one
An empty corpus is worth nothing, so haive init seeds from signals the repo already has — and every
seed passes a quality floor so cold-start never ships generic, guessable advice. A seed earns its
place only if it carries an enforceable sensor or is concrete and non-generic.
| Source | What it seeds | Quality gate |
|---|---|---|
| Stack packs | Detected-framework traps (Next/Nest/Prisma/Flask/Rails/Tailwind/Docker… 20+ packs), with block sensors where high-signal | specificity floor — generic advice is dropped, audited in CI |
Git history (--seed, on by default) | Draft memories from revert/hotfix/workaround commits — your repo's real scars | noise-subject denylist (merge/bump/deps/wip/format dropped) |
Scanner findings (haive ingest) | SonarQube / SARIF / ESLint / npm audit findings as proposed, anchored memories with sensors | auto-fixable stylistic rules dropped (incl. Sonar numeric keys); --include-stylistic to keep |
haive init # Detect stack + seed packs + seed git history
haive ingest --from sonar issues.json --min-severity major
haive ingest --from eslint report.json
haive ingest --from sarif report.sarif --dry-run # Preview without writing
Ingested and git-seeded memories land as proposed (warn-only sensors). Review them with
haive memory list --status proposed; promote vetted sensors to block with haive sensors promote.
.ai/ directory layout
your-project/
├── .ai/
│ ├── project-context.md # Shared project overview
│ ├── modules/ # Per-component context files
│ │ ├── backend/context.md
│ │ └── frontend/context.md
│ └── memories/
│ ├── personal/ # Private — gitignored
│ ├── team/ # Shared — committed to git
│ └── module/<name>/ # Module-scoped memories
├── CLAUDE.md # Auto-generated bridge (Claude Code)
├── AGENTS.md / GEMINI.md / … # …and 10 more native bridges (see below)
└── .github/
├── copilot-instructions.md # Auto-generated bridge for Copilot
└── workflows/
├── haive-sync.yml # Anchor verification on merge
└── haive-enforcement.yml # Required policy gate
Native bridges — meet every agent where it is
For CLI/IDE agents without MCP, haive init generates native config files from the same corpus, so
the team's memories and block sensors travel to whatever agent a developer uses — not just an empty
template, the enforcement edge too. haive sync keeps them fresh; never hand-edit them (regenerate with
haive bridges sync).
| Agent | File | Agent | File |
|---|---|---|---|
| Claude Code | CLAUDE.md | Cline | .clinerules |
| Cursor | .cursor/rules/haive-memories.mdc | Windsurf | .windsurfrules |
| Codex / generic | AGENTS.md | Continue | .continuerules |
| GitHub Copilot | .github/copilot-instructions.md | Cody | .sourcegraph/cody-rules.md |
| Gemini CLI | GEMINI.md | Zed | .rules |
| Aider | CONVENTIONS.md | Roo | .roo/rules/haive.md |
haive bridges list # Show target status
haive bridges sync --all # Regenerate every native bridge
haive init --bridge-targets cursor,copilot # Or scope to specific agents
Context policy records
| Type | Description |
|---|---|
decision | Architectural or design choices the team has locked in |
gotcha | Non-obvious constraints, known footguns, subtle invariants |
convention | Naming, patterns, style rules specific to this codebase |
attempt | Failed approaches — so agents don't repeat them |
architecture | Component boundaries, interfaces, data flow |
All records can be anchored to file paths and symbol names. When anchored code changes, hAIve flags the record as potentially stale.
MCP tools reference
| Tool | Description |
|---|---|
get_briefing | ⭐ Project context + decisions + gotchas + ranked breadcrumbs in one call |
mem_save | Save repo policy knowledge (decision, gotcha, convention, attempt, architecture) |
mem_tried | Record a failed approach so future agents do not repeat it |
mem_search | Full-text or semantic search across context records |
mem_relevant_to | Ranked context records for a task when project context is already loaded |
mem_get | Fetch one context record after a compact briefing/search result |
code_map | Look up symbols without manual grep when code-map is indexed |
mem_verify | Check anchor freshness, detect stale records |
pre_commit_check | Diff against known gotchas, decisions, and stale anchors |
mem_session_end | Save end-of-session recap for the next agent |
MCP profiles keep the product focused:
HAIVE_TOOL_PROFILE=enforcement(default): compact coding-agent harness.HAIVE_TOOL_PROFILE=maintenance: corpus review, lifecycle, distillation, code-search, and project-context maintenance.HAIVE_TOOL_PROFILE=experimental: broader diagnostics such as runtime journal, pattern detection, why-this-file, why-this-decision, and conflict analysis.HAIVE_TOOL_PROFILE=full: legacy alias forexperimental.
MCP prompts reference
| Prompt | Description |
|---|---|
post_task | ⭐ Post-task checklist — capture learnings before closing every session |
bootstrap_repo | ⭐ First-agent bootstrap — fills the whole knowledge layer the bootstrap gate requires (project-context, module contexts, anchored memories, a validated sensor per main area). Tailors a concrete checklist from the current corpus state and drives bootstrap_project_save → mem_save → propose_sensor until ready |
bootstrap_project | Analyze the codebase and write .ai/project-context.md |
Packages
| Package | Install | Description |
|---|---|---|
@hiveai/cli | npm i -g @hiveai/cli | Main product: init, enforce, run agents, briefing, memory, sync, CI/Git hooks |
@hiveai/mcp | bundled into @hiveai/cli | Policy-aware MCP server |
@hiveai/core | dependency | Types, schema, anchors, policy primitives, token budgets |
@hiveai/embeddings | npm i -g @hiveai/embeddings | Optional: local semantic ranking (bge-small-en-v1.5, fully offline) |
Also in this repo: a VS Code extension (surfaces memories inline + a Strategic Cockpit over the CLI's observability) and a GitHub Action (posts relevant team memories as a PR comment so reviewers and agents never miss a non-obvious constraint).
Adaptive briefing
A briefing only earns its place when it carries unguessable knowledge, so get_briefing returns
briefing_value: "high" | "low". When nothing team-specific matches the files/task, the auto-generated
project context is trimmed to a one-line note (config: adaptiveBriefing, default on) — so hAIve
surfaces deeper context only when it actually knows something the model doesn't.
CLI reference
# Setup
haive init [--with-ci] [--no-bridges] # Initialize .ai/ + bridge files + seed stack/git
haive init --bridge-targets <all|csv> # Scope generated bridges to specific agents
haive enforce install # Install Git hooks + CI enforcement
haive enforce status # Enforcement posture report
haive bridges list/sync [--all] # Inspect / regenerate native agent bridges
haive index code # Build .ai/code-map.json
haive index code --status [--json] # Report code-map / code-search index freshness
# Daily use
haive briefing [--task <text>] [--files] [--json] # Print context + relevant memories
haive run -- <agent command> # Wrap any CLI agent in hAIve session
haive enforce check [--stage pre-commit] # Policy gate
haive enforce ci # CI entrypoint
haive enforce finish # Final agent-exit gate: commit/push + version/tag protocol
haive coverage [--source git|agent|both] # Find changed files no memory covers
haive sync [--since <ref>] [--embed] # Verify anchors + auto-promote
haive sensors list/check/export/promote # Operate executable memory sensors
# Memory
haive memory save --type <type> [--paths|--files <csv>] # Save a memory (anchor to files)
haive memory list [--scope] [--status] # List memories
haive memory search <text> # Full-text / semantic search
haive memory get <id> # Read one record
haive memory approve [<id>|--all] # Mark as validated
haive memory promote <id> # personal → team
haive memory tried # Record a failed approach
haive memory resolve-conflict [--yes] # Guided supersede of contradicting memories
haive memory verify [--update] [--json] # Check anchor freshness
haive memory import --from <file> # Import docs as memories
# Cold start (seed from existing signals)
haive ingest --from sonar|sarif|eslint|npm-audit <file> # Scanner findings → anchored memories
haive ingest --from <fmt> <file> --dry-run # Preview without writing
# Semantic search
haive embeddings index # Build index (first run: downloads model)
haive embeddings query <text> # Semantic search
# Diagnostics
haive doctor # Analyze setup, emit recommendations
haive eval --fail-under 80 # Retrieval + sensor quality gate
haive tui # Interactive terminal dashboard
haive bench # Self-test MCP tools
haive eval auto-synthesizes retrieval cases from anchored memories and, when present, also loads
.ai/eval/spec.json for labeled retrieval/sensor cases. This repo uses that file to keep executable
memory sensors in CI, so a broken guardrail is caught before release.
haive doctor reports local setup drift that can make agents misdiagnose the repo: missing pnpm,
stale workspace dist artifacts, global CLI/MCP version skew, outdated code-search indexes, and low
memory-anchor coverage.
Multi-component projects
For projects with multiple components (frontend/backend/microservices), create one module context per component. get_briefing auto-loads the relevant module context based on the files being edited.
mkdir -p .ai/modules/backend .ai/modules/frontend
cat > .ai/modules/backend/context.md << 'EOF'
# Module: backend
- Spring Boot, Java 17, PostgreSQL
- Always filter by tenantId in every repository query
- Never modify existing Flyway migrations — create V{N+1}__desc.sql
EOF
cat > .ai/modules/frontend/context.md << 'EOF'
# Module: frontend
- React 19, TypeScript, TanStack Query v5
- All API calls go through hooks in features/<domain>/api/
- Env vars must start with VITE_ to be exposed to the client
EOF
Development
git clone https://github.com/Doucs91/hAIve.git
cd hAIve
pnpm install
pnpm -r build # Build all packages
pnpm -r test # Run tests
Requires Node 20 LTS+, pnpm 9+.
Contributing
Issues and PRs are welcome. Please open an issue before starting significant work so we can align on direction.
License
Apache 2.0 — see LICENSE.