Skip to main content

Unified Memory Layer CLI for canonical, derived, and agent-aware project memory.

Project description

Unified Memory Layer

aimem is a local CLI for building a canonical, derived, and agent-aware shared memory layer inside a Git repository.

Scope

A versão publicada em pyproject.toml (actualmente 0.2.x) inclui, entre outros:

  • aimem init
  • aimem compile --profile <name>
  • aimem compile --profile <name> --objective "<goal>"
  • aimem query "<objective>"
  • aimem verify
  • aimem verify --refresh
  • aimem verify --fast
  • aimem verify --strict
  • aimem record decision
  • aimem record task
  • aimem install-hooks
  • aimem promote
  • aimem drift scan|report|reconcile|apply
  • aimem manifest get <uuid>
  • aimem context — pacote único (stdout) com meta do repo, pinados do perfil, retrieval, drift e referência ao último ACM; --objective / --profile / --format json / --after-compile

The tool creates a .ai_memory contract with canonical Markdown documents, derived outputs, journal primitives, and Git ignore rules for generated and indexed artifacts.

Governança operacional (modos verify, ciclo de vida, drift, ACM após promote): docs/governance.md.

Alterações entre versões: CHANGELOG.md. Contrato JSON do pacote de contexto: docs/context-bundle.md. Roadmap C3 / multi-LLM: docs/c3-multillm.md. Templates vs governança: docs/templates-governance-sync.md. Testes intensivos / pré-PyPI: docs/pre-publish-testing.md. Matriz operacional (comandos e custo): docs/operations-matrix.md. Perfilar compile/drift: docs/performance-profiling.md. RFC MCP sections (condicional): docs/rfc-mcp-context-sections.md.

🚀 Guia Rápido de Instalação e Uso

A forma mais simples de começar a utilizar o aimem é através do nosso painel interativo. Basta abrires o terminal na raiz do projeto e correres:

./aimem-menu.sh

Isto abrirá um menu guiado onde podes instalar o pacote, inicializar a memória, gravar decisões técnicas e ver as instruções detalhadas de como ligar a Inteligência Artificial do teu IDE (como o Cursor) ao sistema.

Instalação Manual (Sem Script)

Passo 1: Instalação no Sistema

O pacote PyPI chama-se uml-aimem (o nome aimem já estava ocupado). Os comandos na shell continuam a ser aimem e aimem-mcp.

PyPI (utilizadores finais) — não uses pip install no Python do sistema (PEP 668 no Ubuntu); preferir uv ou pipx:

uv tool install "uml-aimem[mcp,tokens]==0.2.5"
# ou: pipx install "uml-aimem[mcp,tokens]==0.2.5"

Desenvolvimento neste repositório:

uv tool install -e ".[mcp,tokens]"

(O -e reflecte alterações ao código fonte; [mcp,tokens] activa MCP e estimativa de tokens no compile.)

Confirma a instalação:

aimem --help
aimem-mcp --help

Passo 2: Inicializar um Repositório (O dia a dia do CLI)

Para usar o aimem noutro projeto qualquer (ou até neste repositório), cria a Camada de Memória Unificada. No terminal do projeto alvo, corre:

aimem init

O que isto faz:

  • Cria a pasta .ai_memory/ na raiz do teu projeto.
  • Gera os templates padrão (manifest.yaml, regras arquiteturais, etc.).
  • Atualiza automaticamente o teu .gitignore.

Sempre que tomas uma decisão arquitetural, assumes tu o controlo canónico (e não a IA):

aimem record decision "Decidimos mudar do SQLite FTS5 puro para um motor híbrido com Vetores"

Isto vai gerar um ficheiro Markdown validado em .ai_memory/decisions/ com o formato e frontmatter que a IA precisa.

Passo 3: Ligar a Inteligência Artificial (O Servidor MCP)

O verdadeiro poder da ferramenta é como injetamos esta memória no teu editor de código via Model Context Protocol (MCP). Exemplo no Cursor:

  1. Abre as Definições do Cursor.
  2. Procura por "MCP".
  3. Adiciona um novo servidor com a seguinte configuração:
    • Name: Aimem Server
    • Type: command
    • Command: aimem-mcp (ou o caminho absoluto gerado pelo uv, ex: ~/.local/bin/aimem-mcp)
    • Args: --repo /caminho/absoluto/do/teu/projeto

A partir desse momento, quando abrires o chat e pedires uma nova funcionalidade, o Cursor vai automaticamente ler as regras da arquitetura e as decisões técnicas usando a ferramenta get_agent_context_bundle, poupando milhares de tokens da tua conta e garantindo que a IA não alucina decisões.

Passo 4: Verificação de Derivação (Drift Sentinel)

Antes de fazeres commit de código, deves garantir que as regras da memória correspondem ao código final:

aimem drift scan .

O motor local vai comparar as declarações documentadas (os claims) com o código fonte e verificar se as regras estão a ser cumpridas.

Instalação e extras (núcleo vs opcional)

Extra uv Conteúdo Quando usar
(nenhum) Só dependências do pacote: Typer + PyYAML — CLI, SQLite local, FTS5 no fluxo actual. uv sync para uso normal do aimem sem MCP nem testes.
dev pytest, pytest-benchmark, pytest-asyncio, locust Desenvolvimento e CI local, e testes de concorrência.
mcp Pacote mcp + entrada aimem-mcp Servidor MCP stdio para IDEs.
tokens tiktoken Estimativa de tokens mais precisa no compile quando max_tokens está activo (estimate_tokens no compilador).
semantic sqlite-vec Caminho opt-in para extensão vectorial (v0.2b / retrieval avançado).
local-embed / openai Embeddings opcionais Caminho opt-in; não fazem parte da instalação base.

Para agentes / IDEs

aimem context imprime um único bloco (markdown, texto ou JSON) com estado do repositório, documentos pinados do perfil de compile (por defeito bootstrap), resultados de query_memory, eventos de drift abertos e o último manifesto ACM conhecido. Complementa aimem query e o servidor MCP para memória canónica em .ai_memory; não substitui verify, fontes externas (ver política MCP-first em CONTRIBUTING.md) nem julgamento humano sobre decisões.

Orçamento de caracteres (--max-chars, aplica-se à saída markdown/texto): reserva para cabeçalhos e meta; o remanescente reparte-se de forma fixa entre pinados (~45%), retrieval (~40%) e margem para listagens (drift, ACM).

Exemplos (mesmo padrão uv run --directory que no CI):

export AIMEM=/caminho/absoluto/para/aimem
uv run --directory "$AIMEM" aimem context "$(pwd)"
uv run --directory "$AIMEM" aimem context "$(pwd)" --profile bootstrap --objective "Implementar feature X"
uv run --directory "$AIMEM" aimem context "$(pwd)" --format json
# Opcional: corre um compile antes e inclui o manifesto dessa corrida no bundle
uv run --directory "$AIMEM" aimem context "$(pwd)" --after-compile --compile-profile bootstrap
# Objectivo só do compile (o retrieval continua a usar --objective se o passares)
uv run --directory "$AIMEM" aimem context "$(pwd)" --after-compile --compile-objective "handoff notes"

No Cursor, ao editares ficheiros sob .ai_memory/, a regra .cursor/rules/aimem-context-bootstrap.mdc sugere este fluxo (não é alwaysApply).

Contributing

Development setup, MCP-first retrieval policy (external docs/APIs vs canonical .ai_memory), and remote/PR workflow are described in CONTRIBUTING.md and docs/releasing.md. Cursor loads the same rules from .cursor/rules/mcp-first-retrieval.mdc.

Drift Sentinel

Drift compares gold (or reviewed) memory claims (aimem_claims in canonical frontmatter) against the working tree using rules declared under aimem_drift in .ai_memory/manifest.yaml.

uv run aimem drift scan .
uv run aimem drift report .
uv run aimem drift reconcile .
uv run aimem drift apply .          # dry-run: shows planned governance updates
uv run aimem drift apply . --write  # sets verification_status: drifted on affected docs (uses .ai_memory lock)

Open drift rows are stored in .ai_memory/index/aimem.sqlite and referenced from compile output / MCP helpers as aimem://drift-event/<id>.

Context manifests (ACM)

Each aimem compile run can emit an auditable context manifest (JSON) under .ai_memory/journal/manifests/<manifest_id>.json. The CLI prints a line such as:

Context manifest: aimem://manifest/<manifest_id>

Inspect a manifest:

uv run aimem manifest get <manifest_id> .

The aimem_version field reflects the installed aimem package version.

MCP server (stdio, optional)

With the optional mcp extra, this package exposes aimem-mcp, a stdio MCP server that wraps query_capsules, get_drift_alerts, get_context_manifest, get_agent_context_bundle (same structured JSON as aimem context --format json), and resource templates aimem://manifest/{manifest_id} (JSON) and aimem://capsule/{capsule_id} (Markdown on disk under .ai_memory/journal/capsules/).

uv sync --extra mcp

Example Cursor MCP entry (.cursor/mcp.json or equivalent), pointing at this repo’s virtualenv:

{
  "mcpServers": {
    "aimem": {
      "command": "uv",
      "args": ["run", "--directory", "/absolute/path/to/this/repo", "aimem-mcp", "--repo", "/absolute/path/to/target/repo"]
    }
  }
}

Adjust --directory to the checkout where aimem is installed and --repo to the Git project whose .ai_memory you want to query.

For a longer dogfooding checklist (paths, extras, typical errors), see docs/dogfooding-mcp.md.

Record Commands

Use the record subcommands to create canonical documents with consistent IDs, filenames, frontmatter, and journal entries.

uv run aimem record decision "Adopt MCP"
uv run aimem record task "Add SQLite index" --done-when "query returns relevant docs"

Use --allow-secrets only in controlled scenarios when you intentionally need to bypass high-confidence secret blocking.

Query

aimem query refreshes a local SQLite index in .ai_memory/index/aimem.sqlite from canonical memory and returns the most relevant documents for an objective. The index is local-only and remains Git-ignored.

Default retrieval mode is hybrid_metadata (FTS5 + metadata reranking). Semantic/vector retrieval remains opt-in.

Objective-Aware Compile

aimem compile keeps the previous ordered behavior when no objective is provided. When --objective is present and the selected profile uses selection_mode: retrieval, the command includes pinned baseline documents first and then fills the remaining budget with the most relevant retrieved documents.

Compile profiles support max_tokens with max_chars fallback for environments without tokenizer extras.

Governance Lifecycle

Canonical documents use a lifecycle aimed at safe shared memory:

  • draft
  • reviewed
  • gold
  • deprecated

Deprecated documents are strongly penalized during retrieval and excluded by default from objective-focused context packs.

Hooks and Fast Verification

Install local Git hooks with:

uv run aimem install-hooks

The generated pre-commit hook runs aimem verify --fast for low-latency local checks.

Strict Governance

For stricter checks (including high-criticality review requirements), use:

uv run aimem verify --strict

Verification Refresh

aimem verify --refresh rewrites canonical documents with the current verified_at timestamp and the current Git HEAD in verified_from.git_commit, then reports the refreshed verification status.

Memory Model

  • rules, state, decisions, tasks: canonical memory
  • journal: append-only operational history
  • generated: derived outputs
  • cache, index, workspaces: local-only artifacts ignored by Git

Each canonical Markdown document uses YAML frontmatter with ownership, verification, and provenance metadata.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

uml_aimem-0.2.5.tar.gz (69.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

uml_aimem-0.2.5-py3-none-any.whl (71.5 kB view details)

Uploaded Python 3

File details

Details for the file uml_aimem-0.2.5.tar.gz.

File metadata

  • Download URL: uml_aimem-0.2.5.tar.gz
  • Upload date:
  • Size: 69.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for uml_aimem-0.2.5.tar.gz
Algorithm Hash digest
SHA256 e4f47a12f72c2d0dc8b0874e9c7542d321dc8751ee4310e653549fac4a59c014
MD5 51cc55cfa74d30f32f06194b04f65fc4
BLAKE2b-256 cb7d15659dcea908cbef2b83a7bbd81e4f4a4fa563416d7399ab744ee8336d86

See more details on using hashes here.

File details

Details for the file uml_aimem-0.2.5-py3-none-any.whl.

File metadata

  • Download URL: uml_aimem-0.2.5-py3-none-any.whl
  • Upload date:
  • Size: 71.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for uml_aimem-0.2.5-py3-none-any.whl
Algorithm Hash digest
SHA256 31e33236f28bd9c821d0f573fa42711ecb281f1c732eb1cd8b550ff0360de23d
MD5 daf6e8c57acff9e1d6b2adf075768819
BLAKE2b-256 070aa9d8cac9c1558caef1e1103e4854b4d4920a9b104ba5ebcb67b38baa5201

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page