Compare commits
61
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a60b2d366c | ||
|
|
0244ebe38c | ||
|
|
e3b5a1bc9c | ||
|
|
8aeb042bb7 | ||
|
|
635d2572c9 | ||
|
|
6113e2351e | ||
|
|
b5a8a78c69 | ||
|
|
fd12c8f1c0 | ||
|
|
e089d4b800 | ||
|
|
b370663870 | ||
|
|
8ea6996859 | ||
|
|
dc740604d2 | ||
|
|
55bf946bcc | ||
|
|
14fcc6fe38 | ||
|
|
1ef0766891 | ||
|
|
3370a715dd | ||
|
|
638d1b7bde | ||
|
|
d6890793ec | ||
|
|
32bf05f821 | ||
|
|
b6e6a3fb43 | ||
|
|
4e44f59026 | ||
|
|
35bd56ddd0 | ||
|
|
2cea39da4f | ||
|
|
059e3a4903 | ||
|
|
0a9b10dbfc | ||
|
|
3a74a33456 | ||
|
|
514bf5c47b | ||
|
|
4bc918af7a | ||
|
|
75163a0d1e | ||
|
|
09e4bc8a30 | ||
|
|
4dbf7b6ed2 | ||
|
|
8f1c4045e9 | ||
|
|
8918098fa8 | ||
|
|
0afe787c95 | ||
|
|
67ae43f920 | ||
|
|
3ce89ea560 | ||
|
|
7b7fd217a8 | ||
|
|
7efe054e83 | ||
|
|
fdbcd9934d | ||
|
|
3171007b3c | ||
|
|
a04fcb50d5 | ||
|
|
a28ade2faf | ||
|
|
1c424928a2 | ||
|
|
688878171e | ||
|
|
a3f09f4cac | ||
|
|
0c59413ad8 | ||
|
|
625f877b43 | ||
|
|
1608a4cfc2 | ||
|
|
20b92d8a89 | ||
|
|
2a4c5e38e7 | ||
|
|
c891a1fd1d | ||
|
|
7741e17f09 | ||
|
|
2a4dc2ffa2 | ||
|
|
61b5ef30a9 | ||
|
|
f79770cdb0 | ||
|
|
9ba602ffd2 | ||
|
|
842fbe6044 | ||
|
|
268ad16d26 | ||
|
|
8903872b47 | ||
|
|
1aed8d7507 | ||
|
|
1c31295e13 |
No files matched your search
@@ -86,6 +86,7 @@ MEMORY_VECTOR_STORE=chroma
|
||||
# MEMORY_CODING_DB_PATH= # coding_memory.db 路径(默认 {DATA_DIR}/data/coding_memory.db)
|
||||
# MEMORY_CODING_TOOL_RESULT_MAX_BYTES=2048 # 单条 tool_result 截断字节上限
|
||||
# MEMORY_CODING_VERBATIM_FALLBACK_ENABLED=false # 模型无结果时是否保存原文 fact;默认关,避免 tool trace 外泄
|
||||
# MEMORY_CODING_CHAIN_BLOCK_ENABLED=false # search 是否注入版本演进链块(diff);默认关,省 token
|
||||
# MEMORY_EXTRACT_HISTORY_TURNS=5 # 除本次 write 外,额外注入 extractor 的历史 user-turn 数
|
||||
|
||||
# ── 写入流程开关 ──
|
||||
|
||||
@@ -59,4 +59,30 @@ jobs:
|
||||
- run: corepack enable
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: uv sync --directory apps/core --all-groups --locked
|
||||
- run: pnpm check
|
||||
- name: Verify public source structure and privacy boundaries
|
||||
run: |
|
||||
python3 scripts/verify_structure.py
|
||||
python3 scripts/generate_core_test_index.py --check
|
||||
python3 scripts/verify_zero_collection.py
|
||||
python3 scripts/verify_zero_collection.py --self-test
|
||||
- name: Lint Node workspaces
|
||||
run: pnpm lint
|
||||
- name: Typecheck Node workspaces
|
||||
run: pnpm typecheck
|
||||
- name: Test Node workspaces
|
||||
run: pnpm test
|
||||
- name: Test release tooling
|
||||
run: pnpm test:release-scripts
|
||||
- name: Fetch and verify the pinned embedding model
|
||||
run: |
|
||||
pnpm fetch:embedding-model
|
||||
uv run --directory apps/core python -c \
|
||||
"from one_memory.embedding_assets import assets_present, verify_assets; assert assets_present(); verify_assets()"
|
||||
- name: Test public Core smoke suite
|
||||
run: >-
|
||||
bash scripts/run-tests-isolated.sh core-pr
|
||||
tests/test_core_test_reporting.py
|
||||
tests/test_import_api.py
|
||||
tests/test_recent_first_import.py
|
||||
tests/test_source_session_count_api.py
|
||||
tests/test_schema_migrations.py
|
||||
@@ -102,3 +102,71 @@ jobs:
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
retention-days: 14
|
||||
|
||||
publish-draft-release:
|
||||
if: ${{ inputs.run_lifecycle && startsWith(github.ref, 'refs/tags/v') }}
|
||||
needs: matrix
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
|
||||
with:
|
||||
pattern: memhub-runtime-linux-*
|
||||
path: memhub/release-assets
|
||||
merge-multiple: true
|
||||
- name: Verify tag and Linux release assets
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
shopt -s globstar nullglob
|
||||
version=$(node -p 'require("./package.json").version')
|
||||
node scripts/verify-release-version.mjs \
|
||||
--channel stable \
|
||||
--version "$version" \
|
||||
--build-number "$(node -p 'require("./package.json").release.build_number')" \
|
||||
--tag "$GITHUB_REF_NAME"
|
||||
mkdir -p publish-assets
|
||||
for arch in x64 arm64; do
|
||||
name="memhub-runtime-v${version}-linux-${arch}.tar.gz"
|
||||
archives=(release-assets/**/"$name")
|
||||
checksums=(release-assets/**/"$name.sha256")
|
||||
test "${#archives[@]}" -eq 1
|
||||
test "${#checksums[@]}" -eq 1
|
||||
cp -- "${archives[0]}" "publish-assets/$name"
|
||||
cp -- "${checksums[0]}" "publish-assets/$name.sha256"
|
||||
(
|
||||
cd publish-assets
|
||||
sha256sum -c "$name.sha256"
|
||||
)
|
||||
done
|
||||
- name: Upload Linux assets to a draft GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if gh release view "$GITHUB_REF_NAME" \
|
||||
--repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
|
||||
test "$(
|
||||
gh release view "$GITHUB_REF_NAME" \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--json isDraft \
|
||||
--jq .isDraft
|
||||
)" = "true"
|
||||
else
|
||||
gh release create "$GITHUB_REF_NAME" \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--verify-tag \
|
||||
--draft \
|
||||
--generate-notes \
|
||||
--title "$GITHUB_REF_NAME"
|
||||
fi
|
||||
gh release upload "$GITHUB_REF_NAME" \
|
||||
publish-assets/memhub-runtime-v*-linux-*.tar.gz \
|
||||
publish-assets/memhub-runtime-v*-linux-*.tar.gz.sha256 \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--clobber
|
||||
+126
-8
@@ -2,6 +2,101 @@
|
||||
|
||||
Hy Memory and MemHub are versioned and released independently.
|
||||
|
||||
## Hy Memory 2.0.5.dev4 — 2026-10-21
|
||||
|
||||
- Development preview; not the final `2.0.5` release.
|
||||
- Adds idempotent `process_raw` / `async_process_raw` APIs that extract and
|
||||
reconcile ordered existing L1 raw IDs without embedding or inserting raw
|
||||
again.
|
||||
- Returns durable raw/memory ID receipts for MemHub queue recovery.
|
||||
|
||||
## Hy Memory 2.0.5.dev3 — 2026-10-21
|
||||
|
||||
- Development preview; not the final `2.0.5` release.
|
||||
- Published as
|
||||
[`hy-memory==2.0.5.dev3`](https://pypi.org/project/hy-memory/2.0.5.dev3/).
|
||||
- Lets the existing `search` API explicitly query SDK raw with
|
||||
`layers=["l1_raw"]`, including existing source filters.
|
||||
|
||||
## Hy Memory 2.0.5.dev2 — 2026-10-21
|
||||
|
||||
- Development preview; not the final `2.0.5` release.
|
||||
- Published as
|
||||
[`hy-memory==2.0.5.dev2`](https://pypi.org/project/hy-memory/2.0.5.dev2/).
|
||||
- Adds exact, idempotent semantic-memory import for legacy MemHub cutover
|
||||
without extraction, reconciliation or identity changes.
|
||||
|
||||
## Hy Memory 2.0.5.dev1 — 2026-10-21
|
||||
|
||||
- Development preview for the MemHub SDK-authority migration; this is not the
|
||||
final `2.0.5` release.
|
||||
- Published as
|
||||
[`hy-memory==2.0.5.dev1`](https://pypi.org/project/hy-memory/2.0.5.dev1/).
|
||||
- Adds lifecycle status filtering, durable idempotent write outcomes, exact raw
|
||||
APIs, offline local data-plane snapshot/restore, and fail-closed physical
|
||||
delete receipts.
|
||||
|
||||
## Hy Memory 2.0.3 — 2026-10-17
|
||||
|
||||
- Added an optional runtime HTTP transport factory so embedded products can
|
||||
enforce request budgets without wrapping or restricting SDK local-store
|
||||
access.
|
||||
- Published
|
||||
[`hy-memory==2.0.3`](https://pypi.org/project/hy-memory/2.0.3/) with
|
||||
unchanged memory extraction, reconciliation, storage, and Coding/Working
|
||||
behavior.
|
||||
|
||||
## Unreleased
|
||||
|
||||
- `search(..., layers=["l1_raw"])` now explicitly searches SDK raw records in
|
||||
pro/ultra mode and keeps existing user/agent/session/source filters; default
|
||||
search continues to hide raw.
|
||||
- Added `import_memory_exact` for idempotent migration of an existing semantic
|
||||
memory with its canonical ID, lifecycle and supersession links, without
|
||||
extraction or reconciliation.
|
||||
- Added SDK-authoritative lifecycle listing with explicit status filters,
|
||||
idempotent durable write outcomes, exact raw import/get/list APIs, and
|
||||
quiesced local data-plane snapshot/restore contracts for the MemHub
|
||||
authority migration.
|
||||
- Physical delete now reports incomplete VDB/Graph cleanup as a partial failure
|
||||
instead of claiming success after only one store was changed.
|
||||
- Coding search no longer injects the version-evolution diff block
|
||||
(`chain_block`) by default. Enable with
|
||||
`MEMORY_CODING_CHAIN_BLOCK_ENABLED=true` or
|
||||
`CodingConfig.chain_block_enabled=True` (write-side observe unchanged).
|
||||
- Fixed governed-memory revisions and repeated evidence links failing when the
|
||||
visibility dirty-marker trigger encounters the same memory twice. Startup
|
||||
now replaces the affected legacy trigger without changing schema versions
|
||||
or governed and visibility data.
|
||||
- Serialized each SDK SQLite store's shared connection lifecycle so concurrent
|
||||
history/cache operations cannot race with `close()` and crash the process.
|
||||
- Scoped Coding reconciliation targets to the current HY authority,
|
||||
conversation, and workspace, preventing near-duplicate sessions from
|
||||
mutating an experience or working fact owned by another evidence context.
|
||||
- Kept post-write authority verification failures available for read-only
|
||||
reconciliation while preventing automatic or generic confirmed retries from
|
||||
invoking the model again. Automatic reconciliation skips those sticky rows
|
||||
before applying its batch limit, and linked durable jobs exclusively own
|
||||
retry scheduling for their memory tasks.
|
||||
- Clarified that `add(metadata=...)` carries legacy SDK processing options,
|
||||
while persistent caller business context belongs in `meta`.
|
||||
- Added an opt-in `get(..., include_raw=True)` path for reading `L1_RAW`
|
||||
memories, including memories written in lite mode. The default remains
|
||||
hidden for backward compatibility.
|
||||
- Removed MemHub's task-scoped HyPermission store wrappers and global
|
||||
model-content consent switch. The trusted embedded Hy Memory SDK now uses
|
||||
its native local stores directly.
|
||||
- Existing installations ignore the retired config flag, readmit previously
|
||||
parked pre-invocation work, and drop only the obsolete
|
||||
`hy_node_permissions` proof table. Evidence, governed memories, model
|
||||
profiles, SDK stores, and source/host grants are preserved.
|
||||
|
||||
## Hy Memory 2.0.2 — 2026-10-17
|
||||
|
||||
- Published
|
||||
[`hy-memory==2.0.2`](https://pypi.org/project/hy-memory/2.0.2/) with the
|
||||
current SDK fixes and Apache-2.0 package metadata.
|
||||
|
||||
## Hy Memory 2.0.1 — 2026-10-16
|
||||
|
||||
- Published the Python distribution as
|
||||
@@ -10,13 +105,36 @@ Hy Memory and MemHub are versioned and released independently.
|
||||
Because PyPI release metadata is immutable, the next SDK patch release must
|
||||
carry the updated license metadata; `2.0.1` retains its published metadata.
|
||||
|
||||
## MemHub
|
||||
## MemHub 1.0.3 — Unreleased
|
||||
|
||||
MemHub has no public release yet. The source version is `1.0.0` (build 4), the
|
||||
selected npm package is `memhub-cli`, and both npm publication and GitHub
|
||||
Release artifacts are still pending. Internal release-candidate builds are not
|
||||
public releases.
|
||||
- Updated the source version to `1.0.3` (build 7).
|
||||
- Pinned the public SDK to `hy-memory==2.0.3`.
|
||||
- Removed the HyPermission store wrappers and global model-content consent
|
||||
switch; the trusted embedded SDK now uses native local stores.
|
||||
- Prevented uncertain writes from blocking later source work and added one
|
||||
reconciled automatic retry after ten seconds.
|
||||
- Added product-facing memory pipeline counters and the log troubleshooting
|
||||
runbook.
|
||||
- Allowed a verified packaged Desktop Runtime from a different commit to take
|
||||
over an equal-build install atomically while preserving downgrade and
|
||||
tamper refusal.
|
||||
|
||||
No compatibility or deprecation policy has been adopted beyond the explicit
|
||||
CLI/Runtime protocol ranges stored in the release manifests. Future public
|
||||
releases must record user-visible changes and supported platforms here.
|
||||
## MemHub 1.0.2 — 2026-10-17
|
||||
|
||||
- Updated the source version to `1.0.2` (build 6).
|
||||
- Pinned the public SDK to `hy-memory==2.0.2`.
|
||||
- Pinned `onnxruntime==1.23.2` to retain macOS x64 packaging support.
|
||||
- Fixed relaunch and upgrade failures when a prior managed Runtime exists.
|
||||
- Embedded canonical build identity when an external packaging pipeline omits
|
||||
release environment fields.
|
||||
- Added automatic Linux Runtime upload to tagged Draft Releases.
|
||||
|
||||
## MemHub 1.0.1 — Superseded before release
|
||||
|
||||
- The candidate tag was not published as a GitHub Release; `1.0.2` replaces it
|
||||
after the managed-Runtime relaunch fix.
|
||||
|
||||
## MemHub 1.0.0
|
||||
|
||||
- Published the initial GitHub Release with macOS arm64 and Linux Runtime
|
||||
artifacts.
|
||||
@@ -32,7 +32,9 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Latest News
|
||||
|
||||
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **Released** **Hy Memory 2.0 (`hy-memory==2.0.1`)** on [PyPI](https://pypi.org/project/hy-memory/2.0.1/) and open-sourced the **Hy-Memory** monorepo together with **[MemHub](memhub/README.md)**!
|
||||
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **Open-sourced** quantized **FP8** (**[Hy-Memory-30B-A3B-FP8](https://huggingface.co/tencent/Hy-Memory-30B-A3B-FP8)**) and **GGUF** (**[Hy-Memory-30B-A3B-GGUF](https://huggingface.co/tencent/Hy-Memory-30B-A3B-GGUF)**) versions of **Hy-Memory-30B-A3B** on Hugging Face!
|
||||
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 📦 **Released [MemHub v1.0.4](https://github.com/Tencent-Hunyuan/Hy-Memory/releases/tag/v1.0.4)** and **[memhub-cli 1.0.5](https://www.npmjs.com/package/memhub-cli/v/1.0.5)**, with a signed macOS desktop app and verified macOS/Linux Runtimes!
|
||||
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **Released** **Hy Memory 2.0 (`hy-memory==2.0.4`)** on [PyPI](https://pypi.org/project/hy-memory/2.0.4/) and open-sourced the **Hy-Memory** monorepo together with **[MemHub](memhub/README.md)**!
|
||||
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **Open-sourced** **[Hy-Memory-30B-A3B](https://huggingface.co/tencent/Hy-Memory-30B-A3B)** on Hugging Face along with its [technical report](https://arxiv.org/abs/2610.22196) on attributed reinforcement learning for long-term memory writing!
|
||||
* *<mark>[new]</mark>* 🔥🔥 **[2026-09]**: 📊 **Released** **[CMB: A Coding Memory Benchmark for Long-Horizon and Interleaved Coding Agents](docs/papers/CMB_A_Coding_Memory_Benchmark_for_Long_Horizon_and_Interleaved_Coding_Agents.pdf)** (submitted to **ICLR 2027**).
|
||||
* *<mark>[new]</mark>* 🔥🔥 **[2026-08]**: 🎉 **Accepted** at **EMNLP 2026**: **[Memory Beyond Recall: A Dual-Process Cognitive Memory System for Self-Evolving LLM Agents](https://arxiv.org/abs/2606.09483)**!
|
||||
@@ -63,13 +65,13 @@ Welcome to the **Hy Memory Research Family**, covering cognitive chat memory, lo
|
||||
### 1. Installation
|
||||
|
||||
```bash
|
||||
pip install hy-memory==2.0.1 # core (includes ChromaDB and Kuzu)
|
||||
pip install "hy-memory[qdrant]==2.0.1" # + Qdrant
|
||||
pip install "hy-memory[faiss]==2.0.1" # + FAISS
|
||||
pip install "hy-memory[graph]==2.0.1" # + Neo4j
|
||||
pip install "hy-memory[mysql]==2.0.1" # + MySQL cache
|
||||
pip install "hy-memory[rerank]==2.0.1" # + local multilingual cross-encoder rerank
|
||||
pip install "hy-memory[all]==2.0.1" # everything
|
||||
pip install hy-memory==2.0.4 # core (includes ChromaDB and Kuzu)
|
||||
pip install "hy-memory[qdrant]==2.0.4" # + Qdrant
|
||||
pip install "hy-memory[faiss]==2.0.4" # + FAISS
|
||||
pip install "hy-memory[graph]==2.0.4" # + Neo4j
|
||||
pip install "hy-memory[mysql]==2.0.4" # + MySQL cache
|
||||
pip install "hy-memory[rerank]==2.0.4" # + local multilingual cross-encoder rerank
|
||||
pip install "hy-memory[all]==2.0.4" # everything
|
||||
```
|
||||
|
||||
### 2. Configuration
|
||||
@@ -151,7 +153,7 @@ result = client.search(
|
||||
|
||||
result["facts"] # fact layer
|
||||
result["experiences"] # experience layer
|
||||
result["chain_block"] # coding only: version-evolution context
|
||||
result["chain_block"] # coding only: version-evolution context (empty unless MEMORY_CODING_CHAIN_BLOCK_ENABLED)
|
||||
```
|
||||
|
||||
### 5. Routing, Source Isolation & Advanced APIs
|
||||
|
||||
+11
-9
@@ -32,7 +32,9 @@
|
||||
|
||||
## 最新动态
|
||||
|
||||
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **正式发布** **Hy Memory 2.0 (`hy-memory==2.0.1`)**(已上线 [PyPI](https://pypi.org/project/hy-memory/2.0.1/)),并开源 **Hy-Memory** monorepo 与 **[MemHub](memhub/README.md)**!
|
||||
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **模型开源** 在 Hugging Face 发布 **Hy-Memory-30B-A3B** 的 **FP8**(**[Hy-Memory-30B-A3B-FP8](https://huggingface.co/tencent/Hy-Memory-30B-A3B-FP8)**)与 **GGUF**(**[Hy-Memory-30B-A3B-GGUF](https://huggingface.co/tencent/Hy-Memory-30B-A3B-GGUF)**)量化版本模型!
|
||||
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 📦 **正式发布 [MemHub v1.0.4](https://github.com/Tencent-Hunyuan/Hy-Memory/releases/tag/v1.0.4)** 与 **[memhub-cli 1.0.5](https://www.npmjs.com/package/memhub-cli/v/1.0.5)**,提供已签名的 macOS 桌面应用及经过验证的 macOS/Linux Runtime!
|
||||
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **正式发布** **Hy Memory 2.0 (`hy-memory==2.0.4`)**(已上线 [PyPI](https://pypi.org/project/hy-memory/2.0.4/)),并开源 **Hy-Memory** monorepo 与 **[MemHub](memhub/README.md)**!
|
||||
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **模型开源** 在 Hugging Face 发布 **[Hy-Memory-30B-A3B](https://huggingface.co/tencent/Hy-Memory-30B-A3B)** 长期记忆写入模型及[技术报告](https://arxiv.org/abs/2610.22196)!
|
||||
* *<mark>[new]</mark>* 🔥🔥 **[2026-09]**: 📊 **基准与方法发布** 推出长周期与交错式编程记忆评测基准 **[CMB: A Coding Memory Benchmark for Long-Horizon and Interleaved Coding Agents](docs/papers/CMB_A_Coding_Memory_Benchmark_for_Long_Horizon_and_Interleaved_Coding_Agents.pdf)**(已投稿 **ICLR 2027**)。
|
||||
* *<mark>[new]</mark>* 🔥🔥 **[2026-08]**: 🎉 **论文录用** 双系统认知记忆架构论文 **[Memory Beyond Recall: A Dual-Process Cognitive Memory System for Self-Evolving LLM Agents](https://arxiv.org/abs/2606.09483)** 被 **EMNLP 2026** 接收!
|
||||
@@ -63,13 +65,13 @@
|
||||
### 1. 安装
|
||||
|
||||
```bash
|
||||
pip install hy-memory==2.0.1 # 核心(含 ChromaDB 与 Kuzu)
|
||||
pip install "hy-memory[qdrant]==2.0.1" # + Qdrant
|
||||
pip install "hy-memory[faiss]==2.0.1" # + FAISS
|
||||
pip install "hy-memory[graph]==2.0.1" # + Neo4j
|
||||
pip install "hy-memory[mysql]==2.0.1" # + MySQL 缓存
|
||||
pip install "hy-memory[rerank]==2.0.1" # + 本地多语言 cross-encoder rerank
|
||||
pip install "hy-memory[all]==2.0.1" # 全部
|
||||
pip install hy-memory==2.0.4 # 核心(含 ChromaDB 与 Kuzu)
|
||||
pip install "hy-memory[qdrant]==2.0.4" # + Qdrant
|
||||
pip install "hy-memory[faiss]==2.0.4" # + FAISS
|
||||
pip install "hy-memory[graph]==2.0.4" # + Neo4j
|
||||
pip install "hy-memory[mysql]==2.0.4" # + MySQL 缓存
|
||||
pip install "hy-memory[rerank]==2.0.4" # + 本地多语言 cross-encoder rerank
|
||||
pip install "hy-memory[all]==2.0.4" # 全部
|
||||
```
|
||||
|
||||
### 2. 配置
|
||||
@@ -151,7 +153,7 @@ result = client.search(
|
||||
|
||||
result["facts"] # 事实层
|
||||
result["experiences"] # 经验层
|
||||
result["chain_block"] # 仅 coding:版本演进上下文
|
||||
result["chain_block"] # 仅 coding:版本演进上下文(默认空;需 MEMORY_CODING_CHAIN_BLOCK_ENABLED)
|
||||
```
|
||||
|
||||
### 5. 自动路由、来源过滤与进阶 API
|
||||
|
||||
@@ -197,6 +197,7 @@ SDK 不设置 Rerank Search 并发上限。开启后模型在 `HyMemoryClient`
|
||||
| `MEMORY_HISTORY_DB_PATH` | `{DATA_DIR}/data/history.db` | History SQLite 路径 |
|
||||
| `MEMORY_HISTORY_RECORD_SEARCHES` | `false` | 是否记录 Search 操作 |
|
||||
| `MEMORY_CODING_CHAIN_REPO_ROOT` | — | coding 版本链读取本地 Git diff 的仓库根目录 |
|
||||
| `MEMORY_CODING_CHAIN_BLOCK_ENABLED` | `false` | search(scene=coding) 是否注入版本演进链块(diff / `chain_block`);默认关 |
|
||||
|
||||
## HTTP Server
|
||||
|
||||
|
||||
@@ -78,7 +78,8 @@ default 多-query 超过 `MEMORY_QUERY_REWRITE_MAX_CHARS` 时不改写:Coding
|
||||
Coding 关闭则直接使用最后一条 query。
|
||||
|
||||
路由到 `working` / `coding` 后,Search 读取独立生产力记忆库,返回 `facts` /
|
||||
`experiences`,不使用 chat 三通道结构。`coding` 还返回 `chain_block` / `chain_used`。
|
||||
`experiences`,不使用 chat 三通道结构。`coding` 还返回 `chain_block` / `chain_used`
|
||||
(默认空;需 `MEMORY_CODING_CHAIN_BLOCK_ENABLED` 才注入 diff 块)。
|
||||
|
||||
## Chat 成功返回结构
|
||||
|
||||
@@ -152,7 +153,7 @@ client = HyMemoryClient.from_config({
|
||||
安装可选依赖:
|
||||
|
||||
```bash
|
||||
pip install 'hy-memory[rerank]==2.0.1'
|
||||
pip install 'hy-memory[rerank]==2.0.4'
|
||||
```
|
||||
|
||||
启用后,`HyMemoryClient(...)` 构造阶段会完成模型下载/读取、device 放置和一次 dummy
|
||||
|
||||
+2
-3
@@ -37,8 +37,7 @@ do not belong in the public source tree.
|
||||
- Root GitHub workflows run SDK and MemHub checks from their respective working
|
||||
directories. Native lifecycle workflows produce reviewable Actions artifacts;
|
||||
tag releases remain fail-closed on public identity, signing and notarization.
|
||||
- Hy Memory is published as `hy-memory==2.0.1`. MemHub pins that public
|
||||
distribution; its selected npm package is `memhub-cli`, which is not yet
|
||||
published.
|
||||
- Hy Memory is published as `hy-memory==2.0.4`. MemHub pins that public
|
||||
distribution; its selected npm package is `memhub-cli` 1.0.5.
|
||||
- Hy-Memory source uses Apache-2.0 at the repository root. Third-party
|
||||
components retain their own licenses and attribution notices.
|
||||
@@ -168,9 +168,11 @@ working/coding 搜索返回:
|
||||
|
||||
`limit` 分别限制 facts 与 experiences,因此两层最多各返回 `limit` 条。
|
||||
|
||||
`scene="coding"` 额外返回 `chain_block` 和 `chain_used`:
|
||||
`scene="coding"` 额外返回 `chain_block` 和 `chain_used` 字段(键始终存在;默认内容为空):
|
||||
|
||||
- `chain_block` 是与已召回 fact 对齐的版本演进上下文;无法挂链时为 `""`。
|
||||
- 注入 diff / 版本演进块需显式开启 `MEMORY_CODING_CHAIN_BLOCK_ENABLED=true`
|
||||
(或 `CodingConfig.chain_block_enabled=True`)。默认关闭,以节约 prompt token。
|
||||
- 开启后,`chain_block` 是与已召回 fact 对齐的版本演进上下文;无法挂链时为 `""`。
|
||||
- `chain_used` 是已经进入 chain block 的 `facts` 下标。
|
||||
- SDK 不会从 `facts` 删除这些条目。调用方若要拼成“chain block + 剩余 facts”,需自行按 `chain_used` 过滤。
|
||||
|
||||
@@ -222,10 +224,12 @@ working/coding 搜索返回:
|
||||
| `MEMORY_CODING_DB_PATH` | `{DATA_DIR}/data/coding_memory.db` | working 基础 SQLite 路径;coding/trace 路径由此派生 |
|
||||
| `MEMORY_CODING_TOOL_RESULT_MAX_BYTES` | `2048` | 单条 tool result 的字节上限 |
|
||||
| `MEMORY_CODING_VERBATIM_FALLBACK_ENABLED` | `false` | 模型无结果时是否保存原文 fact;默认关闭,避免 assistant/tool trace 直接展示 |
|
||||
| `MEMORY_CODING_CHAIN_BLOCK_ENABLED` | `false` | search 是否注入版本演进链块(`chain_block` / diff);默认关闭(opt-in) |
|
||||
| `MEMORY_EXTRACT_HISTORY_TURNS` | `5` | 回读的历史 user-turn 数;当前 prompt 最终最多使用 5 |
|
||||
| `MEMORY_CODING_CHAIN_REPO_ROOT` | 空 | coding 版本链读取本地 Git diff 的仓库路径 |
|
||||
|
||||
`HCM_*` 变量属于版本链的高级调优项,不是稳定的公共配置契约;普通接入不应依赖其默认值。
|
||||
其中 `HCM_BLOCK_OFF=1` 可在已开启 `MEMORY_CODING_CHAIN_BLOCK_ENABLED` 时做消融(完全不出块)。
|
||||
|
||||
## 8. 定向验证
|
||||
|
||||
|
||||
+23
-7
@@ -5,14 +5,14 @@
|
||||
## 安装与快速开始
|
||||
|
||||
```bash
|
||||
pip install hy-memory==2.0.1
|
||||
pip install hy-memory==2.0.4
|
||||
|
||||
# 可选后端
|
||||
pip install 'hy-memory[qdrant]==2.0.1'
|
||||
pip install 'hy-memory[faiss]==2.0.1'
|
||||
pip install 'hy-memory[graph]==2.0.1' # Neo4j;Kuzu 已在核心依赖中
|
||||
pip install 'hy-memory[mysql]==2.0.1'
|
||||
pip install 'hy-memory[rerank]==2.0.1' # 本地多语言 cross-encoder rerank
|
||||
pip install 'hy-memory[qdrant]==2.0.4'
|
||||
pip install 'hy-memory[faiss]==2.0.4'
|
||||
pip install 'hy-memory[graph]==2.0.4' # Neo4j;Kuzu 已在核心依赖中
|
||||
pip install 'hy-memory[mysql]==2.0.4'
|
||||
pip install 'hy-memory[rerank]==2.0.4' # 本地多语言 cross-encoder rerank
|
||||
```
|
||||
|
||||
默认 LLM 和 Embedding 均使用 OpenAI-compatible 接口。使用 OpenAI 时可只设置:
|
||||
@@ -106,6 +106,15 @@ result = client.add(
|
||||
)
|
||||
```
|
||||
|
||||
`metadata` 与 `meta` 不是同一字段:
|
||||
|
||||
- `metadata` 是兼容旧调用方保留的 SDK 处理选项,会进入内部
|
||||
`WriteRequest.extra`,不保证持久化或随查询结果返回。
|
||||
- `meta` 是调用方的业务上下文,会持久化并在 `search()`、`get()` 等结果中返回。
|
||||
同一记忆被多次合并时,各次 `meta` 会按写入顺序保存在列表中。
|
||||
|
||||
需要以后读回的数据必须放在 `meta`,不要放在 `metadata`。
|
||||
|
||||
`scene` 的公开取值:
|
||||
|
||||
- `None`:普通文本直接走 chat;messages 含 tool 时执行快速场景判断。
|
||||
@@ -201,7 +210,8 @@ result = client.search(
|
||||
```
|
||||
|
||||
`working` / `coding` 路径返回 `scene="productivity"`、`facts`、`experiences`,不使用
|
||||
chat 的三桶结构;`coding` 还会返回 `chain_block` 和 `chain_used`。
|
||||
chat 的三桶结构;`coding` 还会返回 `chain_block` 和 `chain_used` 字段(默认空;
|
||||
需 `MEMORY_CODING_CHAIN_BLOCK_ENABLED=true` 才注入 diff 块)。
|
||||
|
||||
#### `search_mode`
|
||||
|
||||
@@ -263,6 +273,8 @@ catalog 也可以在没有基础 L0 时形成只读的合成画像。
|
||||
|
||||
```python
|
||||
memory = client.get("memory_id")
|
||||
# lite 模式写入的是 L1_RAW;按 ID 读取时必须显式选择返回原文。
|
||||
raw_memory = client.get("memory_id", include_raw=True)
|
||||
result = client.update("memory_id", "更新后的内容")
|
||||
result = client.delete("memory_id")
|
||||
result = client.delete_all(user_id="user_001")
|
||||
@@ -282,6 +294,10 @@ result = client.clone_user("user_001", "user_002", agent_id=None)
|
||||
对应异步方法为 `async_get()`、`async_update()`、`async_delete()`、
|
||||
`async_delete_all()`、`async_list_memories()`、`async_clone_user()`。
|
||||
|
||||
`get()` / `async_get()` 默认继续隐藏 `L1_RAW`,因此不会改变现有调用方的原文访问
|
||||
边界。只有显式传入 `include_raw=True` 才返回该层;这也是 lite 模式按 ID 读取
|
||||
写入内容及其 `meta` 的方式。MemHub 的 HTTP 读取接口不开放此参数。
|
||||
|
||||
普通 `list_memories()` 返回 `vdb` 桶,并在 Graph 有结果时附带 `graph`;传入
|
||||
`workspace_id` 时返回生产力记忆的 `scene="productivity"` 和 `experiences`。
|
||||
|
||||
|
||||
@@ -55,6 +55,13 @@ except Exception:
|
||||
from .client import HyMemoryClient
|
||||
from .inspector import MemoryInspector
|
||||
from .runtime import SharedRuntime
|
||||
from .snapshot import (
|
||||
DataPlaneRestore,
|
||||
DataPlaneSnapshot,
|
||||
DataPlaneSnapshotRejected,
|
||||
restore_local_data_plane,
|
||||
snapshot_local_data_plane,
|
||||
)
|
||||
|
||||
# ====== 配置 ======
|
||||
from .config import MemoryConfig
|
||||
@@ -111,6 +118,11 @@ __all__ = [
|
||||
"HyMemoryClient",
|
||||
"MemoryInspector",
|
||||
"SharedRuntime",
|
||||
"DataPlaneRestore",
|
||||
"DataPlaneSnapshot",
|
||||
"DataPlaneSnapshotRejected",
|
||||
"restore_local_data_plane",
|
||||
"snapshot_local_data_plane",
|
||||
# 配置
|
||||
"MemoryConfig",
|
||||
# Embedding 端点覆盖
|
||||
|
||||
@@ -22,7 +22,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
# ================================================================
|
||||
# 数据结构
|
||||
# ================================================================@dataclass
|
||||
# ================================================================
|
||||
@dataclass
|
||||
class SessionSummaryResult:
|
||||
"""Session 摘要结果 (V2)"""
|
||||
success: bool
|
||||
|
||||
@@ -39,6 +39,7 @@ import logging
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
import uuid
|
||||
|
||||
@@ -252,6 +253,17 @@ def _series_episode_id(
|
||||
return str(uuid.uuid5(uuid.NAMESPACE_URL, "hy-memory:series-episode:" + raw))
|
||||
|
||||
|
||||
def _series_memory_at(times: List[int]) -> Optional[datetime]:
|
||||
"""Earliest member timestamp as the same local wall clock it came from.
|
||||
|
||||
``_node_timestamp`` produces ``datetime.timestamp()`` values. Reading them
|
||||
back with ``utcfromtimestamp`` turns them into a naive *UTC* datetime, which
|
||||
the vector payload later re-interprets as local time and shifts by the
|
||||
machine's UTC offset.
|
||||
"""
|
||||
return datetime.fromtimestamp(min(times)) if times else None
|
||||
|
||||
|
||||
def _node_timestamp(node: Any) -> Optional[int]:
|
||||
value = getattr(node, "memory_at", None) or getattr(node, "gmt_created", None)
|
||||
if value is None:
|
||||
@@ -974,8 +986,6 @@ async def finalize_series_episode_containers(
|
||||
Stored text is only a title plus a structural intro. Exact L2 bodies remain in
|
||||
their canonical nodes and are referenced by ID from dated timeline segments.
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from ..models.memory import MemoryLayer, MemoryNode, MemoryStatus, SourceType
|
||||
from ..pipelines._retrieval.session_episode import (
|
||||
add_parent_episode_membership,
|
||||
@@ -1061,7 +1071,7 @@ async def finalize_series_episode_containers(
|
||||
segment["memory_at"] for segment in plan["timeline"]
|
||||
if segment.get("memory_at") is not None
|
||||
]
|
||||
memory_at = datetime.utcfromtimestamp(min(times)) if times else None
|
||||
memory_at = _series_memory_at(times)
|
||||
content = f"{plan['title']}. {plan['intro']}".strip()
|
||||
series = MemoryNode(
|
||||
node_id=series_id, user_id=user_id,
|
||||
|
||||
@@ -1123,6 +1123,7 @@ class Extractor:
|
||||
max_tokens=self._llm_config.agent_max_tokens,
|
||||
tools=None,
|
||||
tool_choice=None,
|
||||
audit_stage="extract",
|
||||
)
|
||||
self._call_count += 1
|
||||
total_tokens += response.tokens_used
|
||||
@@ -1233,6 +1234,7 @@ class Extractor:
|
||||
max_tokens=self._llm_config.agent_max_tokens,
|
||||
tools=None,
|
||||
tool_choice=None,
|
||||
audit_stage="extract",
|
||||
)
|
||||
self._call_count += 1
|
||||
total_tokens += response.tokens_used
|
||||
|
||||
@@ -34,6 +34,7 @@ import os
|
||||
import weakref
|
||||
|
||||
from ..config import MemoryConfig
|
||||
from ..utils.model_call_context import model_call_stage
|
||||
from ..core.workload import llm_slot
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -348,6 +349,7 @@ class LLMProvider:
|
||||
stop: List[str] = None,
|
||||
tools: Optional[List[Dict[str, Any]]] = None,
|
||||
tool_choice: Optional[Any] = None,
|
||||
audit_stage: Optional[str] = None,
|
||||
**kwargs
|
||||
) -> LLMResponse:
|
||||
"""
|
||||
@@ -386,15 +388,16 @@ class LLMProvider:
|
||||
len(prompt), _content_fingerprint(prompt),
|
||||
)
|
||||
|
||||
response = await self._call_llm(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
stop=stop,
|
||||
tools=tools,
|
||||
tool_choice=tool_choice,
|
||||
**kwargs
|
||||
)
|
||||
with model_call_stage(audit_stage):
|
||||
response = await self._call_llm(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
stop=stop,
|
||||
tools=tools,
|
||||
tool_choice=tool_choice,
|
||||
**kwargs
|
||||
)
|
||||
|
||||
self._total_calls += 1
|
||||
self._total_tokens += response.tokens_used
|
||||
@@ -496,11 +499,21 @@ class LLMProvider:
|
||||
clients = self._clients.setdefault(loop, {})
|
||||
client = clients.get(client_key)
|
||||
if client is None:
|
||||
client_options: Dict[str, Any] = {
|
||||
"api_key": base_api_key,
|
||||
"base_url": base_url,
|
||||
"timeout": self._llm_config.timeout,
|
||||
"max_retries": 0,
|
||||
}
|
||||
transport_factory = getattr(self.config, "http_transport_factory", None)
|
||||
if callable(transport_factory):
|
||||
import httpx
|
||||
|
||||
client_options["http_client"] = httpx.AsyncClient(
|
||||
transport=transport_factory()
|
||||
)
|
||||
client = AsyncOpenAI(
|
||||
api_key=base_api_key,
|
||||
base_url=base_url,
|
||||
timeout=self._llm_config.timeout,
|
||||
max_retries=0,
|
||||
**client_options,
|
||||
)
|
||||
clients[client_key] = client
|
||||
|
||||
@@ -585,6 +598,7 @@ class LLMProvider:
|
||||
temperature: Optional[float] = None,
|
||||
tools: Optional[List[Dict[str, Any]]] = None,
|
||||
tool_choice: Optional[Any] = None,
|
||||
audit_stage: Optional[str] = None,
|
||||
) -> LLMResponse:
|
||||
"""
|
||||
多轮 messages 调用(支持 tool results 回传)。
|
||||
@@ -612,13 +626,14 @@ class LLMProvider:
|
||||
f"msgs={len(messages)} tools={len(tools) if tools else 0}"
|
||||
)
|
||||
|
||||
response = await self._chat_completions(
|
||||
messages,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
tools=tools,
|
||||
tool_choice=tool_choice,
|
||||
)
|
||||
with model_call_stage(audit_stage):
|
||||
response = await self._chat_completions(
|
||||
messages,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
tools=tools,
|
||||
tool_choice=tool_choice,
|
||||
)
|
||||
|
||||
self._total_calls += 1
|
||||
self._total_tokens += response.tokens_used
|
||||
|
||||
@@ -669,6 +669,7 @@ class MemoryReconciler:
|
||||
response = await llm.complete(
|
||||
prompt=prompt,
|
||||
max_tokens=500,
|
||||
audit_stage="reconcile",
|
||||
)
|
||||
text = response.content.strip()
|
||||
if "```json" in text:
|
||||
@@ -1383,6 +1384,7 @@ class MemoryReconciler:
|
||||
response = await llm.complete(
|
||||
prompt=prompt,
|
||||
max_tokens=dyn_max_tokens,
|
||||
audit_stage="reconcile",
|
||||
)
|
||||
except Exception as e:
|
||||
# LLM 彻底不可用(provider 已按 max_retries 重试过,网关 500 /
|
||||
|
||||
+1116
-121
File diff suppressed because it is too large.
Load diff
@@ -647,7 +647,9 @@ class HyCodeMem:
|
||||
top-k,但它们的 diff 对当前工作区不可能有用,因此挂链前必须做同仓过滤。
|
||||
"""
|
||||
facts = facts or []
|
||||
# 开关: HCM_BLOCK_OFF=1 → 完全不出块, 也不从 bullet 删任何 fact。
|
||||
# 高级消融开关: HCM_BLOCK_OFF=1 → 完全不出块, 也不从 bullet 删任何 fact。
|
||||
# 公共 opt-in 见 CodingConfig.chain_block_enabled /
|
||||
# MEMORY_CODING_CHAIN_BLOCK_ENABLED(默认关;客户端在调用 decorate 前拦截)。
|
||||
if os.environ.get("HCM_BLOCK_OFF") == "1":
|
||||
return "", []
|
||||
picked, used = [], []
|
||||
|
||||
@@ -919,6 +919,7 @@ class CodingMemoryExtractor:
|
||||
resp = await self.llm_provider.complete(
|
||||
prompt=prompt,
|
||||
max_tokens=self.max_tokens,
|
||||
audit_stage="coding_extract",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[coding-extract] LLM call failed: {e}")
|
||||
|
||||
@@ -466,7 +466,13 @@ class WorkingFactReconciler:
|
||||
return [], []
|
||||
|
||||
candidates = await self._retrieve_candidates(
|
||||
drafts, user_id=user_id, source=source,
|
||||
drafts,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
session_id=session_id,
|
||||
workspace_id=workspace_id,
|
||||
branch=branch,
|
||||
source=source,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -499,7 +505,15 @@ class WorkingFactReconciler:
|
||||
# ------------------------------------------------------------
|
||||
|
||||
async def _retrieve_candidates(
|
||||
self, drafts: List[WorkingFactDraft], *, user_id: str, source: str
|
||||
self,
|
||||
drafts: List[WorkingFactDraft],
|
||||
*,
|
||||
user_id: str,
|
||||
agent_id: str,
|
||||
session_id: Optional[str],
|
||||
workspace_id: Optional[str],
|
||||
branch: Optional[str],
|
||||
source: str,
|
||||
) -> List[List[WorkingFact]]:
|
||||
"""每条 draft 用 statement 召回同 user 的 top-N active 事实。
|
||||
|
||||
@@ -512,6 +526,10 @@ class WorkingFactReconciler:
|
||||
关掉时整份召回原样交给 LLM。适用于 subject 不是稳定实体名的数据集(自由文本、
|
||||
位置标签),那里精确字符串相等会把同实体判成不同主体,反而拦掉真实更新。
|
||||
"""
|
||||
# Empty/legacy session metadata remains readable, but cannot prove
|
||||
# conversation authority for a destructive SUPERSEDE.
|
||||
if not session_id:
|
||||
return [[] for _ in drafts]
|
||||
try:
|
||||
embeddings = await self.embed_service.embed_batch(
|
||||
[d.statement for d in drafts]
|
||||
@@ -525,6 +543,10 @@ class WorkingFactReconciler:
|
||||
try:
|
||||
hits = await self.store.search_facts(
|
||||
emb, user_id=user_id, top=self.candidates_per_draft,
|
||||
agent_id=agent_id,
|
||||
session_id=session_id,
|
||||
workspace_id=workspace_id,
|
||||
branch=branch,
|
||||
# 写入侧同样接词面通道:候选选错了 LLM 就没有机会判对。这里不传
|
||||
# min_score——写入侧要的是"有哪些可能的前身",让 LLM 看更宽的名单,
|
||||
# 阈值过滤是读取侧的事。
|
||||
@@ -571,6 +593,7 @@ class WorkingFactReconciler:
|
||||
resp = await self.llm_provider.complete(
|
||||
prompt=prompt,
|
||||
max_tokens=self.max_tokens,
|
||||
audit_stage="coding_fact_reconcile",
|
||||
)
|
||||
return self._parse_ops(resp.content)
|
||||
|
||||
@@ -637,6 +660,7 @@ class WorkingFactReconciler:
|
||||
resp = await self.llm_provider.complete(
|
||||
prompt=prompt,
|
||||
max_tokens=_CHAIN_SUMMARY_MAX_TOKENS,
|
||||
audit_stage="coding_fact_summary",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[fact-reconcile] chain summary failed: {e}")
|
||||
@@ -792,6 +816,15 @@ class WorkingFactReconciler:
|
||||
old = await self.store.get_fact(old_id, user_id=user_id)
|
||||
if old is None:
|
||||
continue
|
||||
if (
|
||||
old.agent_id != agent_id
|
||||
or old.session_id != session_id
|
||||
or old.workspace_id != workspace_id
|
||||
):
|
||||
logger.warning(
|
||||
f"[fact-reconcile] refused cross-authority SUPERSEDE: {old.fact_id}"
|
||||
)
|
||||
continue
|
||||
# 闸门在候选阶段已经拦过一道,这里再拦一次:候选是按 statement 召回的,
|
||||
# 而 LLM 只能覆盖候选名单里的 id,理论上到不了这儿。真到了就说明前面
|
||||
# 哪一环漏了,宁可让这次覆盖不生效——多留一条旧事实是可恢复的,删掉
|
||||
|
||||
@@ -29,6 +29,9 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
_JUDGE_MAX_TURNS = 20
|
||||
_JUDGE_HEAD_TURNS = 5
|
||||
_JUDGE_USER_CONTENT_LIMIT = 1_000
|
||||
_JUDGE_USER_CONTENT_HEAD = 200
|
||||
_JUDGE_USER_CONTENT_TAIL = 200
|
||||
_JUDGE_MAX_QUERY_CHARS = 300
|
||||
_JUDGE_MAX_QUERIES = 20
|
||||
|
||||
@@ -186,6 +189,7 @@ async def classify_messages_scene(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
audit_stage="coding_judge",
|
||||
)
|
||||
_elapsed = round((time.perf_counter() - _t0) * 1000, 2)
|
||||
result = _parse_scene_json(resp.content)
|
||||
@@ -631,9 +635,13 @@ def _format_turns(summary: List[Dict[str, Any]]) -> str:
|
||||
rows = []
|
||||
for t in summary:
|
||||
user = t.get("user", "") or ""
|
||||
# 单 turn 用户文本截到 200 字符
|
||||
if len(user) > 200:
|
||||
user = user[:200] + "..."
|
||||
if len(user) > _JUDGE_USER_CONTENT_LIMIT:
|
||||
omitted = len(user) - _JUDGE_USER_CONTENT_HEAD - _JUDGE_USER_CONTENT_TAIL
|
||||
user = (
|
||||
user[:_JUDGE_USER_CONTENT_HEAD]
|
||||
+ f"\n[...{omitted} chars omitted...]\n"
|
||||
+ user[-_JUDGE_USER_CONTENT_TAIL:]
|
||||
)
|
||||
tools = t.get("tools", []) or []
|
||||
rows.append(
|
||||
f"- turn {t.get('turn', '?')}: user={user!r}, tools={tools}"
|
||||
|
||||
@@ -240,7 +240,7 @@ class CodingMemoryReconciler:
|
||||
)
|
||||
|
||||
# 3. 校验 + 执行
|
||||
executed = await self._execute(ops, drafts)
|
||||
executed = await self._execute(ops, drafts, candidates_per_draft)
|
||||
logger.info(
|
||||
f"[coding-reconcile] drafts={len(drafts)} ops={len(executed)} "
|
||||
+ ", ".join(f"{a}={sum(1 for o in executed if o.action == a)}"
|
||||
@@ -263,6 +263,12 @@ class CodingMemoryReconciler:
|
||||
"""
|
||||
result: List[List[CodingMemory]] = []
|
||||
for d in drafts:
|
||||
# A coding mutation must be attributable to one conversation.
|
||||
# Empty/legacy session metadata stays readable through ordinary
|
||||
# search, but it cannot authorize UPDATE/DELETE.
|
||||
if not d.session_id:
|
||||
result.append([])
|
||||
continue
|
||||
try:
|
||||
# task 为主入口,search_keys 为附加入口(去重、去空)
|
||||
queries = [d.task] + [k for k in (d.search_keys or []) if k and k != d.task]
|
||||
@@ -274,6 +280,8 @@ class CodingMemoryReconciler:
|
||||
hits = await self.store.search_by_query_embedding(
|
||||
emb,
|
||||
user_id=d.user_id,
|
||||
agent_id=d.agent_id,
|
||||
session_id=d.session_id,
|
||||
workspace_id=d.workspace_id,
|
||||
branch=d.branch,
|
||||
top=self.candidates_per_draft * 4,
|
||||
@@ -310,6 +318,7 @@ class CodingMemoryReconciler:
|
||||
resp = await self.llm_provider.complete(
|
||||
prompt=prompt,
|
||||
max_tokens=self.max_tokens,
|
||||
audit_stage="coding_reconcile",
|
||||
)
|
||||
return self._parse_ops(resp.content), prompt, resp.content, resp
|
||||
|
||||
@@ -414,6 +423,7 @@ class CodingMemoryReconciler:
|
||||
self,
|
||||
ops: List[ReconcileOp],
|
||||
drafts: List[CodingMemoryDraft],
|
||||
candidates_per_draft: List[List[CodingMemory]],
|
||||
) -> List[ReconcileOp]:
|
||||
"""
|
||||
校验 + 执行 ops。返回成功执行的 ops(filter 掉无效 op)。
|
||||
@@ -453,6 +463,11 @@ class CodingMemoryReconciler:
|
||||
if not op.target_experience_id:
|
||||
logger.warning(f"[coding-reconcile] drop UPDATE missing target: {op.to_dict()}")
|
||||
continue
|
||||
if not self._target_was_offered(op, candidates_per_draft):
|
||||
logger.warning(
|
||||
f"[coding-reconcile] drop UPDATE outside authority scope: {op.to_dict()}"
|
||||
)
|
||||
continue
|
||||
if op.draft_idx in consumed:
|
||||
logger.warning(f"[coding-reconcile] drop UPDATE on consumed draft: {op.to_dict()}")
|
||||
continue
|
||||
@@ -475,6 +490,11 @@ class CodingMemoryReconciler:
|
||||
if not op.target_experience_id:
|
||||
logger.warning(f"[coding-reconcile] drop DELETE missing target: {op.to_dict()}")
|
||||
continue
|
||||
if not self._target_was_offered(op, candidates_per_draft):
|
||||
logger.warning(
|
||||
f"[coding-reconcile] drop DELETE outside authority scope: {op.to_dict()}"
|
||||
)
|
||||
continue
|
||||
# DELETE 需要知道 user_id;通过 draft_idx(如有)或第一个 draft 推断
|
||||
user_id = self._infer_user_id(op, drafts)
|
||||
if not user_id:
|
||||
@@ -511,6 +531,19 @@ class CodingMemoryReconciler:
|
||||
|
||||
return executed
|
||||
|
||||
@staticmethod
|
||||
def _target_was_offered(
|
||||
op: ReconcileOp,
|
||||
candidates_per_draft: List[List[CodingMemory]],
|
||||
) -> bool:
|
||||
"""Only mutate a target frozen into this draft's scoped candidate set."""
|
||||
if op.draft_idx is None or not (0 <= op.draft_idx < len(candidates_per_draft)):
|
||||
return False
|
||||
return any(
|
||||
candidate.experience_id == op.target_experience_id
|
||||
for candidate in candidates_per_draft[op.draft_idx]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _infer_user_id(
|
||||
op: ReconcileOp, drafts: List[CodingMemoryDraft]
|
||||
|
||||
+98
-15
@@ -209,6 +209,14 @@ def _scope_where(
|
||||
return sql, params
|
||||
|
||||
|
||||
def _in_clause(column: str, values: Optional[List[str]]) -> Tuple[str, List[Any]]:
|
||||
"""SQL ``column IN (...)`` + parameters; empty values mean no condition."""
|
||||
if not values:
|
||||
return "", []
|
||||
placeholders = ",".join("?" for _ in values)
|
||||
return f"{column} IN ({placeholders})", list(values)
|
||||
|
||||
|
||||
def _scope_matches(
|
||||
row_workspace_id: Optional[str],
|
||||
row_branch: Optional[str],
|
||||
@@ -529,10 +537,20 @@ class CodingMemoryStore:
|
||||
"""覆盖式更新一条 coding memory。"""
|
||||
# 拿旧 keys 长度,先删旧 VDB rows
|
||||
prev = await self.get_by_id(memory.experience_id, user_id=memory.user_id)
|
||||
prev_key_count = (1 + len(prev.search_keys)) if prev else 0
|
||||
if prev is None:
|
||||
raise ValueError("coding_memory_update_target_missing")
|
||||
if (
|
||||
not prev.session_id
|
||||
or not memory.session_id
|
||||
or prev.agent_id != memory.agent_id
|
||||
or prev.session_id != memory.session_id
|
||||
or prev.workspace_id != memory.workspace_id
|
||||
):
|
||||
raise ValueError("coding_memory_update_authority_mismatch")
|
||||
prev_key_count = 1 + len(prev.search_keys)
|
||||
|
||||
memory.updated_at = datetime.utcnow()
|
||||
if memory.created_at is None and prev is not None:
|
||||
if memory.created_at is None:
|
||||
memory.created_at = prev.created_at
|
||||
await _run_in_pool(self._upsert_sql_sync, memory)
|
||||
# 删旧 VDB
|
||||
@@ -671,6 +689,10 @@ class CodingMemoryStore:
|
||||
query_embedding: List[float],
|
||||
user_id: str,
|
||||
*,
|
||||
agent_id: Optional[str] = None,
|
||||
session_id: Optional[str] = None,
|
||||
agent_ids: Optional[List[str]] = None,
|
||||
session_ids: Optional[List[str]] = None,
|
||||
workspace_id: Optional[str] = None,
|
||||
branch: Optional[str] = None,
|
||||
top: int = 40,
|
||||
@@ -688,21 +710,34 @@ class CodingMemoryStore:
|
||||
},
|
||||
...
|
||||
]
|
||||
workspace_id / branch 是作用域过滤,规则见 _scope_where:不传则纯语义召回
|
||||
(行为与加过滤前完全一致);传了则只保留 SQLite 里落在作用域内的经验,并按
|
||||
作用域的选择率放大向量取数,避免"先取 top-N 再过滤"把召回吃掉。
|
||||
agent_id / session_id(或 agent_ids / session_ids)是写授权作用域,
|
||||
传入时精确匹配;workspace_id / branch 的规则见 _scope_where。
|
||||
不传任何作用域则维持纯语义召回;传了则只保留 SQLite 里落在作用域内的经验,
|
||||
并按选择率放大向量取数,避免"先取 top-N 再过滤"把召回吃掉。
|
||||
"""
|
||||
if self._vec is None:
|
||||
return []
|
||||
|
||||
effective_agent_ids = list(agent_ids) if agent_ids else (
|
||||
[agent_id] if agent_id else []
|
||||
)
|
||||
effective_session_ids = list(session_ids) if session_ids else (
|
||||
[session_id] if session_id else []
|
||||
)
|
||||
allowed: Optional[Set[str]] = None
|
||||
if workspace_id:
|
||||
if effective_agent_ids or effective_session_ids or workspace_id:
|
||||
allowed, total = await _run_in_pool(
|
||||
self._scoped_experience_ids_sync, user_id, workspace_id, branch
|
||||
self._authority_scoped_experience_ids_sync,
|
||||
user_id,
|
||||
effective_agent_ids,
|
||||
effective_session_ids,
|
||||
workspace_id,
|
||||
branch,
|
||||
)
|
||||
if not allowed:
|
||||
logger.info(
|
||||
f"[coding-store] no experience in scope: "
|
||||
f"agent_id={agent_id!r} session_id={session_id!r} "
|
||||
f"workspace_id={workspace_id!r} branch={branch!r} "
|
||||
f"(user has {total}); skip vdb search"
|
||||
)
|
||||
@@ -778,6 +813,10 @@ class CodingMemoryStore:
|
||||
query_embedding: List[float],
|
||||
user_id: str,
|
||||
*,
|
||||
agent_id: Optional[str] = None,
|
||||
session_id: Optional[str] = None,
|
||||
agent_ids: Optional[List[str]] = None,
|
||||
session_ids: Optional[List[str]] = None,
|
||||
workspace_id: Optional[str] = None,
|
||||
branch: Optional[str] = None,
|
||||
top: int = 5,
|
||||
@@ -791,8 +830,9 @@ class CodingMemoryStore:
|
||||
SUPERSEDE 时向量行已被删掉,理论上召不到 superseded;这里再按 SQLite 的
|
||||
status 过一道,避免两边不一致时把过期结论放出去。
|
||||
|
||||
workspace_id / branch 是作用域过滤,规则见 _scope_where,语义与经验层一致:
|
||||
不传不过滤,传了按 SQLite 里的值筛,并按选择率放大向量取数。
|
||||
agent_id / session_id(或 agent_ids / session_ids)是写授权作用域,
|
||||
传入时精确匹配;workspace_id / branch 的规则见 _scope_where。
|
||||
不传任何作用域则不过滤,传了按 SQLite 里的值筛,并按选择率放大向量取数。
|
||||
|
||||
向量库按 top 的 4 倍过采样:向量行和 SQLite 行不是一个事务里写的,中间挂掉
|
||||
就会留下"向量还在、SQLite 没了"的孤儿,软删时删向量失败也会留下 superseded
|
||||
@@ -808,14 +848,27 @@ class CodingMemoryStore:
|
||||
if self._fact_vec is None:
|
||||
return []
|
||||
|
||||
effective_agent_ids = list(agent_ids) if agent_ids else (
|
||||
[agent_id] if agent_id else []
|
||||
)
|
||||
effective_session_ids = list(session_ids) if session_ids else (
|
||||
[session_id] if session_id else []
|
||||
)
|
||||
fetch = top * 4
|
||||
if workspace_id:
|
||||
if effective_agent_ids or effective_session_ids or workspace_id:
|
||||
scoped, total = await _run_in_pool(
|
||||
self._count_active_facts_sync, user_id, workspace_id, branch
|
||||
self._count_active_facts_sync,
|
||||
user_id,
|
||||
effective_agent_ids,
|
||||
effective_session_ids,
|
||||
workspace_id,
|
||||
branch,
|
||||
)
|
||||
if not scoped:
|
||||
logger.info(
|
||||
f"[coding-store] no active fact in scope: "
|
||||
f"agent_ids={effective_agent_ids!r} "
|
||||
f"session_ids={effective_session_ids!r} "
|
||||
f"workspace_id={workspace_id!r} branch={branch!r} "
|
||||
f"(user has {total}); skip fact vdb search"
|
||||
)
|
||||
@@ -852,6 +905,8 @@ class CodingMemoryStore:
|
||||
alive = [
|
||||
(f, scores[f.fact_id]) for f in facts
|
||||
if f.status == "active"
|
||||
and (not effective_agent_ids or f.agent_id in effective_agent_ids)
|
||||
and (not effective_session_ids or f.session_id in effective_session_ids)
|
||||
and _scope_matches(f.workspace_id, f.branch, workspace_id, branch)
|
||||
]
|
||||
kept = [(f, s) for f, s in alive if s >= min_score]
|
||||
@@ -1050,14 +1105,28 @@ class CodingMemoryStore:
|
||||
by_id = {r["experience_id"]: _row_to_memory(r) for r in rows}
|
||||
return [by_id[eid] for eid in experience_ids if eid in by_id]
|
||||
|
||||
def _scoped_experience_ids_sync(
|
||||
self, user_id: str, workspace_id: str, branch: Optional[str]
|
||||
def _authority_scoped_experience_ids_sync(
|
||||
self,
|
||||
user_id: str,
|
||||
agent_ids: Optional[List[str]],
|
||||
session_ids: Optional[List[str]],
|
||||
workspace_id: Optional[str],
|
||||
branch: Optional[str],
|
||||
) -> Tuple[Set[str], int]:
|
||||
"""返回 (落在作用域内的 experience_id 集合, 该 user 的经验总数)。
|
||||
"""返回 (落在授权作用域内的 experience_id 集合, 该 user 的经验总数)。
|
||||
|
||||
一次查询同时拿到过滤结果和选择率分母:前者供向量命中做交集,后者定放大倍数。
|
||||
agent_ids / session_ids 为空表示该维度不筛;非空按 IN 精确匹配。
|
||||
"""
|
||||
scope_sql, scope_params = _scope_where(workspace_id, branch)
|
||||
agent_sql, agent_params = _in_clause("agent_id", agent_ids)
|
||||
if agent_sql:
|
||||
scope_sql = f"({agent_sql}) AND ({scope_sql})"
|
||||
scope_params = [*agent_params, *scope_params]
|
||||
session_sql, session_params = _in_clause("session_id", session_ids)
|
||||
if session_sql:
|
||||
scope_sql = f"({session_sql}) AND ({scope_sql})"
|
||||
scope_params = [*session_params, *scope_params]
|
||||
with self._lock:
|
||||
assert self._conn is not None
|
||||
cur = self._conn.execute(
|
||||
@@ -1069,13 +1138,27 @@ class CodingMemoryStore:
|
||||
return {r["experience_id"] for r in rows if r["in_scope"]}, len(rows)
|
||||
|
||||
def _count_active_facts_sync(
|
||||
self, user_id: str, workspace_id: str, branch: Optional[str]
|
||||
self,
|
||||
user_id: str,
|
||||
agent_ids: Optional[List[str]],
|
||||
session_ids: Optional[List[str]],
|
||||
workspace_id: Optional[str],
|
||||
branch: Optional[str],
|
||||
) -> Tuple[int, int]:
|
||||
"""返回 (作用域内 active 事实数, 该 user 的 active 事实总数)。
|
||||
|
||||
事实层的过滤在 get_facts 拿到对象之后用 _scope_matches 做,这里只要选择率。
|
||||
agent_ids / session_ids 为空表示该维度不筛;非空按 IN 精确匹配。
|
||||
"""
|
||||
scope_sql, scope_params = _scope_where(workspace_id, branch)
|
||||
agent_sql, agent_params = _in_clause("agent_id", agent_ids)
|
||||
if agent_sql:
|
||||
scope_sql = f"({agent_sql}) AND ({scope_sql})"
|
||||
scope_params = [*agent_params, *scope_params]
|
||||
session_sql, session_params = _in_clause("session_id", session_ids)
|
||||
if session_sql:
|
||||
scope_sql = f"({session_sql}) AND ({scope_sql})"
|
||||
scope_params = [*session_params, *scope_params]
|
||||
with self._lock:
|
||||
assert self._conn is not None
|
||||
row = self._conn.execute(
|
||||
|
||||
+15
-1
@@ -6,7 +6,7 @@ Agent Memory - 配置管理
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional, Dict, Any, List
|
||||
from typing import Optional, Dict, Any, Callable, List
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -1136,6 +1136,9 @@ class CodingConfig:
|
||||
# LLM 失败或没有抽出 fact 时,是否把对话原文存成 working fact。
|
||||
# 默认关闭,避免 assistant/tool 轨迹以 statement 形式直接暴露给消费方。
|
||||
verbatim_fallback_enabled: bool = None
|
||||
# search(scene="coding") 是否注入版本演进链块(diff / chain_block)。
|
||||
# 默认关闭(opt-in):中重度 coding 用户可省下大量 prompt token;写入侧仍可 observe。
|
||||
chain_block_enabled: bool = None
|
||||
|
||||
def __post_init__(self):
|
||||
if self.enable is None:
|
||||
@@ -1153,6 +1156,10 @@ class CodingConfig:
|
||||
self.verbatim_fallback_enabled = _get_env_bool(
|
||||
"MEMORY_CODING_VERBATIM_FALLBACK_ENABLED", False
|
||||
)
|
||||
if self.chain_block_enabled is None:
|
||||
self.chain_block_enabled = _get_env_bool(
|
||||
"MEMORY_CODING_CHAIN_BLOCK_ENABLED", False
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -1252,6 +1259,13 @@ class MemoryConfig:
|
||||
enable_agent: bool = False
|
||||
debug: bool = False
|
||||
metrics_enabled: bool = True
|
||||
# Runtime-only HTTP transport factory. MemHub uses this for request-cost
|
||||
# budgeting without restricting the embedded SDK's local store access.
|
||||
http_transport_factory: Optional[Callable[[], Any]] = field(
|
||||
default=None,
|
||||
repr=False,
|
||||
compare=False,
|
||||
)
|
||||
|
||||
def __post_init__(self):
|
||||
# enable_graph 跟随 mode 走:mode=ultra 时自动启用,无需独立环境变量
|
||||
|
||||
@@ -356,11 +356,21 @@ class EmbedService:
|
||||
key = self._client_cache_key(base_url, api_key, timeout)
|
||||
client = self._client_cache.get(key)
|
||||
if client is None:
|
||||
client_options = {
|
||||
"api_key": api_key,
|
||||
"base_url": base_url or None,
|
||||
"timeout": timeout,
|
||||
"max_retries": 0,
|
||||
}
|
||||
transport_factory = getattr(self.config, "http_transport_factory", None)
|
||||
if callable(transport_factory):
|
||||
import httpx
|
||||
|
||||
client_options["http_client"] = httpx.AsyncClient(
|
||||
transport=transport_factory()
|
||||
)
|
||||
client = AsyncOpenAI(
|
||||
api_key=api_key,
|
||||
base_url=base_url or None,
|
||||
timeout=timeout,
|
||||
max_retries=0,
|
||||
**client_options,
|
||||
)
|
||||
self._client_cache[key] = client
|
||||
return client
|
||||
|
||||
@@ -114,6 +114,37 @@ class CacheBase(ABC):
|
||||
"""查询 pipeline 中间结果日志"""
|
||||
...
|
||||
|
||||
# ================================================================
|
||||
# Durable write outcomes
|
||||
# ================================================================
|
||||
|
||||
@abstractmethod
|
||||
async def claim_write_outcome(
|
||||
self,
|
||||
request_id: str,
|
||||
user_id: str,
|
||||
agent_id: str,
|
||||
session_id: str,
|
||||
operation: str,
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
"""Claim one idempotent write; return the existing row if already claimed."""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
async def finish_write_outcome(
|
||||
self,
|
||||
request_id: str,
|
||||
status: str,
|
||||
result: Dict[str, Any],
|
||||
) -> bool:
|
||||
"""Persist the terminal/unknown result for a claimed write."""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
async def get_write_outcome(self, request_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""Read one durable write outcome by exact request id."""
|
||||
...
|
||||
|
||||
# ================================================================
|
||||
# Summary Buffer(rolling summary 的未消费 turn 暂存)
|
||||
#
|
||||
|
||||
+130
-16
@@ -81,6 +81,21 @@ _CREATE_TABLES_SQL = [
|
||||
)
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS write_outcomes (
|
||||
request_id VARCHAR(256) NOT NULL,
|
||||
user_id VARCHAR(255) NOT NULL,
|
||||
agent_id VARCHAR(255) NOT NULL DEFAULT '',
|
||||
session_id VARCHAR(255) NOT NULL DEFAULT '',
|
||||
operation VARCHAR(32) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL,
|
||||
result_json LONGTEXT NOT NULL,
|
||||
created_at VARCHAR(64) NOT NULL,
|
||||
updated_at VARCHAR(64) NOT NULL,
|
||||
PRIMARY KEY (request_id),
|
||||
KEY idx_write_outcomes_owner (user_id, agent_id, session_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS system_metrics (
|
||||
minute_ts VARCHAR(32) NOT NULL,
|
||||
data LONGTEXT NOT NULL,
|
||||
@@ -459,29 +474,128 @@ class MysqlCache(CacheBase):
|
||||
logger.warning(f"get_pipeline_logs failed: {e}")
|
||||
return []
|
||||
|
||||
async def claim_write_outcome(
|
||||
self,
|
||||
request_id: str,
|
||||
user_id: str,
|
||||
agent_id: str,
|
||||
session_id: str,
|
||||
operation: str,
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
now = datetime.now().isoformat()
|
||||
inserted = await self._execute(
|
||||
"""
|
||||
INSERT IGNORE INTO write_outcomes (
|
||||
request_id, user_id, agent_id, session_id, operation,
|
||||
status, result_json, created_at, updated_at
|
||||
) VALUES (%s, %s, %s, %s, %s, 'running', '{}', %s, %s)
|
||||
""",
|
||||
(request_id, user_id, agent_id, session_id, operation, now, now),
|
||||
)
|
||||
if inserted == 1:
|
||||
return None
|
||||
return await self.get_write_outcome(request_id)
|
||||
|
||||
async def finish_write_outcome(
|
||||
self,
|
||||
request_id: str,
|
||||
status: str,
|
||||
result: Dict[str, Any],
|
||||
) -> bool:
|
||||
updated = await self._execute(
|
||||
"""
|
||||
UPDATE write_outcomes
|
||||
SET status = %s, result_json = %s, updated_at = %s
|
||||
WHERE request_id = %s
|
||||
""",
|
||||
(
|
||||
status,
|
||||
json.dumps(result, ensure_ascii=False, default=str),
|
||||
datetime.now().isoformat(),
|
||||
request_id,
|
||||
),
|
||||
)
|
||||
return updated == 1
|
||||
|
||||
async def get_write_outcome(self, request_id: str) -> Optional[Dict[str, Any]]:
|
||||
row = await self._fetchone(
|
||||
"SELECT * FROM write_outcomes WHERE request_id = %s",
|
||||
(request_id,),
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
try:
|
||||
row["result"] = json.loads(row.pop("result_json") or "{}")
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
row["result"] = {}
|
||||
return row
|
||||
|
||||
# ================================================================
|
||||
# System Metrics(分钟粒度落盘)
|
||||
# ================================================================
|
||||
|
||||
async def store_metrics_minute(self, minute_ts: str, data: dict) -> None:
|
||||
import aiomysql
|
||||
|
||||
try:
|
||||
now = datetime.now().isoformat()
|
||||
# 尝试 UPSERT
|
||||
existing = await self._fetchone(
|
||||
"SELECT data FROM system_metrics WHERE minute_ts = %s", (minute_ts,)
|
||||
)
|
||||
if existing:
|
||||
old_data = json.loads(existing["data"])
|
||||
merged = self._merge_metric_buckets(old_data, data)
|
||||
await self._execute(
|
||||
"UPDATE system_metrics SET data = %s, created_at = %s WHERE minute_ts = %s",
|
||||
(json.dumps(merged, default=str), now, minute_ts),
|
||||
)
|
||||
else:
|
||||
await self._execute(
|
||||
"INSERT INTO system_metrics (minute_ts, data, created_at) VALUES (%s, %s, %s)",
|
||||
(minute_ts, json.dumps(data, default=str), now),
|
||||
)
|
||||
# Read-merge-write must be one transaction: two instances flushing
|
||||
# the same minute used to overwrite each other's counters, and a
|
||||
# concurrent insert could lose the whole batch to a duplicate key.
|
||||
for attempt in range(2):
|
||||
try:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.begin()
|
||||
try:
|
||||
async with conn.cursor(aiomysql.DictCursor) as cur:
|
||||
await cur.execute(
|
||||
"SELECT data FROM system_metrics "
|
||||
"WHERE minute_ts = %s FOR UPDATE",
|
||||
(minute_ts,),
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
if row is not None:
|
||||
old_raw = (
|
||||
row["data"]
|
||||
if isinstance(row, dict)
|
||||
else row[0]
|
||||
)
|
||||
merged = self._merge_metric_buckets(
|
||||
json.loads(old_raw), data,
|
||||
)
|
||||
await cur.execute(
|
||||
"UPDATE system_metrics SET data = %s, "
|
||||
"created_at = %s WHERE minute_ts = %s",
|
||||
(
|
||||
json.dumps(merged, default=str),
|
||||
now,
|
||||
minute_ts,
|
||||
),
|
||||
)
|
||||
else:
|
||||
await cur.execute(
|
||||
"INSERT INTO system_metrics "
|
||||
"(minute_ts, data, created_at) "
|
||||
"VALUES (%s, %s, %s)",
|
||||
(
|
||||
minute_ts,
|
||||
json.dumps(data, default=str),
|
||||
now,
|
||||
),
|
||||
)
|
||||
await conn.commit()
|
||||
return
|
||||
except Exception:
|
||||
await conn.rollback()
|
||||
raise
|
||||
except (aiomysql.IntegrityError, aiomysql.OperationalError) as error:
|
||||
code = error.args[0] if error.args else None
|
||||
deadlock = code in (1205, 1213)
|
||||
if attempt or (isinstance(error, aiomysql.OperationalError) and not deadlock):
|
||||
raise
|
||||
# A competing writer inserted the row, or InnoDB chose us
|
||||
# as the deadlock victim. Retry so this batch merges.
|
||||
continue
|
||||
except Exception as e:
|
||||
logger.warning(f"store_metrics_minute failed: {e}")
|
||||
|
||||
|
||||
+232
-125
@@ -7,7 +7,7 @@ Agent Memory V2 - SqliteCache
|
||||
设计模式跟随 history_store.py:
|
||||
- 标准库 sqlite3 + _run_in_sqlite_pool()
|
||||
- WAL 模式 + check_same_thread=False
|
||||
- threading.Lock 保护写操作
|
||||
- 每实例 threading.RLock 保护共享连接的全部操作与关闭
|
||||
|
||||
三张表:
|
||||
- memory_operations / pipeline_logs / system_metrics: 审计与观测
|
||||
@@ -87,6 +87,20 @@ CREATE TABLE IF NOT EXISTS pipeline_logs_v2 (
|
||||
CREATE INDEX IF NOT EXISTS idx_plog_request ON pipeline_logs_v2(request_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_plog_user ON pipeline_logs_v2(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS write_outcomes (
|
||||
request_id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
agent_id TEXT NOT NULL DEFAULT '',
|
||||
session_id TEXT NOT NULL DEFAULT '',
|
||||
operation TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
result_json TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_write_outcomes_owner
|
||||
ON write_outcomes(user_id, agent_id, session_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS system_metrics (
|
||||
minute_ts TEXT PRIMARY KEY,
|
||||
data TEXT NOT NULL,
|
||||
@@ -122,7 +136,10 @@ class SqliteCache(CacheBase):
|
||||
def __init__(self, config: MemoryConfig):
|
||||
self.config = config
|
||||
self._conn: Optional[sqlite3.Connection] = None
|
||||
self._lock = threading.Lock()
|
||||
# One connection is shared by the executor workers. Use the same lock
|
||||
# for reads, writes, initialization and close so close() cannot free
|
||||
# the connection while another worker is inside sqlite3.
|
||||
self._lock = threading.RLock()
|
||||
|
||||
# 读取 db_path
|
||||
cache_cfg = getattr(config, "cache", None)
|
||||
@@ -144,35 +161,37 @@ class SqliteCache(CacheBase):
|
||||
logger.debug(f"SqliteCache initialized: {self._db_path}")
|
||||
|
||||
def _init_sync(self) -> None:
|
||||
db_dir = os.path.dirname(self._db_path)
|
||||
if db_dir:
|
||||
os.makedirs(db_dir, exist_ok=True)
|
||||
self._conn = sqlite3.connect(self._db_path, check_same_thread=False)
|
||||
self._conn.row_factory = sqlite3.Row
|
||||
self._conn.execute("PRAGMA journal_mode=WAL;")
|
||||
self._conn.executescript(_CREATE_TABLES_SQL)
|
||||
self._migrate_pipeline_logs_columns()
|
||||
self._conn.commit()
|
||||
with self._lock:
|
||||
db_dir = os.path.dirname(self._db_path)
|
||||
if db_dir:
|
||||
os.makedirs(db_dir, exist_ok=True)
|
||||
self._conn = sqlite3.connect(self._db_path, check_same_thread=False)
|
||||
self._conn.row_factory = sqlite3.Row
|
||||
self._conn.execute("PRAGMA journal_mode=WAL;")
|
||||
self._conn.executescript(_CREATE_TABLES_SQL)
|
||||
self._migrate_pipeline_logs_columns()
|
||||
self._conn.commit()
|
||||
|
||||
def _migrate_pipeline_logs_columns(self) -> None:
|
||||
"""给旧库的 pipeline_logs_v2 补 namespace/session/event time 列。"""
|
||||
try:
|
||||
cols = {
|
||||
row["name"]
|
||||
for row in self._conn.execute("PRAGMA table_info(pipeline_logs_v2)")
|
||||
}
|
||||
_text_cols = ("namespace", "session_id")
|
||||
for col in _text_cols:
|
||||
if col not in cols:
|
||||
with self._lock:
|
||||
try:
|
||||
cols = {
|
||||
row["name"]
|
||||
for row in self._conn.execute("PRAGMA table_info(pipeline_logs_v2)")
|
||||
}
|
||||
_text_cols = ("namespace", "session_id")
|
||||
for col in _text_cols:
|
||||
if col not in cols:
|
||||
self._conn.execute(
|
||||
f"ALTER TABLE pipeline_logs_v2 ADD COLUMN {col} TEXT NOT NULL DEFAULT ''"
|
||||
)
|
||||
if "event_at_ms" not in cols:
|
||||
self._conn.execute(
|
||||
f"ALTER TABLE pipeline_logs_v2 ADD COLUMN {col} TEXT NOT NULL DEFAULT ''"
|
||||
"ALTER TABLE pipeline_logs_v2 ADD COLUMN event_at_ms INTEGER NOT NULL DEFAULT 0"
|
||||
)
|
||||
if "event_at_ms" not in cols:
|
||||
self._conn.execute(
|
||||
"ALTER TABLE pipeline_logs_v2 ADD COLUMN event_at_ms INTEGER NOT NULL DEFAULT 0"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.debug(f"[sqlite] pipeline_logs_v2 column migration skipped: {e}")
|
||||
except Exception as e:
|
||||
logger.debug(f"[sqlite] pipeline_logs_v2 column migration skipped: {e}")
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._conn is not None:
|
||||
@@ -180,9 +199,10 @@ class SqliteCache(CacheBase):
|
||||
logger.info("SqliteCache closed")
|
||||
|
||||
def _close_sync(self) -> None:
|
||||
if self._conn:
|
||||
self._conn.close()
|
||||
self._conn = None
|
||||
with self._lock:
|
||||
if self._conn:
|
||||
self._conn.close()
|
||||
self._conn = None
|
||||
|
||||
# ================================================================
|
||||
# 统计
|
||||
@@ -255,39 +275,40 @@ class SqliteCache(CacheBase):
|
||||
"""
|
||||
try:
|
||||
def _query():
|
||||
conditions = []
|
||||
params = []
|
||||
if request_id:
|
||||
conditions.append("request_id = ?")
|
||||
params.append(request_id)
|
||||
if memory_id:
|
||||
conditions.append("memory_id = ?")
|
||||
params.append(memory_id)
|
||||
if user_id:
|
||||
conditions.append("user_id = ?")
|
||||
params.append(user_id)
|
||||
with self._lock:
|
||||
conditions = []
|
||||
params = []
|
||||
if request_id:
|
||||
conditions.append("request_id = ?")
|
||||
params.append(request_id)
|
||||
if memory_id:
|
||||
conditions.append("memory_id = ?")
|
||||
params.append(memory_id)
|
||||
if user_id:
|
||||
conditions.append("user_id = ?")
|
||||
params.append(user_id)
|
||||
|
||||
if not conditions:
|
||||
return []
|
||||
if not conditions:
|
||||
return []
|
||||
|
||||
where = " AND ".join(conditions)
|
||||
rows = self._conn.execute(
|
||||
f"SELECT * FROM memory_operations_v2 WHERE {where} "
|
||||
f"ORDER BY id DESC LIMIT ?",
|
||||
params + [limit],
|
||||
).fetchall()
|
||||
result = []
|
||||
for r in rows:
|
||||
row = dict(r)
|
||||
# 反序列化 supersedes JSON 字符串 → list
|
||||
import json as _json
|
||||
raw_sup = row.get("supersedes", "")
|
||||
try:
|
||||
row["supersedes"] = _json.loads(raw_sup) if raw_sup else []
|
||||
except Exception:
|
||||
row["supersedes"] = []
|
||||
result.append(row)
|
||||
return result
|
||||
where = " AND ".join(conditions)
|
||||
rows = self._conn.execute(
|
||||
f"SELECT * FROM memory_operations_v2 WHERE {where} "
|
||||
f"ORDER BY id DESC LIMIT ?",
|
||||
params + [limit],
|
||||
).fetchall()
|
||||
result = []
|
||||
for r in rows:
|
||||
row = dict(r)
|
||||
# 反序列化 supersedes JSON 字符串 → list
|
||||
import json as _json
|
||||
raw_sup = row.get("supersedes", "")
|
||||
try:
|
||||
row["supersedes"] = _json.loads(raw_sup) if raw_sup else []
|
||||
except Exception:
|
||||
row["supersedes"] = []
|
||||
result.append(row)
|
||||
return result
|
||||
|
||||
return await _run_in_sqlite_pool(_query)
|
||||
except Exception as e:
|
||||
@@ -369,43 +390,126 @@ class SqliteCache(CacheBase):
|
||||
"""
|
||||
try:
|
||||
def _query():
|
||||
conditions = []
|
||||
params = []
|
||||
if request_id:
|
||||
conditions.append("request_id = ?")
|
||||
params.append(request_id)
|
||||
if user_id:
|
||||
conditions.append("user_id = ?")
|
||||
params.append(user_id)
|
||||
if step:
|
||||
conditions.append("step = ?")
|
||||
params.append(step)
|
||||
with self._lock:
|
||||
conditions = []
|
||||
params = []
|
||||
if request_id:
|
||||
conditions.append("request_id = ?")
|
||||
params.append(request_id)
|
||||
if user_id:
|
||||
conditions.append("user_id = ?")
|
||||
params.append(user_id)
|
||||
if step:
|
||||
conditions.append("step = ?")
|
||||
params.append(step)
|
||||
|
||||
if not conditions:
|
||||
return []
|
||||
if not conditions:
|
||||
return []
|
||||
|
||||
where = " AND ".join(conditions)
|
||||
rows = self._conn.execute(
|
||||
f"SELECT * FROM pipeline_logs_v2 WHERE {where} "
|
||||
f"ORDER BY id ASC LIMIT ?",
|
||||
params + [limit],
|
||||
).fetchall()
|
||||
out = [dict(r) for r in rows]
|
||||
# 派生可读的 event_at(ISO ms)供查询接口直接用;event_at_ms 为 0 时留空
|
||||
from datetime import datetime as _dt
|
||||
for _r in out:
|
||||
_ms = _r.get("event_at_ms") or 0
|
||||
_r["event_at"] = (
|
||||
_dt.fromtimestamp(_ms / 1000.0).isoformat(timespec="milliseconds")
|
||||
if _ms else ""
|
||||
)
|
||||
return out
|
||||
where = " AND ".join(conditions)
|
||||
rows = self._conn.execute(
|
||||
f"SELECT * FROM pipeline_logs_v2 WHERE {where} "
|
||||
f"ORDER BY id ASC LIMIT ?",
|
||||
params + [limit],
|
||||
).fetchall()
|
||||
out = [dict(r) for r in rows]
|
||||
# 派生可读的 event_at(ISO ms)供查询接口直接用;event_at_ms 为 0 时留空
|
||||
from datetime import datetime as _dt
|
||||
for _r in out:
|
||||
_ms = _r.get("event_at_ms") or 0
|
||||
_r["event_at"] = (
|
||||
_dt.fromtimestamp(_ms / 1000.0).isoformat(timespec="milliseconds")
|
||||
if _ms else ""
|
||||
)
|
||||
return out
|
||||
|
||||
return await _run_in_sqlite_pool(_query)
|
||||
except Exception as e:
|
||||
logger.warning(f"get_pipeline_logs failed: {e}")
|
||||
return []
|
||||
|
||||
# ================================================================
|
||||
# Durable write outcomes
|
||||
# ================================================================
|
||||
|
||||
async def claim_write_outcome(
|
||||
self,
|
||||
request_id: str,
|
||||
user_id: str,
|
||||
agent_id: str,
|
||||
session_id: str,
|
||||
operation: str,
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
def _claim():
|
||||
with self._lock:
|
||||
now = datetime.now().isoformat()
|
||||
cursor = self._conn.execute(
|
||||
"""
|
||||
INSERT OR IGNORE INTO write_outcomes (
|
||||
request_id, user_id, agent_id, session_id, operation,
|
||||
status, result_json, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, 'running', '{}', ?, ?)
|
||||
""",
|
||||
(request_id, user_id, agent_id, session_id, operation, now, now),
|
||||
)
|
||||
self._conn.commit()
|
||||
if cursor.rowcount == 1:
|
||||
return None
|
||||
row = self._conn.execute(
|
||||
"SELECT * FROM write_outcomes WHERE request_id = ?",
|
||||
(request_id,),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
existing = await _run_in_sqlite_pool(_claim)
|
||||
if existing is None:
|
||||
return None
|
||||
return await self.get_write_outcome(request_id)
|
||||
|
||||
async def finish_write_outcome(
|
||||
self,
|
||||
request_id: str,
|
||||
status: str,
|
||||
result: Dict[str, Any],
|
||||
) -> bool:
|
||||
def _finish():
|
||||
with self._lock:
|
||||
cursor = self._conn.execute(
|
||||
"""
|
||||
UPDATE write_outcomes
|
||||
SET status = ?, result_json = ?, updated_at = ?
|
||||
WHERE request_id = ?
|
||||
""",
|
||||
(
|
||||
status,
|
||||
json.dumps(result, ensure_ascii=False, default=str),
|
||||
datetime.now().isoformat(),
|
||||
request_id,
|
||||
),
|
||||
)
|
||||
self._conn.commit()
|
||||
return cursor.rowcount == 1
|
||||
|
||||
return await _run_in_sqlite_pool(_finish)
|
||||
|
||||
async def get_write_outcome(self, request_id: str) -> Optional[Dict[str, Any]]:
|
||||
def _get():
|
||||
with self._lock:
|
||||
row = self._conn.execute(
|
||||
"SELECT * FROM write_outcomes WHERE request_id = ?",
|
||||
(request_id,),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
row = await _run_in_sqlite_pool(_get)
|
||||
if row is None:
|
||||
return None
|
||||
try:
|
||||
row["result"] = json.loads(row.pop("result_json") or "{}")
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
row["result"] = {}
|
||||
return row
|
||||
|
||||
# ================================================================
|
||||
# System Metrics(分钟粒度落盘)
|
||||
# ================================================================
|
||||
@@ -414,26 +518,27 @@ class SqliteCache(CacheBase):
|
||||
"""存储一个分钟桶的增量指标数据(UPSERT: 同一分钟多次写入会合并)"""
|
||||
try:
|
||||
def _store():
|
||||
now = datetime.now().isoformat()
|
||||
# UPSERT: 如果同一分钟已存在,合并数据
|
||||
existing = self._conn.execute(
|
||||
"SELECT data FROM system_metrics WHERE minute_ts = ?",
|
||||
(minute_ts,),
|
||||
).fetchone()
|
||||
if existing:
|
||||
import json as _json
|
||||
old_data = _json.loads(existing["data"])
|
||||
merged = self._merge_metric_buckets(old_data, data)
|
||||
self._conn.execute(
|
||||
"UPDATE system_metrics SET data = ?, created_at = ? WHERE minute_ts = ?",
|
||||
(_json.dumps(merged, default=str), now, minute_ts),
|
||||
)
|
||||
else:
|
||||
self._conn.execute(
|
||||
"INSERT INTO system_metrics (minute_ts, data, created_at) VALUES (?, ?, ?)",
|
||||
(minute_ts, json.dumps(data, default=str), now),
|
||||
)
|
||||
self._conn.commit()
|
||||
with self._lock:
|
||||
now = datetime.now().isoformat()
|
||||
# UPSERT: 如果同一分钟已存在,合并数据
|
||||
existing = self._conn.execute(
|
||||
"SELECT data FROM system_metrics WHERE minute_ts = ?",
|
||||
(minute_ts,),
|
||||
).fetchone()
|
||||
if existing:
|
||||
import json as _json
|
||||
old_data = _json.loads(existing["data"])
|
||||
merged = self._merge_metric_buckets(old_data, data)
|
||||
self._conn.execute(
|
||||
"UPDATE system_metrics SET data = ?, created_at = ? WHERE minute_ts = ?",
|
||||
(_json.dumps(merged, default=str), now, minute_ts),
|
||||
)
|
||||
else:
|
||||
self._conn.execute(
|
||||
"INSERT INTO system_metrics (minute_ts, data, created_at) VALUES (?, ?, ?)",
|
||||
(minute_ts, json.dumps(data, default=str), now),
|
||||
)
|
||||
self._conn.commit()
|
||||
await _run_in_sqlite_pool(_store)
|
||||
except Exception as e:
|
||||
logger.warning(f"store_metrics_minute failed: {e}")
|
||||
@@ -442,17 +547,18 @@ class SqliteCache(CacheBase):
|
||||
"""读取指定时间范围内的分钟指标数据"""
|
||||
try:
|
||||
def _load():
|
||||
rows = self._conn.execute(
|
||||
"SELECT data FROM system_metrics WHERE minute_ts >= ? AND minute_ts <= ? ORDER BY minute_ts",
|
||||
(start_ts, end_ts),
|
||||
).fetchall()
|
||||
results = []
|
||||
for row in rows:
|
||||
try:
|
||||
results.append(json.loads(row["data"]))
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
return results
|
||||
with self._lock:
|
||||
rows = self._conn.execute(
|
||||
"SELECT data FROM system_metrics WHERE minute_ts >= ? AND minute_ts <= ? ORDER BY minute_ts",
|
||||
(start_ts, end_ts),
|
||||
).fetchall()
|
||||
results = []
|
||||
for row in rows:
|
||||
try:
|
||||
results.append(json.loads(row["data"]))
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
return results
|
||||
return await _run_in_sqlite_pool(_load)
|
||||
except Exception as e:
|
||||
logger.warning(f"load_metrics_range failed: {e}")
|
||||
@@ -462,11 +568,12 @@ class SqliteCache(CacheBase):
|
||||
"""删除指定时间之前的 metrics 数据"""
|
||||
try:
|
||||
def _cleanup():
|
||||
self._conn.execute(
|
||||
"DELETE FROM system_metrics WHERE minute_ts < ?",
|
||||
(before_ts,),
|
||||
)
|
||||
self._conn.commit()
|
||||
with self._lock:
|
||||
self._conn.execute(
|
||||
"DELETE FROM system_metrics WHERE minute_ts < ?",
|
||||
(before_ts,),
|
||||
)
|
||||
self._conn.commit()
|
||||
await _run_in_sqlite_pool(_cleanup)
|
||||
except Exception as e:
|
||||
logger.warning(f"cleanup_old_metrics failed: {e}")
|
||||
|
||||
+113
-69
@@ -16,6 +16,7 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, List, Any, Optional
|
||||
|
||||
@@ -65,6 +66,11 @@ def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _escape_like(value: str) -> str:
|
||||
"""Escape LIKE wildcards so a user id is matched literally."""
|
||||
return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
|
||||
|
||||
class HistoryStore:
|
||||
"""
|
||||
SQLite 历史存储 - 记录所有内存操作的审计日志。
|
||||
@@ -89,6 +95,10 @@ class HistoryStore:
|
||||
"""
|
||||
self._db_path = config.history.db_path
|
||||
self._conn: Optional[sqlite3.Connection] = None
|
||||
# sqlite3.Connection.close() must never race with an execute() on the
|
||||
# same connection. The lock also serializes operations on this shared
|
||||
# connection; separate HistoryStore instances remain independent.
|
||||
self._conn_lock = threading.RLock()
|
||||
|
||||
async def initialize(self) -> None:
|
||||
"""创建表和索引(如果不存在)"""
|
||||
@@ -97,20 +107,21 @@ class HistoryStore:
|
||||
|
||||
def _init_sync(self) -> None:
|
||||
"""同步初始化:创建目录、连接数据库、建表建索引"""
|
||||
# 确保目录存在
|
||||
db_dir = os.path.dirname(self._db_path)
|
||||
if db_dir:
|
||||
os.makedirs(db_dir, exist_ok=True)
|
||||
with self._conn_lock:
|
||||
# 确保目录存在
|
||||
db_dir = os.path.dirname(self._db_path)
|
||||
if db_dir:
|
||||
os.makedirs(db_dir, exist_ok=True)
|
||||
|
||||
self._conn = sqlite3.connect(self._db_path, check_same_thread=False)
|
||||
self._conn.row_factory = sqlite3.Row
|
||||
# 开启 WAL 模式,提高并发读写性能
|
||||
self._conn.execute("PRAGMA journal_mode=WAL;")
|
||||
self._conn = sqlite3.connect(self._db_path, check_same_thread=False)
|
||||
self._conn.row_factory = sqlite3.Row
|
||||
# 开启 WAL 模式,提高并发读写性能
|
||||
self._conn.execute("PRAGMA journal_mode=WAL;")
|
||||
|
||||
self._conn.execute(_CREATE_TABLE_SQL)
|
||||
for idx_sql in _CREATE_INDEXES_SQL:
|
||||
self._conn.execute(idx_sql)
|
||||
self._conn.commit()
|
||||
self._conn.execute(_CREATE_TABLE_SQL)
|
||||
for idx_sql in _CREATE_INDEXES_SQL:
|
||||
self._conn.execute(idx_sql)
|
||||
self._conn.commit()
|
||||
|
||||
# ================================================================
|
||||
# 记录操作
|
||||
@@ -218,13 +229,14 @@ class HistoryStore:
|
||||
return await _run_in_sqlite_pool(self._get_history_sync, memory_id)
|
||||
|
||||
def _get_history_sync(self, memory_id: str) -> List[Dict[str, Any]]:
|
||||
if self._conn is None:
|
||||
return []
|
||||
cursor = self._conn.execute(
|
||||
"SELECT * FROM memory_history WHERE memory_id = ? ORDER BY created_at ASC",
|
||||
(memory_id,),
|
||||
)
|
||||
return [dict(row) for row in cursor.fetchall()]
|
||||
with self._conn_lock:
|
||||
if self._conn is None:
|
||||
return []
|
||||
cursor = self._conn.execute(
|
||||
"SELECT * FROM memory_history WHERE memory_id = ? ORDER BY created_at ASC",
|
||||
(memory_id,),
|
||||
)
|
||||
return [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
async def get_recent(
|
||||
self,
|
||||
@@ -244,14 +256,43 @@ class HistoryStore:
|
||||
return await _run_in_sqlite_pool(self._get_recent_sync, isolation_key, limit)
|
||||
|
||||
def _get_recent_sync(self, isolation_key: str, limit: int) -> List[Dict[str, Any]]:
|
||||
if self._conn is None:
|
||||
return []
|
||||
cursor = self._conn.execute(
|
||||
"SELECT * FROM memory_history WHERE isolation_key = ? "
|
||||
"ORDER BY created_at DESC LIMIT ?",
|
||||
(isolation_key, limit),
|
||||
with self._conn_lock:
|
||||
if self._conn is None:
|
||||
return []
|
||||
cursor = self._conn.execute(
|
||||
"SELECT * FROM memory_history WHERE isolation_key = ? "
|
||||
"ORDER BY created_at DESC LIMIT ?",
|
||||
(isolation_key, limit),
|
||||
)
|
||||
return [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
async def get_recent_for_user(
|
||||
self,
|
||||
user_id: str,
|
||||
limit: int = 50,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""获取某 user 下所有 agent 的最近操作。
|
||||
|
||||
isolation_key 形如 ``"{user_id}:{agent_id}"``。user_id 里的 LIKE
|
||||
通配符会被转义,保证只匹配这个 user,不会漏到 ``u1`` 之外。
|
||||
"""
|
||||
prefix = _escape_like(f"{user_id}:") + "%"
|
||||
return await _run_in_sqlite_pool(
|
||||
self._get_recent_prefix_sync, prefix, limit,
|
||||
)
|
||||
return [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
def _get_recent_prefix_sync(
|
||||
self, pattern: str, limit: int,
|
||||
) -> List[Dict[str, Any]]:
|
||||
with self._conn_lock:
|
||||
if self._conn is None:
|
||||
return []
|
||||
cursor = self._conn.execute(
|
||||
"SELECT * FROM memory_history WHERE isolation_key LIKE ? ESCAPE '\\' "
|
||||
"ORDER BY created_at DESC LIMIT ?",
|
||||
(pattern, limit),
|
||||
)
|
||||
return [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
async def count(self, isolation_key: str = "") -> int:
|
||||
"""
|
||||
@@ -266,16 +307,17 @@ class HistoryStore:
|
||||
return await _run_in_sqlite_pool(self._count_sync, isolation_key)
|
||||
|
||||
def _count_sync(self, isolation_key: str) -> int:
|
||||
if self._conn is None:
|
||||
return 0
|
||||
if isolation_key:
|
||||
cursor = self._conn.execute(
|
||||
"SELECT COUNT(*) FROM memory_history WHERE isolation_key = ?",
|
||||
(isolation_key,),
|
||||
)
|
||||
else:
|
||||
cursor = self._conn.execute("SELECT COUNT(*) FROM memory_history")
|
||||
return cursor.fetchone()[0]
|
||||
with self._conn_lock:
|
||||
if self._conn is None:
|
||||
return 0
|
||||
if isolation_key:
|
||||
cursor = self._conn.execute(
|
||||
"SELECT COUNT(*) FROM memory_history WHERE isolation_key = ?",
|
||||
(isolation_key,),
|
||||
)
|
||||
else:
|
||||
cursor = self._conn.execute("SELECT COUNT(*) FROM memory_history")
|
||||
return cursor.fetchone()[0]
|
||||
|
||||
async def close(self) -> None:
|
||||
"""关闭数据库连接"""
|
||||
@@ -284,9 +326,10 @@ class HistoryStore:
|
||||
logger.info("[HistoryStore] closed")
|
||||
|
||||
def _close_sync(self) -> None:
|
||||
if self._conn:
|
||||
self._conn.close()
|
||||
self._conn = None
|
||||
with self._conn_lock:
|
||||
if self._conn:
|
||||
self._conn.close()
|
||||
self._conn = None
|
||||
|
||||
# ================================================================
|
||||
# 内部
|
||||
@@ -339,33 +382,34 @@ class HistoryStore:
|
||||
role: str = "",
|
||||
extra: Optional[Dict[str, Any]] = None,
|
||||
) -> int:
|
||||
if self._conn is None:
|
||||
return -1
|
||||
now = _now_iso()
|
||||
extra_json = json.dumps(extra or {}, ensure_ascii=False)
|
||||
cursor = self._conn.execute(
|
||||
"""INSERT INTO memory_history
|
||||
(memory_id, isolation_key, event,
|
||||
old_memory, new_memory, old_status, new_status,
|
||||
change_reason, layer, actor_id, role, extra,
|
||||
created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
memory_id,
|
||||
isolation_key,
|
||||
event,
|
||||
old_memory,
|
||||
new_memory,
|
||||
old_status,
|
||||
new_status,
|
||||
change_reason,
|
||||
layer,
|
||||
actor_id,
|
||||
role,
|
||||
extra_json,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
self._conn.commit()
|
||||
return cursor.lastrowid
|
||||
with self._conn_lock:
|
||||
if self._conn is None:
|
||||
return -1
|
||||
now = _now_iso()
|
||||
extra_json = json.dumps(extra or {}, ensure_ascii=False)
|
||||
cursor = self._conn.execute(
|
||||
"""INSERT INTO memory_history
|
||||
(memory_id, isolation_key, event,
|
||||
old_memory, new_memory, old_status, new_status,
|
||||
change_reason, layer, actor_id, role, extra,
|
||||
created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
memory_id,
|
||||
isolation_key,
|
||||
event,
|
||||
old_memory,
|
||||
new_memory,
|
||||
old_status,
|
||||
new_status,
|
||||
change_reason,
|
||||
layer,
|
||||
actor_id,
|
||||
role,
|
||||
extra_json,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
self._conn.commit()
|
||||
return cursor.lastrowid
|
||||
@@ -462,14 +462,39 @@ class FaissVectorStore(VectorStoreBase):
|
||||
return None
|
||||
|
||||
async def get_embeddings(self, node_ids: List[str]) -> Dict[str, List[float]]:
|
||||
"""批量取向量(in-memory _data 直接读 embedding),供去重算 cosine。"""
|
||||
out: Dict[str, List[float]] = {}
|
||||
for nid in node_ids:
|
||||
point_id = self._node_id_to_point_id(nid)
|
||||
entry = self._data.get(point_id)
|
||||
if entry and entry.get("embedding"):
|
||||
out[nid] = list(entry["embedding"])
|
||||
return out
|
||||
"""批量取向量,供去重 / episode 摘要计算 cosine。
|
||||
|
||||
``_data`` 只保存 payload 与 FAISS 内部下标;普通 upsert 不额外存一份
|
||||
embedding,向量本体在 FAISS index 里。这里按当前有效下标 reconstruct,
|
||||
并用 ``_idx_to_id`` 校验,避免读到已被替换的旧下标。
|
||||
"""
|
||||
|
||||
def _get() -> Dict[str, List[float]]:
|
||||
out: Dict[str, List[float]] = {}
|
||||
with self._lock:
|
||||
for nid in node_ids:
|
||||
point_id = self._node_id_to_point_id(nid)
|
||||
entry = self._data.get(point_id)
|
||||
if entry is None:
|
||||
continue
|
||||
embedding = entry.get("embedding")
|
||||
if embedding:
|
||||
out[nid] = list(embedding)
|
||||
continue
|
||||
idx = entry.get("idx")
|
||||
if (
|
||||
idx is None
|
||||
or self._index is None
|
||||
or self._idx_to_id.get(int(idx)) != point_id
|
||||
):
|
||||
continue
|
||||
try:
|
||||
out[nid] = self._index.reconstruct(int(idx)).tolist()
|
||||
except Exception:
|
||||
continue
|
||||
return out
|
||||
|
||||
return await _run_in_vdb_pool(_get)
|
||||
|
||||
# ================================================================
|
||||
# 删除
|
||||
|
||||
@@ -10,8 +10,8 @@ HY Memory - Intention (L7) 召回 + 惰性过期转换 + 复本判定
|
||||
节点的 layer 改写为 l2_fact(持久化 update_payload),并从意图结果里剔除——
|
||||
过期意图变成普通历史事实,下次走 normal 召回;
|
||||
- **判重(重点)**:对幸存意图按下述规则分组,同组只留一条本次返回:
|
||||
同 user_id + 同一天 memory_at + valid_until 相同(都为 None 或都相等)
|
||||
+ cosine 相似度 ≥ MEMORY_DEDUP_THRESHOLD (默认 0.95)
|
||||
同 user_id + 同 agent_id + 同一天 memory_at + valid_until 相同
|
||||
(都为 None 或都相等)+ cosine 相似度 ≥ MEMORY_DEDUP_THRESHOLD (默认 0.95)
|
||||
→ 视为同一个意图的复本(extractor 复读机 / 多 session 重复表达)。
|
||||
保留组里 `gmt_created` 最早的(老的先来先得,稳定 id);
|
||||
- **异步删库**:其余复本 fire-and-forget 从 VDB 删除,不影响本次调用 RT。
|
||||
@@ -112,11 +112,19 @@ def _partition_duplicates(
|
||||
if len(hits) < 2:
|
||||
return list(hits), []
|
||||
|
||||
# 1. 按 (memory_at day, valid_until day) 分桶
|
||||
buckets: Dict[Tuple[Any, Any], List[int]] = {}
|
||||
# 1. 按 (user_id, agent_id, memory_at day, valid_until day) 分桶。
|
||||
# user_id / agent_id 必须进键:多用户检索时不同用户的同一天意图可能
|
||||
# 文本、日期都相同,但它们是两个独立的租户数据;只按日期分桶会把其中
|
||||
# 一个判成复本并硬删除。
|
||||
buckets: Dict[Tuple[Any, Any, Any, Any], List[int]] = {}
|
||||
for idx, h in enumerate(hits):
|
||||
node = h.get("node")
|
||||
key = (_memory_at_day(node), _valid_until_key(node))
|
||||
key = (
|
||||
getattr(node, "user_id", None) if node else None,
|
||||
getattr(node, "agent_id", None) if node else None,
|
||||
_memory_at_day(node),
|
||||
_valid_until_key(node),
|
||||
)
|
||||
buckets.setdefault(key, []).append(idx)
|
||||
|
||||
def _gmt(h: Dict[str, Any]) -> float:
|
||||
@@ -229,6 +237,8 @@ async def recall_intentions(
|
||||
*,
|
||||
user_ids: Optional[List[str]] = None,
|
||||
agent_ids: Optional[List[str]] = None,
|
||||
isolation_key: str = "",
|
||||
isolation_keys: Optional[List[str]] = None,
|
||||
limit: int = 10,
|
||||
now: Optional[datetime] = None,
|
||||
stats_out: Optional[Dict[str, Any]] = None,
|
||||
@@ -243,6 +253,9 @@ async def recall_intentions(
|
||||
query_embedding: 查询向量
|
||||
user_ids: 用户隔离(单/多用户)
|
||||
agent_ids: 可选 agent 过滤
|
||||
isolation_key / isolation_keys: 精确的 (user, agent, session) 隔离键。
|
||||
与其它召回通道一致:调用方在按 session 过滤时只生成这两项,
|
||||
user_ids / agent_ids 为 None;不把它们透传下去就会退化成全库检索。
|
||||
limit: 召回上限(返回给上游的条数)
|
||||
now: 当前时间(默认 datetime.now(),测试可注入)
|
||||
stats_out: 可选 dict,本函数把分段耗时与数量**原地回填**进去,供调用方落
|
||||
@@ -283,6 +296,8 @@ async def recall_intentions(
|
||||
query_embedding=query_embedding,
|
||||
user_ids=user_ids or None,
|
||||
agent_ids=agent_ids,
|
||||
isolation_key=isolation_key,
|
||||
isolation_keys=isolation_keys,
|
||||
layers=[MemoryLayer.L7_INTENTION],
|
||||
limit=fetch_limit,
|
||||
score_threshold=0.0, # intention 不设语义门槛
|
||||
|
||||
@@ -231,6 +231,10 @@ class WriteRequest:
|
||||
# 已有记忆 (V1 合并检测用)
|
||||
existing_memories: Optional[List[Dict[str, Any]]] = None
|
||||
|
||||
# Public client process_raw() only: reuse these exact L1 nodes as input.
|
||||
# Ordinary add() never populates this field.
|
||||
existing_raw_ids: List[str] = field(default_factory=list)
|
||||
|
||||
# 记忆时间戳(不传则用当前时间 datetime.now())
|
||||
memory_at: Optional[datetime] = None
|
||||
|
||||
|
||||
@@ -1840,6 +1840,8 @@ class BaseReadPipeline(ReadPipeline):
|
||||
query_embedding,
|
||||
user_ids=isolation_params.get("user_ids"),
|
||||
agent_ids=isolation_params.get("agent_ids"),
|
||||
isolation_key=isolation_params.get("isolation_key") or "",
|
||||
isolation_keys=isolation_params.get("isolation_keys"),
|
||||
limit=request.intention_limit,
|
||||
stats_out=_intent_stats,
|
||||
include_sources=request.include_sources,
|
||||
|
||||
@@ -280,6 +280,27 @@ class MemoryWriter(WritePipeline):
|
||||
custom["source_raw_memory_ids"] = source_ids
|
||||
return custom
|
||||
|
||||
async def _attach_existing_raw_ids(
|
||||
self,
|
||||
vector_store,
|
||||
memory_ids: List[str],
|
||||
raw_ids: List[str],
|
||||
) -> None:
|
||||
"""Attach every reused raw record to canonical outputs."""
|
||||
for memory_id in memory_ids:
|
||||
node = await vector_store.get_by_id(memory_id)
|
||||
if node is None:
|
||||
continue
|
||||
custom = dict(node.custom or {})
|
||||
source_ids = list(custom.get("source_raw_memory_ids") or [])
|
||||
legacy_source = str(getattr(node, "source_raw_memory_id", "") or "")
|
||||
for raw_id in (legacy_source, *raw_ids):
|
||||
if raw_id and raw_id not in source_ids:
|
||||
source_ids.append(raw_id)
|
||||
if source_ids:
|
||||
custom["source_raw_memory_ids"] = source_ids
|
||||
await vector_store.update_payload(memory_id, {"custom": custom})
|
||||
|
||||
@staticmethod
|
||||
def _attach_client_meta(custom: Dict[str, Any], request: Optional[WriteRequest]) -> None:
|
||||
"""给新建节点挂上调用方 meta(单份 list)。
|
||||
@@ -968,7 +989,7 @@ class MemoryWriter(WritePipeline):
|
||||
async def _run():
|
||||
try:
|
||||
nid = await summarize_closed_episode(
|
||||
vector_store=self.vector_store,
|
||||
vector_store=await self._get_vector_store(),
|
||||
embed_service=self.embed_service,
|
||||
llm_provider=self.llm_provider,
|
||||
episode_id=episode_id,
|
||||
@@ -2596,13 +2617,23 @@ class MemoryWriter(WritePipeline):
|
||||
from ..metrics import MetricsCollector
|
||||
MetricsCollector.get().sys1_start()
|
||||
|
||||
# 2. 向量化 + 持久化(L1_RAW)
|
||||
existing_raw_ids = request.existing_raw_ids
|
||||
if (
|
||||
not isinstance(existing_raw_ids, list)
|
||||
or any(not isinstance(raw_id, str) or not raw_id for raw_id in existing_raw_ids)
|
||||
):
|
||||
raise ValueError("_existing_raw_ids must be a list of non-empty ids")
|
||||
|
||||
# 2. 向量化(处理已有 raw 时复用已存节点,不再次 embed)
|
||||
_t_embed = datetime.now()
|
||||
with tracer.span("embed") as s:
|
||||
embedding, embed_meta = await self.embed_service.embed_queued_with_meta(
|
||||
request.content
|
||||
)
|
||||
s.set_output({"dims": len(embedding), "content_len": len(request.content)})
|
||||
if existing_raw_ids:
|
||||
embedding, embed_meta = [], {"reused_raw": True}
|
||||
else:
|
||||
with tracer.span("embed") as s:
|
||||
embedding, embed_meta = await self.embed_service.embed_queued_with_meta(
|
||||
request.content
|
||||
)
|
||||
s.set_output({"dims": len(embedding), "content_len": len(request.content)})
|
||||
_embed_ms = (datetime.now() - _t_embed).total_seconds() * 1000
|
||||
response.extra["embedding"] = embedding
|
||||
await self._emit_pipeline_step(
|
||||
@@ -2625,27 +2656,43 @@ class MemoryWriter(WritePipeline):
|
||||
with tracer.span("qdrant_upsert") as s:
|
||||
try:
|
||||
vector_store = await self._get_vector_store()
|
||||
layer_enum = MemoryLayer.from_string(suggested_layer)
|
||||
_raw_custom: Dict[str, Any] = {}
|
||||
self._attach_client_meta(_raw_custom, request)
|
||||
mem_node = MemoryNode(
|
||||
user_id=request.user_id,
|
||||
agent_id=request.agent_id or "default_agent",
|
||||
session_id=request.session_id or "default_session",
|
||||
source=request.source,
|
||||
layer=layer_enum,
|
||||
content=request.content,
|
||||
source_type=SourceType.EXPLICIT,
|
||||
status=MemoryStatus.ACTIVE,
|
||||
is_latest=True,
|
||||
embedding=embedding,
|
||||
memory_at=request.memory_at,
|
||||
custom=_raw_custom,
|
||||
)
|
||||
memory_id = await vector_store.upsert(mem_node)
|
||||
if existing_raw_ids:
|
||||
memory_id = existing_raw_ids[-1]
|
||||
mem_node = await vector_store.get_by_id(memory_id)
|
||||
if (
|
||||
mem_node is None
|
||||
or mem_node.layer != MemoryLayer.L1_RAW
|
||||
or mem_node.user_id != request.user_id
|
||||
or mem_node.agent_id != (request.agent_id or "default_agent")
|
||||
or mem_node.session_id != (request.session_id or "default_session")
|
||||
or mem_node.source != request.source
|
||||
):
|
||||
raise ValueError("existing raw record is outside the write scope")
|
||||
else:
|
||||
layer_enum = MemoryLayer.from_string(suggested_layer)
|
||||
_raw_custom: Dict[str, Any] = {}
|
||||
self._attach_client_meta(_raw_custom, request)
|
||||
mem_node = MemoryNode(
|
||||
user_id=request.user_id,
|
||||
agent_id=request.agent_id or "default_agent",
|
||||
session_id=request.session_id or "default_session",
|
||||
source=request.source,
|
||||
layer=layer_enum,
|
||||
content=request.content,
|
||||
source_type=SourceType.EXPLICIT,
|
||||
status=MemoryStatus.ACTIVE,
|
||||
is_latest=True,
|
||||
embedding=embedding,
|
||||
memory_at=request.memory_at,
|
||||
custom=_raw_custom,
|
||||
)
|
||||
memory_id = await vector_store.upsert(mem_node)
|
||||
response.memory_id = memory_id
|
||||
s.set_output({"memory_id": memory_id, "layer": suggested_layer})
|
||||
logger.debug(f"[write] persisted: id={memory_id} layer={suggested_layer}")
|
||||
logger.debug(
|
||||
f"[write] {'reused' if existing_raw_ids else 'persisted'}: "
|
||||
f"id={memory_id} layer={suggested_layer}"
|
||||
)
|
||||
except Exception as persist_err:
|
||||
_l1_error = str(persist_err)
|
||||
s.set_error(_l1_error)
|
||||
@@ -2709,6 +2756,12 @@ class MemoryWriter(WritePipeline):
|
||||
recent_history_count=_recent_history_count,
|
||||
)
|
||||
total_tokens += response.extra.get("_agent_tokens", 0)
|
||||
if existing_raw_ids and response.extra.get("agent_stored_ids"):
|
||||
await self._attach_existing_raw_ids(
|
||||
vector_store,
|
||||
list(response.extra["agent_stored_ids"]),
|
||||
existing_raw_ids,
|
||||
)
|
||||
if response.extra.get("agent_status") == "failed":
|
||||
await self._emit_pipeline_step(
|
||||
request,
|
||||
@@ -2718,12 +2771,13 @@ class MemoryWriter(WritePipeline):
|
||||
"error": response.extra.get("agent_error", ""),
|
||||
},
|
||||
)
|
||||
await self._rollback_failed_l1(
|
||||
request=request,
|
||||
response=response,
|
||||
vector_store=vector_store,
|
||||
memory_id=memory_id,
|
||||
)
|
||||
if not existing_raw_ids:
|
||||
await self._rollback_failed_l1(
|
||||
request=request,
|
||||
response=response,
|
||||
vector_store=vector_store,
|
||||
memory_id=memory_id,
|
||||
)
|
||||
response.tokens_used = total_tokens
|
||||
_failed_workflow_ms = (
|
||||
datetime.now() - _t_workflow
|
||||
|
||||
+19
-6
@@ -29,7 +29,7 @@ import logging
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any, Dict, Optional
|
||||
@@ -495,6 +495,16 @@ class MemoryHTTPHandler(BaseHTTPRequestHandler):
|
||||
_json_response(self, 200, result)
|
||||
|
||||
|
||||
def _request_shutdown(server: ThreadingHTTPServer) -> None:
|
||||
"""Ask ``serve_forever`` to stop without blocking the calling thread.
|
||||
|
||||
``BaseServer.shutdown()`` waits for the ``serve_forever`` loop to exit. A
|
||||
signal handler runs on the very thread executing that loop, so calling it
|
||||
there deadlocks forever. Hand the call to a helper thread instead.
|
||||
"""
|
||||
threading.Thread(target=server.shutdown, daemon=True).start()
|
||||
|
||||
|
||||
def run_server(port: int = 19527, host: str = "127.0.0.1"):
|
||||
"""Start the HTTP server (blocking)."""
|
||||
# Configure logging — basicConfig for root; hy_memory level set after client init
|
||||
@@ -523,13 +533,12 @@ def run_server(port: int = 19527, host: str = "127.0.0.1"):
|
||||
logger.info(f"[server] Listening on http://{host}:{port}")
|
||||
logger.info(f"[server] Health check: http://{host}:{port}/healthz")
|
||||
|
||||
# Graceful shutdown
|
||||
# Graceful shutdown. The signal handler only asks a helper thread to stop
|
||||
# the loop; cleanup runs after serve_forever() returns so it cannot race
|
||||
# the request threads or deadlock the serving thread.
|
||||
def _shutdown(signum, frame):
|
||||
logger.info("[server] Shutting down...")
|
||||
server.shutdown()
|
||||
if _client is not None:
|
||||
_client.close()
|
||||
sys.exit(0)
|
||||
_request_shutdown(server)
|
||||
|
||||
signal.signal(signal.SIGINT, _shutdown)
|
||||
signal.signal(signal.SIGTERM, _shutdown)
|
||||
@@ -538,6 +547,10 @@ def run_server(port: int = 19527, host: str = "127.0.0.1"):
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
_shutdown(None, None)
|
||||
finally:
|
||||
server.server_close()
|
||||
if _client is not None:
|
||||
_client.close()
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Public, offline snapshot support for the SDK-owned local data plane."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class DataPlaneSnapshotRejected(RuntimeError):
|
||||
def __init__(self, code: str) -> None:
|
||||
super().__init__(code)
|
||||
self.code = code
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DataPlaneSnapshot:
|
||||
source_root: Path
|
||||
snapshot_root: Path
|
||||
files: tuple[dict[str, object], ...]
|
||||
total_bytes: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DataPlaneRestore:
|
||||
restored_root: Path
|
||||
previous_root: Path | None
|
||||
files_restored: int
|
||||
total_bytes: int
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def snapshot_local_data_plane(
|
||||
*,
|
||||
source_root: Path,
|
||||
target_root: Path,
|
||||
writers_stopped: bool,
|
||||
) -> DataPlaneSnapshot:
|
||||
"""Copy one quiesced local SDK root and return a verified inventory.
|
||||
|
||||
Remote providers require their own export implementation and must not call
|
||||
this local-path contract.
|
||||
"""
|
||||
if not writers_stopped:
|
||||
raise DataPlaneSnapshotRejected("data_plane_snapshot_writers_running")
|
||||
source = source_root.resolve()
|
||||
target = target_root.resolve()
|
||||
if source.is_symlink() or not source.is_dir():
|
||||
raise DataPlaneSnapshotRejected("data_plane_snapshot_source_invalid")
|
||||
if target.exists():
|
||||
raise DataPlaneSnapshotRejected("data_plane_snapshot_target_exists")
|
||||
|
||||
try:
|
||||
target.mkdir(parents=True)
|
||||
for root, directories, files in os.walk(source, followlinks=False):
|
||||
root_path = Path(root)
|
||||
relative = root_path.relative_to(source)
|
||||
target_directory = target / relative
|
||||
target_directory.mkdir(parents=True, exist_ok=True)
|
||||
for name in directories:
|
||||
if (root_path / name).is_symlink():
|
||||
raise DataPlaneSnapshotRejected("data_plane_snapshot_symlink")
|
||||
for name in files:
|
||||
item = root_path / name
|
||||
if item.is_symlink():
|
||||
raise DataPlaneSnapshotRejected("data_plane_snapshot_symlink")
|
||||
shutil.copy2(item, target_directory / name)
|
||||
|
||||
inventory: list[dict[str, object]] = []
|
||||
for path in sorted(item for item in target.rglob("*") if item.is_file()):
|
||||
inventory.append(
|
||||
{
|
||||
"path": path.relative_to(target).as_posix(),
|
||||
"bytes": path.stat().st_size,
|
||||
"sha256": _sha256(path),
|
||||
}
|
||||
)
|
||||
for item in inventory:
|
||||
copied = target / str(item["path"])
|
||||
if copied.stat().st_size != item["bytes"] or _sha256(copied) != item["sha256"]:
|
||||
raise DataPlaneSnapshotRejected("data_plane_snapshot_verify_failed")
|
||||
except DataPlaneSnapshotRejected:
|
||||
shutil.rmtree(target, ignore_errors=True)
|
||||
raise
|
||||
except OSError as error:
|
||||
shutil.rmtree(target, ignore_errors=True)
|
||||
raise DataPlaneSnapshotRejected("data_plane_snapshot_failed") from error
|
||||
|
||||
return DataPlaneSnapshot(
|
||||
source_root=source,
|
||||
snapshot_root=target,
|
||||
files=tuple(inventory),
|
||||
total_bytes=sum(int(item["bytes"]) for item in inventory),
|
||||
)
|
||||
|
||||
|
||||
def restore_local_data_plane(
|
||||
*,
|
||||
snapshot_root: Path,
|
||||
target_root: Path,
|
||||
writers_stopped: bool,
|
||||
protective_root: Path | None = None,
|
||||
) -> DataPlaneRestore:
|
||||
"""Replace one local SDK root from a verified snapshot with rollback."""
|
||||
if not writers_stopped:
|
||||
raise DataPlaneSnapshotRejected("data_plane_restore_writers_running")
|
||||
source = snapshot_root.resolve()
|
||||
target = target_root.resolve()
|
||||
protective = (
|
||||
protective_root.resolve()
|
||||
if protective_root is not None
|
||||
else target.parent / f".{target.name}.pre-restore"
|
||||
)
|
||||
staging = target.parent / f".{target.name}.restore.tmp"
|
||||
if target.is_symlink() or protective.exists() or staging.exists():
|
||||
raise DataPlaneSnapshotRejected("data_plane_restore_target_unsafe")
|
||||
|
||||
copied = snapshot_local_data_plane(
|
||||
source_root=source,
|
||||
target_root=staging,
|
||||
writers_stopped=True,
|
||||
)
|
||||
previous: Path | None = None
|
||||
try:
|
||||
if target.exists():
|
||||
target.replace(protective)
|
||||
previous = protective
|
||||
staging.replace(target)
|
||||
except OSError as error:
|
||||
if previous is not None and previous.exists() and not target.exists():
|
||||
previous.replace(target)
|
||||
previous = None
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
raise DataPlaneSnapshotRejected("data_plane_restore_replace_failed") from error
|
||||
|
||||
return DataPlaneRestore(
|
||||
restored_root=target,
|
||||
previous_root=previous,
|
||||
files_restored=len(copied.files),
|
||||
total_bytes=copied.total_bytes,
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Context propagated to host-provided HTTP transports for cost accounting."""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar, Token
|
||||
|
||||
_model_call_stage: ContextVar[str] = ContextVar(
|
||||
"hy_memory_model_call_stage",
|
||||
default="other",
|
||||
)
|
||||
|
||||
|
||||
def current_model_call_stage() -> str:
|
||||
return _model_call_stage.get()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def model_call_stage(stage: str | None) -> Iterator[None]:
|
||||
normalized = (stage or "other").strip().lower() or "other"
|
||||
token: Token[str] = _model_call_stage.set(normalized)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_model_call_stage.reset(token)
|
||||
@@ -18,12 +18,32 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: A namespace is a single path component, not a path. `\w` keeps Unicode
|
||||
#: names working while excluding separators, drive letters and NUL.
|
||||
_SAFE_SUBDIR = re.compile(r"[\w.-]{1,64}", re.UNICODE)
|
||||
|
||||
|
||||
def _safe_subdir(value: str) -> Optional[str]:
|
||||
"""Return ``value`` if it is safe as one directory name, else ``None``.
|
||||
|
||||
``user_id`` is caller-controlled. Without this check a value such as
|
||||
``"/tmp/evil__u1"`` makes ``Path(base) / "/tmp/evil"`` discard ``base``
|
||||
entirely; ``"../.."`` escapes it the same way.
|
||||
"""
|
||||
candidate = (value or "").strip()
|
||||
if not candidate or candidate in {".", ".."}:
|
||||
return None
|
||||
if not _SAFE_SUBDIR.fullmatch(candidate):
|
||||
return None
|
||||
return candidate
|
||||
|
||||
# 兼容旧 import
|
||||
TraceFileWriter = None # set after class definition
|
||||
|
||||
@@ -40,7 +60,7 @@ class PipelineLogWriter:
|
||||
|
||||
def __init__(self, log_dir: str, default_subdir: str = "default"):
|
||||
self._log_dir = log_dir
|
||||
self._default_subdir = default_subdir or "default"
|
||||
self._default_subdir = _safe_subdir(default_subdir) or "default"
|
||||
try:
|
||||
(Path(self._log_dir) / self._default_subdir).mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
@@ -49,7 +69,7 @@ class PipelineLogWriter:
|
||||
def _resolve_subdir(self, user_id: str) -> str:
|
||||
"""从 user_id 的 "{prefix}__{user_id}" 前缀取 prefix 作为子目录;无前缀则回落。"""
|
||||
if user_id and "__" in user_id:
|
||||
prefix = user_id.split("__", 1)[0].strip()
|
||||
prefix = _safe_subdir(user_id.split("__", 1)[0])
|
||||
if prefix:
|
||||
return prefix
|
||||
return self._default_subdir
|
||||
@@ -80,7 +100,11 @@ class PipelineLogWriter:
|
||||
split_namespace_user,
|
||||
)
|
||||
|
||||
tokens = (prompt_tokens or 0) + (completion_tokens or 0) + (total_tokens or 0)
|
||||
# Providers define total_tokens as prompt+completion. Adding all
|
||||
# three fields doubled every cost estimate in this JSONL.
|
||||
tokens = (total_tokens or 0) or (
|
||||
(prompt_tokens or 0) + (completion_tokens or 0)
|
||||
)
|
||||
namespace, uid = split_namespace_user(user_id or "")
|
||||
if not is_llm_content_logging_enabled():
|
||||
prompt = redact_content(prompt)
|
||||
@@ -111,7 +135,14 @@ class PipelineLogWriter:
|
||||
line = json.dumps(record, ensure_ascii=False, default=str)
|
||||
date_str = datetime.now().strftime("%Y-%m-%d")
|
||||
subdir = self._resolve_subdir(user_id)
|
||||
log_dir = Path(self._log_dir) / subdir
|
||||
base_dir = Path(self._log_dir).resolve()
|
||||
log_dir = (base_dir / subdir).resolve()
|
||||
# Defence in depth: even if a future change lets a suspicious
|
||||
# component through, never write outside the configured root.
|
||||
try:
|
||||
log_dir.relative_to(base_dir)
|
||||
except ValueError:
|
||||
log_dir = base_dir / self._default_subdir
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_file = log_dir / f"{date_str}.log"
|
||||
with open(log_file, "a", encoding="utf-8") as f:
|
||||
|
||||
+44
-7
@@ -15,12 +15,12 @@ write、search,并把搜索结果格式化为可交给模型的 memory text ch
|
||||
|
||||
```text
|
||||
distribution: hy-memory
|
||||
version: 2.0.1
|
||||
version: 2.0.3
|
||||
mode: 按运行时配置选择
|
||||
reader: hybrid
|
||||
```
|
||||
|
||||
仓库 pin、lockfile 和运行时版本守卫均固定到公开的 `hy-memory==2.0.1`。
|
||||
仓库 pin、lockfile 和运行时版本守卫均固定到公开的 `hy-memory==2.0.3`。
|
||||
MemHub 在本地 Runtime 内嵌入 SDK,但不绕过自身的来源授权、模型授权、Evidence、
|
||||
Governance 和撤权边界。
|
||||
|
||||
@@ -37,6 +37,40 @@ MemHub 对 SDK 使用以下公开、可复现的本地策略:
|
||||
- API Key 进入系统安全存储,不写入仓库、安装包、日志或 HY metadata;
|
||||
- 服务端数据库、租户队列及宿主 shell 中的 ambient 凭据不会进入 SDK config。
|
||||
|
||||
发布包固定应用以下 SDK 行为配置:
|
||||
|
||||
| 环境变量 | 值 |
|
||||
|---|---|
|
||||
| `MEMORY_MODE` | `ultra` |
|
||||
| `MEMORY_ENABLE_GRAPH` | `true` |
|
||||
| `MEMORY_GRAPH_RERANK_ENABLED` | `false` |
|
||||
| `MEMORY_GRAPH_TEMPORAL_SPINE` | `true` |
|
||||
| `MEMORY_TOPIC_SUMMARY_ENABLED` | `false` |
|
||||
| `MEMORY_EPISODE_SUMMARY_ENABLED` | `false` |
|
||||
| `MEMORY_EPISODE_RECALL_ENABLED` | `true` |
|
||||
| `MEMORY_DYNAMIC_EPISODE_ENABLED` | `true` |
|
||||
| `MEMORY_SESSION_EPISODE_ENABLED` | `false` |
|
||||
| `MEMORY_SESSION_EPISODE_CONTEXT_ENABLED` | `false` |
|
||||
| `MEMORY_EPISODE_CAPSULE_CONTEXT_ENABLED` | `true` |
|
||||
| `MEMORY_EPISODE_CAPSULE_QUERY_MIN` | `0.65` |
|
||||
| `MEMORY_EPISODE_CAPSULE_ASSIGNMENT_MIN` | `0.60` |
|
||||
| `MEMORY_EPISODE_CAPSULE_FIRST_RANK_MAX` | `3` |
|
||||
| `MEMORY_EPISODE_CAPSULE_MEMBER_LIMIT` | `3` |
|
||||
| `MEMORY_ENABLE_INTENTION` | `false` |
|
||||
| `MEMORY_ENABLE_QUERY_REWRITE` | `false` |
|
||||
| `MEMORY_FEW_SHOT_ENABLED` | `true` |
|
||||
| `MEMORY_HYBRID_V2_QUERY_EXPAND` | `1` |
|
||||
| `MEMORY_HYBRID_V2_GEO_INTENT_PRIOR` | `0.6` |
|
||||
| `MEMORY_HYBRID_V2_DIVERSITY` | `1` |
|
||||
| `MEMORY_HYBRID_V2_TEMPORAL_ADMIT_PRIOR` | `0.55` |
|
||||
| `MEMORY_HYBRID_V2_TEMPORAL_BOOST` | `0.18` |
|
||||
| `MEMORY_CROSS_DOMAIN_CON_THRESHOLD` | `0.5` |
|
||||
| `MEMORY_READER_ENABLE_SUMMARY` | `false` |
|
||||
| `MEMORY_SUMMARY_ENABLED_IN_SYS2` | `false` |
|
||||
| `MEMORY_LOCAL_RERANK_ENABLED` | `false` |
|
||||
| `RECONCILE_ENABLED` | `true` |
|
||||
| `HY_MEMORY_READER` | `hybrid` |
|
||||
|
||||
这些默认值集中在
|
||||
`apps/core/src/one_memory/hy_runtime_config.py`,并由发布测试和 lockfile 共同约束。
|
||||
独立脚本若绕过 MemHub 直接导入 SDK,应自行显式配置存储目录和模型端点。
|
||||
@@ -271,9 +305,9 @@ Runtime 应长期复用 client,不为每次请求重新初始化数据库和
|
||||
|
||||
```text
|
||||
Evidence
|
||||
-> ModelProcessingPermissionLease
|
||||
-> HyPermissionTransport
|
||||
-> HyMemoryBridge.ingest / ingest_extracted / search_ids
|
||||
-> HyMemoryBridge
|
||||
-> embedded Hy Memory SDK
|
||||
-> native Vector / Coding / Graph stores
|
||||
-> write result verification
|
||||
-> Governance
|
||||
-> Recall Broker / UI
|
||||
@@ -282,8 +316,11 @@ Evidence
|
||||
不要在新业务模块里直接创建 `HyMemoryClient`,否则会绕过:
|
||||
|
||||
- 来源读取授权;
|
||||
- 模型内容处理授权;
|
||||
- 发送前与响应后的撤权复核;
|
||||
- 共享 Runtime、模型配置、API Key 安全存储与请求预算;
|
||||
- Evidence 引用与作者归属;
|
||||
- 写后回读验证;
|
||||
- Governance 状态、版本、更正和删除级联。
|
||||
|
||||
Hy Memory SDK 是 MemHub 的内置可信组件,可自由访问和管理本机的全部
|
||||
Hy Memory 数据。来源授权仍决定哪些宿主数据可以进入本机;宿主 Recall Grant
|
||||
仍决定哪些外部 AI 应用可以读取治理后的记忆。这两类边界不限制内置 SDK 的本地 CRUD。
|
||||
+22
-8
@@ -1,18 +1,30 @@
|
||||
# MemHub / One Memory
|
||||
# MemHub
|
||||
|
||||
MemHub 是一个本地优先的共享记忆产品:把用户授权的多个 AI 产品中的历史对话和新增内容
|
||||
汇总到同一份记忆,并让这些 AI 在独立授权后复用它。Hy Memory 是 MemHub 使用的 Python
|
||||
SDK 和记忆引擎。One Memory / `one-memory` 是历史模块、数据目录、服务和兼容命令名称。
|
||||
MemHub是一个本地优先的共享记忆产品。它把用户明确授权的AI对话和编码记录汇总到一份本地记忆中,再由用户分别授权给支持的AI工具调用。你可以继续使用熟悉的客户端,同时保留跨工具延续的上下文。Hy Memory是MemHub使用的Python SDK和记忆引擎。
|
||||
|
||||
# 💡❤️ MemHub 刚刚开源,欢迎一起优化共建! ❤️💡
|
||||
|
||||
**# 💭 MemHub处于preview阶段,当前公开版本可以下载和体验,部分平台制品、安装路径与宿主体验仍在持续优化验证。安装前请先查看Release里的实际制品和版本说明。**
|
||||
|
||||
> 🙋 如果你遇到问题/有建议:欢迎提交Issue,并附上MemHub版本、操作系统与芯片架构、复现步骤、预期结果、实际结果和经过脱敏的日志。请不要上传APIKey、真实对话、个人路径或其他敏感信息。
|
||||
|
||||
> 我们会公开跟进可复现的问题,持续发布修复,并根据真实反馈完善安装、同步和召回体验。
|
||||
|
||||
**# 感谢每一条反馈,期待你和我们一起打磨MemHub的体验 :)**
|
||||
|
||||
> 💗 MemHub has just been open-sourced and is under active development. The current public release is available for download andevaluation. Some platform packages, installation paths, and host integrations are still being completed and verified. Check the assets
|
||||
and release notes before installing.
|
||||
If you run into a problem, please open an Issue with the version, platform,reproduction steps, and sanitized logs, We wilreviewreports, publish fixes, and keep the support matrix up to date.
|
||||
|
||||
## 发行与平台合同
|
||||
|
||||
公共 Python SDK 为 `hy-memory==2.0.1`。MemHub 源码版本为 `1.0.0`
|
||||
(build 4),GitHub 仓库为
|
||||
公共 Python SDK 为 `hy-memory==2.0.4`。MemHub 源码版本为 `1.0.4`
|
||||
(build 13),GitHub 仓库为
|
||||
[`Tencent-Hunyuan/Hy-Memory`](https://github.com/Tencent-Hunyuan/Hy-Memory),npm 包名为
|
||||
`memhub-cli`。当前代码架构见
|
||||
[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)。
|
||||
|
||||
`v1.0.0` 的发行目标是 Linux x64/arm64 Runtime 与 macOS arm64/x64 App 和 Runtime。
|
||||
`v1.0.4` 的发行目标是 Linux x64/arm64 Runtime 与 macOS arm64/x64 App 和 Runtime。
|
||||
Linux 制品由 GitHub Actions 在原生架构 runner 上构建并完成生命周期验收;macOS
|
||||
制品由发行流水线完成 Developer ID 签名、公证和验收后手动上传。Windows 不支持。
|
||||
只有同时出现在 GitHub Release 与 `release-manifest.json` 中、且通过公开校验的制品才属于
|
||||
@@ -42,6 +54,8 @@ Linux 制品由 GitHub Actions 在原生架构 runner 上构建并完成生命
|
||||
|
||||
架构详情见 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) 和
|
||||
[`docs/contracts/runtime-unification.md`](docs/contracts/runtime-unification.md)。
|
||||
产品、测试和一线支持排查导入与记忆沉淀时,使用
|
||||
[`docs/PRODUCT_LOG_TROUBLESHOOTING.md`](docs/PRODUCT_LOG_TROUBLESHOOTING.md)。
|
||||
|
||||
## 开发环境
|
||||
|
||||
@@ -99,7 +113,7 @@ MemHub 的 SQLite 数据默认位于 `~/.one-memory`,不在 npm 包或 Runtime
|
||||
|
||||
## Hy Memory
|
||||
|
||||
当前开发依赖固定为公开 PyPI 包 `hy-memory==2.0.1`。SDK 配置、权限边界及 search
|
||||
当前开发依赖固定为公开 PyPI 包 `hy-memory==2.0.4`。SDK 配置、权限边界及 search
|
||||
返回格式见 [`MEMORY.md`](MEMORY.md)。HY search 返回的 `content` 已包含 SDK 统一生成的
|
||||
逻辑时间和演化上下文;调用方不应再次转换时间戳或重复拼接 `When`。
|
||||
|
||||
|
||||
+96
-8
@@ -3,9 +3,9 @@
|
||||
"dataLicense": "CC0-1.0",
|
||||
"SPDXID": "SPDXRef-DOCUMENT",
|
||||
"name": "one-memory",
|
||||
"documentNamespace": "https://one-memory.local/spdx/2026-10-15T17:26:47Z",
|
||||
"documentNamespace": "https://one-memory.local/spdx/2026-10-17T13:52:48Z",
|
||||
"creationInfo": {
|
||||
"created": "2026-10-15T17:26:47Z",
|
||||
"created": "2026-10-17T13:52:48Z",
|
||||
"creators": [
|
||||
"Tool: one-memory-generate-sbom"
|
||||
]
|
||||
@@ -479,6 +479,23 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-pypi-coloredlogs",
|
||||
"name": "coloredlogs",
|
||||
"versionInfo": "15.0.1",
|
||||
"downloadLocation": "NOASSERTION",
|
||||
"filesAnalyzed": false,
|
||||
"licenseConcluded": "NOASSERTION",
|
||||
"licenseDeclared": "NOASSERTION",
|
||||
"copyrightText": "NOASSERTION",
|
||||
"externalRefs": [
|
||||
{
|
||||
"referenceCategory": "PACKAGE-MANAGER",
|
||||
"referenceType": "purl",
|
||||
"referenceLocator": "pkg:pypi/coloredlogs@15.0.1"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-pypi-distro",
|
||||
"name": "distro",
|
||||
@@ -751,6 +768,23 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-pypi-humanfriendly",
|
||||
"name": "humanfriendly",
|
||||
"versionInfo": "10.0",
|
||||
"downloadLocation": "NOASSERTION",
|
||||
"filesAnalyzed": false,
|
||||
"licenseConcluded": "NOASSERTION",
|
||||
"licenseDeclared": "NOASSERTION",
|
||||
"copyrightText": "NOASSERTION",
|
||||
"externalRefs": [
|
||||
{
|
||||
"referenceCategory": "PACKAGE-MANAGER",
|
||||
"referenceType": "purl",
|
||||
"referenceLocator": "pkg:pypi/humanfriendly@10.0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-pypi-idna",
|
||||
"name": "idna",
|
||||
@@ -1125,6 +1159,23 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-pypi-mpmath",
|
||||
"name": "mpmath",
|
||||
"versionInfo": "1.3.0",
|
||||
"downloadLocation": "NOASSERTION",
|
||||
"filesAnalyzed": false,
|
||||
"licenseConcluded": "NOASSERTION",
|
||||
"licenseDeclared": "NOASSERTION",
|
||||
"copyrightText": "NOASSERTION",
|
||||
"externalRefs": [
|
||||
{
|
||||
"referenceCategory": "PACKAGE-MANAGER",
|
||||
"referenceType": "purl",
|
||||
"referenceLocator": "pkg:pypi/mpmath@1.3.0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-pypi-multidict",
|
||||
"name": "multidict",
|
||||
@@ -1230,7 +1281,7 @@
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-pypi-onnxruntime",
|
||||
"name": "onnxruntime",
|
||||
"versionInfo": "1.29.0",
|
||||
"versionInfo": "1.23.2",
|
||||
"downloadLocation": "NOASSERTION",
|
||||
"filesAnalyzed": false,
|
||||
"licenseConcluded": "NOASSERTION",
|
||||
@@ -1240,7 +1291,7 @@
|
||||
{
|
||||
"referenceCategory": "PACKAGE-MANAGER",
|
||||
"referenceType": "purl",
|
||||
"referenceLocator": "pkg:pypi/onnxruntime@1.29.0"
|
||||
"referenceLocator": "pkg:pypi/onnxruntime@1.23.2"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -1992,6 +2043,23 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-pypi-sympy",
|
||||
"name": "sympy",
|
||||
"versionInfo": "1.14.0",
|
||||
"downloadLocation": "NOASSERTION",
|
||||
"filesAnalyzed": false,
|
||||
"licenseConcluded": "NOASSERTION",
|
||||
"licenseDeclared": "NOASSERTION",
|
||||
"copyrightText": "NOASSERTION",
|
||||
"externalRefs": [
|
||||
{
|
||||
"referenceCategory": "PACKAGE-MANAGER",
|
||||
"referenceType": "purl",
|
||||
"referenceLocator": "pkg:pypi/sympy@1.14.0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-pypi-tenacity",
|
||||
"name": "tenacity",
|
||||
@@ -2267,12 +2335,12 @@
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-hy-memory",
|
||||
"name": "hy-memory",
|
||||
"versionInfo": "2.0.1",
|
||||
"versionInfo": "2.0.4",
|
||||
"downloadLocation": "NOASSERTION",
|
||||
"filesAnalyzed": false,
|
||||
"licenseConcluded": "MIT",
|
||||
"licenseDeclared": "MIT",
|
||||
"copyrightText": "Copyright (c) 2025 HY Memory Contributors"
|
||||
"licenseConcluded": "Apache-2.0",
|
||||
"licenseDeclared": "Apache-2.0",
|
||||
"copyrightText": "Copyright (C) 2026 Tencent. All rights reserved."
|
||||
},
|
||||
{
|
||||
"SPDXID": "SPDXRef-Package-memmy-agent-derived",
|
||||
@@ -2427,6 +2495,11 @@
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
"relatedSpdxElement": "SPDXRef-Package-pypi-cloudpickle"
|
||||
},
|
||||
{
|
||||
"spdxElementId": "SPDXRef-Package-one-memory",
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
"relatedSpdxElement": "SPDXRef-Package-pypi-coloredlogs"
|
||||
},
|
||||
{
|
||||
"spdxElementId": "SPDXRef-Package-one-memory",
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
@@ -2507,6 +2580,11 @@
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
"relatedSpdxElement": "SPDXRef-Package-pypi-huggingface-hub"
|
||||
},
|
||||
{
|
||||
"spdxElementId": "SPDXRef-Package-one-memory",
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
"relatedSpdxElement": "SPDXRef-Package-pypi-humanfriendly"
|
||||
},
|
||||
{
|
||||
"spdxElementId": "SPDXRef-Package-one-memory",
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
@@ -2617,6 +2695,11 @@
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
"relatedSpdxElement": "SPDXRef-Package-pypi-more-itertools"
|
||||
},
|
||||
{
|
||||
"spdxElementId": "SPDXRef-Package-one-memory",
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
"relatedSpdxElement": "SPDXRef-Package-pypi-mpmath"
|
||||
},
|
||||
{
|
||||
"spdxElementId": "SPDXRef-Package-one-memory",
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
@@ -2872,6 +2955,11 @@
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
"relatedSpdxElement": "SPDXRef-Package-pypi-starlette"
|
||||
},
|
||||
{
|
||||
"spdxElementId": "SPDXRef-Package-one-memory",
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
"relatedSpdxElement": "SPDXRef-Package-pypi-sympy"
|
||||
},
|
||||
{
|
||||
"spdxElementId": "SPDXRef-Package-one-memory",
|
||||
"relationshipType": "DEPENDS_ON",
|
||||
|
||||
@@ -2,39 +2,79 @@
|
||||
|
||||
MemHub itself is licensed under Apache-2.0 (see `LICENSE`).
|
||||
It bundles the runtime dependencies listed below.
|
||||
Generated from the installed dependency tree on 2026-10-15T17:26:47Z
|
||||
Generated from the installed dependency tree on 2026-10-17T13:52:48Z
|
||||
by `python3 scripts/generate_sbom.py`. Do not edit by hand.
|
||||
|
||||
Per-package license texts are not reproduced here yet; the license
|
||||
column is filled in as part of release review, and the SBOM records
|
||||
`NOASSERTION` until then rather than guessing.
|
||||
|
||||
## hy-memory 2.0.1
|
||||
## hy-memory 2.0.4
|
||||
|
||||
License: MIT
|
||||
License: Apache-2.0
|
||||
|
||||
```text
|
||||
MIT License
|
||||
Tencent is pleased to support the community by making Hy-Memory available.
|
||||
|
||||
Copyright (c) 2025 HY Memory Contributors
|
||||
Copyright (C) 2026 Tencent. All rights reserved.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
Hy-Memory is licensed under Apache-2.0. Hy-Memory does not impose any additional restrictions beyond those specified in the license.
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
For the avoidance of doubt, Hy-Memory refers solely to code, parameters, and weights made publicly available by Tencent in accordance with Apache-2.0.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Terms of the Apache-2.0 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:
|
||||
|
||||
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
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
|
||||
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
|
||||
```
|
||||
|
||||
## MemTensor memmy-agent (adapted)
|
||||
@@ -85,7 +125,7 @@ No Memmy brand, icon, font or mascot assets are distributed.
|
||||
- tar 7.5.22
|
||||
- three 0.185.1
|
||||
|
||||
## Python (PyPI) — 122 packages
|
||||
## Python (PyPI) — 126 packages
|
||||
|
||||
- aiohappyeyeballs 2.7.1
|
||||
- aiohttp 3.14.3
|
||||
@@ -104,6 +144,7 @@ No Memmy brand, icon, font or mascot assets are distributed.
|
||||
- chromadb 1.5.9
|
||||
- click 8.5.0
|
||||
- cloudpickle 3.1.2
|
||||
- coloredlogs 15.0.1
|
||||
- distro 1.9.0
|
||||
- durationpy 0.11
|
||||
- execnet 2.1.2
|
||||
@@ -120,6 +161,7 @@ No Memmy brand, icon, font or mascot assets are distributed.
|
||||
- httptools 0.8.0
|
||||
- httpx 0.28.1
|
||||
- huggingface-hub 1.29.0
|
||||
- humanfriendly 10.0
|
||||
- idna 3.19
|
||||
- importlib-resources 7.1.0
|
||||
- iniconfig 2.3.0
|
||||
@@ -142,13 +184,14 @@ No Memmy brand, icon, font or mascot assets are distributed.
|
||||
- mdurl 0.1.2
|
||||
- mmh3 5.3.0
|
||||
- more-itertools 11.1.0
|
||||
- mpmath 1.3.0
|
||||
- multidict 6.7.1
|
||||
- mypy 2.3.1
|
||||
- mypy-extensions 1.1.0
|
||||
- narwhals 2.25.0
|
||||
- numpy 2.5.2
|
||||
- oauthlib 3.3.1
|
||||
- onnxruntime 1.29.0
|
||||
- onnxruntime 1.23.2
|
||||
- openai 2.54.0
|
||||
- opentelemetry-api 1.44.0
|
||||
- opentelemetry-exporter-otlp-proto-common 1.44.0
|
||||
@@ -193,6 +236,7 @@ No Memmy brand, icon, font or mascot assets are distributed.
|
||||
- six 1.17.0
|
||||
- sniffio 1.3.1
|
||||
- starlette 1.6.0
|
||||
- sympy 1.14.0
|
||||
- tenacity 9.1.4
|
||||
- threadpoolctl 3.6.0
|
||||
- tiktoken 0.14.0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@one-memory/cli",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.4",
|
||||
"description": "MemHub bootstrap CLI for installing and managing the local-first shared memory runtime",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
|
||||
@@ -12,25 +12,23 @@
|
||||
* It is generated rather than hand-written so the two cannot drift: this reads
|
||||
* the real package.json and only strips what is provably not needed at runtime.
|
||||
*/
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const root = resolve(here, "..");
|
||||
const repositoryRoot = resolve(root, "../..");
|
||||
const require = createRequire(import.meta.url);
|
||||
const { resolveBuildVersion } = require("../../../scripts/release-version.cjs");
|
||||
const releaseVersion = resolveBuildVersion(process.env, repositoryRoot);
|
||||
const { assertSemver } = require("../../../scripts/release-version.cjs");
|
||||
const pkgPath = resolve(root, "package.json");
|
||||
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
|
||||
const publishVersion = assertSemver(
|
||||
process.env.MEMHUB_NPM_VERSION?.trim() || pkg.version,
|
||||
"MEMHUB_NPM_VERSION",
|
||||
);
|
||||
const publishName = process.env.MEMHUB_NPM_PACKAGE?.trim();
|
||||
if (
|
||||
!publishName ||
|
||||
!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(publishName)
|
||||
) {
|
||||
if (!publishName || !/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(publishName)) {
|
||||
throw new Error(
|
||||
"MEMHUB_NPM_PACKAGE must name the explicit npm publish identity",
|
||||
);
|
||||
@@ -38,8 +36,12 @@ if (
|
||||
|
||||
const bundle = resolve(root, "dist/one-memory.cjs");
|
||||
const source = readFileSync(bundle, "utf8");
|
||||
const runtimeRequires = [...source.matchAll(/require\(["']([^"']+)["']\)/g)].map((m) => m[1]);
|
||||
const workspaceLeaked = runtimeRequires.filter((name) => name.startsWith("@one-memory/"));
|
||||
const runtimeRequires = [
|
||||
...source.matchAll(/require\(["']([^"']+)["']\)/g),
|
||||
].map((m) => m[1]);
|
||||
const workspaceLeaked = runtimeRequires.filter((name) =>
|
||||
name.startsWith("@one-memory/"),
|
||||
);
|
||||
if (workspaceLeaked.length > 0) {
|
||||
throw new Error(
|
||||
`bundle still requires workspace packages at runtime: ${workspaceLeaked.join(", ")}. ` +
|
||||
@@ -52,7 +54,7 @@ mkdirSync(outDir, { recursive: true });
|
||||
|
||||
const published = { ...pkg };
|
||||
published.name = publishName;
|
||||
published.version = releaseVersion;
|
||||
published.version = publishVersion;
|
||||
for (const section of ["dependencies", "devDependencies", "peerDependencies"]) {
|
||||
if (!published[section]) continue;
|
||||
published[section] = Object.fromEntries(
|
||||
@@ -61,9 +63,7 @@ for (const section of ["dependencies", "devDependencies", "peerDependencies"]) {
|
||||
// else is build-time only. The bundle is inlined (tsup noExternal), so
|
||||
// in practice only Node builtins remain — but compute it rather than
|
||||
// assume, so a future non-inlined dep is not silently dropped.
|
||||
runtimeRequires.some(
|
||||
(req) => req === name || req.startsWith(`${name}/`),
|
||||
),
|
||||
runtimeRequires.some((req) => req === name || req.startsWith(`${name}/`)),
|
||||
),
|
||||
);
|
||||
if (Object.keys(published[section]).length === 0) delete published[section];
|
||||
@@ -77,8 +77,15 @@ published.files = ["dist", "scripts", "package.json"];
|
||||
// in the staging dir overrides that and makes the manifest authoritative.
|
||||
writeFileSync(
|
||||
resolve(outDir, ".npmignore"),
|
||||
["# Ship the built bundle: the repo root .gitignore excludes dist/.", "!dist/", ""].join("\n"),
|
||||
[
|
||||
"# Ship the built bundle: the repo root .gitignore excludes dist/.",
|
||||
"!dist/",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
writeFileSync(resolve(outDir, "package.json"), `${JSON.stringify(published, null, 2)}\n`);
|
||||
writeFileSync(
|
||||
resolve(outDir, "package.json"),
|
||||
`${JSON.stringify(published, null, 2)}\n`,
|
||||
);
|
||||
console.log("wrote", resolve(outDir, "package.json"));
|
||||
@@ -20,11 +20,7 @@ import { pathToFileURL } from "node:url";
|
||||
|
||||
const REQUIRED_ALIASES = {
|
||||
daemon: ["start", "stop", "restart", "status"],
|
||||
"startup-service": [
|
||||
"service-plan",
|
||||
"service-install",
|
||||
"service-uninstall",
|
||||
],
|
||||
"startup-service": ["service-plan", "service-install", "service-uninstall"],
|
||||
};
|
||||
|
||||
const REQUIRED_COMMAND_SURFACE = [
|
||||
@@ -36,7 +32,6 @@ const REQUIRED_COMMAND_SURFACE = [
|
||||
"calls",
|
||||
"import-file",
|
||||
"notes",
|
||||
"permission",
|
||||
"extraction",
|
||||
"graph",
|
||||
"models",
|
||||
@@ -81,7 +76,7 @@ const REQUIRED_MARKERS = [
|
||||
|
||||
/**
|
||||
* Sub-commands the UI-write parity work added. A package can declare the
|
||||
* parent command (`permission`, `models`) while still missing the new verb, so
|
||||
* parent command (`models`) while still missing the new verb, so
|
||||
* checking command names alone would pass a stale bundle. The marker is the
|
||||
* exact literal the catalog usage string contains.
|
||||
*/
|
||||
@@ -92,9 +87,6 @@ const REQUIRED_SUBCOMMANDS = [
|
||||
{ command: "import-file", marker: "memhub import-file discard" },
|
||||
{ command: "notes", marker: "memhub notes add" },
|
||||
{ command: "notes", marker: "memhub notes process" },
|
||||
{ command: "permission", marker: "memhub permission status" },
|
||||
{ command: "permission", marker: "memhub permission allow" },
|
||||
{ command: "permission", marker: "memhub permission deny" },
|
||||
{ command: "extraction", marker: "memhub extraction set" },
|
||||
{ command: "graph", marker: "memhub graph width" },
|
||||
{ command: "models", marker: "memhub models edit" },
|
||||
@@ -112,19 +104,83 @@ const REQUIRED_SUBCOMMANDS = [
|
||||
* These run without `--lifecycle`, so they are safe against any package.
|
||||
*/
|
||||
const STOPPED_DESTRUCTIVE_PROBES = [
|
||||
{ name: "calls_clear_preview", args: ["calls", "clear", "--event", "11111111-1111-4111-8111-111111111111"] },
|
||||
{ name: "calls_clear_apply", args: ["calls", "clear", "--event", "11111111-1111-4111-8111-111111111111", "--confirm"] },
|
||||
{ name: "calls_clear_all_apply", args: ["calls", "clear", "--all", "--confirm"] },
|
||||
{ name: "import_file_commit_apply", args: ["import-file", "commit", "22222222-2222-4222-8222-222222222222", "--confirm"] },
|
||||
{ name: "import_file_discard_apply", args: ["import-file", "discard", "22222222-2222-4222-8222-222222222222", "--confirm"] },
|
||||
{ name: "notes_process_apply", args: ["notes", "process", "33333333-3333-4333-8333-333333333333", "--confirm"] },
|
||||
{ name: "permission_allow", args: ["permission", "allow"] },
|
||||
{ name: "permission_deny", args: ["permission", "deny"] },
|
||||
{ name: "extraction_set_apply", args: ["extraction", "set", "--window", "6m", "--confirm"] },
|
||||
{ name: "graph_width_apply", args: ["graph", "width", "--decision", "keep_existing", "--confirm"] },
|
||||
{ name: "processing_extract_apply", args: ["processing", "extract", "--confirm"] },
|
||||
{ name: "models_activate_apply", args: ["models", "activate", "44444444-4444-4444-8444-444444444444", "--confirm"] },
|
||||
{ name: "models_edit_apply", args: ["models", "edit", "44444444-4444-4444-8444-444444444444", "--config-file", "/nonexistent/patch.json", "--confirm"] },
|
||||
{
|
||||
name: "calls_clear_preview",
|
||||
args: ["calls", "clear", "--event", "11111111-1111-4111-8111-111111111111"],
|
||||
},
|
||||
{
|
||||
name: "calls_clear_apply",
|
||||
args: [
|
||||
"calls",
|
||||
"clear",
|
||||
"--event",
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
"--confirm",
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "calls_clear_all_apply",
|
||||
args: ["calls", "clear", "--all", "--confirm"],
|
||||
},
|
||||
{
|
||||
name: "import_file_commit_apply",
|
||||
args: [
|
||||
"import-file",
|
||||
"commit",
|
||||
"22222222-2222-4222-8222-222222222222",
|
||||
"--confirm",
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "import_file_discard_apply",
|
||||
args: [
|
||||
"import-file",
|
||||
"discard",
|
||||
"22222222-2222-4222-8222-222222222222",
|
||||
"--confirm",
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "notes_process_apply",
|
||||
args: [
|
||||
"notes",
|
||||
"process",
|
||||
"33333333-3333-4333-8333-333333333333",
|
||||
"--confirm",
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "extraction_set_apply",
|
||||
args: ["extraction", "set", "--window", "6m", "--confirm"],
|
||||
},
|
||||
{
|
||||
name: "graph_width_apply",
|
||||
args: ["graph", "width", "--decision", "keep_existing", "--confirm"],
|
||||
},
|
||||
{
|
||||
name: "processing_extract_apply",
|
||||
args: ["processing", "extract", "--confirm"],
|
||||
},
|
||||
{
|
||||
name: "models_activate_apply",
|
||||
args: [
|
||||
"models",
|
||||
"activate",
|
||||
"44444444-4444-4444-8444-444444444444",
|
||||
"--confirm",
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "models_edit_apply",
|
||||
args: [
|
||||
"models",
|
||||
"edit",
|
||||
"44444444-4444-4444-8444-444444444444",
|
||||
"--config-file",
|
||||
"/nonexistent/patch.json",
|
||||
"--confirm",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export function validateCatalog(document) {
|
||||
@@ -201,7 +257,9 @@ export async function runPackageMatrix(runtimeDist, options = {}) {
|
||||
const markers = REQUIRED_MARKERS.filter(
|
||||
(marker) => !bundle.toString("utf8").includes(marker),
|
||||
);
|
||||
const isolatedRoot = await mkdtemp(path.join(tmpdir(), "memhub-package-matrix-"));
|
||||
const isolatedRoot = await mkdtemp(
|
||||
path.join(tmpdir(), "memhub-package-matrix-"),
|
||||
);
|
||||
const home = path.join(isolatedRoot, "home");
|
||||
const dataDir = path.join(isolatedRoot, "data");
|
||||
const hostHome = path.join(isolatedRoot, "host-home");
|
||||
@@ -343,7 +401,10 @@ async function runStoppedDestructive(node, cli, environment) {
|
||||
`${probe.name} exit ${result.code}, expected 3 while Runtime is stopped`,
|
||||
);
|
||||
}
|
||||
if (document?.state !== "unknown" || document?.code !== "runtime_not_running") {
|
||||
if (
|
||||
document?.state !== "unknown" ||
|
||||
document?.code !== "runtime_not_running"
|
||||
) {
|
||||
failures.push(
|
||||
`${probe.name} did not fail closed with unknown/runtime_not_running`,
|
||||
);
|
||||
@@ -451,8 +512,7 @@ async function main() {
|
||||
}
|
||||
const asJson = rest.includes("--json");
|
||||
const expectShaIndex = rest.indexOf("--expect-sha");
|
||||
const expectSha =
|
||||
expectShaIndex >= 0 ? rest[expectShaIndex + 1] : undefined;
|
||||
const expectSha = expectShaIndex >= 0 ? rest[expectShaIndex + 1] : undefined;
|
||||
if (expectSha !== undefined && !/^[0-9a-fA-F]{64}$/.test(expectSha)) {
|
||||
process.stderr.write("--expect-sha must be a 64-character SHA-256\n");
|
||||
process.exitCode = 2;
|
||||
|
||||
@@ -30,12 +30,16 @@ describe("managed restore over HTTP", { timeout: 15_000 }, () => {
|
||||
}
|
||||
if (request.headers.authorization === "Bearer r409") {
|
||||
response.statusCode = 409;
|
||||
response.end(JSON.stringify({ detail: "backup_restore_runtime_running" }));
|
||||
response.end(
|
||||
JSON.stringify({ detail: "backup_restore_runtime_running" }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (request.headers.authorization === "Bearer r422") {
|
||||
response.statusCode = 422;
|
||||
response.end(JSON.stringify({ detail: "backup_restore_source_outside_home" }));
|
||||
response.end(
|
||||
JSON.stringify({ detail: "backup_restore_source_outside_home" }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
response.end(
|
||||
@@ -48,9 +52,12 @@ describe("managed restore over HTTP", { timeout: 15_000 }, () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
await new Promise<void>((resolve) =>
|
||||
server.listen(0, "127.0.0.1", resolve),
|
||||
);
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string") throw new Error("no port");
|
||||
if (address === null || typeof address === "string")
|
||||
throw new Error("no port");
|
||||
port = address.port;
|
||||
});
|
||||
|
||||
@@ -137,8 +144,18 @@ describe("maintenance Core identity", { timeout: 15_000 }, () => {
|
||||
|
||||
it("rejects a squatter, wrong service, wrong instance, and non-200", async () => {
|
||||
const cases = [
|
||||
{ status: 200, data: { status: "ok", service: "other", instance_id: "x" } },
|
||||
{ status: 200, data: { status: "ok", service: "one-memory-core", instance_id: "wrong" } },
|
||||
{
|
||||
status: 200,
|
||||
data: { status: "ok", service: "other", instance_id: "x" },
|
||||
},
|
||||
{
|
||||
status: 200,
|
||||
data: {
|
||||
status: "ok",
|
||||
service: "one-memory-core",
|
||||
instance_id: "wrong",
|
||||
},
|
||||
},
|
||||
{ status: 503, data: {} },
|
||||
{ status: 200, data: null },
|
||||
];
|
||||
|
||||
@@ -91,7 +91,8 @@ export async function callRestore(
|
||||
source: string,
|
||||
request: typeof defaultPost = defaultPost,
|
||||
): Promise<
|
||||
{ state: "restored"; result: RestoreResult } | { state: "rejected"; code: string }
|
||||
| { state: "restored"; result: RestoreResult }
|
||||
| { state: "rejected"; code: string }
|
||||
> {
|
||||
const response = await request(
|
||||
`http://${options.host}:${options.port}/api/v1/backup/restore`,
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { CoreReader, ReadOutcome } from "./core-client.js";
|
||||
import type { CoreOperations } from "./core-operations.js";
|
||||
import {
|
||||
batchScanExitCode,
|
||||
executeBatchImport,
|
||||
planBatchImport,
|
||||
renderBatchScanText,
|
||||
} from "./batch-import-flow.js";
|
||||
import type { CoreReader, ReadOutcome } from "./core-client.js";
|
||||
import type { CoreOperations } from "./core-operations.js";
|
||||
|
||||
function readerFor(catalog: unknown): CoreReader {
|
||||
return (async (path: string) =>
|
||||
path === "/api/v1/sources"
|
||||
? ({ state: "ok", data: catalog } as ReadOutcome<unknown>)
|
||||
: ({ state: "not_found", code: "http_404" } as ReadOutcome<unknown>)) as CoreReader;
|
||||
: ({
|
||||
state: "not_found",
|
||||
code: "http_404",
|
||||
} as ReadOutcome<unknown>)) as CoreReader;
|
||||
}
|
||||
|
||||
function found(source_id: string, extra: Record<string, unknown> = {}) {
|
||||
@@ -81,18 +83,36 @@ describe("A19 batch execution", () => {
|
||||
readerFor([found("codex"), found("cursor")]),
|
||||
);
|
||||
if (planned.state !== "preview") throw new Error("expected preview");
|
||||
const post = vi.fn(async (_path: string, body: Record<string, unknown>) => ({
|
||||
state: "committed" as const,
|
||||
data: {
|
||||
request_id: body.request_id,
|
||||
accepted_source_ids: ["codex", "cursor"],
|
||||
failed_sources: {},
|
||||
jobs: [
|
||||
{ job_id: "j1", source_id: "codex", status: "pending", discovered: 3, stored: 3, errors: 0, operation: "history" },
|
||||
{ job_id: "j2", source_id: "cursor", status: "pending", discovered: 5, stored: 5, errors: 0, operation: "history" },
|
||||
],
|
||||
},
|
||||
}));
|
||||
const post = vi.fn(
|
||||
async (_path: string, body: Record<string, unknown>) => ({
|
||||
state: "committed" as const,
|
||||
data: {
|
||||
request_id: body.request_id,
|
||||
accepted_source_ids: ["codex", "cursor"],
|
||||
failed_sources: {},
|
||||
jobs: [
|
||||
{
|
||||
job_id: "j1",
|
||||
source_id: "codex",
|
||||
status: "pending",
|
||||
discovered: 3,
|
||||
stored: 3,
|
||||
errors: 0,
|
||||
operation: "history",
|
||||
},
|
||||
{
|
||||
job_id: "j2",
|
||||
source_id: "cursor",
|
||||
status: "pending",
|
||||
discovered: 5,
|
||||
stored: 5,
|
||||
errors: 0,
|
||||
operation: "history",
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const operations = { post } as unknown as CoreOperations;
|
||||
const document = await executeBatchImport(
|
||||
planned.candidates,
|
||||
@@ -127,7 +147,15 @@ describe("A19 batch execution", () => {
|
||||
accepted_source_ids: ["codex"],
|
||||
failed_sources: { cursor: "source_identity_changed" },
|
||||
jobs: [
|
||||
{ job_id: "j1", source_id: "codex", status: "pending", discovered: 1, stored: 1, errors: 0, operation: "history" },
|
||||
{
|
||||
job_id: "j1",
|
||||
source_id: "codex",
|
||||
status: "pending",
|
||||
discovered: 1,
|
||||
stored: 1,
|
||||
errors: 0,
|
||||
operation: "history",
|
||||
},
|
||||
],
|
||||
},
|
||||
})),
|
||||
@@ -242,7 +270,15 @@ describe("A19 batch execution", () => {
|
||||
accepted_source_ids: ["codex"],
|
||||
failed_sources: {},
|
||||
jobs: [
|
||||
{ job_id: "j1", source_id: "codex", status: "pending", discovered: 1, stored: 1, errors: 0, operation: "history" },
|
||||
{
|
||||
job_id: "j1",
|
||||
source_id: "codex",
|
||||
status: "pending",
|
||||
discovered: 1,
|
||||
stored: 1,
|
||||
errors: 0,
|
||||
operation: "history",
|
||||
},
|
||||
],
|
||||
},
|
||||
})),
|
||||
|
||||
@@ -14,15 +14,14 @@
|
||||
*/
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { buildSourceImportRequest } from "@one-memory/operations";
|
||||
|
||||
import type { ImportJob } from "@one-memory/contracts";
|
||||
import { buildSourceImportRequest } from "@one-memory/operations";
|
||||
import type { CoreReader } from "./core-client.js";
|
||||
import type { CoreOperations } from "./core-operations.js";
|
||||
import {
|
||||
type SourceConnectionCandidate,
|
||||
validateSourceConnectionCandidates,
|
||||
} from "./core-responses.js";
|
||||
import type { CoreReader } from "./core-client.js";
|
||||
import type { CoreOperations } from "./core-operations.js";
|
||||
import { PRODUCT } from "./version.js";
|
||||
|
||||
export interface BatchSourceRow {
|
||||
@@ -57,19 +56,34 @@ export function detectedSourceIds(
|
||||
return candidates.map((candidate) => candidate.source_id);
|
||||
}
|
||||
|
||||
export async function planBatchImport(
|
||||
reader: CoreReader,
|
||||
): Promise<
|
||||
| { state: "preview"; candidates: SourceConnectionCandidate[]; rows: BatchSourceRow[]; notFound: string[] }
|
||||
| { state: "rejected" | "unknown" | "no_sources"; code: string; notFound: string[] }
|
||||
export async function planBatchImport(reader: CoreReader): Promise<
|
||||
| {
|
||||
state: "preview";
|
||||
candidates: SourceConnectionCandidate[];
|
||||
rows: BatchSourceRow[];
|
||||
notFound: string[];
|
||||
}
|
||||
| {
|
||||
state: "rejected" | "unknown" | "no_sources";
|
||||
code: string;
|
||||
notFound: string[];
|
||||
}
|
||||
> {
|
||||
const outcome = await reader<unknown>("/api/v1/sources");
|
||||
if (outcome.state !== "ok") {
|
||||
return { state: outcome.state === "unavailable" ? "unknown" : "rejected", code: outcome.code, notFound: [] };
|
||||
return {
|
||||
state: outcome.state === "unavailable" ? "unknown" : "rejected",
|
||||
code: outcome.code,
|
||||
notFound: [],
|
||||
};
|
||||
}
|
||||
const catalog = outcome.data;
|
||||
if (!Array.isArray(catalog) || catalog.length > SOURCE_LIST_LIMIT) {
|
||||
return { state: "rejected", code: "sources_response_invalid", notFound: [] };
|
||||
return {
|
||||
state: "rejected",
|
||||
code: "sources_response_invalid",
|
||||
notFound: [],
|
||||
};
|
||||
}
|
||||
const candidates = validateSourceConnectionCandidates(catalog);
|
||||
if (!candidates) {
|
||||
@@ -165,9 +179,7 @@ export async function executeBatchImport(
|
||||
receipt.failed_sources && typeof receipt.failed_sources === "object"
|
||||
? (receipt.failed_sources as Record<string, string>)
|
||||
: {};
|
||||
const jobs = Array.isArray(receipt.jobs)
|
||||
? (receipt.jobs as ImportJob[])
|
||||
: [];
|
||||
const jobs = Array.isArray(receipt.jobs) ? (receipt.jobs as ImportJob[]) : [];
|
||||
const firstSeen = jobs.map((job) => ({
|
||||
source_id: job.source_id,
|
||||
discovered: job.discovered,
|
||||
@@ -262,7 +274,8 @@ export async function executeBatchImport(
|
||||
}
|
||||
|
||||
export function batchScanExitCode(document: BatchScanDocument): number {
|
||||
if (document.state === "committed" || document.state === "no_sources") return 0;
|
||||
if (document.state === "committed" || document.state === "no_sources")
|
||||
return 0;
|
||||
if (document.state === "partial") return 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
+49
-84
@@ -4,7 +4,11 @@ import { createReadStream } from "node:fs";
|
||||
import { access } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { HealthResponse, ImportJob } from "@one-memory/contracts";
|
||||
import {
|
||||
type HealthResponse,
|
||||
type ImportJob,
|
||||
isHostId,
|
||||
} from "@one-memory/contracts";
|
||||
import {
|
||||
type AcquiredRuntimeDistribution,
|
||||
acquireRuntimeDistribution,
|
||||
@@ -81,6 +85,7 @@ import {
|
||||
readMemoryWrite,
|
||||
readScanRoots,
|
||||
removeScanRoot,
|
||||
resetOnboarding,
|
||||
submitBackup,
|
||||
submitMemoryWrite,
|
||||
submitScan,
|
||||
@@ -190,13 +195,6 @@ import {
|
||||
renderMemoryDetailText,
|
||||
renderMemoryPageText,
|
||||
} from "./memory-report.js";
|
||||
import {
|
||||
type ModelContentPermissionDocument,
|
||||
modelContentPermissionExitCode,
|
||||
readModelContentPermission,
|
||||
renderModelContentPermissionText,
|
||||
setModelContentPermission,
|
||||
} from "./model-content-permission-flow.js";
|
||||
import {
|
||||
executeModelProbe,
|
||||
inspectModelProbePlan,
|
||||
@@ -217,12 +215,10 @@ import {
|
||||
executeModelProfileActivate,
|
||||
executeModelProfileEdit,
|
||||
type ModelWriteDocument,
|
||||
type ModelWritePlan,
|
||||
modelWriteExitCode,
|
||||
planModelProfileActivate,
|
||||
planModelProfileEdit,
|
||||
renderModelWriteText,
|
||||
validateModelWritePlan,
|
||||
} from "./model-write-flows.js";
|
||||
import { claimPlanAttempt } from "./operation-journal.js";
|
||||
import {
|
||||
@@ -339,7 +335,7 @@ import {
|
||||
renderVersion,
|
||||
renderVersionDocument,
|
||||
} from "./usage.js";
|
||||
import { CLI_VERSION, PRODUCT } from "./version.js";
|
||||
import { CLI_VERSION, PRODUCT, RUNTIME_RELEASE_VERSION } from "./version.js";
|
||||
import { runWatchLoop, type WatchEvent, type WatchRead } from "./watch-loop.js";
|
||||
|
||||
export interface RunControls {
|
||||
@@ -425,7 +421,8 @@ async function selectInstallSource(
|
||||
throw new Error("release_manifest_url_unavailable");
|
||||
}
|
||||
const manifestUrl =
|
||||
explicitManifestUrl ?? template.replaceAll("{version}", CLI_VERSION);
|
||||
explicitManifestUrl ??
|
||||
template.replaceAll("{version}", RUNTIME_RELEASE_VERSION);
|
||||
const allowedHosts = parseAllowedReleaseHosts(
|
||||
environment.MEMHUB_RELEASE_ALLOWED_HOSTS,
|
||||
);
|
||||
@@ -470,7 +467,7 @@ async function resolveRemoteInstallPreview(
|
||||
): Promise<ResolvedRuntimeRelease> {
|
||||
return (controls.resolveRuntimeRelease ?? resolveRuntimeRelease)({
|
||||
manifestUrl: selection.manifestUrl,
|
||||
expectedVersion: CLI_VERSION,
|
||||
expectedVersion: RUNTIME_RELEASE_VERSION,
|
||||
channel: selection.channel,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
@@ -484,7 +481,7 @@ async function acquireRemoteInstallSource(
|
||||
): Promise<AcquiredRuntimeDistribution> {
|
||||
return (controls.acquireRuntimeDistribution ?? acquireRuntimeDistribution)({
|
||||
manifestUrl: selection.manifestUrl,
|
||||
expectedVersion: CLI_VERSION,
|
||||
expectedVersion: RUNTIME_RELEASE_VERSION,
|
||||
channel: selection.channel,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
@@ -697,6 +694,36 @@ async function runCommand(
|
||||
// `path list` and `adapter list` are read-only: they have no plan to confirm,
|
||||
// so they are answered here rather than falling into the two-phase branch
|
||||
// (which would reject them for having nothing to apply).
|
||||
// Back to the cold-start screens on purpose. Deleting the app cannot do this
|
||||
// (the completion flag lives with the memories, by design), and deleting the
|
||||
// data to get there would cost the user everything they have stored.
|
||||
if (named === "onboarding" && arguments_.includes("reset")) {
|
||||
if (
|
||||
arguments_.filter((item) => item === "--json").length > 1 ||
|
||||
arguments_.filter((item) => item !== "--json").join(" ") !==
|
||||
"onboarding reset"
|
||||
) {
|
||||
return usage();
|
||||
}
|
||||
const attachment = await attachToRuntime(
|
||||
resolveRuntimeCliConfig(environment, process.argv[1]).dataDir,
|
||||
);
|
||||
if (attachment === null) {
|
||||
return runtimeUnavailable(descriptor, asJson);
|
||||
}
|
||||
const state = await resetOnboarding(attachment);
|
||||
if (state === null) {
|
||||
return reject(descriptor, asJson, "引导状态端点不可用。");
|
||||
}
|
||||
if (asJson) {
|
||||
process.stdout.write(`${JSON.stringify(state)}\n`);
|
||||
return EXIT_OK;
|
||||
}
|
||||
process.stdout.write(
|
||||
`引导流程已回到首次运行(status=${state.status}),记忆数据未改动。\n`,
|
||||
);
|
||||
return EXIT_OK;
|
||||
}
|
||||
if (named === "path" && arguments_.includes("list")) {
|
||||
if (
|
||||
arguments_.filter((item) => item === "--json").length > 1 ||
|
||||
@@ -2462,45 +2489,6 @@ async function runCommand(
|
||||
);
|
||||
return uiWriteExitCode(document);
|
||||
}
|
||||
if (named === "permission") {
|
||||
const parsed = parsePermissionCommand(arguments_.slice(1));
|
||||
if (!parsed) return usage();
|
||||
const config = resolveRuntimeCliConfig(environment, process.argv[1]);
|
||||
const runtime = await inspectRuntimeStatus({
|
||||
dataDir: config.dataDir,
|
||||
probeIdentity,
|
||||
requireServiceReceipt: true,
|
||||
});
|
||||
const attached =
|
||||
runtime.state === "running"
|
||||
? await attachClients(config.dataDir)
|
||||
: { reader: null, operations: null, failure: runtime.code };
|
||||
if (
|
||||
runtime.state !== "running" ||
|
||||
(parsed === "status" ? !attached.reader : !attached.operations)
|
||||
) {
|
||||
const document: ModelContentPermissionDocument = {
|
||||
schema_version: 1,
|
||||
product: PRODUCT,
|
||||
state: "unknown",
|
||||
code:
|
||||
runtime.state !== "running"
|
||||
? runtime.code
|
||||
: (attached.failure ?? "runtime_attach_failed"),
|
||||
};
|
||||
emitModelContentPermissionDocument(document, asJson);
|
||||
return runtime.state === "stopped" ? 3 : 1;
|
||||
}
|
||||
const document =
|
||||
parsed === "status"
|
||||
? await readModelContentPermission(attached.reader!)
|
||||
: await setModelContentPermission(
|
||||
attached.operations!,
|
||||
parsed === "allow",
|
||||
);
|
||||
emitModelContentPermissionDocument(document, asJson);
|
||||
return modelContentPermissionExitCode(document);
|
||||
}
|
||||
if (named === "notes" || named === "extraction" || named === "graph") {
|
||||
const parsed = parseExtendedWriteCommand(
|
||||
named as "notes" | "extraction" | "graph",
|
||||
@@ -5124,18 +5112,6 @@ function parseHeadlessCommand(
|
||||
: null;
|
||||
}
|
||||
|
||||
function parsePermissionCommand(
|
||||
rest: readonly string[],
|
||||
): "status" | "allow" | "deny" | null {
|
||||
if (rest.filter((item) => item === "--json").length > 1) return null;
|
||||
const tokens = rest.filter((item) => item !== "--json");
|
||||
const action = tokens[0];
|
||||
return tokens.length === 1 &&
|
||||
(action === "status" || action === "allow" || action === "deny")
|
||||
? action
|
||||
: null;
|
||||
}
|
||||
|
||||
function unwrapPlan(value: unknown): unknown {
|
||||
if (
|
||||
value &&
|
||||
@@ -5184,10 +5160,10 @@ type HostCommand =
|
||||
args: unknown[];
|
||||
};
|
||||
|
||||
// `deepseek-harness:web` is a real id — that host is configured per profile —
|
||||
// and `host list` prints it. Rejecting it here would mean listing a host the
|
||||
// CLI then refuses to act on.
|
||||
const HOST_ID = /^[a-z0-9][a-z0-9-]{0,31}(:[a-z0-9][a-z0-9-]{0,31})?$/;
|
||||
// Host ids are read with the same grammar as the permission layer and the
|
||||
// grant store (`@one-memory/contracts`): `deepseek-harness:web` is a real id —
|
||||
// that host is configured per profile — and `host list` prints it, so rejecting
|
||||
// it here would mean listing a host the CLI then refuses to act on.
|
||||
const FINGERPRINT = /^[0-9a-f]{64}$/;
|
||||
|
||||
/** Host subcommands.
|
||||
@@ -5210,7 +5186,7 @@ function parseHostCommand(rest: readonly string[]): HostCommand | null {
|
||||
const token = tokens[index];
|
||||
if (token === "--host") {
|
||||
const value = tokens[index + 1];
|
||||
if (!value || !HOST_ID.test(value)) return null;
|
||||
if (!value || !isHostId(value)) return null;
|
||||
if (hostId !== undefined) return null;
|
||||
hostId = value;
|
||||
index += 1;
|
||||
@@ -5243,7 +5219,7 @@ function parseHostCommand(rest: readonly string[]): HostCommand | null {
|
||||
qualifier !== undefined &&
|
||||
(verb === "status" || verb === "install" || verb === "uninstall")
|
||||
) {
|
||||
if (!HOST_ID.test(qualifier)) return null;
|
||||
if (!isHostId(qualifier)) return null;
|
||||
hostId = qualifier;
|
||||
// Drop the consumed host positional so the verb/qualifier checks below see
|
||||
// the same shape as the flag form.
|
||||
@@ -5259,7 +5235,7 @@ function parseHostCommand(rest: readonly string[]): HostCommand | null {
|
||||
positional[2] !== undefined
|
||||
) {
|
||||
const trailing = positional[2];
|
||||
if (!HOST_ID.test(trailing)) return null;
|
||||
if (!isHostId(trailing)) return null;
|
||||
hostId = trailing;
|
||||
positional.splice(2, 1);
|
||||
verb = positional[0];
|
||||
@@ -5323,17 +5299,6 @@ function emitModelReportDocument(
|
||||
);
|
||||
}
|
||||
|
||||
function emitModelContentPermissionDocument(
|
||||
document: ModelContentPermissionDocument,
|
||||
asJson: boolean,
|
||||
): void {
|
||||
process.stdout.write(
|
||||
asJson
|
||||
? `${JSON.stringify(document)}\n`
|
||||
: renderModelContentPermissionText(document),
|
||||
);
|
||||
}
|
||||
|
||||
function emitSourceSyncDocument(
|
||||
document: SourceSyncFlowDocument,
|
||||
asJson: boolean,
|
||||
@@ -6560,7 +6525,7 @@ function parseInstallOptions(
|
||||
...(releaseManifestUrl ? { releaseManifestUrl } : {}),
|
||||
releaseChannel:
|
||||
releaseChannel ??
|
||||
(CLI_VERSION.includes("-") ? "prerelease" : "stable"),
|
||||
(RUNTIME_RELEASE_VERSION.includes("-") ? "prerelease" : "stable"),
|
||||
installRoot: resolvedInstallRoot,
|
||||
home: resolvedHome,
|
||||
uid: uid ?? process.getuid?.(),
|
||||
|
||||
@@ -282,11 +282,7 @@ export const COMMANDS: readonly CommandDescriptor[] = [
|
||||
summary: "列出来源、执行已确认的导入计划。",
|
||||
usage:
|
||||
"memhub sources list [--json]\n memhub sources import --plan-file <path> --confirm [--json]\n memhub sources receipt <request-id> [--json]",
|
||||
options: [
|
||||
PLAN_FILE_OPTION,
|
||||
EXPLICIT_CONFIRM_OPTION,
|
||||
JSON_OPTION,
|
||||
],
|
||||
options: [PLAN_FILE_OPTION, EXPLICIT_CONFIRM_OPTION, JSON_OPTION],
|
||||
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
|
||||
},
|
||||
{
|
||||
@@ -497,14 +493,6 @@ export const COMMANDS: readonly CommandDescriptor[] = [
|
||||
],
|
||||
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
|
||||
},
|
||||
{
|
||||
name: "permission",
|
||||
summary: "读取或直接设置全局模型内容外发许可。",
|
||||
usage:
|
||||
"memhub permission status [--json]\n memhub permission allow [--json]\n memhub permission deny [--json]",
|
||||
options: [JSON_OPTION],
|
||||
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
|
||||
},
|
||||
{
|
||||
name: "extraction",
|
||||
summary: "设置提取窗口;默认只出计划,--confirm 后才写入。",
|
||||
@@ -663,6 +651,14 @@ export const COMMANDS: readonly CommandDescriptor[] = [
|
||||
],
|
||||
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_PLAN_BLOCKED],
|
||||
},
|
||||
{
|
||||
name: "onboarding",
|
||||
summary:
|
||||
"onboarding reset 回到首次运行的引导流程。只清除引导完成状态:不删记忆数据,也不需要卸载重装。",
|
||||
usage: "memhub onboarding reset [--json]",
|
||||
options: [JSON_OPTION],
|
||||
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE],
|
||||
},
|
||||
{
|
||||
name: "help",
|
||||
summary: "显示总帮助或单个命令的用法。",
|
||||
|
||||
@@ -81,7 +81,6 @@ const COMMANDS = [
|
||||
"calls",
|
||||
"import-file",
|
||||
"notes",
|
||||
"permission",
|
||||
"extraction",
|
||||
"graph",
|
||||
"host",
|
||||
@@ -93,6 +92,7 @@ const COMMANDS = [
|
||||
"uninstall",
|
||||
"upgrade",
|
||||
"delete-data",
|
||||
"onboarding",
|
||||
"help",
|
||||
"version",
|
||||
// A6 product commands. Appended, not inserted: the catalog is a stable
|
||||
@@ -259,7 +259,14 @@ describe("CLI-22 shared output contract", () => {
|
||||
|
||||
describe("argument validation", () => {
|
||||
it("fails unknown commands without printing data or running anything", async () => {
|
||||
for (const argv of [["unknown"], ["unknown", "--help"], ["--typo"]]) {
|
||||
for (const argv of [
|
||||
["unknown"],
|
||||
["unknown", "--help"],
|
||||
["--typo"],
|
||||
["permission", "status"],
|
||||
["permission", "allow"],
|
||||
["permission", "deny"],
|
||||
]) {
|
||||
const streams = captureStreams();
|
||||
try {
|
||||
expect(await run(argv, {})).toBe(2);
|
||||
@@ -300,11 +307,7 @@ describe("CLI-22 shared output contract", () => {
|
||||
`${PRODUCT} sync`,
|
||||
],
|
||||
[
|
||||
[
|
||||
"sync",
|
||||
"receipt",
|
||||
"123e4567-e89b-12d3-a456-426614174000",
|
||||
],
|
||||
["sync", "receipt", "123e4567-e89b-12d3-a456-426614174000"],
|
||||
`${PRODUCT} sync`,
|
||||
],
|
||||
[["sync", "pause", "--source"], `${PRODUCT} sync`],
|
||||
@@ -555,12 +558,7 @@ describe("documented commands", () => {
|
||||
// Source processing is one Freeze/Thaw switch under `sync`; the obsolete
|
||||
// independent read/write `sources access` command must not return here.
|
||||
sources: ["list", "import", "receipt"],
|
||||
jobs: [
|
||||
"list",
|
||||
"show",
|
||||
"start",
|
||||
"<pause|resume|cancel>",
|
||||
],
|
||||
jobs: ["list", "show", "start", "<pause|resume|cancel>"],
|
||||
// `sync <pause|resume>` is documented as one alternation, so it is
|
||||
// checked as an entry rather than as two literal subcommands.
|
||||
sync: ["status", "<pause|resume>"],
|
||||
|
||||
@@ -342,17 +342,20 @@ describe("unified context search", () => {
|
||||
["--limit", "1", "2"],
|
||||
["--character-budget", "200", "300"],
|
||||
["--timeout-ms", "100", "200"],
|
||||
])("rejects a repeated %s before Runtime attach", async (flag, first, second) => {
|
||||
const streams = captureStreams();
|
||||
try {
|
||||
expect(
|
||||
await run(["recall", "q", flag, first, flag, second, "--json"], {}),
|
||||
).toBe(2);
|
||||
} finally {
|
||||
streams.restore();
|
||||
}
|
||||
expect(streams.stdout()).toBe("");
|
||||
});
|
||||
])(
|
||||
"rejects a repeated %s before Runtime attach",
|
||||
async (flag, first, second) => {
|
||||
const streams = captureStreams();
|
||||
try {
|
||||
expect(
|
||||
await run(["recall", "q", flag, first, flag, second, "--json"], {}),
|
||||
).toBe(2);
|
||||
} finally {
|
||||
streams.restore();
|
||||
}
|
||||
expect(streams.stdout()).toBe("");
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses malformed success bodies instead of leaking nested values", async () => {
|
||||
transport.post.mockResolvedValue({
|
||||
@@ -381,6 +384,101 @@ describe("unified context search", () => {
|
||||
expect(streams.stdout()).not.toContain("must-not-print");
|
||||
});
|
||||
|
||||
it("counts characters as code points so an emoji hit stays grounded", async () => {
|
||||
// Core reports used_characters with Python's len(), which counts code
|
||||
// points: this text is 10 characters there and 12 UTF-16 units here.
|
||||
const text = "消费保 📍 扩展 📡";
|
||||
expect(text.length).toBe(12);
|
||||
expect(Array.from(text).length).toBe(10);
|
||||
transport.post.mockResolvedValue({
|
||||
status: 200,
|
||||
data: {
|
||||
...RESPONSE,
|
||||
paths: {
|
||||
...RESPONSE.paths,
|
||||
memory: {
|
||||
...RESPONSE.paths.memory,
|
||||
status: "empty",
|
||||
returned_count: 0,
|
||||
},
|
||||
},
|
||||
items: [
|
||||
{
|
||||
...(RESPONSE.items[0] as Record<string, unknown>),
|
||||
messages: [
|
||||
{
|
||||
...(
|
||||
RESPONSE.items[0] as {
|
||||
messages: Array<Record<string, unknown>>;
|
||||
}
|
||||
).messages[0],
|
||||
text,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
used_characters: 10,
|
||||
},
|
||||
});
|
||||
const streams = captureStreams();
|
||||
try {
|
||||
expect(await run(["recall", "test", "--json"])).toBe(0);
|
||||
} finally {
|
||||
streams.restore();
|
||||
}
|
||||
expect(JSON.parse(streams.stdout())).toMatchObject({
|
||||
state: "grounded",
|
||||
used_characters: 10,
|
||||
items: [{ kind: "raw", messages: [{ text }] }],
|
||||
});
|
||||
});
|
||||
|
||||
it("still rejects a response whose character total does not match", async () => {
|
||||
// The same text counted as UTF-16 units is exactly what Core does not mean,
|
||||
// so the cross-check must keep failing instead of accepting both totals.
|
||||
const text = "消费保 📍 扩展 📡";
|
||||
transport.post.mockResolvedValue({
|
||||
status: 200,
|
||||
data: {
|
||||
...RESPONSE,
|
||||
paths: {
|
||||
...RESPONSE.paths,
|
||||
memory: {
|
||||
...RESPONSE.paths.memory,
|
||||
status: "empty",
|
||||
returned_count: 0,
|
||||
},
|
||||
},
|
||||
items: [
|
||||
{
|
||||
...(RESPONSE.items[0] as Record<string, unknown>),
|
||||
messages: [
|
||||
{
|
||||
...(
|
||||
RESPONSE.items[0] as {
|
||||
messages: Array<Record<string, unknown>>;
|
||||
}
|
||||
).messages[0],
|
||||
text,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
used_characters: 12,
|
||||
},
|
||||
});
|
||||
const streams = captureStreams();
|
||||
try {
|
||||
expect(await run(["recall", "test", "--json"])).toBe(1);
|
||||
} finally {
|
||||
streams.restore();
|
||||
}
|
||||
expect(JSON.parse(streams.stdout())).toMatchObject({
|
||||
state: "invalid",
|
||||
code: "response_invalid",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports endpoint denial without exposing the response body", async () => {
|
||||
transport.post.mockResolvedValue({
|
||||
status: 403,
|
||||
|
||||
@@ -181,9 +181,9 @@ function validateContextResponse(
|
||||
items.push(item);
|
||||
characters +=
|
||||
item.kind === "memory"
|
||||
? String(item.content).length
|
||||
? characterCount(item.content)
|
||||
: (item.messages as Array<Record<string, unknown>>).reduce(
|
||||
(sum, message) => sum + String(message.text).length,
|
||||
(sum, message) => sum + characterCount(message.text),
|
||||
0,
|
||||
);
|
||||
}
|
||||
@@ -330,6 +330,17 @@ function record(value: unknown): Record<string, unknown> | null {
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count characters the way Core does. Python's len() counts Unicode code
|
||||
* points; String.prototype.length counts UTF-16 code units, so an emoji outside
|
||||
* the BMP is one character to Core and two here. Comparing the two totals made
|
||||
* every response containing an emoji fail the used_characters cross-check and
|
||||
* surface as response_invalid.
|
||||
*/
|
||||
function characterCount(value: unknown): number {
|
||||
return Array.from(String(value)).length;
|
||||
}
|
||||
|
||||
function boundedText(
|
||||
value: unknown,
|
||||
maximum: number,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import axios from "axios";
|
||||
import { classifyModelRemove } from "@one-memory/operations";
|
||||
import axios from "axios";
|
||||
|
||||
/**
|
||||
* Only paths proven side-effect free by reading the Core handlers belong here.
|
||||
@@ -8,7 +8,6 @@ import { classifyModelRemove } from "@one-memory/operations";
|
||||
*/
|
||||
const READ_ONLY_PATHS = [
|
||||
"/api/v1/call-events",
|
||||
"/api/v1/model-content-permission",
|
||||
"/api/v1/home-summary",
|
||||
"/api/v1/import-jobs",
|
||||
"/api/v1/live-sync",
|
||||
@@ -56,7 +55,10 @@ export function createUiSessionRequest(attachment: {
|
||||
return { state: "ok" as const, data: response.data };
|
||||
}
|
||||
if (response.status === 503) {
|
||||
return { state: "unavailable" as const, code: "ui_web_assets_unavailable" };
|
||||
return {
|
||||
state: "unavailable" as const,
|
||||
code: "ui_web_assets_unavailable",
|
||||
};
|
||||
}
|
||||
return { state: "unavailable" as const, code: `http_${response.status}` };
|
||||
};
|
||||
@@ -395,15 +397,30 @@ export async function readMemoryWrite(
|
||||
}
|
||||
}
|
||||
|
||||
export async function readScanRoots(
|
||||
export interface OnboardingState {
|
||||
status: string;
|
||||
selected_source_ids: string[];
|
||||
started_at: string | null;
|
||||
completed_at: string | null;
|
||||
}
|
||||
|
||||
/** Send onboarding back to its first-run state.
|
||||
*
|
||||
* Returns null when the endpoint is not there, so an older runtime degrades to
|
||||
* "not available" instead of failing the command. Only the completion flag
|
||||
* moves: memories, sources and settings live in other tables, which is what
|
||||
* makes this the honest way to see the cold-start screens again.
|
||||
*/
|
||||
export async function resetOnboarding(
|
||||
attachment: RuntimeAttachmentLike,
|
||||
): Promise<{ schema_version: number; revision: number; roots: unknown[] } | null> {
|
||||
): Promise<OnboardingState | null> {
|
||||
try {
|
||||
const response = await axios.get<{ schema_version: number; revision: number; roots: unknown[] }>(
|
||||
`${baseUrlOf(attachment)}/api/v1/scan-roots`,
|
||||
const response = await axios.post<OnboardingState>(
|
||||
`${baseUrlOf(attachment)}/api/v1/onboarding/reset`,
|
||||
undefined,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${attachment.apiToken}` },
|
||||
timeout: 10_000,
|
||||
timeout: 15_000,
|
||||
proxy: false,
|
||||
maxRedirects: 0,
|
||||
maxContentLength: MAX_RESPONSE_BYTES,
|
||||
@@ -415,12 +432,19 @@ export async function readScanRoots(
|
||||
}
|
||||
}
|
||||
|
||||
export async function addScanRoot(
|
||||
export async function readScanRoots(
|
||||
attachment: RuntimeAttachmentLike,
|
||||
body: { root: string; source?: string; recursive?: boolean },
|
||||
): Promise<unknown | null> {
|
||||
): Promise<{
|
||||
schema_version: number;
|
||||
revision: number;
|
||||
roots: unknown[];
|
||||
} | null> {
|
||||
try {
|
||||
const response = await axios.post<unknown>(`${baseUrlOf(attachment)}/api/v1/scan-roots`, body, {
|
||||
const response = await axios.get<{
|
||||
schema_version: number;
|
||||
revision: number;
|
||||
roots: unknown[];
|
||||
}>(`${baseUrlOf(attachment)}/api/v1/scan-roots`, {
|
||||
headers: { Authorization: `Bearer ${attachment.apiToken}` },
|
||||
timeout: 10_000,
|
||||
proxy: false,
|
||||
@@ -428,6 +452,28 @@ export async function addScanRoot(
|
||||
maxContentLength: MAX_RESPONSE_BYTES,
|
||||
});
|
||||
return response.data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function addScanRoot(
|
||||
attachment: RuntimeAttachmentLike,
|
||||
body: { root: string; source?: string; recursive?: boolean },
|
||||
): Promise<unknown | null> {
|
||||
try {
|
||||
const response = await axios.post<unknown>(
|
||||
`${baseUrlOf(attachment)}/api/v1/scan-roots`,
|
||||
body,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${attachment.apiToken}` },
|
||||
timeout: 10_000,
|
||||
proxy: false,
|
||||
maxRedirects: 0,
|
||||
maxContentLength: MAX_RESPONSE_BYTES,
|
||||
},
|
||||
);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
return { _error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
@@ -438,14 +484,17 @@ export async function removeScanRoot(
|
||||
body: { root: string },
|
||||
): Promise<unknown | null> {
|
||||
try {
|
||||
const response = await axios.delete<unknown>(`${baseUrlOf(attachment)}/api/v1/scan-roots`, {
|
||||
headers: { Authorization: `Bearer ${attachment.apiToken}` },
|
||||
data: body,
|
||||
timeout: 10_000,
|
||||
proxy: false,
|
||||
maxRedirects: 0,
|
||||
maxContentLength: MAX_RESPONSE_BYTES,
|
||||
});
|
||||
const response = await axios.delete<unknown>(
|
||||
`${baseUrlOf(attachment)}/api/v1/scan-roots`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${attachment.apiToken}` },
|
||||
data: body,
|
||||
timeout: 10_000,
|
||||
proxy: false,
|
||||
maxRedirects: 0,
|
||||
maxContentLength: MAX_RESPONSE_BYTES,
|
||||
},
|
||||
);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
return { _error: error instanceof Error ? error.message : String(error) };
|
||||
@@ -456,16 +505,16 @@ export async function readAdapters(
|
||||
attachment: RuntimeAttachmentLike,
|
||||
): Promise<{ schema_version: number; adapters: unknown[] } | null> {
|
||||
try {
|
||||
const response = await axios.get<{ schema_version: number; adapters: unknown[] }>(
|
||||
`${baseUrlOf(attachment)}/api/v1/adapters`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${attachment.apiToken}` },
|
||||
timeout: 10_000,
|
||||
proxy: false,
|
||||
maxRedirects: 0,
|
||||
maxContentLength: MAX_RESPONSE_BYTES,
|
||||
},
|
||||
);
|
||||
const response = await axios.get<{
|
||||
schema_version: number;
|
||||
adapters: unknown[];
|
||||
}>(`${baseUrlOf(attachment)}/api/v1/adapters`, {
|
||||
headers: { Authorization: `Bearer ${attachment.apiToken}` },
|
||||
timeout: 10_000,
|
||||
proxy: false,
|
||||
maxRedirects: 0,
|
||||
maxContentLength: MAX_RESPONSE_BYTES,
|
||||
});
|
||||
return response.data;
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -30,7 +30,6 @@ const IMPORT_FILE =
|
||||
const MEMORY_NOTES_PATH = "/api/v1/memory-notes";
|
||||
const MEMORY_NOTE_PROCESS =
|
||||
/^\/api\/v1\/memory-notes\/[A-Za-z0-9][\w.:-]{0,127}\/process$/;
|
||||
const MODEL_CONTENT_PERMISSION_PATH = "/api/v1/model-content-permission";
|
||||
const EXTRACTION_SETTINGS_PATH = "/api/v1/extraction-settings";
|
||||
const GRAPH_WIDTH_PATH = "/api/v1/graph-width";
|
||||
const MANUAL_EXTRACT_PATH = "/api/v1/memory-processing/manual-extract";
|
||||
@@ -134,7 +133,6 @@ export function createCoreOperations(attachment: {
|
||||
!IMPORT_FILE_COMMIT.test(path) &&
|
||||
path !== MEMORY_NOTES_PATH &&
|
||||
!MEMORY_NOTE_PROCESS.test(path) &&
|
||||
path !== MODEL_CONTENT_PERMISSION_PATH &&
|
||||
path !== GRAPH_WIDTH_PATH &&
|
||||
path !== MANUAL_EXTRACT_PATH &&
|
||||
path !== ONBOARDING_COMPLETE_PATH &&
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdtemp, mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
@@ -23,14 +23,22 @@ describe("explicit data deletion", () => {
|
||||
"one-memory.sqlite3": "db",
|
||||
"runtime-service.json": "{}",
|
||||
});
|
||||
const plan = await planDataDeletion({ dataDir, home, runtimeRunning: false });
|
||||
const plan = await planDataDeletion({
|
||||
dataDir,
|
||||
home,
|
||||
runtimeRunning: false,
|
||||
});
|
||||
expect(plan.state).toBe("preview");
|
||||
expect(plan.entries).toContain(path.join(dataDir, "one-memory.sqlite3"));
|
||||
});
|
||||
|
||||
it("refuses while the Runtime is still running", async () => {
|
||||
const { home, dataDir } = await homeWith();
|
||||
const plan = await planDataDeletion({ dataDir, home, runtimeRunning: true });
|
||||
const plan = await planDataDeletion({
|
||||
dataDir,
|
||||
home,
|
||||
runtimeRunning: true,
|
||||
});
|
||||
expect(plan).toMatchObject({
|
||||
state: "blocked",
|
||||
code: "runtime_still_running",
|
||||
@@ -66,16 +74,23 @@ describe("explicit data deletion", () => {
|
||||
home,
|
||||
runtimeRunning: false,
|
||||
});
|
||||
expect(plan).toMatchObject({ state: "blocked", code: "data_dir_refused" });
|
||||
expect(plan).toMatchObject({
|
||||
state: "blocked",
|
||||
code: "data_dir_refused",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("requires the second confirmation to name the exact directory", async () => {
|
||||
const { home, dataDir } = await homeWith();
|
||||
const plan = await planDataDeletion({ dataDir, home, runtimeRunning: false });
|
||||
await expect(applyDataDeletion(plan, path.join(home, "other"))).rejects.toThrow(
|
||||
"data_deletion_confirmation_mismatch",
|
||||
);
|
||||
const plan = await planDataDeletion({
|
||||
dataDir,
|
||||
home,
|
||||
runtimeRunning: false,
|
||||
});
|
||||
await expect(
|
||||
applyDataDeletion(plan, path.join(home, "other")),
|
||||
).rejects.toThrow("data_deletion_confirmation_mismatch");
|
||||
// The data survived a mismatched confirmation.
|
||||
await expect(
|
||||
stat(path.join(dataDir, "one-memory.sqlite3")),
|
||||
@@ -84,7 +99,11 @@ describe("explicit data deletion", () => {
|
||||
|
||||
it("deletes an owned Home only when both confirmations match", async () => {
|
||||
const { home, dataDir } = await homeWith({ "one-memory.sqlite3": "db" });
|
||||
const plan = await planDataDeletion({ dataDir, home, runtimeRunning: false });
|
||||
const plan = await planDataDeletion({
|
||||
dataDir,
|
||||
home,
|
||||
runtimeRunning: false,
|
||||
});
|
||||
const receipt = await applyDataDeletion(plan, dataDir);
|
||||
expect(receipt.state).toBe("deleted");
|
||||
await expect(stat(dataDir)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
@@ -68,7 +68,8 @@ export function renderDoctorText(document: DoctorDocument): string {
|
||||
return [
|
||||
`MemHub 检查:${doctorState(document.state)}`,
|
||||
...document.checks.map(
|
||||
(check) => `${symbol(check.state)} ${labels[check.id]}:${checkState(check.state)}`,
|
||||
(check) =>
|
||||
`${symbol(check.state)} ${labels[check.id]}:${checkState(check.state)}`,
|
||||
),
|
||||
...(document.state === "healthy"
|
||||
? []
|
||||
|
||||
@@ -28,11 +28,7 @@ export function resolveEntryDiagnostics(input: {
|
||||
// comparison would misread that as isolated and silently drop diagnostics.
|
||||
const home = resolve(input.home);
|
||||
const accountHome = resolve(input.accountHome);
|
||||
if (
|
||||
home === undefined ||
|
||||
accountHome === undefined ||
|
||||
home === accountHome
|
||||
) {
|
||||
if (home === undefined || accountHome === undefined || home === accountHome) {
|
||||
return { kind: "log" };
|
||||
}
|
||||
// Isolated HOME with no explicit data dir: the fallback path would write
|
||||
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
resolveRuntimeCliConfig,
|
||||
} from "@one-memory/runtime-control";
|
||||
import { run } from "./cli.js";
|
||||
import { resolveDiagnosticsDataDir } from "./install-receipt.js";
|
||||
import { resolveEntryDiagnostics } from "./entry-diagnostics.js";
|
||||
import { resolveDiagnosticsDataDir } from "./install-receipt.js";
|
||||
|
||||
function accountHomeDirectory(): string | undefined {
|
||||
try {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import type { ImportJob, ModelProfile } from "@one-memory/contracts";
|
||||
import {
|
||||
ModelProfileInputError,
|
||||
SourceImportInputError,
|
||||
buildModelProfileCreateRequest,
|
||||
buildSourceImportRequest,
|
||||
ModelProfileInputError,
|
||||
parseModelProfileReceipt,
|
||||
SourceImportInputError,
|
||||
} from "@one-memory/operations";
|
||||
import type { ImportJob, ModelProfile } from "@one-memory/contracts";
|
||||
import type { CoreReader, ReadOutcome } from "./core-client.js";
|
||||
import type { CoreOperations } from "./core-operations.js";
|
||||
import {
|
||||
@@ -117,9 +117,7 @@ function classifySourceImport(
|
||||
product: PRODUCT,
|
||||
state: "rejected",
|
||||
operation_id: operationId,
|
||||
code: onlyBusy
|
||||
? "source_import_all_busy"
|
||||
: "source_import_all_rejected",
|
||||
code: onlyBusy ? "source_import_all_busy" : "source_import_all_rejected",
|
||||
receipt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -266,7 +266,9 @@ export function renderHostText(document: HostFlowDocument): string {
|
||||
}
|
||||
if (review.length > 12) lines.push(` … 另有 ${review.length - 12} 处`);
|
||||
lines.push("");
|
||||
lines.push("这些不是我们安装的内容,卸载不会替你删除;需自行处理后才能卸载。");
|
||||
lines.push(
|
||||
"这些不是我们安装的内容,卸载不会替你删除;需自行处理后才能卸载。",
|
||||
);
|
||||
}
|
||||
}
|
||||
return `${lines.join("\n")}\n`;
|
||||
|
||||
@@ -259,7 +259,7 @@ describe("A2 dual-mode init", () => {
|
||||
expect(streams.value()).toContain("处理:已开启");
|
||||
});
|
||||
|
||||
it("continues the TTY wizard through model probe and content permission", async () => {
|
||||
it("continues the TTY wizard through model setup and probe", async () => {
|
||||
const profileId = "22222222-2222-4222-8222-222222222222";
|
||||
const profile = {
|
||||
profile_id: profileId,
|
||||
@@ -361,12 +361,6 @@ describe("A2 dual-mode init", () => {
|
||||
};
|
||||
}
|
||||
if (url.endsWith("/activate")) return { status: 200, data: profile };
|
||||
if (url === "/api/v1/model-content-permission") {
|
||||
return {
|
||||
status: 200,
|
||||
data: { allowed: body.allowed },
|
||||
};
|
||||
}
|
||||
if (url === "/api/v1/onboarding/complete") {
|
||||
return {
|
||||
status: 200,
|
||||
@@ -383,7 +377,7 @@ describe("A2 dual-mode init", () => {
|
||||
},
|
||||
);
|
||||
const prompt = extendedPrompter(
|
||||
["", "", "", "", "", "", "", "", "n"],
|
||||
["", "", "", "", "", "", "", "n"],
|
||||
"sk-never-print-this",
|
||||
);
|
||||
const streams = captureStdout();
|
||||
@@ -402,7 +396,6 @@ describe("A2 dual-mode init", () => {
|
||||
streams.restore();
|
||||
}
|
||||
expect(streams.value()).toContain("已接入来源:codex");
|
||||
expect(prompt.written.join("\n")).toContain("模型内容外发:已允许");
|
||||
expect(streams.value()).toContain("首次设置完成。");
|
||||
expect(`${streams.value()}\n${prompt.written.join("\n")}`).not.toContain(
|
||||
"sk-never-print-this",
|
||||
@@ -412,10 +405,10 @@ describe("A2 dual-mode init", () => {
|
||||
expect.objectContaining({ api_key: "sk-never-print-this" }),
|
||||
undefined,
|
||||
);
|
||||
expect(transport.post).toHaveBeenCalledWith(
|
||||
expect(transport.post).not.toHaveBeenCalledWith(
|
||||
"/api/v1/model-content-permission",
|
||||
{ allowed: true },
|
||||
undefined,
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
);
|
||||
expect(transport.post).toHaveBeenCalledWith(
|
||||
"/api/v1/onboarding/complete",
|
||||
|
||||
@@ -7,7 +7,9 @@ import {
|
||||
type WizardPrompter,
|
||||
} from "./init-wizard.js";
|
||||
|
||||
function scripted(lines: string[]): WizardPrompter & { asked: string[]; wrote: string[] } {
|
||||
function scripted(
|
||||
lines: string[],
|
||||
): WizardPrompter & { asked: string[]; wrote: string[] } {
|
||||
let index = 0;
|
||||
const asked: string[] = [];
|
||||
const wrote: string[] = [];
|
||||
|
||||
@@ -99,8 +99,7 @@ export async function runInitWizard(
|
||||
"开启处理?开启后会处理历史未完成会话并持续接收新会话;输入 n 保持冻结。[Y/n]: ",
|
||||
);
|
||||
const processing = parseYesNo(processingAnswer, true);
|
||||
if (processing === null)
|
||||
return { state: "invalid", code: "invalid_answer" };
|
||||
if (processing === null) return { state: "invalid", code: "invalid_answer" };
|
||||
|
||||
return {
|
||||
state: "answered",
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import {
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
readdir,
|
||||
readFile,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveEntryDiagnostics } from "./entry-diagnostics.js";
|
||||
import {
|
||||
defaultInstallReceiptPath,
|
||||
readInstallReceipt,
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
resolveInstalledDataDir,
|
||||
writeInstallReceipt,
|
||||
} from "./install-receipt.js";
|
||||
import { resolveEntryDiagnostics } from "./entry-diagnostics.js";
|
||||
|
||||
async function root(): Promise<string> {
|
||||
return mkdtemp(path.join(tmpdir(), "memhub-install-receipt-"));
|
||||
@@ -230,9 +229,9 @@ describe("managed install receipt", () => {
|
||||
}),
|
||||
).toBe("/tmp/env data");
|
||||
// Receipt beats default.
|
||||
expect(
|
||||
await resolveDiagnosticsDataDir(["install"], { HOME: home }),
|
||||
).toBe(path.join(home, "receipt data"));
|
||||
expect(await resolveDiagnosticsDataDir(["install"], { HOME: home })).toBe(
|
||||
path.join(home, "receipt data"),
|
||||
);
|
||||
// Invalid explicit flag must not silently fall back to the receipt.
|
||||
expect(
|
||||
await resolveDiagnosticsDataDir(
|
||||
|
||||
@@ -132,12 +132,6 @@ function clients(options: { failedProbes?: number } = {}) {
|
||||
if (path.endsWith("/activate")) {
|
||||
return { state: "committed" as const, data: profile(true) };
|
||||
}
|
||||
if (path === "/api/v1/model-content-permission") {
|
||||
return {
|
||||
state: "committed" as const,
|
||||
data: { allowed: body.allowed },
|
||||
};
|
||||
}
|
||||
return {
|
||||
state: "rejected" as const,
|
||||
code: "unexpected_path",
|
||||
@@ -160,8 +154,8 @@ function clients(options: { failedProbes?: number } = {}) {
|
||||
}
|
||||
|
||||
describe("interactive model setup", () => {
|
||||
it("uses App defaults, keeps the key out of output, and allows model content", async () => {
|
||||
const prompt = prompter(["", "", "", "", "", ""]);
|
||||
it("uses App defaults and keeps the key out of output", async () => {
|
||||
const prompt = prompter(["", "", ""]);
|
||||
const api = clients();
|
||||
|
||||
const result = await runInteractiveModelSetup(prompt.value, api, {
|
||||
@@ -170,10 +164,7 @@ describe("interactive model setup", () => {
|
||||
installHosts: false,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: "configured",
|
||||
model_content_allowed: true,
|
||||
});
|
||||
expect(result).toMatchObject({ state: "configured" });
|
||||
expect(api.post).toHaveBeenCalledWith(
|
||||
"/api/v1/model-profiles",
|
||||
expect.objectContaining({
|
||||
@@ -184,9 +175,9 @@ describe("interactive model setup", () => {
|
||||
embedding_provider_kind: "local_onnx",
|
||||
}),
|
||||
);
|
||||
expect(api.post).toHaveBeenCalledWith(
|
||||
expect(api.post).not.toHaveBeenCalledWith(
|
||||
"/api/v1/model-content-permission",
|
||||
{ allowed: true },
|
||||
expect.anything(),
|
||||
);
|
||||
expect(prompt.written.join("\n")).not.toContain("sk-do-not-print");
|
||||
});
|
||||
@@ -206,7 +197,7 @@ describe("interactive model setup", () => {
|
||||
});
|
||||
|
||||
it("removes an unverified profile before skipping after a failed probe", async () => {
|
||||
const prompt = prompter(["", "", "", "n", "0"]);
|
||||
const prompt = prompter(["", "", "", "0"]);
|
||||
const api = clients();
|
||||
api.post.mockImplementation(
|
||||
async (path: string, body: Record<string, unknown>) => {
|
||||
@@ -281,7 +272,7 @@ describe("interactive model setup", () => {
|
||||
});
|
||||
|
||||
it("cleans a failed probe and lets the user re-enter the model settings", async () => {
|
||||
const prompt = prompter(["", "", "", "", "", "", "", "", "", "", ""]);
|
||||
const prompt = prompter(["", "", "", "", "", "", ""]);
|
||||
const api = clients({ failedProbes: 1 });
|
||||
|
||||
const result = await runInteractiveModelSetup(prompt.value, api, {
|
||||
@@ -290,10 +281,7 @@ describe("interactive model setup", () => {
|
||||
installHosts: false,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: "configured",
|
||||
model_content_allowed: true,
|
||||
});
|
||||
expect(result).toMatchObject({ state: "configured" });
|
||||
expect(api.remove).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
api.post.mock.calls.filter(([path]) => path === "/api/v1/model-profiles"),
|
||||
@@ -306,7 +294,7 @@ describe("interactive model setup", () => {
|
||||
const prompt = prompter(["", "", ""]);
|
||||
prompt.value.ask = async () => {
|
||||
asked += 1;
|
||||
if (asked === 4) throw new Error("interrupted");
|
||||
if (asked === 3) throw new Error("interrupted");
|
||||
return "";
|
||||
};
|
||||
const api = clients();
|
||||
@@ -323,7 +311,7 @@ describe("interactive model setup", () => {
|
||||
});
|
||||
|
||||
it("installs selected detected hosts through preview and fingerprint apply", async () => {
|
||||
const prompt = prompter(["", "", "", "n", "", ""]);
|
||||
const prompt = prompter(["", "", "", "", ""]);
|
||||
const api = clients();
|
||||
const read = vi
|
||||
.fn()
|
||||
@@ -361,7 +349,6 @@ describe("interactive model setup", () => {
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: "configured",
|
||||
model_content_allowed: false,
|
||||
installed_hosts: ["codex"],
|
||||
});
|
||||
expect(read).toHaveBeenNthCalledWith(
|
||||
@@ -374,7 +361,7 @@ describe("interactive model setup", () => {
|
||||
});
|
||||
|
||||
it("lists and installs only hosts that are actually present", async () => {
|
||||
const prompt = prompter(["", "", "", "n", "", ""]);
|
||||
const prompt = prompter(["", "", "", "", ""]);
|
||||
const api = clients();
|
||||
const read = vi
|
||||
.fn()
|
||||
@@ -421,7 +408,7 @@ describe("interactive model setup", () => {
|
||||
});
|
||||
|
||||
it("completes the wizard and keeps onboarding reachable when one host install fails", async () => {
|
||||
const prompt = prompter(["", "", "", "n", "", ""]);
|
||||
const prompt = prompter(["", "", "", "", ""]);
|
||||
const api = clients();
|
||||
const read = vi
|
||||
.fn()
|
||||
@@ -470,7 +457,6 @@ describe("interactive model setup", () => {
|
||||
// calling the install a failure.
|
||||
expect(result).toMatchObject({
|
||||
state: "configured",
|
||||
model_content_allowed: false,
|
||||
installed_hosts: ["codex"],
|
||||
});
|
||||
const summary = prompt.written.join("\n");
|
||||
@@ -480,7 +466,7 @@ describe("interactive model setup", () => {
|
||||
});
|
||||
|
||||
it("tells the user to install App-only hosts in the App instead of calling them failed", async () => {
|
||||
const prompt = prompter(["", "", "", "n", "", ""]);
|
||||
const prompt = prompter(["", "", "", "", ""]);
|
||||
const api = clients();
|
||||
const read = vi
|
||||
.fn()
|
||||
@@ -507,7 +493,6 @@ describe("interactive model setup", () => {
|
||||
// only the App can install, so nothing counts as "installed".
|
||||
expect(result).toMatchObject({
|
||||
state: "configured",
|
||||
model_content_allowed: false,
|
||||
installed_hosts: [],
|
||||
});
|
||||
const summary = prompt.written.join("\n");
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
executeModelProfileActivate,
|
||||
planModelProfileActivate,
|
||||
} from "./model-write-flows.js";
|
||||
import { setModelContentPermission } from "./model-content-permission-flow.js";
|
||||
|
||||
type ProviderPreset = {
|
||||
id: string;
|
||||
@@ -122,7 +121,6 @@ export type InteractiveModelSetupState =
|
||||
| {
|
||||
state: "configured";
|
||||
profile: ModelProfile;
|
||||
model_content_allowed: boolean;
|
||||
installed_hosts: string[];
|
||||
}
|
||||
| { state: "skipped" }
|
||||
@@ -289,15 +287,11 @@ async function installHosts(
|
||||
function writeSummary(
|
||||
prompter: WizardPrompter,
|
||||
profile: ModelProfile,
|
||||
modelContentAllowed: boolean,
|
||||
installedHosts: readonly string[],
|
||||
failedHosts: readonly { hostId: string; label: string }[],
|
||||
): void {
|
||||
prompter.write("配置摘要:");
|
||||
prompter.write(` 模型:${profile.name} / ${profile.model}`);
|
||||
prompter.write(
|
||||
` 模型内容外发:${modelContentAllowed ? "已允许" : "已禁止"}`,
|
||||
);
|
||||
prompter.write(
|
||||
` 应用接入:${installedHosts.length > 0 ? installedHosts.join("、") : "已跳过"}`,
|
||||
);
|
||||
@@ -353,14 +347,6 @@ export async function runInteractiveModelSetup(
|
||||
prompter.write("未填写 API Key。输入 back 返回,或重新选择模型服务。");
|
||||
continue;
|
||||
}
|
||||
const permissionAnswer = (
|
||||
await prompter.ask("允许将对话内容发送给模型以整理记忆?[Y/n]: ")
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const modelContentAllowed = !["n", "no", "否", "0"].includes(
|
||||
permissionAnswer,
|
||||
);
|
||||
const hostApi = options.hostApi ?? { list: listHosts, read: readHost };
|
||||
const selectedHosts = options.installHosts
|
||||
? await chooseDetectedHosts(prompter, options.hostHome, hostApi)
|
||||
@@ -452,13 +438,6 @@ export async function runInteractiveModelSetup(
|
||||
return { state: "failed", code: "model_activate_failed" };
|
||||
}
|
||||
|
||||
const permission = await setModelContentPermission(
|
||||
clients.operations,
|
||||
modelContentAllowed,
|
||||
);
|
||||
if (permission.state !== "ok") {
|
||||
return { state: "failed", code: "model_content_permission_set_failed" };
|
||||
}
|
||||
const { installed, failed } = await installHosts(
|
||||
options.dataDir,
|
||||
selectedHosts,
|
||||
@@ -467,7 +446,6 @@ export async function runInteractiveModelSetup(
|
||||
writeSummary(
|
||||
prompter,
|
||||
profile,
|
||||
modelContentAllowed,
|
||||
installed,
|
||||
failed.map((hostId) => ({
|
||||
hostId,
|
||||
@@ -477,7 +455,6 @@ export async function runInteractiveModelSetup(
|
||||
return {
|
||||
state: "configured",
|
||||
profile,
|
||||
model_content_allowed: modelContentAllowed,
|
||||
installed_hosts: installed,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ vi.mock("axios", () => ({
|
||||
default: { create: vi.fn(() => transport), get: vi.fn() },
|
||||
}));
|
||||
|
||||
import type { CoreOperations } from "./core-operations.js";
|
||||
import { createCoreOperations } from "./core-operations.js";
|
||||
import {
|
||||
executeJobAction,
|
||||
@@ -25,7 +26,6 @@ import {
|
||||
planJobAction,
|
||||
planJobStart,
|
||||
} from "./job-flow.js";
|
||||
import type { CoreOperations } from "./core-operations.js";
|
||||
|
||||
function operations(
|
||||
post: (path: string, body: Record<string, unknown>) => Promise<unknown>,
|
||||
@@ -180,5 +180,8 @@ describe("import-job write allow-list", () => {
|
||||
await expect(
|
||||
operations.post("/api/v1/import-jobs/job-1/delete", {}),
|
||||
).rejects.toThrow("core_operation_path_not_allowed");
|
||||
await expect(
|
||||
operations.post("/api/v1/model-content-permission", { allowed: true }),
|
||||
).rejects.toThrow("core_operation_path_not_allowed");
|
||||
});
|
||||
});
|
||||
@@ -145,9 +145,7 @@ function jobMutationResult(
|
||||
export function jobExitCode(document: JobFlowDocument): number {
|
||||
if (document.state === "preview" || document.state === "committed") return 0;
|
||||
if (document.state === "recovered") return 0;
|
||||
return document.state === "rejected" || document.state === "unknown"
|
||||
? 1
|
||||
: 2;
|
||||
return document.state === "rejected" || document.state === "unknown" ? 1 : 2;
|
||||
}
|
||||
|
||||
function invalid(code: string): JobFlowDocument {
|
||||
|
||||
@@ -105,10 +105,7 @@ describe("memhub jobs", () => {
|
||||
const output = captureStdout();
|
||||
let code: number;
|
||||
try {
|
||||
code = await run(
|
||||
["jobs", "start", "--source", "codex", "--json"],
|
||||
{},
|
||||
);
|
||||
code = await run(["jobs", "start", "--source", "codex", "--json"], {});
|
||||
} finally {
|
||||
output.restore();
|
||||
}
|
||||
@@ -154,10 +151,7 @@ describe("memhub jobs", () => {
|
||||
const output = captureStdout();
|
||||
let code: number;
|
||||
try {
|
||||
code = await run(
|
||||
["jobs", action, "--job", "job-1", "--json"],
|
||||
{},
|
||||
);
|
||||
code = await run(["jobs", action, "--job", "job-1", "--json"], {});
|
||||
} finally {
|
||||
output.restore();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { DiagnosticEventV1 } from "@one-memory/runtime-control";
|
||||
import { diagnosticLogFiles, readDiagnosticEvents } from "@one-memory/runtime-control";
|
||||
import { lstat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { DiagnosticEventV1 } from "@one-memory/runtime-control";
|
||||
import {
|
||||
diagnosticLogFiles,
|
||||
readDiagnosticEvents,
|
||||
} from "@one-memory/runtime-control";
|
||||
|
||||
export interface LogQuery {
|
||||
since?: Date;
|
||||
@@ -160,10 +163,21 @@ export async function readLogReport(
|
||||
const logsDirectory = path.join(path.resolve(dataDir), "logs");
|
||||
const info = await lstat(logsDirectory).catch(() => null);
|
||||
if (info !== null && (!info.isDirectory() || info.isSymbolicLink())) {
|
||||
return { events: [], invalid_lines: 0, failure: "log_directory_unreadable" };
|
||||
return {
|
||||
events: [],
|
||||
invalid_lines: 0,
|
||||
failure: "log_directory_unreadable",
|
||||
};
|
||||
}
|
||||
if (info !== null && (await diagnosticLogFiles(dataDir).catch(() => null)) === null) {
|
||||
return { events: [], invalid_lines: 0, failure: "log_directory_unreadable" };
|
||||
if (
|
||||
info !== null &&
|
||||
(await diagnosticLogFiles(dataDir).catch(() => null)) === null
|
||||
) {
|
||||
return {
|
||||
events: [],
|
||||
invalid_lines: 0,
|
||||
failure: "log_directory_unreadable",
|
||||
};
|
||||
}
|
||||
const explicit =
|
||||
query.since ||
|
||||
@@ -239,15 +253,27 @@ export function redactDiagnosticEvent(
|
||||
outcome: event.outcome,
|
||||
session_id: event.session_id,
|
||||
...(event.trace_id === undefined ? {} : { trace_id: event.trace_id }),
|
||||
...(event.incident_id === undefined ? {} : { incident_id: event.incident_id }),
|
||||
...(event.instance_id === undefined ? {} : { instance_id: event.instance_id }),
|
||||
...(event.operation_id === undefined ? {} : { operation_id: event.operation_id }),
|
||||
...(event.incident_id === undefined
|
||||
? {}
|
||||
: { incident_id: event.incident_id }),
|
||||
...(event.instance_id === undefined
|
||||
? {}
|
||||
: { instance_id: event.instance_id }),
|
||||
...(event.operation_id === undefined
|
||||
? {}
|
||||
: { operation_id: event.operation_id }),
|
||||
...(event.request_id === undefined ? {} : { request_id: event.request_id }),
|
||||
...(event.job_id === undefined ? {} : { job_id: event.job_id }),
|
||||
...(event.task_id === undefined ? {} : { task_id: event.task_id }),
|
||||
...(event.duration_ms === undefined ? {} : { duration_ms: event.duration_ms }),
|
||||
...(event.state_before === undefined ? {} : { state_before: event.state_before }),
|
||||
...(event.state_after === undefined ? {} : { state_after: event.state_after }),
|
||||
...(event.duration_ms === undefined
|
||||
? {}
|
||||
: { duration_ms: event.duration_ms }),
|
||||
...(event.state_before === undefined
|
||||
? {}
|
||||
: { state_before: event.state_before }),
|
||||
...(event.state_after === undefined
|
||||
? {}
|
||||
: { state_after: event.state_after }),
|
||||
...(event.error_code === undefined ? {} : { error_code: event.error_code }),
|
||||
...(event.error_type === undefined ? {} : { error_type: event.error_type }),
|
||||
...(event.safe_stack === undefined
|
||||
|
||||
@@ -11,9 +11,8 @@ import {
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { CliLinkPlan } from "@one-memory/runtime-control";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
installManagedCliAlias,
|
||||
installManagedCliLink,
|
||||
@@ -107,7 +106,9 @@ describe("managed memhub CLI alias", () => {
|
||||
await installManagedCliAlias(plan);
|
||||
|
||||
await expect(removeManagedCliAlias(plan)).resolves.toBe("removed");
|
||||
await expect(lstat(plan.link_path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(lstat(plan.link_path)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
|
||||
// C8 P1 (2026-09-29): `runtime-control.applyLocalUninstall` deletes
|
||||
@@ -156,7 +157,10 @@ describe("managed memhub CLI alias", () => {
|
||||
it("manages the one-memory companion when memhub is already present", async () => {
|
||||
if (process.platform === "win32") return;
|
||||
const f = await fixture();
|
||||
const primary = { ...f.base, link_path: path.join(f.base.bin_directory, "memhub") };
|
||||
const primary = {
|
||||
...f.base,
|
||||
link_path: path.join(f.base.bin_directory, "memhub"),
|
||||
};
|
||||
await mkdir(f.base.bin_directory, { recursive: true, mode: 0o700 });
|
||||
await (await import("node:fs/promises")).chmod(f.base.bin_directory, 0o700);
|
||||
await (await import("node:fs/promises")).symlink(
|
||||
@@ -168,7 +172,10 @@ describe("managed memhub CLI alias", () => {
|
||||
const plan = await planManagedCliLink(f.base, "one-memory");
|
||||
// The companion does not exist yet, so it is ours to create; crucially it
|
||||
// targets the compat name, not the package's `memhub`.
|
||||
expect(plan).toMatchObject({ status: "create", link_path: f.base.link_path });
|
||||
expect(plan).toMatchObject({
|
||||
status: "create",
|
||||
link_path: f.base.link_path,
|
||||
});
|
||||
|
||||
// The package's memhub link is untouched.
|
||||
expect(await readlink(primary.link_path)).toBe(f.target);
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { access, chmod, lstat, mkdir, readlink, rm, symlink } from "node:fs/promises";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
lstat,
|
||||
mkdir,
|
||||
readlink,
|
||||
rm,
|
||||
symlink,
|
||||
} from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import type { CliLinkPlan, CliLinkReceipt } from "@one-memory/runtime-control";
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { run } from "./cli.js";
|
||||
|
||||
const transport = vi.hoisted(() => ({
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
}));
|
||||
vi.mock("axios", () => ({
|
||||
default: { create: vi.fn(() => transport), get: vi.fn() },
|
||||
}));
|
||||
|
||||
const runtime = vi.hoisted(() => ({
|
||||
inspectRuntimeStatus: vi.fn(),
|
||||
discoverRuntimeAttachment: vi.fn(),
|
||||
}));
|
||||
vi.mock("@one-memory/runtime-control", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@one-memory/runtime-control")>()),
|
||||
...runtime,
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
runtime.inspectRuntimeStatus.mockResolvedValue({
|
||||
state: "running",
|
||||
code: "runtime_verified",
|
||||
instanceId: "instance-1",
|
||||
host: "127.0.0.1",
|
||||
port: 8765,
|
||||
version: "1.2.3",
|
||||
});
|
||||
runtime.discoverRuntimeAttachment.mockResolvedValue({
|
||||
instanceId: "instance-1",
|
||||
apiToken: "synthetic-runtime-token",
|
||||
host: "127.0.0.1",
|
||||
port: 8765,
|
||||
servicePid: 4242,
|
||||
health: {
|
||||
status: "ok",
|
||||
service: "one-memory-core",
|
||||
version: "1.2.3",
|
||||
instance_id: "instance-1",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe("model content permission CLI", () => {
|
||||
it("documents only final-state permission and manual extraction commands", async () => {
|
||||
const permission = await capturedRun(["help", "permission"]);
|
||||
expect(permission.code).toBe(0);
|
||||
expect(permission.stdout).toContain("memhub permission allow");
|
||||
expect(permission.stdout).toContain("memhub permission deny");
|
||||
expect(permission.stdout).not.toMatch(/\b(preview|confirm|process|revoke)\b/);
|
||||
expect(permission.stdout).not.toContain("revision");
|
||||
expect(permission.stdout).not.toContain("receipt");
|
||||
|
||||
const processing = await capturedRun(["help", "processing"]);
|
||||
expect(processing.code).toBe(0);
|
||||
expect(processing.stdout).toContain("memhub processing extract");
|
||||
expect(processing.stdout).not.toMatch(/\b(plan|apply|receipt)\b/);
|
||||
expect(processing.stdout).not.toContain("backlog");
|
||||
});
|
||||
|
||||
it("reads the final state", async () => {
|
||||
transport.get.mockResolvedValue({ status: 200, data: { allowed: true } });
|
||||
|
||||
const result = await capturedRun(["permission", "status", "--json"]);
|
||||
|
||||
expect(result.code).toBe(0);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
state: "ok",
|
||||
allowed: true,
|
||||
});
|
||||
expect(transport.get).toHaveBeenCalledWith(
|
||||
"/api/v1/model-content-permission",
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["allow", true],
|
||||
["deny", false],
|
||||
] as const)("sets %s directly with only allowed", async (verb, allowed) => {
|
||||
transport.post.mockResolvedValue({ status: 200, data: { allowed } });
|
||||
|
||||
const result = await capturedRun(["permission", verb, "--json"]);
|
||||
|
||||
expect(result.code).toBe(0);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ state: "ok", allowed });
|
||||
expect(transport.post).toHaveBeenCalledWith(
|
||||
"/api/v1/model-content-permission",
|
||||
{ allowed },
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["preview", "confirm", "process", "revoke"])(
|
||||
"rejects removed %s commands before runtime access",
|
||||
async (verb) => {
|
||||
const result = await capturedRun(["permission", verb, "--json"]);
|
||||
|
||||
expect(result.code).toBe(2);
|
||||
expect(runtime.inspectRuntimeStatus).not.toHaveBeenCalled();
|
||||
expect(transport.get).not.toHaveBeenCalled();
|
||||
expect(transport.post).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["plan", "apply", "receipt"])(
|
||||
"rejects removed processing %s commands before runtime access",
|
||||
async (verb) => {
|
||||
const result = await capturedRun(["processing", verb, "--json"]);
|
||||
|
||||
expect(result.code).toBe(2);
|
||||
expect(runtime.inspectRuntimeStatus).not.toHaveBeenCalled();
|
||||
expect(transport.get).not.toHaveBeenCalled();
|
||||
expect(transport.post).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
async function capturedRun(arguments_: string[]) {
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
const stdoutSpy = vi
|
||||
.spyOn(process.stdout, "write")
|
||||
.mockImplementation((chunk) => {
|
||||
stdout += String(chunk);
|
||||
return true;
|
||||
});
|
||||
const stderrSpy = vi
|
||||
.spyOn(process.stderr, "write")
|
||||
.mockImplementation((chunk) => {
|
||||
stderr += String(chunk);
|
||||
return true;
|
||||
});
|
||||
try {
|
||||
return {
|
||||
code: await run(arguments_, {
|
||||
ONE_MEMORY_DATA_DIR: "/synthetic/data",
|
||||
}),
|
||||
stdout,
|
||||
stderr,
|
||||
};
|
||||
} finally {
|
||||
stdoutSpy.mockRestore();
|
||||
stderrSpy.mockRestore();
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { CoreReader } from "./core-client.js";
|
||||
import type { CoreOperations } from "./core-operations.js";
|
||||
import {
|
||||
readModelContentPermission,
|
||||
setModelContentPermission,
|
||||
} from "./model-content-permission-flow.js";
|
||||
|
||||
describe("model content permission flow", () => {
|
||||
it("reads the single final-state boolean", async () => {
|
||||
const reader = vi.fn().mockResolvedValue({
|
||||
state: "ok",
|
||||
data: { allowed: true },
|
||||
});
|
||||
|
||||
await expect(
|
||||
readModelContentPermission(reader as CoreReader),
|
||||
).resolves.toMatchObject({ state: "ok", allowed: true });
|
||||
expect(reader).toHaveBeenCalledWith("/api/v1/model-content-permission");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["allow", true],
|
||||
["deny", false],
|
||||
] as const)("sets %s directly without revision or receipt fields", async (_, allowed) => {
|
||||
const post = vi.fn().mockResolvedValue({
|
||||
state: "committed",
|
||||
data: { allowed },
|
||||
});
|
||||
|
||||
await expect(
|
||||
setModelContentPermission({ post } as CoreOperations, allowed),
|
||||
).resolves.toMatchObject({ state: "ok", allowed });
|
||||
expect(post).toHaveBeenCalledWith("/api/v1/model-content-permission", {
|
||||
allowed,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not accept a malformed or mismatched success response", async () => {
|
||||
const malformed = vi.fn().mockResolvedValue({
|
||||
state: "committed",
|
||||
data: { allowed: true, revision: 1 },
|
||||
});
|
||||
await expect(
|
||||
setModelContentPermission({ post: malformed } as CoreOperations, true),
|
||||
).resolves.toMatchObject({
|
||||
state: "unknown",
|
||||
code: "model_content_permission_response_invalid",
|
||||
});
|
||||
|
||||
const mismatched = vi.fn().mockResolvedValue({
|
||||
state: "committed",
|
||||
data: { allowed: false },
|
||||
});
|
||||
await expect(
|
||||
setModelContentPermission({ post: mismatched } as CoreOperations, true),
|
||||
).resolves.toMatchObject({
|
||||
state: "unknown",
|
||||
code: "model_content_permission_state_mismatch",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,93 +0,0 @@
|
||||
import type { CoreReader } from "./core-client.js";
|
||||
import type { CoreOperations } from "./core-operations.js";
|
||||
import { PRODUCT } from "./version.js";
|
||||
|
||||
export type ModelContentPermissionDocument =
|
||||
| {
|
||||
schema_version: 1;
|
||||
product: string;
|
||||
state: "ok";
|
||||
allowed: boolean;
|
||||
}
|
||||
| {
|
||||
schema_version: 1;
|
||||
product: string;
|
||||
state: "rejected" | "unknown";
|
||||
code: string;
|
||||
};
|
||||
|
||||
export async function readModelContentPermission(
|
||||
reader: CoreReader,
|
||||
): Promise<ModelContentPermissionDocument> {
|
||||
const outcome = await reader<unknown>("/api/v1/model-content-permission");
|
||||
if (outcome.state !== "ok") {
|
||||
return failure("unknown", outcome.code);
|
||||
}
|
||||
return permissionState(outcome.data, "model_content_permission_response_invalid");
|
||||
}
|
||||
|
||||
export async function setModelContentPermission(
|
||||
operations: CoreOperations,
|
||||
allowed: boolean,
|
||||
): Promise<ModelContentPermissionDocument> {
|
||||
const outcome = await operations.post<unknown>(
|
||||
"/api/v1/model-content-permission",
|
||||
{ allowed },
|
||||
);
|
||||
if (outcome.state === "rejected") {
|
||||
return failure("rejected", outcome.code);
|
||||
}
|
||||
if (outcome.state === "unknown") {
|
||||
return failure("unknown", outcome.code);
|
||||
}
|
||||
const document = permissionState(
|
||||
outcome.data,
|
||||
"model_content_permission_response_invalid",
|
||||
);
|
||||
return document.state === "ok" && document.allowed !== allowed
|
||||
? failure("unknown", "model_content_permission_state_mismatch")
|
||||
: document;
|
||||
}
|
||||
|
||||
export function modelContentPermissionExitCode(
|
||||
document: ModelContentPermissionDocument,
|
||||
): number {
|
||||
return document.state === "ok" ? 0 : 1;
|
||||
}
|
||||
|
||||
export function renderModelContentPermissionText(
|
||||
document: ModelContentPermissionDocument,
|
||||
): string {
|
||||
if (document.state === "ok") {
|
||||
return `模型内容外发:${document.allowed ? "允许" : "禁止"}\n`;
|
||||
}
|
||||
return `模型内容权限未更新:${document.state}(${document.code})\n`;
|
||||
}
|
||||
|
||||
function permissionState(
|
||||
value: unknown,
|
||||
invalidCode: string,
|
||||
): ModelContentPermissionDocument {
|
||||
if (
|
||||
value === null ||
|
||||
typeof value !== "object" ||
|
||||
Array.isArray(value) ||
|
||||
Object.keys(value).length !== 1 ||
|
||||
typeof (value as Record<string, unknown>).allowed !== "boolean"
|
||||
) {
|
||||
return failure("unknown", invalidCode);
|
||||
}
|
||||
return {
|
||||
schema_version: 1,
|
||||
product: PRODUCT,
|
||||
state: "ok",
|
||||
allowed: (value as { allowed: boolean }).allowed,
|
||||
};
|
||||
}
|
||||
|
||||
function failure(
|
||||
state: "rejected" | "unknown",
|
||||
code: string,
|
||||
): ModelContentPermissionDocument {
|
||||
return { schema_version: 1, product: PRODUCT, state, code };
|
||||
}
|
||||
@@ -13,8 +13,8 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import type { ModelProfile } from "@one-memory/contracts";
|
||||
import {
|
||||
ModelProfileInputError,
|
||||
buildModelProfileUpdateRequest,
|
||||
ModelProfileInputError,
|
||||
parseModelProfileReceipt,
|
||||
} from "@one-memory/operations";
|
||||
import type { CoreOperations, CorePatchOperations } from "./core-operations.js";
|
||||
@@ -78,7 +78,10 @@ function digestOf(value: unknown): string {
|
||||
|
||||
function preview(
|
||||
plan:
|
||||
| Omit<Extract<ModelWritePlan, { kind: "model_profile_activate" }>, "digest">
|
||||
| Omit<
|
||||
Extract<ModelWritePlan, { kind: "model_profile_activate" }>,
|
||||
"digest"
|
||||
>
|
||||
| Omit<Extract<ModelWritePlan, { kind: "model_profile_edit" }>, "digest">,
|
||||
): ModelWriteDocument {
|
||||
return {
|
||||
@@ -198,9 +201,9 @@ export async function executeModelProfileEdit(
|
||||
let request: ReturnType<typeof buildModelProfileUpdateRequest>;
|
||||
try {
|
||||
request = buildModelProfileUpdateRequest(plan.profile_id, {
|
||||
...plan.patch,
|
||||
expected_revision: plan.expected_revision,
|
||||
...(apiKey === undefined ? {} : { api_key: apiKey }),
|
||||
...plan.patch,
|
||||
expected_revision: plan.expected_revision,
|
||||
...(apiKey === undefined ? {} : { api_key: apiKey }),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ModelProfileInputError) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, readFile, writeFile } from "node:fs/promises";
|
||||
import { tmpdir, homedir } from "node:os";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
@@ -137,8 +137,8 @@ describe("package matrix harness", () => {
|
||||
};
|
||||
expect(document.state).toBe("verified");
|
||||
const results = document.commands.stopped_destructive.results;
|
||||
// 13 destructive commands, each unknown/runtime_not_running with exit 3.
|
||||
expect(Object.keys(results)).toHaveLength(13);
|
||||
// 11 destructive commands, each unknown/runtime_not_running with exit 3.
|
||||
expect(Object.keys(results)).toHaveLength(11);
|
||||
for (const [name, result] of Object.entries(results)) {
|
||||
expect(result, `${name} did not fail closed`).toEqual({
|
||||
exit: 3,
|
||||
@@ -162,7 +162,7 @@ describe("package matrix harness", () => {
|
||||
const shim = [
|
||||
"#!/usr/bin/env node",
|
||||
"const a=process.argv.slice(2);",
|
||||
"if(['calls','import-file','notes','permission','extraction','graph','models'].includes(a[0])||(a[0]==='processing'&&a[1]==='extract')){",
|
||||
"if(['calls','import-file','notes','extraction','graph','models'].includes(a[0])||(a[0]==='processing'&&a[1]==='extract')){",
|
||||
' process.stdout.write(\'{"schema_version":1,"product":"memhub","state":"committed","operation_id":"x","receipt":{}}\\n\');',
|
||||
" process.exit(0);",
|
||||
"}",
|
||||
@@ -188,7 +188,7 @@ describe("package matrix harness", () => {
|
||||
expect(failure?.state).toBe("failed");
|
||||
expect(
|
||||
failure?.failures.filter((item) => item.includes("did not fail closed")),
|
||||
).toHaveLength(13);
|
||||
).toHaveLength(11);
|
||||
});
|
||||
|
||||
it("can require an expected bundle SHA and reports bundle metadata", {
|
||||
@@ -280,9 +280,8 @@ describe("package matrix harness", () => {
|
||||
});
|
||||
|
||||
it("rejects a catalog that declares the parent command but not the new verb", async () => {
|
||||
// A bundle can still declare `permission`/`models` while missing
|
||||
// `permission allow` or `models activate`. Names alone would pass it; the
|
||||
// usage marker must not.
|
||||
// A bundle can still declare `models` while missing `models activate`.
|
||||
// Names alone would pass it; the usage marker must not.
|
||||
const declared = [
|
||||
"install",
|
||||
"init",
|
||||
@@ -292,7 +291,6 @@ describe("package matrix harness", () => {
|
||||
"calls",
|
||||
"import-file",
|
||||
"notes",
|
||||
"permission",
|
||||
"extraction",
|
||||
"graph",
|
||||
"models",
|
||||
@@ -342,9 +340,6 @@ describe("package matrix harness", () => {
|
||||
},
|
||||
};
|
||||
const failures = harness.validateCatalog(catalog);
|
||||
expect(failures).toContain(
|
||||
'command "permission" is missing usage "memhub permission allow"',
|
||||
);
|
||||
expect(failures).toContain(
|
||||
'command "models" is missing usage "memhub models activate"',
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdtemp, readFile, readdir, rm } from "node:fs/promises";
|
||||
import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -151,9 +151,6 @@ describe("memhub short-command contract", () => {
|
||||
"memhub import-file discard",
|
||||
"memhub notes add",
|
||||
"memhub notes process",
|
||||
"memhub permission status",
|
||||
"memhub permission allow",
|
||||
"memhub permission deny",
|
||||
"memhub models setup",
|
||||
"memhub models activate",
|
||||
"memhub models edit",
|
||||
@@ -163,6 +160,9 @@ describe("memhub short-command contract", () => {
|
||||
]) {
|
||||
expect(flattened).toContain(shortForm);
|
||||
}
|
||||
expect(COMMANDS.some((command) => command.name === "permission")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("ships a memhub bin entry pointing at a real bundle path", () => {
|
||||
|
||||
@@ -103,26 +103,45 @@ describe("unknown flags are rejected", () => {
|
||||
});
|
||||
|
||||
it("still accepts the documented verbless scan", () => {
|
||||
expect(parseProductCommand("scan", ["--all", "--yes"])?.plan.all).toBe(true);
|
||||
expect(parseProductCommand("scan", ["--source", "codex"])?.plan.sourceId).toBe(
|
||||
"codex",
|
||||
expect(parseProductCommand("scan", ["--all", "--yes"])?.plan.all).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
parseProductCommand("scan", ["--source", "codex"])?.plan.sourceId,
|
||||
).toBe("codex");
|
||||
});
|
||||
|
||||
it("rejects flags that the named verb does not consume", () => {
|
||||
// These were accepted and then silently dropped. An operator who typed
|
||||
// `path remove --source codex` would believe the source filter applied.
|
||||
expect(
|
||||
parseProductCommand("path", ["remove", "--root", "/tmp/x", "--source", "codex"]),
|
||||
parseProductCommand("path", [
|
||||
"remove",
|
||||
"--root",
|
||||
"/tmp/x",
|
||||
"--source",
|
||||
"codex",
|
||||
]),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseProductCommand("path", ["remove", "--root", "/tmp/x", "--no-recursive"]),
|
||||
parseProductCommand("path", [
|
||||
"remove",
|
||||
"--root",
|
||||
"/tmp/x",
|
||||
"--no-recursive",
|
||||
]),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseProductCommand("path", ["add", "--root", "/tmp/x", "--full"]),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseProductCommand("backup", ["create", "--target", "/tmp/b", "--source", "/tmp/s"]),
|
||||
parseProductCommand("backup", [
|
||||
"create",
|
||||
"--target",
|
||||
"/tmp/b",
|
||||
"--source",
|
||||
"/tmp/s",
|
||||
]),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseProductCommand("backup", [
|
||||
@@ -163,9 +182,7 @@ describe("unknown flags are rejected", () => {
|
||||
});
|
||||
|
||||
it("rejects repeated boolean flags instead of treating them as idempotent", () => {
|
||||
expect(
|
||||
parseProductCommand("scan", ["--all", "--all", "--yes"]),
|
||||
).toBeNull();
|
||||
expect(parseProductCommand("scan", ["--all", "--all", "--yes"])).toBeNull();
|
||||
expect(
|
||||
parseProductCommand("scan", ["--full", "--full", "--yes"]),
|
||||
).toBeNull();
|
||||
@@ -179,7 +196,13 @@ describe("unknown flags are rejected", () => {
|
||||
]),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseProductCommand("backup", ["create", "--target", "/tmp/a", "--yes", "--yes"]),
|
||||
parseProductCommand("backup", [
|
||||
"create",
|
||||
"--target",
|
||||
"/tmp/a",
|
||||
"--yes",
|
||||
"--yes",
|
||||
]),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
@@ -215,12 +238,12 @@ describe("unknown flags are rejected", () => {
|
||||
]);
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed?.confirmPath).toBe("/tmp/backups/a.sqlite3");
|
||||
expect(restoreConfirmationMatches("/tmp/backups/a.sqlite3", parsed?.confirmPath)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(restoreConfirmationMatches("/tmp/backups/a.sqlite3", undefined)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
restoreConfirmationMatches("/tmp/backups/a.sqlite3", parsed?.confirmPath),
|
||||
).toBe(true);
|
||||
expect(
|
||||
restoreConfirmationMatches("/tmp/backups/a.sqlite3", undefined),
|
||||
).toBe(false);
|
||||
expect(
|
||||
restoreConfirmationMatches(
|
||||
"/tmp/backups/a.sqlite3",
|
||||
@@ -365,7 +388,11 @@ describe("path add and remove carry what the endpoint needs", () => {
|
||||
});
|
||||
|
||||
it("distinguishes remove from add", () => {
|
||||
const parsed = parseProductCommand("path", ["remove", "--root", "/tmp/scanme"]);
|
||||
const parsed = parseProductCommand("path", [
|
||||
"remove",
|
||||
"--root",
|
||||
"/tmp/scanme",
|
||||
]);
|
||||
if (parsed === null) {
|
||||
throw new Error("path remove must parse");
|
||||
}
|
||||
@@ -375,7 +402,12 @@ describe("path add and remove carry what the endpoint needs", () => {
|
||||
});
|
||||
|
||||
it("does not silently drop --yes", () => {
|
||||
const parsed = parseProductCommand("path", ["add", "--root", "/tmp/a", "--yes"]);
|
||||
const parsed = parseProductCommand("path", [
|
||||
"add",
|
||||
"--root",
|
||||
"/tmp/a",
|
||||
"--yes",
|
||||
]);
|
||||
expect(parsed?.confirmed).toBe(true);
|
||||
// Without this, a typo'd `--yes` would fall through to a plan and the user
|
||||
// would believe the change had been made.
|
||||
|
||||
@@ -6,10 +6,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
/** The app root (one level above this test's `src/`). */
|
||||
const root = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"..",
|
||||
);
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const bundle = path.join(root, "dist", "one-memory.cjs");
|
||||
|
||||
// The published npm package must be self-contained. The bundle inlines
|
||||
@@ -20,9 +17,10 @@ const bundle = path.join(root, "dist", "one-memory.cjs");
|
||||
describe("publish manifest is production-safe", () => {
|
||||
it("declares no npm runtime dependency once dependencies are inlined", () => {
|
||||
// `test` builds with tsup first, so a missing bundle is a real failure.
|
||||
expect(existsSync(bundle), "run `pnpm --filter @one-memory/cli build`").toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
existsSync(bundle),
|
||||
"run `pnpm --filter @one-memory/cli build`",
|
||||
).toBe(true);
|
||||
const source = readFileSync(bundle, "utf8");
|
||||
const external = [
|
||||
...new Set(
|
||||
@@ -37,21 +35,24 @@ describe("publish manifest is production-safe", () => {
|
||||
),
|
||||
];
|
||||
// Every one of these must be a Node builtin, i.e. no npm package.
|
||||
const npmDeps = external.filter(
|
||||
(name) => !builtinModules.includes(name),
|
||||
);
|
||||
const npmDeps = external.filter((name) => !builtinModules.includes(name));
|
||||
expect(npmDeps).toEqual([]);
|
||||
});
|
||||
|
||||
it("strip-out rule keeps only what the bundle requires", () => {
|
||||
expect(existsSync(bundle), "run `pnpm --filter @one-memory/cli build`").toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
existsSync(bundle),
|
||||
"run `pnpm --filter @one-memory/cli build`",
|
||||
).toBe(true);
|
||||
// Run the real generator, then inspect its output manifest.
|
||||
execFileSync("node", ["scripts/prepare-publish-manifest.mjs"], {
|
||||
cwd: root,
|
||||
stdio: "pipe",
|
||||
env: { ...process.env, MEMHUB_NPM_PACKAGE: "@example/memhub-cli" },
|
||||
env: {
|
||||
...process.env,
|
||||
MEMHUB_NPM_PACKAGE: "@example/memhub-cli",
|
||||
MEMHUB_NPM_VERSION: "1.0.5",
|
||||
},
|
||||
});
|
||||
const published = JSON.parse(
|
||||
readFileSync(path.join(root, "dist-publish", "package.json"), "utf8"),
|
||||
@@ -59,6 +60,7 @@ describe("publish manifest is production-safe", () => {
|
||||
expect(published.dependencies).toBeUndefined();
|
||||
expect(published.private).toBe(false);
|
||||
expect(published.name).toBe("@example/memhub-cli");
|
||||
expect(published.version).toBe("1.0.5");
|
||||
expect(published.bin).toMatchObject({
|
||||
memhub: "dist/one-memory.cjs",
|
||||
"memhub-cli": "dist/one-memory.cjs",
|
||||
|
||||
@@ -840,6 +840,7 @@ describe("CLI-21 memory reads", () => {
|
||||
expect(isReadOnlyPath("/api/v1/memories/graph")).toBe(false);
|
||||
expect(isReadOnlyPath("/api/v1/memories/ask")).toBe(false);
|
||||
expect(isReadOnlyPath("/api/v1/memories/m1")).toBe(true);
|
||||
expect(isReadOnlyPath("/api/v1/model-content-permission")).toBe(false);
|
||||
expect(
|
||||
isReadOnlyPath(
|
||||
"/api/v1/memory-mutations/123e4567-e89b-12d3-a456-426614174000",
|
||||
|
||||
@@ -49,9 +49,9 @@ describe("runtime service lock guard", () => {
|
||||
JSON.stringify({ pid: 4321 }),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
await expect(
|
||||
inspectRuntimeServiceLock(dataDir, () => false),
|
||||
).resolves.toBe("clear");
|
||||
await expect(inspectRuntimeServiceLock(dataDir, () => false)).resolves.toBe(
|
||||
"clear",
|
||||
);
|
||||
});
|
||||
|
||||
it("fails closed on a malformed lease", async () => {
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
type CommandResult,
|
||||
inspectLaunchdService,
|
||||
restartManagedService,
|
||||
type ServiceCommandRunner,
|
||||
startManagedService,
|
||||
stopManagedService,
|
||||
type CommandResult,
|
||||
type ServiceCommandRunner,
|
||||
} from "./service-session.js";
|
||||
|
||||
const SERVICE_ID = "com.tencent.onememory.runtime";
|
||||
@@ -35,7 +35,11 @@ describe("service-aware launchd session", () => {
|
||||
it("reports running with the launchd pid and plist", async () => {
|
||||
const run = vi.fn<ServiceCommandRunner>(async () => running(84237));
|
||||
await expect(
|
||||
inspectLaunchdService({ serviceId: SERVICE_ID, uid: UID, runCaptured: run }),
|
||||
inspectLaunchdService({
|
||||
serviceId: SERVICE_ID,
|
||||
uid: UID,
|
||||
runCaptured: run,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
state: "running",
|
||||
pid: 84237,
|
||||
@@ -46,7 +50,11 @@ describe("service-aware launchd session", () => {
|
||||
it("treats 'could not find service' as absent", async () => {
|
||||
const run = vi.fn<ServiceCommandRunner>(async () => absent());
|
||||
await expect(
|
||||
inspectLaunchdService({ serviceId: SERVICE_ID, uid: UID, runCaptured: run }),
|
||||
inspectLaunchdService({
|
||||
serviceId: SERVICE_ID,
|
||||
uid: UID,
|
||||
runCaptured: run,
|
||||
}),
|
||||
).resolves.toEqual({ state: "absent" });
|
||||
});
|
||||
|
||||
@@ -57,7 +65,11 @@ describe("service-aware launchd session", () => {
|
||||
stderr: "Input/output error",
|
||||
}));
|
||||
await expect(
|
||||
inspectLaunchdService({ serviceId: SERVICE_ID, uid: UID, runCaptured: run }),
|
||||
inspectLaunchdService({
|
||||
serviceId: SERVICE_ID,
|
||||
uid: UID,
|
||||
runCaptured: run,
|
||||
}),
|
||||
).resolves.toEqual({ state: "unknown", code: "launchd_inspection_failed" });
|
||||
});
|
||||
|
||||
@@ -146,13 +158,21 @@ describe("service-aware launchd session", () => {
|
||||
if (command[1] === "print") {
|
||||
printed += 1;
|
||||
return printed === 1
|
||||
? { code: 0, stdout: `path = /tmp/x.plist\nstate = not running\n`, stderr: "" }
|
||||
? {
|
||||
code: 0,
|
||||
stdout: `path = /tmp/x.plist\nstate = not running\n`,
|
||||
stderr: "",
|
||||
}
|
||||
: running(84237);
|
||||
}
|
||||
return running(84237);
|
||||
});
|
||||
await expect(
|
||||
startManagedService({ serviceId: SERVICE_ID, uid: UID, runCaptured: run }),
|
||||
startManagedService({
|
||||
serviceId: SERVICE_ID,
|
||||
uid: UID,
|
||||
runCaptured: run,
|
||||
}),
|
||||
).resolves.toBe("started");
|
||||
expect(calls).toContainEqual([
|
||||
"launchctl",
|
||||
@@ -169,7 +189,11 @@ describe("service-aware launchd session", () => {
|
||||
return running(84237);
|
||||
});
|
||||
await expect(
|
||||
startManagedService({ serviceId: SERVICE_ID, uid: UID, runCaptured: run }),
|
||||
startManagedService({
|
||||
serviceId: SERVICE_ID,
|
||||
uid: UID,
|
||||
runCaptured: run,
|
||||
}),
|
||||
).resolves.toBe("started");
|
||||
// Already running -> no kickstart needed.
|
||||
expect(calls.some((c) => c[1] === "kickstart")).toBe(false);
|
||||
@@ -214,7 +238,11 @@ describe("service-aware launchd session", () => {
|
||||
stderr: "",
|
||||
}));
|
||||
await expect(
|
||||
inspectLaunchdService({ serviceId: SERVICE_ID, uid: UID, runCaptured: run }),
|
||||
inspectLaunchdService({
|
||||
serviceId: SERVICE_ID,
|
||||
uid: UID,
|
||||
runCaptured: run,
|
||||
}),
|
||||
).resolves.toEqual({ state: "loaded", plistPath: "/tmp/x.plist" });
|
||||
});
|
||||
|
||||
@@ -225,7 +253,11 @@ describe("service-aware launchd session", () => {
|
||||
return running(101);
|
||||
});
|
||||
await expect(
|
||||
restartManagedService({ serviceId: SERVICE_ID, uid: UID, runCaptured: run }),
|
||||
restartManagedService({
|
||||
serviceId: SERVICE_ID,
|
||||
uid: UID,
|
||||
runCaptured: run,
|
||||
}),
|
||||
).resolves.toBe("restarted");
|
||||
expect(calls).toContainEqual([
|
||||
"launchctl",
|
||||
@@ -286,7 +318,9 @@ describe("service-aware launchd session", () => {
|
||||
stdout: JSON.stringify({
|
||||
Label: SERVICE_ID,
|
||||
ProgramArguments: ["/tmp/node", "/tmp/runtime.cjs", "serve"],
|
||||
EnvironmentVariables: { ONE_MEMORY_DATA_DIR: "/tmp/this-install/data" },
|
||||
EnvironmentVariables: {
|
||||
ONE_MEMORY_DATA_DIR: "/tmp/this-install/data",
|
||||
},
|
||||
}),
|
||||
stderr: "",
|
||||
};
|
||||
|
||||
@@ -49,7 +49,10 @@ function launchdDomain(uid: number): string {
|
||||
/** Deterministic location of the managed LaunchAgent plist. Needed because
|
||||
* after `bootout` launchd no longer reports a path, yet `start` must be able to
|
||||
* bootstrap the very same service back. */
|
||||
export function defaultLaunchAgentPath(home: string, serviceId: string): string {
|
||||
export function defaultLaunchAgentPath(
|
||||
home: string,
|
||||
serviceId: string,
|
||||
): string {
|
||||
return path.posix.join(home, "Library", "LaunchAgents", `${serviceId}.plist`);
|
||||
}
|
||||
|
||||
@@ -162,7 +165,10 @@ export async function stopManagedService(options: {
|
||||
? (["launchctl", "bootout", domain, before.plistPath] as const)
|
||||
: (["launchctl", "bootout", `${domain}/${options.serviceId}`] as const);
|
||||
const result = await options.runCaptured([...target]);
|
||||
if (result.code !== 0 && !/could not find service|service not found/i.test(result.stderr)) {
|
||||
if (
|
||||
result.code !== 0 &&
|
||||
!/could not find service|service not found/i.test(result.stderr)
|
||||
) {
|
||||
throw new Error("launchd_bootout_failed");
|
||||
}
|
||||
// "Stopped" must mean the label stays gone, not that we saw it gone once.
|
||||
@@ -295,9 +301,7 @@ export async function runLaunchctlCaptured(
|
||||
stderr += String(chunk);
|
||||
});
|
||||
child.once("error", () => reject(new Error("launchd_command_failed")));
|
||||
child.once("close", (code) =>
|
||||
resolve({ code: code ?? 1, stdout, stderr }),
|
||||
);
|
||||
child.once("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,11 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { applyShellPath, planShellPath, removeShellPath } from "./shell-path.js";
|
||||
import {
|
||||
applyShellPath,
|
||||
planShellPath,
|
||||
removeShellPath,
|
||||
} from "./shell-path.js";
|
||||
|
||||
async function home(): Promise<string> {
|
||||
return mkdtemp(path.join(tmpdir(), "memhub-shell-path-"));
|
||||
|
||||
@@ -72,9 +72,7 @@ function blockFor(binDirectory: string): string {
|
||||
* original file byte-for-byte regardless of the original's trailing newline. */
|
||||
function ownedBlock(existing: string | null, binDirectory: string): string {
|
||||
const separator =
|
||||
existing === null || existing === "" || existing.endsWith("\n")
|
||||
? ""
|
||||
: "\n";
|
||||
existing === null || existing === "" || existing.endsWith("\n") ? "" : "\n";
|
||||
return `${separator}${blockFor(binDirectory)}`;
|
||||
}
|
||||
|
||||
@@ -104,10 +102,7 @@ export async function planShellPath(options: {
|
||||
disabled: true,
|
||||
};
|
||||
}
|
||||
const blocked = (
|
||||
reason: string,
|
||||
target: string,
|
||||
): ShellPathPlan => ({
|
||||
const blocked = (reason: string, target: string): ShellPathPlan => ({
|
||||
schema_version: 1,
|
||||
status: "blocked",
|
||||
blocked_reason: reason,
|
||||
@@ -229,11 +224,12 @@ async function writeProfileAtomically(
|
||||
// A fresh `--home` may not exist yet; create it (owner-only) before writing
|
||||
// the temp profile, otherwise the write fails with a raw ENOENT. Surface a
|
||||
// structured code for any other failure.
|
||||
await mkdir(path.dirname(profilePath), { recursive: true, mode: 0o700 }).catch(
|
||||
() => {
|
||||
throw new Error("shell_path_home_unwritable");
|
||||
},
|
||||
);
|
||||
await mkdir(path.dirname(profilePath), {
|
||||
recursive: true,
|
||||
mode: 0o700,
|
||||
}).catch(() => {
|
||||
throw new Error("shell_path_home_unwritable");
|
||||
});
|
||||
const temporary = `${profilePath}.memhub.${process.pid}.tmp`;
|
||||
try {
|
||||
await writeFile(temporary, content, { encoding: "utf8", mode: 0o644 });
|
||||
|
||||
@@ -468,7 +468,9 @@ describe("CLI-19 progress and issue reads", () => {
|
||||
);
|
||||
expect(output).toContain("[15:04:05.067] progress #1");
|
||||
expect(output).toContain("[15:04:05.067] progress #2");
|
||||
expect(output.match(/\x1b\[2J\x1b\[H/g)).toHaveLength(2);
|
||||
expect(output.match(new RegExp("\\x1b\\[2J\\x1b\\[H", "g"))).toHaveLength(
|
||||
2,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps non-terminal watch output append-only", async () => {
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { CoreReader, ReadOutcome } from "./core-client.js";
|
||||
import type {
|
||||
CoreOperations,
|
||||
OperationOutcome,
|
||||
} from "./core-operations.js";
|
||||
import type { CoreOperations, OperationOutcome } from "./core-operations.js";
|
||||
import {
|
||||
renderSourceSyncText,
|
||||
setSourceSync,
|
||||
@@ -320,4 +317,3 @@ describe("setSourceSync", () => {
|
||||
expect(renderSourceSyncText(invalid)).toBe("未变更:invalid_source_id\n");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
SourceSyncInputError,
|
||||
buildSourceSyncRequest,
|
||||
hasSourceSyncTarget,
|
||||
SourceSyncInputError,
|
||||
} from "@one-memory/operations";
|
||||
import type { CoreReader } from "./core-client.js";
|
||||
import type { CoreOperations } from "./core-operations.js";
|
||||
@@ -36,7 +36,10 @@ async function current(
|
||||
reader: CoreReader,
|
||||
sourceId: string,
|
||||
): Promise<
|
||||
| { state: "ok"; source: NonNullable<ReturnType<typeof validateSources>>[number] }
|
||||
| {
|
||||
state: "ok";
|
||||
source: NonNullable<ReturnType<typeof validateSources>>[number];
|
||||
}
|
||||
| { state: "invalid" | "unknown"; code: string }
|
||||
> {
|
||||
const outcome = await reader<unknown>("/api/v1/sources");
|
||||
|
||||
@@ -30,6 +30,8 @@ describe("status default output", () => {
|
||||
expect(text).not.toContain("[object Object]");
|
||||
expect(text).toContain("卡住 类型 整理对话/原因 等待模型/数量 2");
|
||||
expect(text).not.toMatch(/background_verified|additions_only|error_codes=/);
|
||||
expect(text).not.toMatch(/provider_kind|has_api_key|credential_state|observed_at/);
|
||||
expect(text).not.toMatch(
|
||||
/provider_kind|has_api_key|credential_state|observed_at/,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -85,12 +85,16 @@ describe("memhub ui command wiring", () => {
|
||||
const output = capture();
|
||||
let code: number;
|
||||
try {
|
||||
code = await run(["ui", "--json"], {}, {
|
||||
openBrowser: async (url) => {
|
||||
opened.push(url);
|
||||
return true;
|
||||
code = await run(
|
||||
["ui", "--json"],
|
||||
{},
|
||||
{
|
||||
openBrowser: async (url) => {
|
||||
opened.push(url);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
} finally {
|
||||
output.restore();
|
||||
}
|
||||
@@ -102,7 +106,9 @@ describe("memhub ui command wiring", () => {
|
||||
state: "opened",
|
||||
url: "http://127.0.0.1:8765/ui/login?code=one-time-code",
|
||||
});
|
||||
expect(opened).toEqual(["http://127.0.0.1:8765/ui/login?code=one-time-code"]);
|
||||
expect(opened).toEqual([
|
||||
"http://127.0.0.1:8765/ui/login?code=one-time-code",
|
||||
]);
|
||||
// The bearer token was sent to Core in the request header, never in output.
|
||||
expect(output.value()).not.toMatch(/synthetic-runtime-token/);
|
||||
});
|
||||
@@ -159,7 +165,11 @@ describe("memhub ui command wiring", () => {
|
||||
const output = capture();
|
||||
let code: number;
|
||||
try {
|
||||
code = await run(["ui", "--json"], {}, { openBrowser: async () => false });
|
||||
code = await run(
|
||||
["ui", "--json"],
|
||||
{},
|
||||
{ openBrowser: async () => false },
|
||||
);
|
||||
} finally {
|
||||
output.restore();
|
||||
}
|
||||
@@ -185,7 +195,11 @@ describe("memhub ui command wiring", () => {
|
||||
const output = capture();
|
||||
let code: number;
|
||||
try {
|
||||
code = await run(["ui", "--json"], {}, { openBrowser: async () => true });
|
||||
code = await run(
|
||||
["ui", "--json"],
|
||||
{},
|
||||
{ openBrowser: async () => true },
|
||||
);
|
||||
} finally {
|
||||
output.restore();
|
||||
}
|
||||
|
||||
@@ -9,7 +9,8 @@ import { parseUiSessionExchange } from "./ui-session.js";
|
||||
describe("ui session exchange over HTTP", () => {
|
||||
let server: Server;
|
||||
let port: number;
|
||||
const seen: Array<{ authorization?: string; method?: string; url?: string }> = [];
|
||||
const seen: Array<{ authorization?: string; method?: string; url?: string }> =
|
||||
[];
|
||||
let status = 200;
|
||||
|
||||
beforeAll(async () => {
|
||||
|
||||
@@ -45,11 +45,31 @@ describe("memhub ui session wiring", () => {
|
||||
for (const doc of [
|
||||
null,
|
||||
{},
|
||||
{ schema_version: 2, exchange_code: "x", expires_in_seconds: 60, url: "http://127.0.0.1:1/ui/login?code=x" },
|
||||
{
|
||||
schema_version: 2,
|
||||
exchange_code: "x",
|
||||
expires_in_seconds: 60,
|
||||
url: "http://127.0.0.1:1/ui/login?code=x",
|
||||
},
|
||||
{ schema_version: 1, exchange_code: "x", expires_in_seconds: 60 },
|
||||
{ schema_version: 1, exchange_code: "", expires_in_seconds: 60, url: "http://127.0.0.1:1/ui/login?code=x" },
|
||||
{ schema_version: 1, exchange_code: "x", expires_in_seconds: 0, url: "http://127.0.0.1:1/ui/login?code=x" },
|
||||
{ schema_version: 1, exchange_code: "x", expires_in_seconds: 60, url: "http://127.0.0.1:1/" },
|
||||
{
|
||||
schema_version: 1,
|
||||
exchange_code: "",
|
||||
expires_in_seconds: 60,
|
||||
url: "http://127.0.0.1:1/ui/login?code=x",
|
||||
},
|
||||
{
|
||||
schema_version: 1,
|
||||
exchange_code: "x",
|
||||
expires_in_seconds: 0,
|
||||
url: "http://127.0.0.1:1/ui/login?code=x",
|
||||
},
|
||||
{
|
||||
schema_version: 1,
|
||||
exchange_code: "x",
|
||||
expires_in_seconds: 60,
|
||||
url: "http://127.0.0.1:1/",
|
||||
},
|
||||
]) {
|
||||
expect(parseUiSessionExchange(doc)).toBeNull();
|
||||
}
|
||||
@@ -59,9 +79,18 @@ describe("memhub ui session wiring", () => {
|
||||
expect(uiSessionFailure("ui_web_assets_unavailable")).toMatchObject({
|
||||
code: "ui_web_assets_unavailable",
|
||||
});
|
||||
expect(uiExitCode({ state: "opened", url: "http://127.0.0.1:1/ui/login?code=x" })).toBe(0);
|
||||
expect(uiExitCode({ state: "blocked", code: "ui_session_contract_unavailable" })).toBe(4);
|
||||
expect(uiExitCode({ state: "failed", code: "ui_session_code_invalid" })).toBe(1);
|
||||
expect(
|
||||
uiExitCode({
|
||||
state: "opened",
|
||||
url: "http://127.0.0.1:1/ui/login?code=x",
|
||||
}),
|
||||
).toBe(0);
|
||||
expect(
|
||||
uiExitCode({ state: "blocked", code: "ui_session_contract_unavailable" }),
|
||||
).toBe(4);
|
||||
expect(
|
||||
uiExitCode({ state: "failed", code: "ui_session_code_invalid" }),
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it("uses a platform-appropriate opener and reports missing openers", async () => {
|
||||
|
||||
@@ -42,7 +42,12 @@ function isLoopbackHttpUrl(value: string): boolean {
|
||||
}
|
||||
if (parsed.protocol !== "http:") return false;
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
|
||||
return (
|
||||
host === "localhost" ||
|
||||
host === "127.0.0.1" ||
|
||||
host === "[::1]" ||
|
||||
host === "::1"
|
||||
);
|
||||
}
|
||||
|
||||
/** Validate the Core exchange document; return null when it does not match the
|
||||
|
||||
@@ -80,7 +80,13 @@ describe("calls clear", () => {
|
||||
});
|
||||
|
||||
it("previews without contacting Core", async () => {
|
||||
const result = await capturedRun(["calls", "clear", "--event", EVENT, "--json"]);
|
||||
const result = await capturedRun([
|
||||
"calls",
|
||||
"clear",
|
||||
"--event",
|
||||
EVENT,
|
||||
"--json",
|
||||
]);
|
||||
expect(result.code).toBe(0);
|
||||
const document = JSON.parse(result.stdout);
|
||||
expect(document.state).toBe("preview");
|
||||
@@ -341,7 +347,10 @@ describe("notes / extraction / graph / manual extract", () => {
|
||||
"--json",
|
||||
]);
|
||||
expect(applied.code).toBe(0);
|
||||
const body = transport.post.mock.calls.at(-1)?.[1] as Record<string, unknown>;
|
||||
const body = transport.post.mock.calls.at(-1)?.[1] as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(body.text).toBe("记住这个决定");
|
||||
expect(body.scope).toBe("all-apps");
|
||||
expect(JSON.parse(applied.stdout).state).toBe("committed");
|
||||
|
||||
@@ -10,18 +10,17 @@
|
||||
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import {
|
||||
MemoryNoteInputError,
|
||||
buildMemoryNoteSaveRequest,
|
||||
parseMemoryNoteReceipt,
|
||||
MemoryNoteInputError,
|
||||
parseExtractionSettingsReceipt,
|
||||
parseGraphWidthDecisionReceipt,
|
||||
parseManualExtractReceipt,
|
||||
parseMemoryNoteReceipt,
|
||||
} from "@one-memory/operations";
|
||||
import type { CoreOperations, CorePutOperations } from "./core-operations.js";
|
||||
import { PRODUCT } from "./version.js";
|
||||
|
||||
const UUID =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
const DIGEST = /^[0-9a-f]{64}$/;
|
||||
const NOTE_MAX_CHARACTERS = 12_000;
|
||||
const EXTRACTION_PRESETS = ["3m", "6m", "1y", "all"] as const;
|
||||
@@ -117,7 +116,10 @@ function digestOf(value: unknown): string {
|
||||
type Draft =
|
||||
| Omit<Extract<ExtendedWritePlan, { kind: "memory_note_add" }>, "digest">
|
||||
| Omit<Extract<ExtendedWritePlan, { kind: "memory_note_process" }>, "digest">
|
||||
| Omit<Extract<ExtendedWritePlan, { kind: "extraction_window_set" }>, "digest">
|
||||
| Omit<
|
||||
Extract<ExtendedWritePlan, { kind: "extraction_window_set" }>,
|
||||
"digest"
|
||||
>
|
||||
| Omit<Extract<ExtendedWritePlan, { kind: "graph_width_decide" }>, "digest">
|
||||
| Omit<Extract<ExtendedWritePlan, { kind: "manual_extract" }>, "digest">;
|
||||
|
||||
@@ -148,7 +150,10 @@ function committed(
|
||||
};
|
||||
}
|
||||
|
||||
function rejected(operationId: string | undefined, code: string): ExtendedWriteOutcome {
|
||||
function rejected(
|
||||
operationId: string | undefined,
|
||||
code: string,
|
||||
): ExtendedWriteOutcome {
|
||||
return {
|
||||
schema_version: 1,
|
||||
product: PRODUCT,
|
||||
@@ -158,7 +163,10 @@ function rejected(operationId: string | undefined, code: string): ExtendedWriteO
|
||||
};
|
||||
}
|
||||
|
||||
function unknown(operationId: string | undefined, code: string): ExtendedWriteOutcome {
|
||||
function unknown(
|
||||
operationId: string | undefined,
|
||||
code: string,
|
||||
): ExtendedWriteOutcome {
|
||||
return {
|
||||
schema_version: 1,
|
||||
product: PRODUCT,
|
||||
@@ -197,7 +205,9 @@ export function validNoteText(text: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
export function planMemoryNoteProcess(evidenceId: string): ExtendedWriteOutcome {
|
||||
export function planMemoryNoteProcess(
|
||||
evidenceId: string,
|
||||
): ExtendedWriteOutcome {
|
||||
return UUID.test(evidenceId)
|
||||
? preview({
|
||||
schema_version: 1,
|
||||
@@ -313,8 +323,7 @@ export function planGraphWidthDecide(decision: string): ExtendedWriteOutcome {
|
||||
|
||||
export function planManualExtract(evidenceIds: string[]): ExtendedWriteOutcome {
|
||||
const ids = [...new Set(evidenceIds)];
|
||||
return ids.length === evidenceIds.length &&
|
||||
ids.every((id) => UUID.test(id))
|
||||
return ids.length === evidenceIds.length && ids.every((id) => UUID.test(id))
|
||||
? preview({
|
||||
schema_version: 1,
|
||||
kind: "manual_extract",
|
||||
@@ -455,12 +464,12 @@ export function validateExtendedWritePlan(
|
||||
}
|
||||
|
||||
export function extendedWriteExitCode(document: ExtendedWriteOutcome): number {
|
||||
return ["preview", "committed", "recovered"].includes(document.state)
|
||||
? 0
|
||||
: 1;
|
||||
return ["preview", "committed", "recovered"].includes(document.state) ? 0 : 1;
|
||||
}
|
||||
|
||||
export function renderExtendedWriteText(document: ExtendedWriteOutcome): string {
|
||||
export function renderExtendedWriteText(
|
||||
document: ExtendedWriteOutcome,
|
||||
): string {
|
||||
if (document.state === "preview") {
|
||||
const lines = ["以下操作尚未执行;加 --confirm 后才会写入:"];
|
||||
const plan = document.plan;
|
||||
|
||||
@@ -61,10 +61,9 @@ describe("UI write execution", () => {
|
||||
}));
|
||||
const plan = planOf(planCallEventsClear([EVENT]));
|
||||
if (plan.kind !== "call_events_clear") throw new Error("kind");
|
||||
const result = await executeCallEventsClear(
|
||||
plan,
|
||||
{ post } as unknown as CoreOperations,
|
||||
);
|
||||
const result = await executeCallEventsClear(plan, {
|
||||
post,
|
||||
} as unknown as CoreOperations);
|
||||
expect(result.state).toBe("committed");
|
||||
expect(post).toHaveBeenCalledWith("/api/v1/call-events/clear", {
|
||||
event_ids: [EVENT],
|
||||
@@ -79,10 +78,9 @@ describe("UI write execution", () => {
|
||||
}));
|
||||
const plan = planOf(planCallEventsClearAll());
|
||||
if (plan.kind !== "call_events_clear_all") throw new Error("kind");
|
||||
await executeCallEventsClearAll(
|
||||
plan,
|
||||
{ post } as unknown as CoreOperations,
|
||||
);
|
||||
await executeCallEventsClearAll(plan, {
|
||||
post,
|
||||
} as unknown as CoreOperations);
|
||||
expect(post).toHaveBeenCalledWith("/api/v1/call-events/clear-all", {
|
||||
user_confirmed: true,
|
||||
});
|
||||
@@ -107,7 +105,7 @@ describe("UI write execution", () => {
|
||||
committed: true,
|
||||
},
|
||||
}));
|
||||
const del = vi.fn(async <T,>() => ({
|
||||
const del = vi.fn(async <T>() => ({
|
||||
state: "committed" as const,
|
||||
data: {} as T,
|
||||
}));
|
||||
@@ -118,10 +116,9 @@ describe("UI write execution", () => {
|
||||
const commit = planOf(planImportFileCommit(UPLOAD));
|
||||
if (commit.kind !== "import_file_commit") throw new Error("kind");
|
||||
await executeImportFileCommit(commit, operations);
|
||||
expect(post).toHaveBeenCalledWith(
|
||||
`/api/v1/import-files/${UPLOAD}/commit`,
|
||||
{ confirmed: true },
|
||||
);
|
||||
expect(post).toHaveBeenCalledWith(`/api/v1/import-files/${UPLOAD}/commit`, {
|
||||
confirmed: true,
|
||||
});
|
||||
const discard = planOf(planImportFileDiscard(UPLOAD));
|
||||
if (discard.kind !== "import_file_discard") throw new Error("kind");
|
||||
expect((await executeImportFileDiscard(discard, operations)).state).toBe(
|
||||
@@ -133,15 +130,12 @@ describe("UI write execution", () => {
|
||||
it("treats a malformed success receipt as unknown", async () => {
|
||||
const plan = planOf(planCallEventsClear([EVENT]));
|
||||
if (plan.kind !== "call_events_clear") throw new Error("kind");
|
||||
const result = await executeCallEventsClear(
|
||||
plan,
|
||||
{
|
||||
post: vi.fn(async () => ({
|
||||
state: "committed" as const,
|
||||
data: { wrong: true },
|
||||
})),
|
||||
} as unknown as CoreOperations,
|
||||
);
|
||||
const result = await executeCallEventsClear(plan, {
|
||||
post: vi.fn(async () => ({
|
||||
state: "committed" as const,
|
||||
data: { wrong: true },
|
||||
})),
|
||||
} as unknown as CoreOperations);
|
||||
expect(result).toMatchObject({
|
||||
state: "unknown",
|
||||
code: "ui_write_receipt_invalid",
|
||||
|
||||
Loaded 100 of 568 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user