uml-aimem 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. uml_aimem-0.2.2/PKG-INFO +282 -0
  2. uml_aimem-0.2.2/README.md +254 -0
  3. uml_aimem-0.2.2/pyproject.toml +60 -0
  4. uml_aimem-0.2.2/setup.cfg +4 -0
  5. uml_aimem-0.2.2/src/aimem/__init__.py +19 -0
  6. uml_aimem-0.2.2/src/aimem/_dist.py +3 -0
  7. uml_aimem-0.2.2/src/aimem/cli.py +37 -0
  8. uml_aimem-0.2.2/src/aimem/commands/compile.py +48 -0
  9. uml_aimem-0.2.2/src/aimem/commands/context.py +100 -0
  10. uml_aimem-0.2.2/src/aimem/commands/drift.py +110 -0
  11. uml_aimem-0.2.2/src/aimem/commands/hooks.py +23 -0
  12. uml_aimem-0.2.2/src/aimem/commands/index.py +27 -0
  13. uml_aimem-0.2.2/src/aimem/commands/init.py +25 -0
  14. uml_aimem-0.2.2/src/aimem/commands/manifest.py +27 -0
  15. uml_aimem-0.2.2/src/aimem/commands/promote.py +26 -0
  16. uml_aimem-0.2.2/src/aimem/commands/query.py +32 -0
  17. uml_aimem-0.2.2/src/aimem/commands/record.py +99 -0
  18. uml_aimem-0.2.2/src/aimem/commands/verify.py +61 -0
  19. uml_aimem-0.2.2/src/aimem/core/agent_context.py +114 -0
  20. uml_aimem-0.2.2/src/aimem/core/agent_context_budget.py +33 -0
  21. uml_aimem-0.2.2/src/aimem/core/agent_context_models.py +48 -0
  22. uml_aimem-0.2.2/src/aimem/core/agent_context_sections.py +211 -0
  23. uml_aimem-0.2.2/src/aimem/core/agent_context_serialize.py +240 -0
  24. uml_aimem-0.2.2/src/aimem/core/compiler.py +323 -0
  25. uml_aimem-0.2.2/src/aimem/core/context_contract.py +141 -0
  26. uml_aimem-0.2.2/src/aimem/core/context_manifest.py +236 -0
  27. uml_aimem-0.2.2/src/aimem/core/drift.py +760 -0
  28. uml_aimem-0.2.2/src/aimem/core/embeddings.py +32 -0
  29. uml_aimem-0.2.2/src/aimem/core/hooks.py +27 -0
  30. uml_aimem-0.2.2/src/aimem/core/locking.py +35 -0
  31. uml_aimem-0.2.2/src/aimem/core/mcp_resources.py +115 -0
  32. uml_aimem-0.2.2/src/aimem/core/memory.py +162 -0
  33. uml_aimem-0.2.2/src/aimem/core/promotion.py +34 -0
  34. uml_aimem-0.2.2/src/aimem/core/recorder.py +224 -0
  35. uml_aimem-0.2.2/src/aimem/core/repo.py +81 -0
  36. uml_aimem-0.2.2/src/aimem/core/retrieval.py +557 -0
  37. uml_aimem-0.2.2/src/aimem/core/security.py +71 -0
  38. uml_aimem-0.2.2/src/aimem/core/sqlite_index.py +110 -0
  39. uml_aimem-0.2.2/src/aimem/core/templates.py +7 -0
  40. uml_aimem-0.2.2/src/aimem/core/verifier.py +320 -0
  41. uml_aimem-0.2.2/src/aimem/mcp_server.py +99 -0
  42. uml_aimem-0.2.2/src/aimem/templates/__init__.py +1 -0
  43. uml_aimem-0.2.2/src/aimem/templates/decision_0001_memory_contract.md +35 -0
  44. uml_aimem-0.2.2/src/aimem/templates/journal_events.jsonl +1 -0
  45. uml_aimem-0.2.2/src/aimem/templates/journal_readme.md +22 -0
  46. uml_aimem-0.2.2/src/aimem/templates/manifest.yaml +119 -0
  47. uml_aimem-0.2.2/src/aimem/templates/rules_engineering.md +27 -0
  48. uml_aimem-0.2.2/src/aimem/templates/rules_product.md +26 -0
  49. uml_aimem-0.2.2/src/aimem/templates/secrets_allowlist.txt +3 -0
  50. uml_aimem-0.2.2/src/aimem/templates/state_architecture.md +27 -0
  51. uml_aimem-0.2.2/src/aimem/templates/state_project.md +30 -0
  52. uml_aimem-0.2.2/src/aimem/templates/task_0001_bootstrap_foundation.md +30 -0
  53. uml_aimem-0.2.2/src/uml_aimem.egg-info/PKG-INFO +282 -0
  54. uml_aimem-0.2.2/src/uml_aimem.egg-info/SOURCES.txt +63 -0
  55. uml_aimem-0.2.2/src/uml_aimem.egg-info/dependency_links.txt +1 -0
  56. uml_aimem-0.2.2/src/uml_aimem.egg-info/entry_points.txt +3 -0
  57. uml_aimem-0.2.2/src/uml_aimem.egg-info/requires.txt +23 -0
  58. uml_aimem-0.2.2/src/uml_aimem.egg-info/top_level.txt +1 -0
  59. uml_aimem-0.2.2/tests/test_benchmark_memory.py +89 -0
  60. uml_aimem-0.2.2/tests/test_cli.py +1015 -0
  61. uml_aimem-0.2.2/tests/test_context_bundle_contract.py +127 -0
  62. uml_aimem-0.2.2/tests/test_context_manifest.py +54 -0
  63. uml_aimem-0.2.2/tests/test_mcp_concurrency.py +45 -0
  64. uml_aimem-0.2.2/tests/test_mcp_server.py +98 -0
  65. uml_aimem-0.2.2/tests/test_sqlite_index.py +84 -0
@@ -0,0 +1,282 @@
1
+ Metadata-Version: 2.4
2
+ Name: uml-aimem
3
+ Version: 0.2.2
4
+ Summary: Unified Memory Layer CLI for canonical, derived, and agent-aware project memory.
5
+ Project-URL: Homepage, https://github.com/Mexicanguy1987/aimem
6
+ Project-URL: Repository, https://github.com/Mexicanguy1987/aimem
7
+ Project-URL: Changelog, https://github.com/Mexicanguy1987/aimem/blob/master/CHANGELOG.md
8
+ Project-URL: PyPI, https://pypi.org/project/uml-aimem/
9
+ Requires-Python: >=3.12
10
+ Description-Content-Type: text/markdown
11
+ Requires-Dist: PyYAML>=6.0
12
+ Requires-Dist: typer<1.0,>=0.12
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=7.4; extra == "dev"
15
+ Requires-Dist: pytest-benchmark>=4.0; extra == "dev"
16
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
17
+ Requires-Dist: locust>=2.30; extra == "dev"
18
+ Provides-Extra: mcp
19
+ Requires-Dist: mcp<2,>=1.0; extra == "mcp"
20
+ Provides-Extra: semantic
21
+ Requires-Dist: sqlite-vec>=0.1.6; extra == "semantic"
22
+ Provides-Extra: local-embed
23
+ Requires-Dist: sentence-transformers>=3.0; extra == "local-embed"
24
+ Provides-Extra: openai
25
+ Requires-Dist: openai>=1.40.0; extra == "openai"
26
+ Provides-Extra: tokens
27
+ Requires-Dist: tiktoken>=0.7.0; extra == "tokens"
28
+
29
+ # Unified Memory Layer
30
+
31
+ `aimem` is a local CLI for building a canonical, derived, and agent-aware shared memory layer inside a Git repository.
32
+
33
+ ## Scope
34
+
35
+ A versão publicada em `pyproject.toml` (actualmente **0.2.x**) inclui, entre outros:
36
+
37
+ - `aimem init`
38
+ - `aimem compile --profile <name>`
39
+ - `aimem compile --profile <name> --objective "<goal>"`
40
+ - `aimem query "<objective>"`
41
+ - `aimem verify`
42
+ - `aimem verify --refresh`
43
+ - `aimem verify --fast`
44
+ - `aimem verify --strict`
45
+ - `aimem record decision`
46
+ - `aimem record task`
47
+ - `aimem install-hooks`
48
+ - `aimem promote`
49
+ - `aimem drift scan|report|reconcile|apply`
50
+ - `aimem manifest get <uuid>`
51
+ - `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`
52
+
53
+ The tool creates a `.ai_memory` contract with canonical Markdown documents, derived outputs, journal primitives, and Git ignore rules for generated and indexed artifacts.
54
+
55
+ **Governança operacional** (modos `verify`, ciclo de vida, drift, ACM após `promote`): [docs/governance.md](docs/governance.md).
56
+
57
+ **Alterações entre versões:** [CHANGELOG.md](CHANGELOG.md). **Contrato JSON do pacote de contexto:** [docs/context-bundle.md](docs/context-bundle.md). **Roadmap C3 / multi-LLM:** [docs/c3-multillm.md](docs/c3-multillm.md). **Templates vs governança:** [docs/templates-governance-sync.md](docs/templates-governance-sync.md). **Testes intensivos / pré-PyPI:** [docs/pre-publish-testing.md](docs/pre-publish-testing.md). **Matriz operacional (comandos e custo):** [docs/operations-matrix.md](docs/operations-matrix.md). **Perfilar compile/drift:** [docs/performance-profiling.md](docs/performance-profiling.md). **RFC MCP `sections` (condicional):** [docs/rfc-mcp-context-sections.md](docs/rfc-mcp-context-sections.md).
58
+
59
+ ## 🚀 Guia Rápido de Instalação e Uso
60
+
61
+ A forma mais simples de começar a utilizar o **aimem** é através do nosso painel interativo.
62
+ Basta abrires o terminal na raiz do projeto e correres:
63
+ ```bash
64
+ ./aimem-menu.sh
65
+ ```
66
+ 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.
67
+
68
+ ### Instalação Manual (Sem Script)
69
+ ### Passo 1: Instalação no Sistema
70
+
71
+ O pacote PyPI chama-se **`uml-aimem`** (o nome `aimem` já estava ocupado). Os comandos na shell continuam a ser `aimem` e `aimem-mcp`.
72
+
73
+ **PyPI (utilizadores finais)** — não uses `pip install` no Python do sistema (PEP 668 no Ubuntu); preferir `uv` ou `pipx`:
74
+
75
+ ```bash
76
+ uv tool install "uml-aimem[mcp,tokens]==0.2.2"
77
+ # ou: pipx install "uml-aimem[mcp,tokens]==0.2.2"
78
+ ```
79
+
80
+ **Desenvolvimento** neste repositório:
81
+
82
+ ```bash
83
+ uv tool install -e ".[mcp,tokens]"
84
+ ```
85
+
86
+ *(O `-e` reflecte alterações ao código fonte; `[mcp,tokens]` activa MCP e estimativa de tokens no compile.)*
87
+
88
+ Confirma a instalação:
89
+ ```bash
90
+ aimem --help
91
+ aimem-mcp --help
92
+ ```
93
+
94
+ ### Passo 2: Inicializar um Repositório (O dia a dia do CLI)
95
+ 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:
96
+ ```bash
97
+ aimem init
98
+ ```
99
+ **O que isto faz:**
100
+ * Cria a pasta `.ai_memory/` na raiz do teu projeto.
101
+ * Gera os *templates* padrão (`manifest.yaml`, regras arquiteturais, etc.).
102
+ * Atualiza automaticamente o teu `.gitignore`.
103
+
104
+ Sempre que tomas uma decisão arquitetural, assumes tu o controlo canónico (e não a IA):
105
+ ```bash
106
+ aimem record decision "Decidimos mudar do SQLite FTS5 puro para um motor híbrido com Vetores"
107
+ ```
108
+ Isto vai gerar um ficheiro Markdown validado em `.ai_memory/decisions/` com o formato e *frontmatter* que a IA precisa.
109
+
110
+ ### Passo 3: Ligar a Inteligência Artificial (O Servidor MCP)
111
+ O verdadeiro poder da ferramenta é como injetamos esta memória no teu editor de código via Model Context Protocol (MCP). Exemplo no **Cursor**:
112
+
113
+ 1. Abre as Definições do Cursor.
114
+ 2. Procura por **"MCP"**.
115
+ 3. Adiciona um novo servidor com a seguinte configuração:
116
+ * **Name:** `Aimem Server`
117
+ * **Type:** `command`
118
+ * **Command:** `aimem-mcp` *(ou o caminho absoluto gerado pelo uv, ex: `~/.local/bin/aimem-mcp`)*
119
+ * **Args:** `--repo /caminho/absoluto/do/teu/projeto`
120
+
121
+ 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.
122
+
123
+ ### Passo 4: Verificação de Derivação (Drift Sentinel)
124
+ Antes de fazeres *commit* de código, deves garantir que as regras da memória correspondem ao código final:
125
+ ```bash
126
+ aimem drift scan .
127
+ ```
128
+ 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.
129
+
130
+ ## Instalação e extras (núcleo vs opcional)
131
+
132
+ | Extra `uv` | Conteúdo | Quando usar |
133
+ | --- | --- | --- |
134
+ | *(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. |
135
+ | `dev` | `pytest`, `pytest-benchmark`, `pytest-asyncio`, `locust` | Desenvolvimento e CI local, e testes de concorrência. |
136
+ | `mcp` | Pacote `mcp` + entrada `aimem-mcp` | Servidor MCP stdio para IDEs. |
137
+ | `tokens` | `tiktoken` | Estimativa de tokens mais precisa no `compile` quando `max_tokens` está activo (`estimate_tokens` no compilador). |
138
+ | `semantic` | `sqlite-vec` | Caminho opt-in para extensão vectorial (v0.2b / retrieval avançado). |
139
+ | `local-embed` / `openai` | Embeddings opcionais | Caminho opt-in; não fazem parte da instalação base. |
140
+
141
+ ## Para agentes / IDEs
142
+
143
+ `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](CONTRIBUTING.md)) nem julgamento humano sobre decisões.
144
+
145
+ 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).
146
+
147
+ Exemplos (mesmo padrão `uv run --directory` que no CI):
148
+
149
+ ```bash
150
+ export AIMEM=/caminho/absoluto/para/aimem
151
+ uv run --directory "$AIMEM" aimem context "$(pwd)"
152
+ uv run --directory "$AIMEM" aimem context "$(pwd)" --profile bootstrap --objective "Implementar feature X"
153
+ uv run --directory "$AIMEM" aimem context "$(pwd)" --format json
154
+ # Opcional: corre um compile antes e inclui o manifesto dessa corrida no bundle
155
+ uv run --directory "$AIMEM" aimem context "$(pwd)" --after-compile --compile-profile bootstrap
156
+ # Objectivo só do compile (o retrieval continua a usar --objective se o passares)
157
+ uv run --directory "$AIMEM" aimem context "$(pwd)" --after-compile --compile-objective "handoff notes"
158
+ ```
159
+
160
+ No Cursor, ao editares ficheiros sob `.ai_memory/`, a regra [`.cursor/rules/aimem-context-bootstrap.mdc`](.cursor/rules/aimem-context-bootstrap.mdc) sugere este fluxo (não é `alwaysApply`).
161
+
162
+ ## Contributing
163
+
164
+ Development setup, **MCP-first retrieval policy** (external docs/APIs vs canonical `.ai_memory`), and **remote/PR workflow** are described in [CONTRIBUTING.md](CONTRIBUTING.md) and [docs/releasing.md](docs/releasing.md). Cursor loads the same rules from [`.cursor/rules/mcp-first-retrieval.mdc`](.cursor/rules/mcp-first-retrieval.mdc).
165
+
166
+ ## Drift Sentinel
167
+
168
+ 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`.
169
+
170
+ ```bash
171
+ uv run aimem drift scan .
172
+ uv run aimem drift report .
173
+ uv run aimem drift reconcile .
174
+ uv run aimem drift apply . # dry-run: shows planned governance updates
175
+ uv run aimem drift apply . --write # sets verification_status: drifted on affected docs (uses .ai_memory lock)
176
+ ```
177
+
178
+ Open drift rows are stored in `.ai_memory/index/aimem.sqlite` and referenced from compile output / MCP helpers as `aimem://drift-event/<id>`.
179
+
180
+ ## Context manifests (ACM)
181
+
182
+ 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:
183
+
184
+ `Context manifest: aimem://manifest/<manifest_id>`
185
+
186
+ Inspect a manifest:
187
+
188
+ ```bash
189
+ uv run aimem manifest get <manifest_id> .
190
+ ```
191
+
192
+ The `aimem_version` field reflects the installed `aimem` package version.
193
+
194
+ ## MCP server (stdio, optional)
195
+
196
+ 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/`).
197
+
198
+ ```bash
199
+ uv sync --extra mcp
200
+ ```
201
+
202
+ Example **Cursor** MCP entry (`.cursor/mcp.json` or equivalent), pointing at this repo’s virtualenv:
203
+
204
+ ```json
205
+ {
206
+ "mcpServers": {
207
+ "aimem": {
208
+ "command": "uv",
209
+ "args": ["run", "--directory", "/absolute/path/to/this/repo", "aimem-mcp", "--repo", "/absolute/path/to/target/repo"]
210
+ }
211
+ }
212
+ }
213
+ ```
214
+
215
+ Adjust `--directory` to the checkout where `aimem` is installed and `--repo` to the Git project whose `.ai_memory` you want to query.
216
+
217
+ For a longer dogfooding checklist (paths, extras, typical errors), see [docs/dogfooding-mcp.md](docs/dogfooding-mcp.md).
218
+
219
+ ## Record Commands
220
+
221
+ Use the `record` subcommands to create canonical documents with consistent IDs, filenames, frontmatter, and journal entries.
222
+
223
+ ```bash
224
+ uv run aimem record decision "Adopt MCP"
225
+ uv run aimem record task "Add SQLite index" --done-when "query returns relevant docs"
226
+ ```
227
+
228
+ Use `--allow-secrets` only in controlled scenarios when you intentionally need to bypass high-confidence secret blocking.
229
+
230
+ ## Query
231
+
232
+ `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.
233
+
234
+ Default retrieval mode is `hybrid_metadata` (`FTS5` + metadata reranking). Semantic/vector retrieval remains opt-in.
235
+
236
+ ## Objective-Aware Compile
237
+
238
+ `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.
239
+
240
+ Compile profiles support `max_tokens` with `max_chars` fallback for environments without tokenizer extras.
241
+
242
+ ## Governance Lifecycle
243
+
244
+ Canonical documents use a lifecycle aimed at safe shared memory:
245
+
246
+ - `draft`
247
+ - `reviewed`
248
+ - `gold`
249
+ - `deprecated`
250
+
251
+ Deprecated documents are strongly penalized during retrieval and excluded by default from objective-focused context packs.
252
+
253
+ ## Hooks and Fast Verification
254
+
255
+ Install local Git hooks with:
256
+
257
+ ```bash
258
+ uv run aimem install-hooks
259
+ ```
260
+
261
+ The generated `pre-commit` hook runs `aimem verify --fast` for low-latency local checks.
262
+
263
+ ## Strict Governance
264
+
265
+ For stricter checks (including high-criticality review requirements), use:
266
+
267
+ ```bash
268
+ uv run aimem verify --strict
269
+ ```
270
+
271
+ ## Verification Refresh
272
+
273
+ `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.
274
+
275
+ ## Memory Model
276
+
277
+ - `rules`, `state`, `decisions`, `tasks`: canonical memory
278
+ - `journal`: append-only operational history
279
+ - `generated`: derived outputs
280
+ - `cache`, `index`, `workspaces`: local-only artifacts ignored by Git
281
+
282
+ Each canonical Markdown document uses YAML frontmatter with ownership, verification, and provenance metadata.
@@ -0,0 +1,254 @@
1
+ # Unified Memory Layer
2
+
3
+ `aimem` is a local CLI for building a canonical, derived, and agent-aware shared memory layer inside a Git repository.
4
+
5
+ ## Scope
6
+
7
+ A versão publicada em `pyproject.toml` (actualmente **0.2.x**) inclui, entre outros:
8
+
9
+ - `aimem init`
10
+ - `aimem compile --profile <name>`
11
+ - `aimem compile --profile <name> --objective "<goal>"`
12
+ - `aimem query "<objective>"`
13
+ - `aimem verify`
14
+ - `aimem verify --refresh`
15
+ - `aimem verify --fast`
16
+ - `aimem verify --strict`
17
+ - `aimem record decision`
18
+ - `aimem record task`
19
+ - `aimem install-hooks`
20
+ - `aimem promote`
21
+ - `aimem drift scan|report|reconcile|apply`
22
+ - `aimem manifest get <uuid>`
23
+ - `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`
24
+
25
+ The tool creates a `.ai_memory` contract with canonical Markdown documents, derived outputs, journal primitives, and Git ignore rules for generated and indexed artifacts.
26
+
27
+ **Governança operacional** (modos `verify`, ciclo de vida, drift, ACM após `promote`): [docs/governance.md](docs/governance.md).
28
+
29
+ **Alterações entre versões:** [CHANGELOG.md](CHANGELOG.md). **Contrato JSON do pacote de contexto:** [docs/context-bundle.md](docs/context-bundle.md). **Roadmap C3 / multi-LLM:** [docs/c3-multillm.md](docs/c3-multillm.md). **Templates vs governança:** [docs/templates-governance-sync.md](docs/templates-governance-sync.md). **Testes intensivos / pré-PyPI:** [docs/pre-publish-testing.md](docs/pre-publish-testing.md). **Matriz operacional (comandos e custo):** [docs/operations-matrix.md](docs/operations-matrix.md). **Perfilar compile/drift:** [docs/performance-profiling.md](docs/performance-profiling.md). **RFC MCP `sections` (condicional):** [docs/rfc-mcp-context-sections.md](docs/rfc-mcp-context-sections.md).
30
+
31
+ ## 🚀 Guia Rápido de Instalação e Uso
32
+
33
+ A forma mais simples de começar a utilizar o **aimem** é através do nosso painel interativo.
34
+ Basta abrires o terminal na raiz do projeto e correres:
35
+ ```bash
36
+ ./aimem-menu.sh
37
+ ```
38
+ 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.
39
+
40
+ ### Instalação Manual (Sem Script)
41
+ ### Passo 1: Instalação no Sistema
42
+
43
+ O pacote PyPI chama-se **`uml-aimem`** (o nome `aimem` já estava ocupado). Os comandos na shell continuam a ser `aimem` e `aimem-mcp`.
44
+
45
+ **PyPI (utilizadores finais)** — não uses `pip install` no Python do sistema (PEP 668 no Ubuntu); preferir `uv` ou `pipx`:
46
+
47
+ ```bash
48
+ uv tool install "uml-aimem[mcp,tokens]==0.2.2"
49
+ # ou: pipx install "uml-aimem[mcp,tokens]==0.2.2"
50
+ ```
51
+
52
+ **Desenvolvimento** neste repositório:
53
+
54
+ ```bash
55
+ uv tool install -e ".[mcp,tokens]"
56
+ ```
57
+
58
+ *(O `-e` reflecte alterações ao código fonte; `[mcp,tokens]` activa MCP e estimativa de tokens no compile.)*
59
+
60
+ Confirma a instalação:
61
+ ```bash
62
+ aimem --help
63
+ aimem-mcp --help
64
+ ```
65
+
66
+ ### Passo 2: Inicializar um Repositório (O dia a dia do CLI)
67
+ 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:
68
+ ```bash
69
+ aimem init
70
+ ```
71
+ **O que isto faz:**
72
+ * Cria a pasta `.ai_memory/` na raiz do teu projeto.
73
+ * Gera os *templates* padrão (`manifest.yaml`, regras arquiteturais, etc.).
74
+ * Atualiza automaticamente o teu `.gitignore`.
75
+
76
+ Sempre que tomas uma decisão arquitetural, assumes tu o controlo canónico (e não a IA):
77
+ ```bash
78
+ aimem record decision "Decidimos mudar do SQLite FTS5 puro para um motor híbrido com Vetores"
79
+ ```
80
+ Isto vai gerar um ficheiro Markdown validado em `.ai_memory/decisions/` com o formato e *frontmatter* que a IA precisa.
81
+
82
+ ### Passo 3: Ligar a Inteligência Artificial (O Servidor MCP)
83
+ O verdadeiro poder da ferramenta é como injetamos esta memória no teu editor de código via Model Context Protocol (MCP). Exemplo no **Cursor**:
84
+
85
+ 1. Abre as Definições do Cursor.
86
+ 2. Procura por **"MCP"**.
87
+ 3. Adiciona um novo servidor com a seguinte configuração:
88
+ * **Name:** `Aimem Server`
89
+ * **Type:** `command`
90
+ * **Command:** `aimem-mcp` *(ou o caminho absoluto gerado pelo uv, ex: `~/.local/bin/aimem-mcp`)*
91
+ * **Args:** `--repo /caminho/absoluto/do/teu/projeto`
92
+
93
+ 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.
94
+
95
+ ### Passo 4: Verificação de Derivação (Drift Sentinel)
96
+ Antes de fazeres *commit* de código, deves garantir que as regras da memória correspondem ao código final:
97
+ ```bash
98
+ aimem drift scan .
99
+ ```
100
+ 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.
101
+
102
+ ## Instalação e extras (núcleo vs opcional)
103
+
104
+ | Extra `uv` | Conteúdo | Quando usar |
105
+ | --- | --- | --- |
106
+ | *(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. |
107
+ | `dev` | `pytest`, `pytest-benchmark`, `pytest-asyncio`, `locust` | Desenvolvimento e CI local, e testes de concorrência. |
108
+ | `mcp` | Pacote `mcp` + entrada `aimem-mcp` | Servidor MCP stdio para IDEs. |
109
+ | `tokens` | `tiktoken` | Estimativa de tokens mais precisa no `compile` quando `max_tokens` está activo (`estimate_tokens` no compilador). |
110
+ | `semantic` | `sqlite-vec` | Caminho opt-in para extensão vectorial (v0.2b / retrieval avançado). |
111
+ | `local-embed` / `openai` | Embeddings opcionais | Caminho opt-in; não fazem parte da instalação base. |
112
+
113
+ ## Para agentes / IDEs
114
+
115
+ `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](CONTRIBUTING.md)) nem julgamento humano sobre decisões.
116
+
117
+ 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).
118
+
119
+ Exemplos (mesmo padrão `uv run --directory` que no CI):
120
+
121
+ ```bash
122
+ export AIMEM=/caminho/absoluto/para/aimem
123
+ uv run --directory "$AIMEM" aimem context "$(pwd)"
124
+ uv run --directory "$AIMEM" aimem context "$(pwd)" --profile bootstrap --objective "Implementar feature X"
125
+ uv run --directory "$AIMEM" aimem context "$(pwd)" --format json
126
+ # Opcional: corre um compile antes e inclui o manifesto dessa corrida no bundle
127
+ uv run --directory "$AIMEM" aimem context "$(pwd)" --after-compile --compile-profile bootstrap
128
+ # Objectivo só do compile (o retrieval continua a usar --objective se o passares)
129
+ uv run --directory "$AIMEM" aimem context "$(pwd)" --after-compile --compile-objective "handoff notes"
130
+ ```
131
+
132
+ No Cursor, ao editares ficheiros sob `.ai_memory/`, a regra [`.cursor/rules/aimem-context-bootstrap.mdc`](.cursor/rules/aimem-context-bootstrap.mdc) sugere este fluxo (não é `alwaysApply`).
133
+
134
+ ## Contributing
135
+
136
+ Development setup, **MCP-first retrieval policy** (external docs/APIs vs canonical `.ai_memory`), and **remote/PR workflow** are described in [CONTRIBUTING.md](CONTRIBUTING.md) and [docs/releasing.md](docs/releasing.md). Cursor loads the same rules from [`.cursor/rules/mcp-first-retrieval.mdc`](.cursor/rules/mcp-first-retrieval.mdc).
137
+
138
+ ## Drift Sentinel
139
+
140
+ 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`.
141
+
142
+ ```bash
143
+ uv run aimem drift scan .
144
+ uv run aimem drift report .
145
+ uv run aimem drift reconcile .
146
+ uv run aimem drift apply . # dry-run: shows planned governance updates
147
+ uv run aimem drift apply . --write # sets verification_status: drifted on affected docs (uses .ai_memory lock)
148
+ ```
149
+
150
+ Open drift rows are stored in `.ai_memory/index/aimem.sqlite` and referenced from compile output / MCP helpers as `aimem://drift-event/<id>`.
151
+
152
+ ## Context manifests (ACM)
153
+
154
+ 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:
155
+
156
+ `Context manifest: aimem://manifest/<manifest_id>`
157
+
158
+ Inspect a manifest:
159
+
160
+ ```bash
161
+ uv run aimem manifest get <manifest_id> .
162
+ ```
163
+
164
+ The `aimem_version` field reflects the installed `aimem` package version.
165
+
166
+ ## MCP server (stdio, optional)
167
+
168
+ 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/`).
169
+
170
+ ```bash
171
+ uv sync --extra mcp
172
+ ```
173
+
174
+ Example **Cursor** MCP entry (`.cursor/mcp.json` or equivalent), pointing at this repo’s virtualenv:
175
+
176
+ ```json
177
+ {
178
+ "mcpServers": {
179
+ "aimem": {
180
+ "command": "uv",
181
+ "args": ["run", "--directory", "/absolute/path/to/this/repo", "aimem-mcp", "--repo", "/absolute/path/to/target/repo"]
182
+ }
183
+ }
184
+ }
185
+ ```
186
+
187
+ Adjust `--directory` to the checkout where `aimem` is installed and `--repo` to the Git project whose `.ai_memory` you want to query.
188
+
189
+ For a longer dogfooding checklist (paths, extras, typical errors), see [docs/dogfooding-mcp.md](docs/dogfooding-mcp.md).
190
+
191
+ ## Record Commands
192
+
193
+ Use the `record` subcommands to create canonical documents with consistent IDs, filenames, frontmatter, and journal entries.
194
+
195
+ ```bash
196
+ uv run aimem record decision "Adopt MCP"
197
+ uv run aimem record task "Add SQLite index" --done-when "query returns relevant docs"
198
+ ```
199
+
200
+ Use `--allow-secrets` only in controlled scenarios when you intentionally need to bypass high-confidence secret blocking.
201
+
202
+ ## Query
203
+
204
+ `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.
205
+
206
+ Default retrieval mode is `hybrid_metadata` (`FTS5` + metadata reranking). Semantic/vector retrieval remains opt-in.
207
+
208
+ ## Objective-Aware Compile
209
+
210
+ `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.
211
+
212
+ Compile profiles support `max_tokens` with `max_chars` fallback for environments without tokenizer extras.
213
+
214
+ ## Governance Lifecycle
215
+
216
+ Canonical documents use a lifecycle aimed at safe shared memory:
217
+
218
+ - `draft`
219
+ - `reviewed`
220
+ - `gold`
221
+ - `deprecated`
222
+
223
+ Deprecated documents are strongly penalized during retrieval and excluded by default from objective-focused context packs.
224
+
225
+ ## Hooks and Fast Verification
226
+
227
+ Install local Git hooks with:
228
+
229
+ ```bash
230
+ uv run aimem install-hooks
231
+ ```
232
+
233
+ The generated `pre-commit` hook runs `aimem verify --fast` for low-latency local checks.
234
+
235
+ ## Strict Governance
236
+
237
+ For stricter checks (including high-criticality review requirements), use:
238
+
239
+ ```bash
240
+ uv run aimem verify --strict
241
+ ```
242
+
243
+ ## Verification Refresh
244
+
245
+ `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.
246
+
247
+ ## Memory Model
248
+
249
+ - `rules`, `state`, `decisions`, `tasks`: canonical memory
250
+ - `journal`: append-only operational history
251
+ - `generated`: derived outputs
252
+ - `cache`, `index`, `workspaces`: local-only artifacts ignored by Git
253
+
254
+ Each canonical Markdown document uses YAML frontmatter with ownership, verification, and provenance metadata.
@@ -0,0 +1,60 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "uml-aimem"
7
+ version = "0.2.2"
8
+ description = "Unified Memory Layer CLI for canonical, derived, and agent-aware project memory."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ dependencies = [
12
+ "PyYAML>=6.0",
13
+ "typer>=0.12,<1.0",
14
+ ]
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/Mexicanguy1987/aimem"
18
+ Repository = "https://github.com/Mexicanguy1987/aimem"
19
+ Changelog = "https://github.com/Mexicanguy1987/aimem/blob/master/CHANGELOG.md"
20
+ PyPI = "https://pypi.org/project/uml-aimem/"
21
+
22
+ [project.optional-dependencies]
23
+ dev = [
24
+ "pytest>=7.4",
25
+ "pytest-benchmark>=4.0",
26
+ "pytest-asyncio>=0.23",
27
+ "locust>=2.30",
28
+ ]
29
+ mcp = [
30
+ "mcp>=1.0,<2",
31
+ ]
32
+ semantic = [
33
+ "sqlite-vec>=0.1.6",
34
+ ]
35
+ local-embed = [
36
+ "sentence-transformers>=3.0",
37
+ ]
38
+ openai = [
39
+ "openai>=1.40.0",
40
+ ]
41
+ tokens = [
42
+ "tiktoken>=0.7.0",
43
+ ]
44
+
45
+ [project.scripts]
46
+ aimem = "aimem.cli:app"
47
+ aimem-mcp = "aimem.mcp_server:main"
48
+
49
+ [tool.setuptools]
50
+ package-dir = {"" = "src"}
51
+
52
+ [tool.setuptools.packages.find]
53
+ where = ["src"]
54
+
55
+ [tool.setuptools.package-data]
56
+ "aimem.templates" = ["*.md", "*.yaml", "*.txt", "*.jsonl"]
57
+
58
+ [tool.pytest.ini_options]
59
+ testpaths = ["tests"]
60
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,19 @@
1
+ """aimem package."""
2
+
3
+ import importlib.metadata
4
+
5
+ from aimem._dist import DISTRIBUTION_NAME
6
+
7
+ __all__ = ["__version__", "DISTRIBUTION_NAME"]
8
+
9
+
10
+ def _installed_version() -> str:
11
+ for dist in (DISTRIBUTION_NAME, "aimem"):
12
+ try:
13
+ return importlib.metadata.version(dist)
14
+ except importlib.metadata.PackageNotFoundError:
15
+ continue
16
+ return "0.0.0+unknown"
17
+
18
+
19
+ __version__ = _installed_version()
@@ -0,0 +1,3 @@
1
+ """PyPI distribution name (import package remains ``aimem``)."""
2
+
3
+ DISTRIBUTION_NAME = "uml-aimem"
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ import typer
4
+
5
+ from aimem.commands.compile import compile_command
6
+ from aimem.commands.context import context_command
7
+ from aimem.commands.drift import drift_app
8
+ from aimem.commands.hooks import install_hooks_command
9
+ from aimem.commands.index import index_app
10
+ from aimem.commands.init import init_command
11
+ from aimem.commands.manifest import manifest_app
12
+ from aimem.commands.promote import promote_command
13
+ from aimem.commands.query import query_command
14
+ from aimem.commands.record import record_app
15
+ from aimem.commands.verify import verify_command
16
+
17
+ app = typer.Typer(help="Unified Memory Layer CLI.")
18
+
19
+ app.command("init")(init_command)
20
+ app.command("compile")(compile_command)
21
+ app.command("context")(context_command)
22
+ app.command("query")(query_command)
23
+ app.command("verify")(verify_command)
24
+ app.command("install-hooks")(install_hooks_command)
25
+ app.command("promote")(promote_command)
26
+ app.add_typer(record_app, name="record")
27
+ app.add_typer(drift_app, name="drift")
28
+ app.add_typer(manifest_app, name="manifest")
29
+ app.add_typer(index_app, name="index")
30
+
31
+
32
+ def main() -> None:
33
+ app()
34
+
35
+
36
+ if __name__ == "__main__":
37
+ main()