cogno-engram 0.1.0__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 (35) hide show
  1. cogno_engram-0.1.0/LICENSE +201 -0
  2. cogno_engram-0.1.0/PKG-INFO +206 -0
  3. cogno_engram-0.1.0/README.md +168 -0
  4. cogno_engram-0.1.0/cogno_engram/__init__.py +43 -0
  5. cogno_engram-0.1.0/cogno_engram/adapters/__init__.py +3 -0
  6. cogno_engram-0.1.0/cogno_engram/adapters/in_memory.py +466 -0
  7. cogno_engram-0.1.0/cogno_engram/adapters/postgres.py +800 -0
  8. cogno_engram-0.1.0/cogno_engram/adapters/redis_buffer.py +97 -0
  9. cogno_engram-0.1.0/cogno_engram/graph_context.py +79 -0
  10. cogno_engram-0.1.0/cogno_engram/hypnos.py +359 -0
  11. cogno_engram-0.1.0/cogno_engram/maintenance.py +83 -0
  12. cogno_engram-0.1.0/cogno_engram/ports.py +149 -0
  13. cogno_engram-0.1.0/cogno_engram/reranker.py +120 -0
  14. cogno_engram-0.1.0/cogno_engram/types.py +160 -0
  15. cogno_engram-0.1.0/cogno_engram.egg-info/PKG-INFO +206 -0
  16. cogno_engram-0.1.0/cogno_engram.egg-info/SOURCES.txt +33 -0
  17. cogno_engram-0.1.0/cogno_engram.egg-info/dependency_links.txt +1 -0
  18. cogno_engram-0.1.0/cogno_engram.egg-info/requires.txt +14 -0
  19. cogno_engram-0.1.0/cogno_engram.egg-info/top_level.txt +1 -0
  20. cogno_engram-0.1.0/pyproject.toml +86 -0
  21. cogno_engram-0.1.0/setup.cfg +4 -0
  22. cogno_engram-0.1.0/tests/test_cognobench_smoke.py +92 -0
  23. cogno_engram-0.1.0/tests/test_completeness_surface.py +100 -0
  24. cogno_engram-0.1.0/tests/test_e2e_lifecycle.py +109 -0
  25. cogno_engram-0.1.0/tests/test_e2e_lifecycle_integration.py +127 -0
  26. cogno_engram-0.1.0/tests/test_hypnos_llm.py +253 -0
  27. cogno_engram-0.1.0/tests/test_hypnos_micro.py +50 -0
  28. cogno_engram-0.1.0/tests/test_in_memory_buffer.py +31 -0
  29. cogno_engram-0.1.0/tests/test_in_memory_graph.py +121 -0
  30. cogno_engram-0.1.0/tests/test_in_memory_store.py +221 -0
  31. cogno_engram-0.1.0/tests/test_maintenance.py +68 -0
  32. cogno_engram-0.1.0/tests/test_postgres_integration.py +421 -0
  33. cogno_engram-0.1.0/tests/test_postgres_validation.py +36 -0
  34. cogno_engram-0.1.0/tests/test_redis_integration.py +103 -0
  35. cogno_engram-0.1.0/tests/test_reranker.py +87 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Sudoers AI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,206 @@
1
+ Metadata-Version: 2.4
2
+ Name: cogno-engram
3
+ Version: 0.1.0
4
+ Summary: Persistence substrate for the Cogno cognitive pipeline — memory store, knowledge graph, conversation buffer, and sleep-time consolidation (hypnos)
5
+ Author: Vinicius Vale
6
+ Maintainer: Sudoers AI
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/sudoers-ai/cogno-engram
9
+ Project-URL: Repository, https://github.com/sudoers-ai/cogno-engram
10
+ Project-URL: Issues, https://github.com/sudoers-ai/cogno-engram/issues
11
+ Keywords: llm,memory,rag,knowledge-graph,pgvector,redis,agents,consolidation
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Database
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Classifier: Operating System :: OS Independent
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8.0; extra == "dev"
28
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
29
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
30
+ Requires-Dist: ruff>=0.5; extra == "dev"
31
+ Requires-Dist: mypy>=1.8; extra == "dev"
32
+ Provides-Extra: postgres
33
+ Requires-Dist: psycopg[binary,pool]>=3.1; extra == "postgres"
34
+ Requires-Dist: pgvector>=0.2; extra == "postgres"
35
+ Provides-Extra: redis
36
+ Requires-Dist: redis>=5.0; extra == "redis"
37
+ Dynamic: license-file
38
+
39
+ # cogno-engram
40
+
41
+ **Persistence substrate for the [Cogno](https://github.com/sudoers-ai/cogno-anima) cognitive pipeline** — memory store, knowledge graph, conversation buffer, and sleep-time consolidation.
42
+
43
+ `cogno-engram` is the *memory* to [`cogno-anima`](https://github.com/sudoers-ai/cogno-anima)'s *mind*. Where `cogno-anima` is pure, infrastructure-agnostic cognition (no I/O), `cogno-engram` is the opinionated **substrate** that remembers: it persists conversation turns, consolidates them into long-term semantic memories, and threads them into a relational knowledge graph.
44
+
45
+ > Status: **alpha** — the contract (ports + types) and the zero-dependency in-memory adapter are in place. The Postgres/Redis reference adapters and the LLM-driven consolidation tiers are in build-out.
46
+
47
+ ## Philosophy: ports, not a universal store
48
+
49
+ A single abstraction over relational + key-value + graph collapses to a lowest-common-denominator that throws away vector search and graph traversal. Instead, `cogno-engram` defines **three capability-scoped ports**, each backed by the storage engine that fits it:
50
+
51
+ | Port | Shape | Reference adapter |
52
+ | --- | --- | --- |
53
+ | `MemoryStore` | sessions / turns / memories + hybrid retrieval + per-turn traces | Postgres + pgvector |
54
+ | `ConversationBuffer` | sliding short-term window (+ TTL) | Redis |
55
+ | `KnowledgeGraph` | typed nodes + directed edges + multi-hop walk | Postgres (recursive CTE) |
56
+
57
+ Vector search is an **optional capability** (`SupportsVectorSearch`) — a store without it degrades retrieval to lexical/chronological instead of breaking.
58
+
59
+ ## Decoupled by an opaque `scope`
60
+
61
+ Every row is isolated by an opaque `scope` string. `cogno-engram` never interprets it — the **host** composes it (e.g. `"tenant/phone"`) and owns its meaning and any cross-scope aggregation. There is no `tenant_id`/`phone_id` in the schema; the substrate is reusable for any domain.
62
+
63
+ ```python
64
+ from cogno_engram import InMemoryStore, MemoryRecord, RetrievalQuery
65
+
66
+ store = InMemoryStore()
67
+ session = await store.create_session(scope="acme/phone1")
68
+ await store.save_memory(MemoryRecord("acme/phone1", "preference", "likes oat milk", embedding=[...]))
69
+
70
+ hits = await store.load_memories(
71
+ "acme/phone1",
72
+ query=RetrievalQuery(text="what milk?", embedding=[...]), # hybrid: vector + lexical + feedback
73
+ )
74
+ ```
75
+
76
+ ## `hypnos` — sleep-time consolidation (3-tier)
77
+
78
+ Named for the god of sleep: consolidation runs while a session "sleeps". As everywhere in Cogno, **engram provides the steps, the host runs the loop** — there is no daemon here.
79
+
80
+ - **Tier 1 — `micro_consolidate`** — synchronous, per-turn, **LLM-free** (goal transitions, sentiment spikes, PII leaks, new-domain interest).
81
+ - **Tier 2 — `periodic_consolidate`** — async, every N turns, LLM extraction (+ KG relations).
82
+ - **Tier 3 — `consolidate_session`** — async, on session close/idle, holistic LLM pass (+ feedback-driven KG pruning).
83
+
84
+ ## Install
85
+
86
+ ```bash
87
+ pip install cogno-engram # core: ports + in-memory adapter (zero deps)
88
+ pip install "cogno-engram[postgres]" # Postgres + pgvector adapter
89
+ pip install "cogno-engram[redis]" # Redis buffer adapter
90
+ ```
91
+
92
+ The Tier-2/3 consolidation drives an LLM through a `cogno-anima` `LLMBackend` (host-injected).
93
+
94
+ ## Postgres + pgvector adapter
95
+
96
+ The reference adapter implements `MemoryStore` (hybrid retrieval = `0.60·vector + 0.40·BM25 + 0.05·feedback`) and `KnowledgeGraph` (recursive-CTE multi-hop walk) over one database. Call `ensure_schema` once for the idempotent DDL (tables + indexes; no alembic required — re-running it additively creates any new table via `CREATE TABLE IF NOT EXISTS`):
97
+
98
+ The high-volume tables (`turns`, `memories`, `turn_traces`) opt into `HASH(scope)` partitioning. `turn_traces` is a dedicated table holding one **opaque JSONB** trace per turn (`save_turn_trace` / `traces_for_session`) — the host composes it (e.g. the pipeline's NER/EGO signals for an audit view); engram never interprets it.
99
+
100
+ ```python
101
+ import psycopg
102
+ from cogno_engram.adapters.postgres import PostgresStore, ensure_schema
103
+
104
+ async with await psycopg.AsyncConnection.connect(dsn, autocommit=True) as conn:
105
+ await ensure_schema(conn) # CREATE TABLE/INDEX IF NOT EXISTS
106
+
107
+ store = PostgresStore(dsn=dsn, mask_pii=True)
108
+ hits = await store.load_memories("acme/phone1", query=RetrievalQuery(text="...", embedding=[...]))
109
+ ```
110
+
111
+ For scale, opt the high-volume tables into HASH(scope) partitioning (the generic
112
+ equivalent of the parent's LIST(tenant), with zero DDL per new scope):
113
+
114
+ ```python
115
+ await ensure_schema(conn, partition_by_scope=True, partitions=8)
116
+ ```
117
+
118
+ ## Maintenance (sleep-time upkeep)
119
+
120
+ Like `hypnos`, the host schedules; engram does the work — keeping the substrate
121
+ bounded and consistent over time:
122
+
123
+ ```python
124
+ from cogno_engram import maintenance
125
+
126
+ await maintenance.prune_memories(store, scope, older_than=timedelta(days=180), max_confidence=0.75)
127
+ await maintenance.reembed_memories(store, embedder, scope) # after an embedding-model change
128
+ await maintenance.prune_orphan_nodes(kg, scope) # drop edgeless graph nodes
129
+ ```
130
+
131
+ ## Reranking
132
+
133
+ `load_memories` returns relevance-ordered candidates; `rerank` refines them with a two-pass pipeline before you inject the top-k:
134
+
135
+ ```python
136
+ from cogno_engram import rerank, RerankConfig
137
+
138
+ candidates = await store.load_memories("acme/phone1", query=q, limit=20)
139
+ top = rerank(candidates, query_text=q.text, top_k=5) # sim + recency-decay + category boost
140
+ ```
141
+
142
+ Pass 1 is pure (`sim·0.60 + recency·0.25 + category·0.15`, half-life and boosts configurable via `RerankConfig`). Pass 2 is an optional **host-injected** cross-encoder callable `(query, [content]) -> [score]` — so cogno-engram ships no heavy ML dependency.
143
+
144
+ ## EngramBench
145
+
146
+ A self-contained quality harness (no DB, no model — deterministic) over the in-memory adapter, scoring the substrate's three jobs:
147
+
148
+ ```bash
149
+ python3 cognobench.py # 5 deterministic dims: retrieval/buffer/consolidation/graph/lifecycle
150
+ python3 cognobench.py --only graph
151
+ python3 cognobench.py --min-score 100 # CI gate
152
+ # opt-in, model-dependent: hypnos Tier-2 extraction quality vs a real Ollama model
153
+ python3 cognobench.py --only llm_consolidation
154
+ # opt-in: the FULL edge-capture path (Tier-2 relation extraction → graph at kg_scope)
155
+ python3 cognobench.py --only graph_capture --model mistral:latest
156
+ # visualize every graph the bench built/captured as one self-contained HTML
157
+ python3 cognobench.py --only graph graph_capture --graph-html graphs.html
158
+ ```
159
+
160
+ Dimensions: **retrieval** (hit@1, vector + BM25-only), **buffer** (sliding-window
161
+ retention), **consolidation** (Tier-1 micro), **graph** (multi-hop walk),
162
+ **lifecycle** (end-to-end: turns → Tier-1 → retrieval+rerank), and the opt-in
163
+ **llm_consolidation** (Tier-2 memory quality against Ollama) and **graph_capture**
164
+ (Tier-2 relation extraction against Ollama: hard invariants — no dangling edges,
165
+ valid confidence, session-tagged, graph rows only at `kg_scope` — plus soft
166
+ entity-connectivity checks). Case distributions are modelled on the parent's real
167
+ data (goal-heavy memories, BM25-dominant retrieval, NEEDS/PREFERS graph) — all
168
+ synthetic.
169
+
170
+ ## The Cogno ecosystem
171
+
172
+ `cogno-engram` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
173
+ small, composable, Apache-2.0 libraries that together form a complete
174
+ conversational-agent platform. Each library owns a single concern and stays
175
+ infra-agnostic; a **host** assembles them into a running agent:
176
+
177
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
178
+
179
+ The open-source libraries are the organs; the **host is the body** that joins
180
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
181
+ private product layer, but it holds no special powers: everything it does rides
182
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
183
+ you can assemble a body of your own.
184
+
185
+ ## Testing
186
+
187
+ ```bash
188
+ pip install -e ".[dev]"
189
+ python3 -m pytest -q # unit + bench-smoke (Postgres tests auto-skip)
190
+
191
+ # Run the integration suites against real services:
192
+ docker run -d --rm --name engram-pg -e POSTGRES_PASSWORD=postgres \
193
+ -p 55432:5432 pgvector/pgvector:pg16
194
+ docker run -d --rm --name engram-redis -p 56379:6379 redis:7-alpine
195
+ ENGRAM_TEST_DSN=postgresql://postgres:postgres@localhost:55432/postgres \
196
+ ENGRAM_TEST_REDIS_URL=redis://localhost:56379/0 \
197
+ python3 -m pytest tests/test_postgres_integration.py tests/test_redis_integration.py -q
198
+ ```
199
+
200
+ ## What lives in the host (not here)
201
+
202
+ Business identity (`tenants`/`identities`), billing/token ledgers, persona/domain schemas, feedback *capture* (emoji → ±1), persona switching, OTP/rate-limiting, and the consolidation **worker loop**. `cogno-engram` only knows `scope`, sessions/turns/memories, the graph, and the buffer.
203
+
204
+ ## License
205
+
206
+ Apache-2.0 © Sudoers AI
@@ -0,0 +1,168 @@
1
+ # cogno-engram
2
+
3
+ **Persistence substrate for the [Cogno](https://github.com/sudoers-ai/cogno-anima) cognitive pipeline** — memory store, knowledge graph, conversation buffer, and sleep-time consolidation.
4
+
5
+ `cogno-engram` is the *memory* to [`cogno-anima`](https://github.com/sudoers-ai/cogno-anima)'s *mind*. Where `cogno-anima` is pure, infrastructure-agnostic cognition (no I/O), `cogno-engram` is the opinionated **substrate** that remembers: it persists conversation turns, consolidates them into long-term semantic memories, and threads them into a relational knowledge graph.
6
+
7
+ > Status: **alpha** — the contract (ports + types) and the zero-dependency in-memory adapter are in place. The Postgres/Redis reference adapters and the LLM-driven consolidation tiers are in build-out.
8
+
9
+ ## Philosophy: ports, not a universal store
10
+
11
+ A single abstraction over relational + key-value + graph collapses to a lowest-common-denominator that throws away vector search and graph traversal. Instead, `cogno-engram` defines **three capability-scoped ports**, each backed by the storage engine that fits it:
12
+
13
+ | Port | Shape | Reference adapter |
14
+ | --- | --- | --- |
15
+ | `MemoryStore` | sessions / turns / memories + hybrid retrieval + per-turn traces | Postgres + pgvector |
16
+ | `ConversationBuffer` | sliding short-term window (+ TTL) | Redis |
17
+ | `KnowledgeGraph` | typed nodes + directed edges + multi-hop walk | Postgres (recursive CTE) |
18
+
19
+ Vector search is an **optional capability** (`SupportsVectorSearch`) — a store without it degrades retrieval to lexical/chronological instead of breaking.
20
+
21
+ ## Decoupled by an opaque `scope`
22
+
23
+ Every row is isolated by an opaque `scope` string. `cogno-engram` never interprets it — the **host** composes it (e.g. `"tenant/phone"`) and owns its meaning and any cross-scope aggregation. There is no `tenant_id`/`phone_id` in the schema; the substrate is reusable for any domain.
24
+
25
+ ```python
26
+ from cogno_engram import InMemoryStore, MemoryRecord, RetrievalQuery
27
+
28
+ store = InMemoryStore()
29
+ session = await store.create_session(scope="acme/phone1")
30
+ await store.save_memory(MemoryRecord("acme/phone1", "preference", "likes oat milk", embedding=[...]))
31
+
32
+ hits = await store.load_memories(
33
+ "acme/phone1",
34
+ query=RetrievalQuery(text="what milk?", embedding=[...]), # hybrid: vector + lexical + feedback
35
+ )
36
+ ```
37
+
38
+ ## `hypnos` — sleep-time consolidation (3-tier)
39
+
40
+ Named for the god of sleep: consolidation runs while a session "sleeps". As everywhere in Cogno, **engram provides the steps, the host runs the loop** — there is no daemon here.
41
+
42
+ - **Tier 1 — `micro_consolidate`** — synchronous, per-turn, **LLM-free** (goal transitions, sentiment spikes, PII leaks, new-domain interest).
43
+ - **Tier 2 — `periodic_consolidate`** — async, every N turns, LLM extraction (+ KG relations).
44
+ - **Tier 3 — `consolidate_session`** — async, on session close/idle, holistic LLM pass (+ feedback-driven KG pruning).
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install cogno-engram # core: ports + in-memory adapter (zero deps)
50
+ pip install "cogno-engram[postgres]" # Postgres + pgvector adapter
51
+ pip install "cogno-engram[redis]" # Redis buffer adapter
52
+ ```
53
+
54
+ The Tier-2/3 consolidation drives an LLM through a `cogno-anima` `LLMBackend` (host-injected).
55
+
56
+ ## Postgres + pgvector adapter
57
+
58
+ The reference adapter implements `MemoryStore` (hybrid retrieval = `0.60·vector + 0.40·BM25 + 0.05·feedback`) and `KnowledgeGraph` (recursive-CTE multi-hop walk) over one database. Call `ensure_schema` once for the idempotent DDL (tables + indexes; no alembic required — re-running it additively creates any new table via `CREATE TABLE IF NOT EXISTS`):
59
+
60
+ The high-volume tables (`turns`, `memories`, `turn_traces`) opt into `HASH(scope)` partitioning. `turn_traces` is a dedicated table holding one **opaque JSONB** trace per turn (`save_turn_trace` / `traces_for_session`) — the host composes it (e.g. the pipeline's NER/EGO signals for an audit view); engram never interprets it.
61
+
62
+ ```python
63
+ import psycopg
64
+ from cogno_engram.adapters.postgres import PostgresStore, ensure_schema
65
+
66
+ async with await psycopg.AsyncConnection.connect(dsn, autocommit=True) as conn:
67
+ await ensure_schema(conn) # CREATE TABLE/INDEX IF NOT EXISTS
68
+
69
+ store = PostgresStore(dsn=dsn, mask_pii=True)
70
+ hits = await store.load_memories("acme/phone1", query=RetrievalQuery(text="...", embedding=[...]))
71
+ ```
72
+
73
+ For scale, opt the high-volume tables into HASH(scope) partitioning (the generic
74
+ equivalent of the parent's LIST(tenant), with zero DDL per new scope):
75
+
76
+ ```python
77
+ await ensure_schema(conn, partition_by_scope=True, partitions=8)
78
+ ```
79
+
80
+ ## Maintenance (sleep-time upkeep)
81
+
82
+ Like `hypnos`, the host schedules; engram does the work — keeping the substrate
83
+ bounded and consistent over time:
84
+
85
+ ```python
86
+ from cogno_engram import maintenance
87
+
88
+ await maintenance.prune_memories(store, scope, older_than=timedelta(days=180), max_confidence=0.75)
89
+ await maintenance.reembed_memories(store, embedder, scope) # after an embedding-model change
90
+ await maintenance.prune_orphan_nodes(kg, scope) # drop edgeless graph nodes
91
+ ```
92
+
93
+ ## Reranking
94
+
95
+ `load_memories` returns relevance-ordered candidates; `rerank` refines them with a two-pass pipeline before you inject the top-k:
96
+
97
+ ```python
98
+ from cogno_engram import rerank, RerankConfig
99
+
100
+ candidates = await store.load_memories("acme/phone1", query=q, limit=20)
101
+ top = rerank(candidates, query_text=q.text, top_k=5) # sim + recency-decay + category boost
102
+ ```
103
+
104
+ Pass 1 is pure (`sim·0.60 + recency·0.25 + category·0.15`, half-life and boosts configurable via `RerankConfig`). Pass 2 is an optional **host-injected** cross-encoder callable `(query, [content]) -> [score]` — so cogno-engram ships no heavy ML dependency.
105
+
106
+ ## EngramBench
107
+
108
+ A self-contained quality harness (no DB, no model — deterministic) over the in-memory adapter, scoring the substrate's three jobs:
109
+
110
+ ```bash
111
+ python3 cognobench.py # 5 deterministic dims: retrieval/buffer/consolidation/graph/lifecycle
112
+ python3 cognobench.py --only graph
113
+ python3 cognobench.py --min-score 100 # CI gate
114
+ # opt-in, model-dependent: hypnos Tier-2 extraction quality vs a real Ollama model
115
+ python3 cognobench.py --only llm_consolidation
116
+ # opt-in: the FULL edge-capture path (Tier-2 relation extraction → graph at kg_scope)
117
+ python3 cognobench.py --only graph_capture --model mistral:latest
118
+ # visualize every graph the bench built/captured as one self-contained HTML
119
+ python3 cognobench.py --only graph graph_capture --graph-html graphs.html
120
+ ```
121
+
122
+ Dimensions: **retrieval** (hit@1, vector + BM25-only), **buffer** (sliding-window
123
+ retention), **consolidation** (Tier-1 micro), **graph** (multi-hop walk),
124
+ **lifecycle** (end-to-end: turns → Tier-1 → retrieval+rerank), and the opt-in
125
+ **llm_consolidation** (Tier-2 memory quality against Ollama) and **graph_capture**
126
+ (Tier-2 relation extraction against Ollama: hard invariants — no dangling edges,
127
+ valid confidence, session-tagged, graph rows only at `kg_scope` — plus soft
128
+ entity-connectivity checks). Case distributions are modelled on the parent's real
129
+ data (goal-heavy memories, BM25-dominant retrieval, NEEDS/PREFERS graph) — all
130
+ synthetic.
131
+
132
+ ## The Cogno ecosystem
133
+
134
+ `cogno-engram` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
135
+ small, composable, Apache-2.0 libraries that together form a complete
136
+ conversational-agent platform. Each library owns a single concern and stays
137
+ infra-agnostic; a **host** assembles them into a running agent:
138
+
139
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
140
+
141
+ The open-source libraries are the organs; the **host is the body** that joins
142
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
143
+ private product layer, but it holds no special powers: everything it does rides
144
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
145
+ you can assemble a body of your own.
146
+
147
+ ## Testing
148
+
149
+ ```bash
150
+ pip install -e ".[dev]"
151
+ python3 -m pytest -q # unit + bench-smoke (Postgres tests auto-skip)
152
+
153
+ # Run the integration suites against real services:
154
+ docker run -d --rm --name engram-pg -e POSTGRES_PASSWORD=postgres \
155
+ -p 55432:5432 pgvector/pgvector:pg16
156
+ docker run -d --rm --name engram-redis -p 56379:6379 redis:7-alpine
157
+ ENGRAM_TEST_DSN=postgresql://postgres:postgres@localhost:55432/postgres \
158
+ ENGRAM_TEST_REDIS_URL=redis://localhost:56379/0 \
159
+ python3 -m pytest tests/test_postgres_integration.py tests/test_redis_integration.py -q
160
+ ```
161
+
162
+ ## What lives in the host (not here)
163
+
164
+ Business identity (`tenants`/`identities`), billing/token ledgers, persona/domain schemas, feedback *capture* (emoji → ±1), persona switching, OTP/rate-limiting, and the consolidation **worker loop**. `cogno-engram` only knows `scope`, sessions/turns/memories, the graph, and the buffer.
165
+
166
+ ## License
167
+
168
+ Apache-2.0 © Sudoers AI
@@ -0,0 +1,43 @@
1
+ """cogno-engram — persistence substrate for the Cogno cognitive pipeline."""
2
+
3
+ from cogno_engram import hypnos, maintenance
4
+ from cogno_engram.adapters.in_memory import InMemoryBuffer, InMemoryGraph, InMemoryStore
5
+ from cogno_engram.graph_context import format_graph_context, ingest_entities
6
+ from cogno_engram.reranker import RerankConfig, recency_score, rerank
7
+ from cogno_engram.ports import (
8
+ ConversationBuffer,
9
+ KnowledgeGraph,
10
+ MemoryStore,
11
+ SupportsVectorSearch,
12
+ )
13
+ from cogno_engram.types import (
14
+ DEFAULT_CONFIDENCE,
15
+ VALID_NODE_TYPES,
16
+ GraphEdge,
17
+ GraphNode,
18
+ HybridWeights,
19
+ MemoryRecord,
20
+ NodeContext,
21
+ RetrievalQuery,
22
+ Session,
23
+ SessionSummary,
24
+ TurnRecord,
25
+ TurnTrace,
26
+ )
27
+
28
+ __version__ = "0.1.0"
29
+
30
+ __all__ = [
31
+ "__version__",
32
+ # ports
33
+ "MemoryStore", "SupportsVectorSearch", "ConversationBuffer", "KnowledgeGraph",
34
+ # types
35
+ "Session", "TurnRecord", "TurnTrace", "MemoryRecord", "GraphNode", "GraphEdge", "NodeContext",
36
+ "RetrievalQuery", "HybridWeights", "SessionSummary",
37
+ "DEFAULT_CONFIDENCE", "VALID_NODE_TYPES",
38
+ # reference adapters
39
+ "InMemoryStore", "InMemoryBuffer", "InMemoryGraph",
40
+ # consolidation + maintenance + reranking + graph helpers
41
+ "hypnos", "maintenance", "rerank", "RerankConfig", "recency_score",
42
+ "ingest_entities", "format_graph_context",
43
+ ]
@@ -0,0 +1,3 @@
1
+ from cogno_engram.adapters.in_memory import InMemoryBuffer, InMemoryGraph, InMemoryStore
2
+
3
+ __all__ = ["InMemoryStore", "InMemoryBuffer", "InMemoryGraph"]