hb-cortex-memory 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 (38) hide show
  1. hb_cortex_memory-0.1.0/LICENSE +201 -0
  2. hb_cortex_memory-0.1.0/PKG-INFO +168 -0
  3. hb_cortex_memory-0.1.0/README.md +136 -0
  4. hb_cortex_memory-0.1.0/__init__.py +126 -0
  5. hb_cortex_memory-0.1.0/_textutil.py +83 -0
  6. hb_cortex_memory-0.1.0/assembly.py +335 -0
  7. hb_cortex_memory-0.1.0/db.py +25 -0
  8. hb_cortex_memory-0.1.0/domains.py +158 -0
  9. hb_cortex_memory-0.1.0/dreaming.py +568 -0
  10. hb_cortex_memory-0.1.0/dreaming_prompts.py +55 -0
  11. hb_cortex_memory-0.1.0/dtos.py +260 -0
  12. hb_cortex_memory-0.1.0/embedding.py +58 -0
  13. hb_cortex_memory-0.1.0/enums.py +78 -0
  14. hb_cortex_memory-0.1.0/episodic_tree.py +466 -0
  15. hb_cortex_memory-0.1.0/experience_tree.py +230 -0
  16. hb_cortex_memory-0.1.0/graph.py +409 -0
  17. hb_cortex_memory-0.1.0/hb_cortex_memory.egg-info/PKG-INFO +168 -0
  18. hb_cortex_memory-0.1.0/hb_cortex_memory.egg-info/SOURCES.txt +60 -0
  19. hb_cortex_memory-0.1.0/hb_cortex_memory.egg-info/dependency_links.txt +1 -0
  20. hb_cortex_memory-0.1.0/hb_cortex_memory.egg-info/requires.txt +10 -0
  21. hb_cortex_memory-0.1.0/hb_cortex_memory.egg-info/top_level.txt +1 -0
  22. hb_cortex_memory-0.1.0/ingestion.py +224 -0
  23. hb_cortex_memory-0.1.0/intelligence_tree.py +275 -0
  24. hb_cortex_memory-0.1.0/knowledge_tree.py +483 -0
  25. hb_cortex_memory-0.1.0/models.py +240 -0
  26. hb_cortex_memory-0.1.0/prompts.py +21 -0
  27. hb_cortex_memory-0.1.0/providers.py +156 -0
  28. hb_cortex_memory-0.1.0/providers_reference.py +121 -0
  29. hb_cortex_memory-0.1.0/py.typed +0 -0
  30. hb_cortex_memory-0.1.0/pyproject.toml +67 -0
  31. hb_cortex_memory-0.1.0/schema.py +43 -0
  32. hb_cortex_memory-0.1.0/scope_policy.py +53 -0
  33. hb_cortex_memory-0.1.0/service.py +1196 -0
  34. hb_cortex_memory-0.1.0/setup.cfg +4 -0
  35. hb_cortex_memory-0.1.0/tests/test_coverage.py +211 -0
  36. hb_cortex_memory-0.1.0/tests/test_integration.py +108 -0
  37. hb_cortex_memory-0.1.0/tests/test_pure.py +255 -0
  38. hb_cortex_memory-0.1.0/tests/test_services.py +177 -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 not
32
+ limited to compiled object code, generated documentation, and
33
+ 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 the
49
+ 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 Derivative
95
+ 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 do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ 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 for
125
+ use, reproduction, or distribution of Your modifications, or for any
126
+ such Derivative Works as a whole, provided Your use, reproduction,
127
+ and distribution of the Work otherwise complies with the conditions
128
+ 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 agreed
144
+ to in writing, Licensor provides the Work (and each Contributor
145
+ provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
146
+ OR CONDITIONS OF ANY KIND, either express or implied, including,
147
+ without limitation, any warranties or conditions of TITLE,
148
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
149
+ 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 has
163
+ been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing the
166
+ Work or Derivative Works thereof, You may choose to offer, and charge
167
+ a fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your own
170
+ behalf and on Your sole responsibility, not on behalf of any other
171
+ Contributor, and only if You agree to indemnify, defend, and hold
172
+ each Contributor harmless for any liability incurred by, or claims
173
+ asserted against, such Contributor by reason of your accepting any
174
+ 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 [yyyy] [name of copyright owner]
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,168 @@
1
+ Metadata-Version: 2.4
2
+ Name: hb-cortex-memory
3
+ Version: 0.1.0
4
+ Summary: CORTEX — a navigable, writable hierarchical-memory engine for LLM agents (PostgreSQL + pgvector).
5
+ Author: HireBuddha
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/gondolerahul/cortex-memory
8
+ Project-URL: Repository, https://github.com/gondolerahul/cortex-memory
9
+ Keywords: llm,agents,memory,rag,pgvector,cortex,knowledge-graph
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: SQLAlchemy>=2.0
23
+ Requires-Dist: pgvector>=0.2.0
24
+ Requires-Dist: pydantic>=2.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7.0; extra == "dev"
27
+ Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
28
+ Requires-Dist: coverage>=7.0; extra == "dev"
29
+ Requires-Dist: mypy>=1.5; extra == "dev"
30
+ Requires-Dist: asyncpg>=0.28; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # cortex-memory
34
+
35
+ A navigable, writable **hierarchical-memory engine for LLM agents** — the agent
36
+ never holds "context", it holds a *viewport* onto a persistent cognitive tree
37
+ (PostgreSQL + pgvector). Extracted as a host-independent package (Phase 12 track
38
+ `04`). **Import:** `cortex_memory`. **Dist:** `cortex-memory`. **License:** Apache-2.0.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install cortex-memory # needs a Postgres with the `vector` extension
44
+ ```
45
+
46
+ ## Quickstart
47
+
48
+ ```python
49
+ import asyncio
50
+ from uuid import uuid4
51
+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
52
+ from cortex_memory import CortexService
53
+ from cortex_memory.providers_reference import EchoLLMProvider # swap for your own adapter
54
+ from cortex_memory.schema import create_all_schema_async
55
+
56
+ async def main():
57
+ engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
58
+ await create_all_schema_async(engine) # idempotent
59
+ async with async_sessionmaker(engine, expire_on_commit=False)() as db:
60
+ cortex = CortexService(db, uuid4(), llm=EchoLLMProvider())
61
+ tree = await cortex.create_tree(entity_id=uuid4(), user_id=None,
62
+ task_description="Summarise the deck")
63
+ await db.commit()
64
+ working = await cortex.get_working_root(tree.id)
65
+ await cortex.write(parent_id=working.id, node_type="finding",
66
+ title="Key point", content="…", summary="…")
67
+ await db.commit()
68
+ print((await cortex.navigate(working.id)).to_prompt_text())
69
+
70
+ asyncio.run(main())
71
+ ```
72
+
73
+ A runnable version: `python -m cortex_memory.examples.quickstart`. The host
74
+ injects real LLM/embedding adapters via the Protocols (see **The boundary rule**);
75
+ the reference providers above let it run with no external services.
76
+
77
+ ## Develop
78
+
79
+ ```bash
80
+ pip install -e ".[dev]"
81
+ mypy --strict cortex_memory # strict-clean
82
+ CORTEX_TEST_DATABASE_URL=postgresql+asyncpg://… coverage run --source=cortex_memory -m pytest
83
+ coverage report # ≥85%
84
+ python -m build # sdist + wheel
85
+ ```
86
+
87
+ Pure-logic tests need nothing; the integration tests are skipped unless
88
+ `CORTEX_TEST_DATABASE_URL` (or `DATABASE_URL`) points at a Postgres+pgvector. CI:
89
+ `.github/workflows/cortex-memory.yml`.
90
+
91
+ ---
92
+
93
+ > Status: **Stages B + C COMPLETE** (in-repo). The package is self-contained,
94
+ > `mypy --strict`-clean, 85%-covered, and builds a wheel; only the move to a
95
+ > public repo + PyPI upload remains. Every CORTEX module now lives here,
96
+ > with **zero host imports** (a package self-test enforces it): the data layer
97
+ > (`db`/`models`/`enums`/`dtos`/`schema`), the provider boundary
98
+ > (`providers`/`providers_reference`), and all services — `service` (the 7 tree
99
+ > ops), `graph`, `ingestion`, the four domain trees (`knowledge_tree`/
100
+ > `episodic_tree`/`experience_tree`/`intelligence_tree`), `dreaming`, and
101
+ > `assembly` (the v2 assembler) — plus `scope_policy`, `domains`, `prompts`, and
102
+ > the embedding/text helpers. The host's `src/ai/memory/` keeps only thin
103
+ > re-export/auto-injection **shims** + the genuine host **adapters**
104
+ > (`cortex_providers`, `cortex_bridge`, `cortex_router`, `embedding_service`,
105
+ > `legacy_episodic_reader`, `failure_pattern_service`). Remaining: Stage C
106
+ > (separate repo + dist packaging, ≥85% coverage, `mypy --strict`, CI, PyPI).
107
+
108
+ ## The boundary rule
109
+
110
+ The package **never imports the host** (`src.ai.*`). CORTEX needs four things
111
+ from its host that are not memory concerns; it takes them via the Protocols in
112
+ `cortex_memory.providers`, which the host implements in a thin adapter
113
+ (`cortex_bridge`, which stays in `src/ai/memory/`):
114
+
115
+ | Protocol | Host adapter wraps | Seam |
116
+ |----------|--------------------|------|
117
+ | `LLMProvider` | `LLMRouter` | S1 |
118
+ | `EmbeddingProvider` | `EmbeddingService` + `resolve_embedding_model` | S4 |
119
+ | `UsageReporter` | `UsageService` / `CostAttribution` | S3 |
120
+ | `RunRegistry` | `ExecutionRun` lookups | S6 |
121
+
122
+ `cortex_memory.providers_reference` ships deterministic, dependency-free
123
+ implementations so the package runs in tests with zero host/DB/LLM.
124
+
125
+ ## Locked decisions (plan `04` §4)
126
+
127
+ | # | Decision |
128
+ |---|----------|
129
+ | K1 | Import `cortex_memory`; distribution `cortex-memory`. |
130
+ | K2 | Apache-2.0. |
131
+ | K3 | Separate public repo; host pins the version (submodule/local path during Stage B). |
132
+ | K4 | Package owns its `Base`; host shares metadata during cutover. |
133
+ | K5 | Opaque nullable UUID FKs in the package; host enforces referential integrity. |
134
+ | K6 | `task_classifier` stays host-side (depends on host task families/bandit). |
135
+ | K7 | One controlled cutover at the end of Stage B, after `01`'s memory deletions (C2, done). |
136
+
137
+ ## Done so far
138
+
139
+ - [x] **Data layer** — own `Base` (`db.py`), ORM (`models.py`, opaque FK-free
140
+ external refs), enums (`enums.py`), DTOs (`dtos.py`), standalone schema
141
+ bootstrap (`schema.py`). Host DB schema migrated (external cortex FK
142
+ constraints dropped). Host shims keep all imports working.
143
+ - [x] **Provider boundary** — Protocols (`providers.py`) + reference impls
144
+ (`providers_reference.py`) + the host adapters
145
+ (`src/ai/memory/cortex_providers.py`: `HostLLMProvider` /
146
+ `HostEmbeddingProvider` / `HostUsageReporter` / `HostRunRegistry` +
147
+ `build_cortex_providers`).
148
+ - [x] **Tree primitives** — `scope_policy.py`, `domains.py` (`DomainTreeBase` +
149
+ retrieval weights).
150
+
151
+ - [x] **All service bodies** — `service` / `graph` / `ingestion` / the four
152
+ domain trees / `dreaming` / `assembly`, each converted from host imports
153
+ (`LLMRouter` / `EmbeddingService` / `ExecutionRun` / usage) to **injected
154
+ providers** (LLM via `LLMProvider`; embeddings via `EmbeddingProvider` +
155
+ the node-aware `cortex_memory.embedding` helpers; RECURSE child runs via an
156
+ injected `child_run_factory`). Host shims auto-inject the adapters so
157
+ existing call sites are unchanged.
158
+
159
+ ## Remaining (Stage C — separate repo + release)
160
+
161
+ 1. Extract this directory to its own public repo with a `pyproject.toml`
162
+ (name `cortex-memory`, Apache-2.0, deps: SQLAlchemy + pgvector + pydantic).
163
+ 2. ≥85% coverage, `mypy --strict`, CI, examples, docs.
164
+ 3. Publish v0.1.0 to PyPI; the host pins the version and drops the in-repo copy.
165
+
166
+ `cortex_bridge.py`, `cortex_router.py` (HTTP), `embedding_service.py`,
167
+ `legacy_episodic_reader.py`, `failure_pattern_service.py` stay host-side as the
168
+ genuine adapters / host-specific code (plan §3).
@@ -0,0 +1,136 @@
1
+ # cortex-memory
2
+
3
+ A navigable, writable **hierarchical-memory engine for LLM agents** — the agent
4
+ never holds "context", it holds a *viewport* onto a persistent cognitive tree
5
+ (PostgreSQL + pgvector). Extracted as a host-independent package (Phase 12 track
6
+ `04`). **Import:** `cortex_memory`. **Dist:** `cortex-memory`. **License:** Apache-2.0.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install cortex-memory # needs a Postgres with the `vector` extension
12
+ ```
13
+
14
+ ## Quickstart
15
+
16
+ ```python
17
+ import asyncio
18
+ from uuid import uuid4
19
+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
20
+ from cortex_memory import CortexService
21
+ from cortex_memory.providers_reference import EchoLLMProvider # swap for your own adapter
22
+ from cortex_memory.schema import create_all_schema_async
23
+
24
+ async def main():
25
+ engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
26
+ await create_all_schema_async(engine) # idempotent
27
+ async with async_sessionmaker(engine, expire_on_commit=False)() as db:
28
+ cortex = CortexService(db, uuid4(), llm=EchoLLMProvider())
29
+ tree = await cortex.create_tree(entity_id=uuid4(), user_id=None,
30
+ task_description="Summarise the deck")
31
+ await db.commit()
32
+ working = await cortex.get_working_root(tree.id)
33
+ await cortex.write(parent_id=working.id, node_type="finding",
34
+ title="Key point", content="…", summary="…")
35
+ await db.commit()
36
+ print((await cortex.navigate(working.id)).to_prompt_text())
37
+
38
+ asyncio.run(main())
39
+ ```
40
+
41
+ A runnable version: `python -m cortex_memory.examples.quickstart`. The host
42
+ injects real LLM/embedding adapters via the Protocols (see **The boundary rule**);
43
+ the reference providers above let it run with no external services.
44
+
45
+ ## Develop
46
+
47
+ ```bash
48
+ pip install -e ".[dev]"
49
+ mypy --strict cortex_memory # strict-clean
50
+ CORTEX_TEST_DATABASE_URL=postgresql+asyncpg://… coverage run --source=cortex_memory -m pytest
51
+ coverage report # ≥85%
52
+ python -m build # sdist + wheel
53
+ ```
54
+
55
+ Pure-logic tests need nothing; the integration tests are skipped unless
56
+ `CORTEX_TEST_DATABASE_URL` (or `DATABASE_URL`) points at a Postgres+pgvector. CI:
57
+ `.github/workflows/cortex-memory.yml`.
58
+
59
+ ---
60
+
61
+ > Status: **Stages B + C COMPLETE** (in-repo). The package is self-contained,
62
+ > `mypy --strict`-clean, 85%-covered, and builds a wheel; only the move to a
63
+ > public repo + PyPI upload remains. Every CORTEX module now lives here,
64
+ > with **zero host imports** (a package self-test enforces it): the data layer
65
+ > (`db`/`models`/`enums`/`dtos`/`schema`), the provider boundary
66
+ > (`providers`/`providers_reference`), and all services — `service` (the 7 tree
67
+ > ops), `graph`, `ingestion`, the four domain trees (`knowledge_tree`/
68
+ > `episodic_tree`/`experience_tree`/`intelligence_tree`), `dreaming`, and
69
+ > `assembly` (the v2 assembler) — plus `scope_policy`, `domains`, `prompts`, and
70
+ > the embedding/text helpers. The host's `src/ai/memory/` keeps only thin
71
+ > re-export/auto-injection **shims** + the genuine host **adapters**
72
+ > (`cortex_providers`, `cortex_bridge`, `cortex_router`, `embedding_service`,
73
+ > `legacy_episodic_reader`, `failure_pattern_service`). Remaining: Stage C
74
+ > (separate repo + dist packaging, ≥85% coverage, `mypy --strict`, CI, PyPI).
75
+
76
+ ## The boundary rule
77
+
78
+ The package **never imports the host** (`src.ai.*`). CORTEX needs four things
79
+ from its host that are not memory concerns; it takes them via the Protocols in
80
+ `cortex_memory.providers`, which the host implements in a thin adapter
81
+ (`cortex_bridge`, which stays in `src/ai/memory/`):
82
+
83
+ | Protocol | Host adapter wraps | Seam |
84
+ |----------|--------------------|------|
85
+ | `LLMProvider` | `LLMRouter` | S1 |
86
+ | `EmbeddingProvider` | `EmbeddingService` + `resolve_embedding_model` | S4 |
87
+ | `UsageReporter` | `UsageService` / `CostAttribution` | S3 |
88
+ | `RunRegistry` | `ExecutionRun` lookups | S6 |
89
+
90
+ `cortex_memory.providers_reference` ships deterministic, dependency-free
91
+ implementations so the package runs in tests with zero host/DB/LLM.
92
+
93
+ ## Locked decisions (plan `04` §4)
94
+
95
+ | # | Decision |
96
+ |---|----------|
97
+ | K1 | Import `cortex_memory`; distribution `cortex-memory`. |
98
+ | K2 | Apache-2.0. |
99
+ | K3 | Separate public repo; host pins the version (submodule/local path during Stage B). |
100
+ | K4 | Package owns its `Base`; host shares metadata during cutover. |
101
+ | K5 | Opaque nullable UUID FKs in the package; host enforces referential integrity. |
102
+ | K6 | `task_classifier` stays host-side (depends on host task families/bandit). |
103
+ | K7 | One controlled cutover at the end of Stage B, after `01`'s memory deletions (C2, done). |
104
+
105
+ ## Done so far
106
+
107
+ - [x] **Data layer** — own `Base` (`db.py`), ORM (`models.py`, opaque FK-free
108
+ external refs), enums (`enums.py`), DTOs (`dtos.py`), standalone schema
109
+ bootstrap (`schema.py`). Host DB schema migrated (external cortex FK
110
+ constraints dropped). Host shims keep all imports working.
111
+ - [x] **Provider boundary** — Protocols (`providers.py`) + reference impls
112
+ (`providers_reference.py`) + the host adapters
113
+ (`src/ai/memory/cortex_providers.py`: `HostLLMProvider` /
114
+ `HostEmbeddingProvider` / `HostUsageReporter` / `HostRunRegistry` +
115
+ `build_cortex_providers`).
116
+ - [x] **Tree primitives** — `scope_policy.py`, `domains.py` (`DomainTreeBase` +
117
+ retrieval weights).
118
+
119
+ - [x] **All service bodies** — `service` / `graph` / `ingestion` / the four
120
+ domain trees / `dreaming` / `assembly`, each converted from host imports
121
+ (`LLMRouter` / `EmbeddingService` / `ExecutionRun` / usage) to **injected
122
+ providers** (LLM via `LLMProvider`; embeddings via `EmbeddingProvider` +
123
+ the node-aware `cortex_memory.embedding` helpers; RECURSE child runs via an
124
+ injected `child_run_factory`). Host shims auto-inject the adapters so
125
+ existing call sites are unchanged.
126
+
127
+ ## Remaining (Stage C — separate repo + release)
128
+
129
+ 1. Extract this directory to its own public repo with a `pyproject.toml`
130
+ (name `cortex-memory`, Apache-2.0, deps: SQLAlchemy + pgvector + pydantic).
131
+ 2. ≥85% coverage, `mypy --strict`, CI, examples, docs.
132
+ 3. Publish v0.1.0 to PyPI; the host pins the version and drops the in-repo copy.
133
+
134
+ `cortex_bridge.py`, `cortex_router.py` (HTTP), `embedding_service.py`,
135
+ `legacy_episodic_reader.py`, `failure_pattern_service.py` stay host-side as the
136
+ genuine adapters / host-specific code (plan §3).
@@ -0,0 +1,126 @@
1
+ """
2
+ cortex_memory — the CORTEX hierarchical-memory engine, extracted as a
3
+ host-independent package (Phase 12 track `04`).
4
+
5
+ Boundary rule (the whole point of the extraction): **this package never
6
+ imports the host** (`src.ai.*`). The host depends on the package and injects
7
+ its concerns — LLM calls, embeddings, usage metering, run lookups — through the
8
+ Protocols in :mod:`cortex_memory.providers`. A host adapter (the thin
9
+ ``cortex_bridge`` that stays in ``src/ai/memory``) implements those Protocols.
10
+
11
+ Stage-B status: the data layer (own ``Base`` + ORM models + enums + DTOs) and
12
+ the provider boundary live here. The CORTEX services move in next; see
13
+ ``README.md``.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from cortex_memory.db import Base, metadata
18
+ from cortex_memory.dtos import (
19
+ DEFAULT_TRUST_BY_SOURCE,
20
+ CortexCheckpointCreate,
21
+ CortexNodeContentResponse,
22
+ CortexNodeCreate,
23
+ CortexNodeDetailResponse,
24
+ CortexNodeSummary,
25
+ CortexRecurseRequest,
26
+ CortexTreeCreate,
27
+ CortexTreeListResponse,
28
+ CortexTreeResponse,
29
+ CortexViewportResponse,
30
+ GoalNode,
31
+ Provenance,
32
+ SourceType,
33
+ )
34
+ from cortex_memory.enums import (
35
+ CortexNodeStatus,
36
+ CortexNodeType,
37
+ CortexTreeStatus,
38
+ MemoryDomain,
39
+ ScopeLevel,
40
+ )
41
+ from cortex_memory.assembly import MemoryAssemblyResult, MemoryAssemblyService
42
+ from cortex_memory.dreaming import DreamingEngine
43
+ from cortex_memory.episodic_tree import EpisodicTreeService
44
+ from cortex_memory.experience_tree import ExperienceTreeService
45
+ from cortex_memory.graph import SemanticGraphService
46
+ from cortex_memory.intelligence_tree import IntelligenceTreeService
47
+ from cortex_memory.knowledge_tree import KnowledgeTreeService
48
+ from cortex_memory.models import CortexEdge, CortexNode, CortexTree
49
+ from cortex_memory.prompts import CORTEX_OPS_HELP
50
+ from cortex_memory.service import (
51
+ CheckpointData,
52
+ CortexService,
53
+ NodeContent,
54
+ NodeSummaryDTO,
55
+ Viewport,
56
+ )
57
+ from cortex_memory.providers import (
58
+ EmbeddingProvider,
59
+ EmbeddingResult,
60
+ LLMProvider,
61
+ LLMResult,
62
+ RunfRef,
63
+ RunRef,
64
+ RunRegistry,
65
+ UsageReporter,
66
+ )
67
+ from cortex_memory.scope_policy import ScopePolicy, ScopeViolation
68
+
69
+ __version__ = "0.1.0"
70
+
71
+ __all__ = [
72
+ # data layer
73
+ "Base",
74
+ "metadata",
75
+ "CortexTree",
76
+ "CortexNode",
77
+ "CortexEdge",
78
+ "CortexTreeStatus",
79
+ "CortexNodeType",
80
+ "CortexNodeStatus",
81
+ "MemoryDomain",
82
+ "ScopeLevel",
83
+ # DTOs
84
+ "Provenance",
85
+ "SourceType",
86
+ "DEFAULT_TRUST_BY_SOURCE",
87
+ "GoalNode",
88
+ "CortexTreeCreate",
89
+ "CortexTreeResponse",
90
+ "CortexTreeListResponse",
91
+ "CortexNodeSummary",
92
+ "CortexViewportResponse",
93
+ "CortexNodeContentResponse",
94
+ "CortexNodeCreate",
95
+ "CortexCheckpointCreate",
96
+ "CortexRecurseRequest",
97
+ "CortexNodeDetailResponse",
98
+ # providers
99
+ "LLMProvider",
100
+ "LLMResult",
101
+ "EmbeddingProvider",
102
+ "EmbeddingResult",
103
+ "UsageReporter",
104
+ "RunRegistry",
105
+ "RunRef",
106
+ "RunfRef",
107
+ # service
108
+ "CortexService",
109
+ "SemanticGraphService",
110
+ "KnowledgeTreeService",
111
+ "EpisodicTreeService",
112
+ "ExperienceTreeService",
113
+ "IntelligenceTreeService",
114
+ "DreamingEngine",
115
+ "MemoryAssemblyService",
116
+ "MemoryAssemblyResult",
117
+ "Viewport",
118
+ "NodeSummaryDTO",
119
+ "NodeContent",
120
+ "CheckpointData",
121
+ "CORTEX_OPS_HELP",
122
+ # tree primitives
123
+ "ScopePolicy",
124
+ "ScopeViolation",
125
+ "__version__",
126
+ ]