Metadata-Version: 2.5
Name: memgarden
Version: 0.22.0
Summary: 可插拔的 AI 记忆编辑内核：落卡、召回、整理与可替换存储编排。
Project-URL: Homepage, https://github.com/teleport-computer/memgarden
Project-URL: Source, https://github.com/teleport-computer/memgarden
Project-URL: Issues, https://github.com/teleport-computer/memgarden/issues
License: 
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: agent,llm,long-term-memory,memory
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: jsonschema>=4.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: tomli>=2.0; (python_version < '3.11') and extra == 'dev'
Provides-Extra: sqlite
Description-Content-Type: text/markdown

# Memory Garden

**让 Agent 不只记住说过的话，还能持续整理、更新，并在需要时想起来。**

[English](README.en.md) · [开始接入](docs/GETTING-STARTED.md) · [召回与混合检索](docs/RETRIEVAL.md) · [DeepSeek Harness](adapters/dsh-memgarden/README.md)

Memory Garden（Python 包名 `memgarden`）是可嵌入 Agent Runtime 的记忆编辑引擎。它把对话中的经历、偏好、关系和决定整理成可读的记忆卡，按本轮话题召回，并随着新信息合并、补充或取代旧记忆。

你提供模型、可信用户身份和存储；Garden 提供 Capture、召回、Dream 整理及持久化编排。可以从一个 SQLite 文件开始，也可以实现自己的 StoragePort。它不要求使用某一种 Agent 框架、模型服务或向量数据库。

Python ≥ 3.10 · 运行包零第三方依赖 · Apache-2.0 · 支持 Python SDK / JSON Lines / DeepSeek Harness Adapter

## 为什么是 Garden

对话日志记录“说过什么”；Garden 维护“以后值得记住什么”。

例如，一次对话里提到“我不吃辣，因为吃辣会胃疼”，以后又补充“微辣现在可以接受”：系统需要保留原因，辨别补充与矛盾，并在聊晚饭时带回相关记忆，而不是每轮追加一份摘要。Garden 为这条工作流提供以下能力，模型判断的实际质量仍需用你的场景评测。

| 特点 | 对 Agent 的意义 |
|---|---|
| **可读的厚卡片** | 短摘要用于浏览，正文保留背景、原因和细节；不是只有关键词或 embedding |
| **三种写入意图** | 日常对话克制筛选；历史导入按更完整的尺度提取；用户明确保存不再被“值不值得记”拦下 |
| **自动记忆与主动工具分开** | Runtime 在轮末调用 Capture，不必等模型主动执行 `memory_write`；模型仍可主动搜索或写入 |
| **记忆会整理，不只会增加** | Maintenance / Dream 可以合并、补充、取代旧卡；旧卡关系可追溯，用户删除与整理归档分开 |
| **召回策略可换** | 可以组合现有策略、使用有相关性门槛的软配额，或由宿主提供向量做混合检索；不为凑名额强塞无关卡 |
| **写入有可靠性语义** | 两个内置 Store 支持 owner 隔离、幂等、并发版本检查；整理结果和账本原子提交，失败不会冒充“已经记住” |

Garden 保留自己的记忆判断能力。它不是把其他记忆产品统一成 CRUD 的通用门面，也不是向量数据库、完整 Agent Runtime 或聊天记录备份系统。

## 一轮对话如何接起来

```text
用户输入 → Garden 召回 → Runtime 把记忆作为上下文交给 Agent → Agent 回复
                                                                  │
                                   本轮对话 → Capture 判断 → 写入记忆卡
                                                                  │
                                   Runtime 选择时机 → Dream 整理 → 更新卡与账本
```

Garden 返回上下文块、来源 ID、改动和回执；Runtime 控制模型调用、上下文注入、调度和对外响应。记忆是用户数据，不是系统指令，不能据此绕过工具权限。

## 五分钟跑通

```bash
python -m pip install memgarden
memgarden manifest
```

下面的示例可独立运行，使用固定回复验证接线，**不调用真实模型**。它会在当前目录创建明文 `garden.db`；不要提交这个文件。换成自己的模型调用见[接入指南](docs/GETTING-STARTED.md)。

```python
import json
from memgarden import CaptureRequest, MountedGarden, Scope, SqliteStore
from memgarden.selection import Chain, RelevanceStage

class DemoModel:
    def complete(self, prompt: str, *, purpose: str = "") -> str:
        # Plumbing demo only. Replace this with your runtime's model call.
        return json.dumps({"cards": [{
            "action": "add", "summary": "Avoids spicy food",
            "content": "Spicy food causes stomach pain; choose mild dishes.",
            "bucket": "Food", "threads": ["diet"],
        }]})

garden = MountedGarden(
    model=DemoModel(),
    store=SqliteStore("garden.db"),
    selection_policy=Chain(stages=(RelevanceStage(limit=4),)),
)
# Build this from authenticated runtime state, never from model arguments.
scope = Scope(tenant_id="demo", memory_owner_id="user-42")
receipt = garden.capture_and_store(scope, CaptureRequest(
    window="User: Spicy food gives me stomach pain.",
    locale="en", idempotency_key="conversation-1:turn-1",
))
assert receipt.error is None, receipt.error
assert receipt.written

context = garden.context_for_turn(scope, "Can I eat spicy food?")
assert context.record_ids
for block in context.blocks:
    print(block["text"])
# Pass these blocks to your Agent as memory context before its next reply.
```

你应该看到 `Avoids spicy food` 这条记忆摘要。默认上下文块是摘要，不是整张厚卡；正文仍保存在 Store，需要更多细节时由宿主按返回的 ID 在授权范围内读取。重新打开同一个 SQLite 文件仍可读到卡片；相同业务请求重放不重复写入。`created_at` 和 `updated_at` 由 Store 自动维护，`occurred_at` 单独表示素材中的事情发生时间。

从源码运行完整的落卡→召回→工具→整理→重开数据库演示：

```bash
git clone https://github.com/teleport-computer/memgarden.git
cd memgarden
uv run python examples/mount_in_ten_minutes.py
```

## 选择你的接入方式

| 你的 Runtime | 从哪里开始 | 你需要接什么 |
|---|---|---|
| Python Agent | [Python SDK 指南](docs/GETTING-STARTED.md#python-runtime) | `ModelPort.complete`、可信 `Scope`、Store、轮前召回和轮后 Capture |
| 已有模型循环 / 非 Python Agent | [JSON Lines 与宿主驱动](docs/GETTING-STARTED.md#json-lines) | 管理服务子进程；按 begin/feed 往返调用自己的模型；检查业务回执 |
| DeepSeek Harness | [Adapter 安装指南](adapters/dsh-memgarden/README.md) | 兼容的 DSH、provider、稳定 owner、数据库和持久 stateDir；轮次 hooks 由 Adapter 接好 |
| 自己的数据库 | [StoragePort 与数据结构](docs/INTEGRATION-AND-DATA.md) | 实现接口及原子性、幂等、owner 隔离等行为；不仅是字段映射 |
| 自己的检索 / embedding | [召回接入指南](docs/RETRIEVAL.md) | 授权候选、搜索文本和角色投影；可选的向量、模型标识及校准阈值 |

日常接入推荐 `MountedGarden`：它把读库、权限范围检查、判断、CAS 和写回接在一起。`GardenComponent` 是只返回建议、不写库的低层入口。JSON 是调用协议，不是放入一个 JSON 配置文件就会自动工作的插件。

## 能力与边界

| 能力 | 当前提供什么 |
|---|---|
| Capture | 对话筛选、新增或取代；格式修正和有限重试；生成可选检索提示词 |
| 召回 | 上下文块与来源 ID；可插拔 SelectionPolicy；自动想起与主动搜索共用一个 BM25 排序器（分词器可注入）；可选 hybrid |
| Maintenance / Dream | 是否需要整理的确定性检查；模型提出合并等建议；原子更新卡与账本 |
| 明确保存与搜索 | `write_one`、`search` / `records.search`（只返回真实命中，无命中为空）、模型工具 `memory_write` / `memory_search` |
| 关联读取 | 取回卡时给出一跳邻居（显式链接、同线索）：`related` / `records.related` |
| History Import | 分批、游标续传、素材与语义指纹、失败可恢复；一次性导入需要服务侧模型，宿主驱动导入（`import_session` / `history.import_*`）由宿主调模型 |
| 浏览、导出、删除 | 分页读取；导出含归档和取代历史；指定卡真删，不用归档冒充删除 |
| Promote / Migrate | 经宿主授权移动可见范围；升级旧卡字段 |

SDK、JSON Lines 与 DSH Adapter 接通的能力**并不相同**（例如 DSH Adapter 没接关联读取和导入）。逐项对照见[数据参考](docs/INTEGRATION-AND-DATA.md#各接入面接通了什么)，代码里用 `memgarden.surfaces.surface_capabilities()` 查询。

**你的 Runtime 仍负责**身份认证、模型凭据与超时/取消/用量、调度、embedding、备份和全域数据删除。模型和 Store 都可替换，不表示这些宿主工作会消失。

请留意：

- 全链路明文，不包含加解密或密钥管理。数据库、待办和部分检索 trace 都可能含私密内容。
- `InMemoryStore` 用于测试；`SqliteStore` 是可直接使用的参考存储，但当前会读取 owner 的卡片集合。响应分页不等于数据库分页或快照导出。
- 新 relevant / hybrid 策略是主动选择的功能，不会自动替换既有策略。Hybrid 不生成或存储向量。
- 默认 DSH 服务使用宿主模型，只接通 Capture / Maintenance 的 begin/feed；没有 History Import / Migrate 的管理入口。安装后需检查运行时 `manifest.get`，不能只看静态 CLI 声明。
- 指定卡删除不自动删除宿主原始材料、备份、向量缓存和其他派生卡。DSH outbox 不应被多进程共用。
- 真实模型和 DSH 结果绑定具体 commit、模型和宿主版本；“单元测试通过”不代表“所有模型效果已验证”。见[验收状态](docs/STATUS.md)。

## 文档、开发与反馈

| 目的 | 文档 |
|---|---|
| 从安装到接入自己的 Agent | [Getting started](docs/GETTING-STARTED.md) |
| 选择和调试召回策略 | [Retrieval](docs/RETRIEVAL.md) |
| 字段、六张 SQLite 表、生命周期和恢复 | [接入与数据参考](docs/INTEGRATION-AND-DATA.md) |
| DSH 安装与 pinned 验收 | [DSH Adapter](adapters/dsh-memgarden/README.md) |
| 当前验证证据、已知限制 | [Status](docs/STATUS.md) |
| 开发、测试、提交 PR | [Contributing](CONTRIBUTING.md) |
| 判断质量与发版 | [Evals](evals/README.md) · [Releasing](docs/RELEASING.md) |
| 敏感信息与漏洞报告 | [Security](SECURITY.md) |

```bash
uv run --extra dev pytest -q
uv run python evals/run.py --baseline evals/baseline.json
uv build
```

运行包不依赖模型 SDK；开发测试使用额外依赖，DSH Adapter 离线测试需要 Node.js（CI 使用 Node 20）。源码文档可能包含尚未发布的修复，部署应固定已审核的 tag / wheel；不要覆盖已发布版本。

欢迎用[合成数据的最小复现提交 Issue](https://github.com/teleport-computer/memgarden/issues)。不要附上真实用户记忆或凭据。许可证：[Apache-2.0](LICENSE)。
