convez.ai
AgenteDevOps & InfraestruturaAvançado
Doucs91

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 GitHub
InicialPluginScore · de 0 a 100

MCP 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/hAIve

1 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

Estrelas
5
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 6 dias
Versão
v0.68.2
Issues abertas
5
Contribuidores
2

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.

npm License Node CI


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
  1. haive init creates a .ai/ context policy layer in your repo.
  2. Agents start every session with get_briefing — one MCP call that returns small default context plus deeper breadcrumbs ranked by task relevance.
  3. 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.
  4. haive enforce check and 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 concernhAIve role
Feedforward guidanceget_briefing, module context, skills, decisions, gotchas, failed attempts
Feedback and gatesMCP ordering policy, pre_commit_check, Git hooks, CI enforcement, stale-anchor detection
Knowledge lifecycleGit-native Markdown records, path/symbol anchors, confidence, retirement, linting
BoundarieshAIve 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.

StageCommandWhat it does
Set uphaive initCreate .ai/, bridge files, MCP config, hooks, CI
haive doctorCheck the install is healthy
haive agent setupWire your AI client (MCP, hooks)
Before editinghaive briefingFeedforward context — the CLI mirror of get_briefing
Capture knowledgehaive memory saveRecord a decision / convention / gotcha
haive memory triedRecord a failed approach so it isn't repeated
Retrievehaive memory search · getFind, then read a record
Feedbackhaive sensors checkScan the diff against documented lessons
Gatehaive enforce finishExit gate before you call the task done
Synchaive syncRe-check stale anchors, refresh bridge files
Closehaive session endSave 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

GateWhat it checks
First-agent bootstrapOn 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 loadedAgent loaded fresh context breadcrumbs before editing
Decision coverageChanged files are covered by relevant anchored decisions in the last briefing
Anti-pattern matchingAnti-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 anchorsMemories anchored to deleted/moved paths are flagged
Session recapAgent captured what changed and what remains before closing
CI enforcementRequired 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/gotcha anchored 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 with enforcement.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.

SourceWhat it seedsQuality gate
Stack packsDetected-framework traps (Next/Nest/Prisma/Flask/Rails/Tailwind/Docker… 20+ packs), with block sensors where high-signalspecificity 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 scarsnoise-subject denylist (merge/bump/deps/wip/format dropped)
Scanner findings (haive ingest)SonarQube / SARIF / ESLint / npm audit findings as proposed, anchored memories with sensorsauto-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).

AgentFileAgentFile
Claude CodeCLAUDE.mdCline.clinerules
Cursor.cursor/rules/haive-memories.mdcWindsurf.windsurfrules
Codex / genericAGENTS.mdContinue.continuerules
GitHub Copilot.github/copilot-instructions.mdCody.sourcegraph/cody-rules.md
Gemini CLIGEMINI.mdZed.rules
AiderCONVENTIONS.mdRoo.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

TypeDescription
decisionArchitectural or design choices the team has locked in
gotchaNon-obvious constraints, known footguns, subtle invariants
conventionNaming, patterns, style rules specific to this codebase
attemptFailed approaches — so agents don't repeat them
architectureComponent 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

ToolDescription
get_briefing⭐ Project context + decisions + gotchas + ranked breadcrumbs in one call
mem_saveSave repo policy knowledge (decision, gotcha, convention, attempt, architecture)
mem_triedRecord a failed approach so future agents do not repeat it
mem_searchFull-text or semantic search across context records
mem_relevant_toRanked context records for a task when project context is already loaded
mem_getFetch one context record after a compact briefing/search result
code_mapLook up symbols without manual grep when code-map is indexed
mem_verifyCheck anchor freshness, detect stale records
pre_commit_checkDiff against known gotchas, decisions, and stale anchors
mem_session_endSave 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 for experimental.

MCP prompts reference

PromptDescription
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_projectAnalyze the codebase and write .ai/project-context.md

Packages

PackageInstallDescription
@hiveai/clinpm i -g @hiveai/cliMain product: init, enforce, run agents, briefing, memory, sync, CI/Git hooks
@hiveai/mcpbundled into @hiveai/cliPolicy-aware MCP server
@hiveai/coredependencyTypes, schema, anchors, policy primitives, token budgets
@hiveai/embeddingsnpm i -g @hiveai/embeddingsOptional: 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.

Ver o original no GitHub

Bom para

Relacionados