Compare commits

...
Author SHA1 Message Date
alvinfeiandClaude Opus 5.5 a653bd4065 feat(memhub): intention dedup switch in memory features
Expose hy-memory 2.0.12's per-client intention dedup in the memory-features
setting: the feature intention_dedup (recall.intention_dedup_enabled, default
on) and the parameter intention_dedup_threshold
(recall.intention_dedup_threshold, default 0.95, accepted 0.8-1.0, else 422).
Both are part of the features key, so a change rebuilds the SDK clients like
the other switches. CLI: memhub settings features set intention_dedup=false,
intention_dedup_threshold=0.9. Refs #241.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 15:04:24 +08:00
alvinfeiandClaude Opus 5.5 07b426ba7f chore(memhub): pin hy-memory 2.0.12
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 15:04:24 +08:00
feitianxiang 3511153f9f Merge pull request #274 from Tencent-Hunyuan/fix/deepseek-harness-profiles
fix(memhub): DeepSeek Harness one switch grants every profile; import versioned sessions and v3 tool text
2026-11-02 14:17:44 +08:00
feitianxiang 23facf75d5 Merge pull request #273 from Tencent-Hunyuan/fix/single-runtime-quit
fix(memhub): one runtime; App quit never stops the background service, stops every runtime when it is disabled
2026-11-02 14:17:32 +08:00
alvinfeiandClaude Opus 5.5 71b8f9be24 Merge github/main into fix/deepseek-harness-profiles
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 14:04:40 +08:00
feitianxiang d257188d09 Merge pull request #270 from Tencent-Hunyuan/fix/commit-validation-and-zh-language
fix(memhub): one commit format at the packaged-runtime boundary; zh-Hans UI sets the SDK language
2026-11-02 14:03:21 +08:00
feitianxiang bde0220373 Merge pull request #268 from Tencent-Hunyuan/feat/sdk-intention-dedup-switch
feat(sdk): configurable intention dedup (on by default, unchanged behaviour)
2026-11-02 14:03:04 +08:00
alvinfeiandClaude Opus 5.5 a88d227cc0 fix(memhub): one DeepSeek Harness switch for every detected profile
The app page assumed one source maps to one host. Harness has none without a
profile, so the switch was greyed out with `unsupported_host` and an installed
profile stayed `install-only` with no way to approve it (#230).

The one switch now covers every `deepseek-harness:<profile>` through the
existing install, grant, revoke and uninstall APIs. On installs and grants each
profile that is not approved, off removes and revokes each linked one. A
profile that fails is named and the others keep their result. The page lists
each profile with its state.

New profiles are connected while the switch is on. The desktop re-reads the
profile list on each host refresh, and the remembered apply gets one more
attempt per new profile. The Runtime re-reads the disk for an unknown profile
id: its list was fixed at start and it outlives the App, so one new profile
made the host list fail for every app.

Rewrite the harness doc to match, removing the sources page it described,
which is not mounted. Add the strings to all 11 locales.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 13:11:19 +08:00
alvinfeiandClaude Opus 5.5 0d0cefb25e fix(core): leave no cursor on a DeepSeek Harness session it refuses
An unknown session version was skipped record by record. Each skip carried a
cursor and the file ended with a cursor touch, so the refused session sat
behind a checkpoint: the release that learned the format would read nothing,
turning "not imported yet" into "never imported". The skip was also not
reported, since `report_issue` defaults to false.

Refuse the file from its header instead, with the cursorless
`ScanFailure(UNSUPPORTED_SCHEMA)` other sources already use. The parser check
stays for callers that hand it records directly.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 12:55:17 +08:00
alvinfeiandClaude Opus 5.5 be8cf028ff test(core): pin DeepSeek Harness text tool output and session name boundary
Cover the #175 tool-output half directly: a `tool/result` written as plain
`text` blocks imports next to the older `tool-result` block shape, goes
through the same credential scrubbing and clipping, and names outside
`session[.vN].jsonl[.zstd]` stay out. Correct the contract-suite comments that
still said only `session.jsonl` was accepted.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 12:47:17 +08:00
alvinfeiandClaude Opus 5.5 d0a4fd60f2 fix(memhub): pass every UI language to the SDK, zh-Hans included
The owner's decision for #243: a zh-Hans UI now sets
MemoryConfig.language="zh-Hans" like every other UI language, so App users
never fall back to the SDK's zh/en auto-detect. Only an unset language
(CLI/API-only installs, or 'settings language system') keeps auto-detect.
status --json pipeline.sdk_language shows zh-Hans for zh-Hans users.

Desktop now syncs the language the GUI shows (snapshot.locale), not the raw
preference: an App that follows the system sends the resolved locale
(e.g. zh-Hans on a Chinese macOS) instead of null.

Refs #243 (MemHub passes the language explicitly; the SDK's System 2
auto-detect is left unchanged for direct SDK users)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 12:35:25 +08:00
alvinfeiandClaude Opus 5.5 aae877b880 fix(memhub): accept only a full 40-character commit at the packaged-runtime boundary
resolvePackagedCommit accepted 7-40 hex characters in any case, while every
downstream check (packaged-runtime install, local install, release download,
release scripts, after-pack) requires 40 lowercase hex characters. It now
accepts exactly 40 hex characters, case-insensitive, returns them lowercased,
and skips a short or malformed value so a bad ONE_MEMORY_COMMIT no longer
shadows the embedded commit. The tsup build fails on a malformed supplied
ONE_MEMORY_COMMIT instead of baking it.

Fixes #236, Fixes #235

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 12:35:14 +08:00
alvinfeiandClaude Opus 5.5 ef5ff06590 fix(sdk): intention dedup switch also gates write-batch dedup
When intention_dedup_enabled is off, no intention dedup should run, but
the writer's batch dedup still dropped near-duplicate intentions from
one extraction. Gate it on the same switch. Its threshold stays on
MEMORY_DEDUP_THRESHOLD.

Also skip the embedding backfill when dedup is off, since only dedup
uses it, and fall back to the env default on an invalid configured
threshold so a bad value cannot fail the read.

Refs #241

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 12:33:56 +08:00
ryanlandClaude Opus 5.5 7eb38aa6ad fix(core): import versioned DeepSeek Harness session files
DSH names a session file after its format generation
(`session.v3.jsonl.zstd`, `session.v4.jsonl.zstd`), but discovery matched only
the two unversioned names, so import jobs completed with `discovered 0` while
the sessions sat on disk.

Discover `session[.vN].jsonl[.zstd]` and gate parsing on the header `version`
field: verified generations (0/3/4) import, anything newer is skipped as
`unsupported_schema` rather than interpreted with today's field rules. v4 tool
results use plain `text` blocks, so read that shape through the same clipping
and credential-scrubbing path as the `tool-result` blocks used by v0/v3.

(cherry picked from commit 2a65e5ab2d8548cfb8d6f72a4b68b702f6b4a3cc; conflicts in CHANGELOG.md and the Core test inventory resolved against main)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 12:32:02 +08:00
alvinfeiandClaude Opus 5.5 2624228f6f feat(sdk): configurable intention dedup (on by default, unchanged behaviour)
Add MemoryConfig.recall.intention_dedup_enabled (default true, env
MEMORY_INTENTION_DEDUP_ENABLED) and recall.intention_dedup_threshold
(env MEMORY_INTENTION_DEDUP_THRESHOLD, falling back to the shared
MEMORY_DEDUP_THRESHOLD, then 0.95). The reader passes both from the
client config to recall_intentions. When off, read-time intention dedup
is skipped entirely: nothing is hidden and nothing is deleted.

Refs #241

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 12:25:37 +08:00
74 changed files with 2942 additions and 321 deletions

No files matched your search

+42
View File
@@ -4,6 +4,48 @@ Hy Memory and MemHub are versioned and released independently.
## Unreleased
- MemHub's DeepSeek Harness app page can grant recall again (#230). The
"一键插入应用" switch used to be greyed out with `unsupported_host`, and a
profile installed from the CLI stayed `install-only` with no way to approve
it. The one switch now covers every detected profile
(`deepseek-harness:<profile>`): on installs each profile's MCP patch and
grants recall, off removes the patch and revokes the grant. The page lists
each profile with its state, and names any profile that failed while
keeping the others. While the switch is on, a profile created later is
installed and granted automatically, without restarting MemHub; the Runtime
also no longer fails every host read when it meets a profile created after
it started. The harness docs no longer describe an unmounted sources page.
- MemHub's `deepseek-harness` source imports session files whose names carry the
format generation: `session.v3.jsonl.zstd` and `session.v4.jsonl.zstd` are now
discovered alongside the original `session.jsonl[.zstd]`. Discovery accepts
any `session[.vN].jsonl[.zstd]` name and the header's `version` decides
whether the session is parsed (v0/v3/v4) or refused as `unsupported_schema`.
A refused file is reported and keeps no cursor, so the release that learns
its format reads it from the top.
v4 tool results, which are written as plain `text` blocks rather than
`tool-result` blocks, are read through the same clipping and credential
scrubbing path. Previously every versioned session was invisible: the import
job completed with `discovered 0` while the files sat on disk.
- SDK: Intention dedup is now configurable per client
(`MemoryConfig.recall.intention_dedup_enabled`, default `true`;
`recall.intention_dedup_threshold`, default `MEMORY_DEDUP_THRESHOLD` or
`0.95`). Env defaults: `MEMORY_INTENTION_DEDUP_ENABLED`,
`MEMORY_INTENTION_DEDUP_THRESHOLD`. When on, behaviour is unchanged
(duplicates found at read time are still deleted); when off, no intention
dedup runs, at read time or within a write batch, and nothing is hidden,
dropped or deleted. The threshold applies to read-time dedup only. Refs #241.
- MemHub pins `hy-memory==2.0.12` and exposes that intention dedup switch in
its memory-features setting (`GET`/`PUT /api/v1/settings/memory-features`,
`memhub settings features`): the feature `intention_dedup` (default on) and
the numeric `intention_dedup_threshold` (default 0.95, accepted 0.8–1.0,
anything else is 422 or a CLI usage error). Unset, both keep the SDK
default, so nothing changes for the App; a change rebuilds the SDK clients
like the other feature switches. The API answer gains `parameters`, and
`pipeline.features` can now carry the threshold as a number. Refs #241.
## MemHub 1.0.6 — 2026-11-02
Build 37, on `hy-memory==2.0.11`. Linux x64/arm64 Runtime and macOS arm64
+20
View File
@@ -182,9 +182,29 @@ SDK 不设置 Rerank Search 并发上限。开启后模型在 `HyMemoryClient`
| `MEMORY_RECALL_STRENGTH_TAU` | `180` | 衰减时间常数,天 |
| `MEMORY_RECALL_ACCESS_TRACKING` | `true` | Strength 开启时是否回写访问信息 |
| `MEMORY_ENTITY_STORE_ENABLED` | `false` | 是否维护独立 entity collection;当前 Reader 不直接读取 |
| `MEMORY_INTENTION_DEDUP_ENABLED` | `true` | 是否对 L7 Intention 判重(读侧和写入侧批内);见下文 |
| `MEMORY_INTENTION_DEDUP_THRESHOLD` | `MEMORY_DEDUP_THRESHOLD`,再缺省为 `0.95` | Intention 读侧判重的 cosine 阈值 |
旧数据可调用当前公开方法 `client.build_entity_store(user_id)` 补建 Entity Store。
Intention 判重:开启时(默认,与以往行为一致),Search 召回的 L7 Intention 中,
同 `user_id` + 同 `agent_id` + `memory_at` 同一天 + `valid_until` 相同、且 cosine ≥ 阈值的
条目视为复本,只返回最早写入的一条,其余在后台从向量库**删除**。判重不区分内容中的项目、
对象等语义差异,内容高度相似但对象不同的意图可能被误删;写入时同一批抽取结果也会做一次
批内判重。关闭后这两处都不判重,不隐藏、不丢弃、也不删除意图。两项对应
`MemoryConfig.recall.intention_dedup_enabled` /
`recall.intention_dedup_threshold`,按 client 生效,环境变量只提供默认值:
```python
client = HyMemoryClient.from_config({
"recall": {"intention_dedup_enabled": False},
})
```
`MEMORY_DEDUP_THRESHOLD` 同时被写入侧批内意图判重和 dedup 内核使用;
`MEMORY_INTENTION_DEDUP_THRESHOLD` 只影响读侧 Intention 判重,写入侧批内判重的阈值
仍取 `MEMORY_DEDUP_THRESHOLD`。
## 日志、Trace 与历史
| 变量 | 默认值 | 说明 |
+19
View File
@@ -432,6 +432,14 @@ class RecallConfig:
retrieval_clauses_require_keyword: bool = None # env: MEMORY_RETRIEVAL_CLAUSES_REQUIRE_KEYWORD
retrieval_clauses_min_keyword_score: float = None # normalized BM25 floor
supplemental_propositions_enabled: bool = None # env: MEMORY_SUPPLEMENTAL_PROPOSITIONS_ENABLED
# ── Intention(L7)判重 ──
# 开启(默认):召回时同 user+agent+同天 memory_at+同 valid_until 且
# cosine≥阈值 的意图视为复本,只返回最早一条,其余异步从 VDB 删除(历史行为)。
# 关闭:读侧与写入侧批内都不判重——不隐藏、不丢弃、不删除任何意图。
intention_dedup_enabled: bool = None # env: MEMORY_INTENTION_DEDUP_ENABLED
# 读侧意图判重 cosine 阈值。env: MEMORY_INTENTION_DEDUP_THRESHOLD,
# 未设置时回退到共享的 MEMORY_DEDUP_THRESHOLD(兼容旧部署),默认 0.95。
intention_dedup_threshold: float = None
# 最小分数阈值
min_score_threshold: float = 0.0
@@ -750,6 +758,15 @@ class RecallConfig:
self.supplemental_propositions_enabled = _get_env_bool(
"MEMORY_SUPPLEMENTAL_PROPOSITIONS_ENABLED", False
)
if self.intention_dedup_enabled is None:
self.intention_dedup_enabled = _get_env_bool(
"MEMORY_INTENTION_DEDUP_ENABLED", True
)
if self.intention_dedup_threshold is None:
self.intention_dedup_threshold = _get_env_float(
"MEMORY_INTENTION_DEDUP_THRESHOLD",
_get_env_float("MEMORY_DEDUP_THRESHOLD", 0.95),
)
@dataclass
@@ -1384,6 +1401,8 @@ class MemoryConfig:
"supplemental_propositions_enabled": (
self.recall.supplemental_propositions_enabled
),
"intention_dedup_enabled": self.recall.intention_dedup_enabled,
"intention_dedup_threshold": self.recall.intention_dedup_threshold,
},
"pipeline": {
"default_version": self.pipeline.default_version,
+31 -10
View File
@@ -15,6 +15,9 @@ HY Memory - Intention (L7) 召回 + 惰性过期转换 + 复本判定
→ 视为同一个意图的复本(extractor 复读机 / 多 session 重复表达)。
保留组里 `gmt_created` 最早的(老的先来先得,稳定 id);
- **异步删库**:其余复本 fire-and-forget 从 VDB 删除,不影响本次调用 RT。
- **开关**:判重受 `MemoryConfig.recall.intention_dedup_enabled`(默认开)与
`recall.intention_dedup_threshold` 控制,由 reader 按 client 配置传入。
关闭时完全跳过判重:不隐藏、不删除任何意图(写入侧批内判重同样跳过)。
Q: 为什么要看 memory_at 和 valid_until?
A: 意图是 point-in-time 信号。同一句"我周五要开会",如果一条 memory_at 在
@@ -38,8 +41,14 @@ from ...models.memory import MemoryLayer, MemoryStatus
logger = logging.getLogger(__name__)
def _get_dedup_threshold() -> float:
"""去重 cosine 阈值:沿用 dedup 内核的 MEMORY_DEDUP_THRESHOLD,默认 0.95。"""
def _get_dedup_threshold(configured: Optional[float] = None) -> float:
"""去重 cosine 阈值:优先用 client 配置;否则(或配置非法)沿用 dedup 内核的
MEMORY_DEDUP_THRESHOLD,默认 0.95。"""
try:
if configured is not None:
return float(configured)
except (TypeError, ValueError):
logger.warning(f"[intention] invalid dedup threshold: {configured!r}")
try:
return float(os.environ.get("MEMORY_DEDUP_THRESHOLD", 0.95))
except (TypeError, ValueError):
@@ -244,6 +253,8 @@ async def recall_intentions(
stats_out: Optional[Dict[str, Any]] = None,
include_sources: Optional[List[str]] = None,
exclude_sources: Optional[List[str]] = None,
dedup_enabled: bool = True,
dedup_threshold: Optional[float] = None,
) -> List[Dict[str, Any]]:
"""
召回未过期的 L7_INTENTION 节点(VDB),惰性过期转 L2_FACT,判重并异步删复本。
@@ -260,6 +271,11 @@ async def recall_intentions(
now: 当前时间(默认 datetime.now(),测试可注入)
stats_out: 可选 dict,本函数把分段耗时与数量**原地回填**进去,供调用方落
READ_INTENTION pipeline log。传 None 则完全不统计(零开销)。
dedup_enabled: 是否执行读侧判重(及复本异步删库)。False 时跳过判重,
所有未过期意图原样返回,不删除任何节点。默认 True(历史行为)。
dedup_threshold: 判重 cosine 阈值。None 时回退到 env
MEMORY_DEDUP_THRESHOLD(默认 0.95),兼容直接调用本函数的旧代码;
reader 总是传入 `recall.intention_dedup_threshold`。
Returns:
[{"node_id", "score", "node", "layer": "l7_intention", "source": "vdb_intention"}, ...]
@@ -272,7 +288,7 @@ async def recall_intentions(
埋点字段(回填进 stats_out):
耗时(ms): vdb_search_ms / expire_ms / backfill_embed_ms / dedup_ms / total_ms
数量: fetched / expired / survivors / dedup_dropped / returned
配置: fetch_limit / out_limit / dedup_threshold
配置: fetch_limit / out_limit / dedup_enabled / dedup_threshold
说明: expire_ms、backfill_embed_ms 只有真的发生了对应操作才非 0,
借此可判断慢在 VDB 检索、逐条过期转换、补拉向量还是判重计算。
"""
@@ -358,7 +374,7 @@ async def recall_intentions(
_t = time.perf_counter()
_backfilled = 0
_missing_cnt = 0
if survivors:
if survivors and dedup_enabled: # 补拉只为判重;关闭时无需这次 VDB 读
missing_ids = [
h.get("node_id") for h in survivors
if h.get("node_id") and not getattr(h.get("node"), "embedding", None)
@@ -391,18 +407,23 @@ async def recall_intentions(
)
# 2. 判重:同 user + 同天 memory_at + valid_until 同日 + cosine≥threshold
# dedup_enabled=False → 完全跳过:不隐藏、不删除。
_t = time.perf_counter()
threshold = _get_dedup_threshold()
try:
kept, delete_ids = _partition_duplicates(survivors, threshold)
except Exception as e:
# 任何 dedup 异常 → 降级为不去重(返回全部 survivors 截断 limit)
logger.warning(f"[intention] dedup partition failed, degrade to raw: {e}")
threshold = _get_dedup_threshold(dedup_threshold)
if dedup_enabled:
try:
kept, delete_ids = _partition_duplicates(survivors, threshold)
except Exception as e:
# 任何 dedup 异常 → 降级为不去重(返回全部 survivors 截断 limit)
logger.warning(f"[intention] dedup partition failed, degrade to raw: {e}")
kept, delete_ids = survivors, []
else:
kept, delete_ids = survivors, []
# 纯 CPU(cosine 两两比较);survivors 多时可能显著
_stat(
dedup_ms=round((time.perf_counter() - _t) * 1000, 2),
dedup_dropped=len(delete_ids),
dedup_enabled=bool(dedup_enabled),
dedup_threshold=threshold,
)
+6
View File
@@ -1856,6 +1856,12 @@ class BaseReadPipeline(ReadPipeline):
stats_out=_intent_stats,
include_sources=request.include_sources,
exclude_sources=request.exclude_sources,
dedup_enabled=bool(getattr(
self.config.recall, "intention_dedup_enabled", True
)),
dedup_threshold=getattr(
self.config.recall, "intention_dedup_threshold", None
),
)
await trace_log.log_intention(
stats=_intent_stats,
+6 -1
View File
@@ -635,6 +635,7 @@ class MemoryWriter(WritePipeline):
不查 VDB、不做"新写入 vs 库里已有"的对比,避免给 VDB 增加读压力。
库内存量污染由 recall 侧异步删除逐步清理。best-effort:任何异常都
回退到"不判重、全写入",绝不影响 upsert 主流程。
`recall.intention_dedup_enabled=False` 时跳过批内判重,全部写入。
"""
if not intentions:
return []
@@ -660,7 +661,11 @@ class MemoryWriter(WritePipeline):
# ============ 批内 dedup(不查 VDB,只对本批 intentions 互斥判重) ============
keep_mask: List[bool] = [True] * len(intentions)
try:
dropped = self._intention_batch_dedup(intentions, embeddings)
dropped = (
self._intention_batch_dedup(intentions, embeddings)
if getattr(self.config.recall, "intention_dedup_enabled", True)
else []
)
for i in dropped:
if 0 <= i < len(keep_mask):
keep_mask[i] = False
+2 -2
View File
@@ -18,7 +18,7 @@ If you run into a problem, please open an Issue with the version, platform,repro
## 发行与平台合同
源码当前固定使用公开 PyPI 正式版 `hy-memory==2.0.11`。MemHub 源码版本为 `1.0.6`
源码当前固定使用公开 PyPI 正式版 `hy-memory==2.0.12`。MemHub 源码版本为 `1.0.6`
(build 37),GitHub 仓库为
[`Tencent-Hunyuan/Hy-Memory`](https://github.com/Tencent-Hunyuan/Hy-Memory),npm 包名为
`memhub-cli`。当前代码架构见
@@ -118,7 +118,7 @@ MemHub 的 SQLite 数据默认位于 `~/.one-memory`,不在 npm 包或 Runtime
## Hy Memory
SDK 依赖固定为公开 PyPI 正式版 `hy-memory==2.0.11`。SDK 配置、权限边界及 search
SDK 依赖固定为公开 PyPI 正式版 `hy-memory==2.0.12`。SDK 配置、权限边界及 search
返回格式见 [`MEMORY.md`](MEMORY.md)。HY search 返回的 `content` 已包含 SDK 统一生成的
逻辑时间和演化上下文;调用方不应再次转换时间戳或重复拼接 `When`。
+1 -1
View File
@@ -2352,7 +2352,7 @@
{
"SPDXID": "SPDXRef-Package-hy-memory",
"name": "hy-memory",
"versionInfo": "2.0.11",
"versionInfo": "2.0.12",
"downloadLocation": "NOASSERTION",
"filesAnalyzed": false,
"licenseConcluded": "Apache-2.0",
+1 -1
View File
@@ -9,7 +9,7 @@ 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.11
## hy-memory 2.0.12
License: Apache-2.0
+3 -2
View File
@@ -461,11 +461,12 @@ export const COMMANDS: readonly CommandDescriptor[] = [
{
name: "settings",
summary:
"查看或切换记忆模式(lite / pro / ultra)。lite 不调用模型,只在原始对话里检索;pro 由模型提取记忆(System 1);ultra 在 pro 之上每晚自动进化(System 2,使用知识图谱)。任何模式都保留全部原始对话。切换不迁移数据:已处理的不会重做,排队中的和新的按新模式处理;需 --yes,不加时只显示计划。环境变量 ONE_MEMORY_GRAPH_STORE 会强制 ultra。settings features 查看或开关 SDK 的可选检索与提取功能(全局设置,默认全部保持 SDK 默认值):graph_rerank 图谱重排(仅 ultra)、same_series_timeline 同系列时间线(需 graph_rerank)、episode_recall 片段召回(pro / ultra,需先开 session_episodes 写入片段)、session_episodes 片段写入、episode_summary 片段摘要(每个片段一次模型调用)、intention 意图提取(默认开)、few_shot 提取示例;set 需 --yes,不加时只显示计划;reset 恢复默认值。settings language 查看或设置界面语言(App 切换语言时会自动设置):简体中文(zh-Hans)和 system 不指定 SDK 语言,SDK 照旧自动识别中文或英文;其余语言(en、zh-Hant、ja、es、de、pt、fr、ko、ru、id)会让提取等 SDK 提示使用该语言,立即生效。",
"查看或切换记忆模式(lite / pro / ultra)。lite 不调用模型,只在原始对话里检索;pro 由模型提取记忆(System 1);ultra 在 pro 之上每晚自动进化(System 2,使用知识图谱)。任何模式都保留全部原始对话。切换不迁移数据:已处理的不会重做,排队中的和新的按新模式处理;需 --yes,不加时只显示计划。环境变量 ONE_MEMORY_GRAPH_STORE 会强制 ultra。settings features 查看或开关 SDK 的可选检索与提取功能(全局设置,默认全部保持 SDK 默认值):graph_rerank 图谱重排(仅 ultra)、same_series_timeline 同系列时间线(需 graph_rerank)、episode_recall 片段召回(pro / ultra,需先开 session_episodes 写入片段)、session_episodes 片段写入、episode_summary 片段摘要(每个片段一次模型调用)、intention 意图提取(默认开)、intention_dedup 意图判重(默认开;关闭则检索与写入都不判重、不删除意图)、few_shot 提取示例,以及数值 intention_dedup_threshold 意图判重阈值(默认 0.95,可设 0.8–1.0);set 需 --yes,不加时只显示计划;reset 恢复默认值。settings language 查看或设置界面语言(App 切换语言时会自动设置):简体中文(zh-Hans)和 system 不指定 SDK 语言,SDK 照旧自动识别中文或英文;其余语言(en、zh-Hant、ja、es、de、pt、fr、ko、ru、id)会让提取等 SDK 提示使用该语言,立即生效。",
usage:
"memhub settings mode [lite|pro|ultra] [--yes] [--json]\n" +
" memhub settings features [--json]\n" +
" memhub settings features set <name>=<true|false> [...] [--yes] [--json]\n" +
" memhub settings features set intention_dedup_threshold=<0.8-1.0> [--yes] [--json]\n" +
" memhub settings features reset [<name> ...] [--json]\n" +
" memhub settings language [<code>|system] [--json]",
options: [
@@ -476,7 +477,7 @@ export const COMMANDS: readonly CommandDescriptor[] = [
{
flag: "features set <name>=<true|false>",
summary:
"开关一个或多个 SDK 功能;功能在当前模式下不生效时会注明原因(例如 graph_rerank 需要 ultra)。",
"开关一个或多个 SDK 功能;功能在当前模式下不生效时会注明原因(例如 graph_rerank 需要 ultra)。intention_dedup_threshold 取 0.8–1.0 的数值。",
},
{
flag: "features reset [<name> ...]",
+173 -6
View File
@@ -36,15 +36,17 @@ const DEFAULTS: Record<string, boolean> = {
session_episodes: false,
episode_summary: false,
intention: true,
intention_dedup: true,
few_shot: false,
};
const THRESHOLD_DEFAULT = 0.95;
function featuresState(
configured: Record<string, boolean> = {},
configured: Record<string, boolean | number> = {},
mode = "pro",
extra: Record<string, unknown> = {},
) {
const nonDefault: Record<string, boolean> = {};
const nonDefault: Record<string, boolean | number> = {};
const features = Object.entries(DEFAULTS).map(([name, fallback]) => {
const enabled = configured[name] ?? fallback;
if (enabled !== fallback) nonDefault[name] = enabled;
@@ -70,7 +72,34 @@ function featuresState(
description: name,
};
});
return { mode, features, non_default: nonDefault, ...extra };
const threshold =
(configured.intention_dedup_threshold as number | undefined) ??
THRESHOLD_DEFAULT;
if (threshold !== THRESHOLD_DEFAULT)
nonDefault.intention_dedup_threshold = threshold;
const dedupOn =
(configured.intention_dedup as boolean | undefined) ??
DEFAULTS.intention_dedup;
const parameters = [
{
name: "intention_dedup_threshold",
value: threshold,
configured:
"intention_dedup_threshold" in configured
? configured.intention_dedup_threshold
: null,
default: THRESHOLD_DEFAULT,
minimum: 0.8,
maximum: 1,
active: dedupOn,
reason: dedupOn ? null : "requires_intention_dedup",
requires_feature: "intention_dedup",
sdk_field: "recall.intention_dedup_threshold",
env: "MEMORY_INTENTION_DEDUP_THRESHOLD",
description: "threshold",
},
];
return { mode, features, parameters, non_default: nonDefault, ...extra };
}
beforeEach(() => {
@@ -110,11 +139,16 @@ describe("memhub settings features", () => {
expect(result.code).toBe(0);
const json = JSON.parse(result.stdout);
expect(json.state).toBe("ok");
expect(json.features.features).toHaveLength(7);
expect(json.features.features).toHaveLength(8);
expect(json.features.parameters[0].name).toBe("intention_dedup_threshold");
expect(transport.put).not.toHaveBeenCalled();
const text = (await capturedRun(["settings", "features"])).stdout;
expect(text).toContain("graph_rerank:关(默认)");
expect(text).toContain("intention:开(默认)");
expect(text).toContain("intention_dedup:开(默认)");
expect(text).toContain(
"intention_dedup_threshold:0.95(默认,可设 0.8–1)",
);
expect(text).toContain("先开启 session_episodes");
});
@@ -160,6 +194,130 @@ describe("memhub settings features", () => {
);
});
it("turns intention dedup off and sets its threshold, round trip", async () => {
transport.put.mockResolvedValueOnce({
status: 200,
data: featuresState({ intention_dedup: false }, "pro", {
changed: ["intention_dedup"],
}),
});
const off = await capturedRun([
"settings",
"features",
"set",
"intention_dedup=false",
"--yes",
"--json",
]);
expect(off.code).toBe(0);
expect(transport.put).toHaveBeenLastCalledWith(
"/api/v1/settings/memory-features",
{ intention_dedup: false },
undefined,
);
const offJson = JSON.parse(off.stdout);
expect(offJson.state).toBe("committed");
expect(offJson.changed).toEqual(["intention_dedup"]);
expect(offJson.features.parameters[0].reason).toBe(
"requires_intention_dedup",
);
transport.get.mockResolvedValue({
status: 200,
data: featuresState({ intention_dedup: false }),
});
transport.put.mockResolvedValueOnce({
status: 200,
data: featuresState(
{ intention_dedup: true, intention_dedup_threshold: 0.9 },
"pro",
{ changed: ["intention_dedup", "intention_dedup_threshold"] },
),
});
const on = await capturedRun([
"settings",
"features",
"set",
"intention_dedup=true",
"intention_dedup_threshold=0.9",
"--yes",
]);
expect(on.code).toBe(0);
expect(transport.put).toHaveBeenLastCalledWith(
"/api/v1/settings/memory-features",
{ intention_dedup: true, intention_dedup_threshold: 0.9 },
undefined,
);
expect(on.stdout).toContain(
"已更新:intention_dedup、intention_dedup_threshold",
);
expect(on.stdout).toContain("intention_dedup_threshold:0.9(已设置");
transport.get.mockResolvedValue({
status: 200,
data: featuresState({ intention_dedup_threshold: 0.9 }),
});
transport.put.mockResolvedValueOnce({
status: 200,
data: featuresState({}, "pro", {
changed: ["intention_dedup_threshold"],
}),
});
const reset = await capturedRun([
"settings",
"features",
"reset",
"intention_dedup_threshold",
]);
expect(reset.code).toBe(0);
expect(transport.put).toHaveBeenLastCalledWith(
"/api/v1/settings/memory-features",
{ intention_dedup_threshold: null },
undefined,
);
});
it("previews a threshold without --yes and refuses one out of range", async () => {
const preview = await capturedRun([
"settings",
"features",
"set",
"intention_dedup_threshold=0.85",
]);
expect(preview.code).toBe(0);
expect(preview.stdout).toContain("- intention_dedup_threshold = 0.85");
for (const value of ["0.5", "0.79", "1.01", "2", "-0.9", "abc", "1e0"]) {
const result = await capturedRun([
"settings",
"features",
"set",
`intention_dedup_threshold=${value}`,
"--yes",
]);
expect(result.code, value).toBe(2);
}
expect(transport.put).not.toHaveBeenCalled();
});
it("does not send a threshold to a Runtime that does not list it", async () => {
const { parameters: _unused, ...older } = featuresState();
transport.get.mockResolvedValue({ status: 200, data: older });
const result = await capturedRun([
"settings",
"features",
"set",
"intention_dedup_threshold=0.9",
"--yes",
"--json",
]);
expect(result.code).toBe(1);
expect(JSON.parse(result.stdout)).toMatchObject({
state: "rejected",
code: "memory_feature_unsupported",
});
expect(transport.put).not.toHaveBeenCalled();
});
it("does nothing when the values are already set", async () => {
transport.get.mockResolvedValue({
status: 200,
@@ -210,6 +368,8 @@ describe("memhub settings features", () => {
["settings", "features", "set", "graph_rerank=yes"],
["settings", "features", "set", "graph_rerank"],
["settings", "features", "set", "few_shot=true", "few_shot=false"],
["settings", "features", "set", "intention_dedup=0.9"],
["settings", "features", "set", "intention_dedup_threshold=true"],
["settings", "features", "reset", "nope"],
["settings", "features", "toggle"],
]) {
@@ -269,7 +429,11 @@ describe("status pipeline features", () => {
last_evolve_at: null,
graph_build: { state: "idle", users: {} },
evolve: { mode: "pro", schedule: null, running: [], users: {} },
features: { episode_recall: true, intention: false },
features: {
episode_recall: true,
intention: false,
intention_dedup_threshold: 0.9,
},
},
};
const report = await composeStatusReport({
@@ -284,9 +448,12 @@ describe("status pipeline features", () => {
expect(report.pipeline?.features).toEqual({
episode_recall: true,
intention: false,
intention_dedup_threshold: 0.9,
});
const text = renderStatusText(report, "MemHub");
expect(text).toContain("SDK 功能:episode_recall=开、intention=关");
expect(text).toContain(
"SDK 功能:episode_recall=开、intention=关、intention_dedup_threshold=0.9",
);
});
});
+118 -28
View File
@@ -2,7 +2,8 @@
* `memhub settings features [set <name>=<true|false> ... | reset [<name> ...]]`.
*
* The SDK's optional retrieval and extraction features (graph rerank, episode
* recall, the episode write side, intention, few-shot). One global setting in
* recall, the episode write side, intention and its dedup, few-shot), plus the
* intention dedup threshold, the one numeric setting. One global setting in
* the Runtime; an unset feature keeps the SDK default, so an install nobody
* touched behaves as before. `set` prints its plan first and needs `--yes`,
* like `settings mode`, because some features spend model calls; `reset`
@@ -20,10 +21,19 @@ export const MEMORY_FEATURES = [
"session_episodes",
"episode_summary",
"intention",
"intention_dedup",
"few_shot",
] as const;
export type MemoryFeature = (typeof MEMORY_FEATURES)[number];
/** Numeric settings, with the range the Runtime accepts (inclusive). */
export const MEMORY_PARAMETERS = {
intention_dedup_threshold: { minimum: 0.8, maximum: 1 },
} as const;
export type MemoryParameter = keyof typeof MEMORY_PARAMETERS;
export type MemorySetting = MemoryFeature | MemoryParameter;
type SettingValues = Partial<Record<MemorySetting, boolean | number>>;
const FEATURE_LABEL: Record<MemoryFeature, string> = {
graph_rerank: "图谱重排(沿知识图谱的边传播支持度;仅 ultra)",
same_series_timeline:
@@ -33,6 +43,8 @@ const FEATURE_LABEL: Record<MemoryFeature, string> = {
session_episodes: "片段写入(同一会话提取的记忆归入同一片段)",
episode_summary: "片段摘要(片段结束时总结一次;每个片段一次模型调用)",
intention: "意图提取(随事实一起提取用户的计划与意图)",
intention_dedup:
"意图判重(检索时把同一天、相似度达到阈值的意图视为重复,只返回最早一条并删除其余;关闭则不判重、不删除)",
few_shot: "提取示例(在提取提示里附上示例;不加调用,输入更长)",
};
@@ -41,21 +53,42 @@ const REASON_TEXT: Record<string, string> = {
requires_pro: "lite 模式下不生效(需要 pro 或 ultra)",
requires_ultra: "当前模式下不生效(需要 ultra)",
requires_graph_rerank: "需要先开启并生效 graph_rerank",
requires_intention_dedup: "intention_dedup 已关闭,阈值不起作用",
};
const PARAMETER_LABEL: Record<MemoryParameter, string> = {
intention_dedup_threshold: "意图判重阈值(余弦相似度,越高保留越多)",
};
export type FeaturesCommand =
| { kind: "show" }
| {
kind: "set";
values: Partial<Record<MemoryFeature, boolean>>;
values: SettingValues;
confirmed: boolean;
}
| { kind: "reset"; names: MemoryFeature[] };
| { kind: "reset"; names: MemorySetting[] };
function isFeature(value: string): value is MemoryFeature {
return (MEMORY_FEATURES as readonly string[]).includes(value);
}
function isParameter(value: string): value is MemoryParameter {
return Object.hasOwn(MEMORY_PARAMETERS, value);
}
function isSetting(value: string): value is MemorySetting {
return isFeature(value) || isParameter(value);
}
/** A parameter's value: a plain decimal in its range; null = usage. */
function parameterValue(name: MemoryParameter, raw: string): number | null {
if (!/^\d+(\.\d+)?$/.test(raw)) return null;
const value = Number(raw);
const { minimum, maximum } = MEMORY_PARAMETERS[name];
return value >= minimum && value <= maximum ? value : null;
}
/** Arguments after `settings features`; null = usage. */
export function parseFeaturesCommand(
values: readonly string[],
@@ -68,18 +101,28 @@ export function parseFeaturesCommand(
const positional = tail.filter((value) => value !== "--yes");
if (verb === "set") {
if (positional.length === 0) return null;
const parsed: Partial<Record<MemoryFeature, boolean>> = {};
const parsed: SettingValues = {};
for (const item of positional) {
const match = /^([a-z_]+)=(true|false)$/.exec(item);
if (!match || !isFeature(match[1]) || match[1] in parsed) return null;
parsed[match[1]] = match[2] === "true";
const match = /^([a-z_]+)=(.+)$/.exec(item);
if (!match || match[1] in parsed) return null;
const [, name, raw] = match;
if (isFeature(name)) {
if (raw !== "true" && raw !== "false") return null;
parsed[name] = raw === "true";
} else if (isParameter(name)) {
const value = parameterValue(name, raw);
if (value === null) return null;
parsed[name] = value;
} else {
return null;
}
}
return { kind: "set", values: parsed, confirmed: yes === 1 };
}
if (verb === "reset") {
if (new Set(positional).size !== positional.length) return null;
if (!positional.every(isFeature)) return null;
return { kind: "reset", names: positional as MemoryFeature[] };
if (!positional.every(isSetting)) return null;
return { kind: "reset", names: positional as MemorySetting[] };
}
return null;
}
@@ -96,11 +139,26 @@ export interface FeatureState {
description: string;
}
export interface ParameterState {
name: MemoryParameter;
value: number;
configured: number | null;
default: number;
minimum: number;
maximum: number;
active: boolean;
reason: string | null;
requires_feature: string;
description: string;
}
export interface FeaturesState {
mode: string;
features: FeatureState[];
non_default: Partial<Record<MemoryFeature, boolean>>;
changed?: MemoryFeature[];
/** Absent from a Runtime older than the intention dedup threshold. */
parameters?: ParameterState[];
non_default: SettingValues;
changed?: MemorySetting[];
}
function featuresState(value: unknown): FeaturesState | null {
@@ -125,6 +183,20 @@ function featuresState(value: unknown): FeaturesState | null {
return null;
}
}
if (item.parameters !== undefined) {
if (!Array.isArray(item.parameters)) return null;
for (const parameter of item.parameters) {
if (
!parameter ||
typeof parameter !== "object" ||
typeof (parameter as ParameterState).name !== "string" ||
typeof (parameter as ParameterState).value !== "number" ||
typeof (parameter as ParameterState).active !== "boolean"
) {
return null;
}
}
}
return item as unknown as FeaturesState;
}
@@ -137,12 +209,12 @@ export type FeaturesDocument = {
| {
state: "preview";
features: FeaturesState;
target: Partial<Record<MemoryFeature, boolean>>;
target: SettingValues;
applied: false;
next_step: string;
}
| { state: "unchanged"; features: FeaturesState }
| { state: "committed"; features: FeaturesState; changed: MemoryFeature[] }
| { state: "committed"; features: FeaturesState; changed: MemorySetting[] }
| { state: "rejected" | "unknown" | "unavailable"; code: string }
);
@@ -170,13 +242,23 @@ export async function runFeaturesCommand(
if (command.kind === "show") {
return { ...BASE, state: "ok", features: current };
}
// What a person set, per name this Runtime lists; null = the default.
const configured = new Map<string, boolean | number | null>([
...current.features.map(
(feature) => [feature.name, feature.configured] as const,
),
...(current.parameters ?? []).map(
(parameter) => [parameter.name, parameter.configured] as const,
),
]);
let body: Record<string, unknown>;
if (command.kind === "set") {
const configured = new Map(
current.features.map((feature) => [feature.name, feature.configured]),
);
if (Object.keys(command.values).some((name) => !configured.has(name))) {
// An older Runtime does not know the name; it would answer 422.
return { ...BASE, state: "rejected", code: "memory_feature_unsupported" };
}
const differs = Object.entries(command.values).some(
([name, value]) => configured.get(name as MemoryFeature) !== value,
([name, value]) => configured.get(name) !== value,
);
if (!differs) return { ...BASE, state: "unchanged", features: current };
if (!command.confirmed) {
@@ -197,16 +279,10 @@ export async function runFeaturesCommand(
const names =
command.names.length > 0
? command.names
: current.features
.filter((feature) => feature.configured !== null)
.map((feature) => feature.name);
if (
names.every(
(name) =>
current.features.find((feature) => feature.name === name)
?.configured === null,
)
) {
: [...configured]
.filter(([, value]) => value !== null)
.map(([name]) => name as MemorySetting);
if (names.every((name) => (configured.get(name) ?? null) === null)) {
return { ...BASE, state: "unchanged", features: current };
}
body = Object.fromEntries(names.map((name) => [name, null]));
@@ -233,6 +309,16 @@ export function featuresExitCode(document: FeaturesDocument): number {
: 1;
}
function parameterLine(parameter: ParameterState): string {
const label = PARAMETER_LABEL[parameter.name] ?? parameter.name;
const origin = parameter.configured === null ? "默认" : "已设置";
const activity =
!parameter.active && parameter.reason
? `,${REASON_TEXT[parameter.reason] ?? parameter.reason}`
: "";
return `${parameter.name}:${parameter.value}(${origin}${activity},可设 ${parameter.minimum}–${parameter.maximum})— ${label}`;
}
function featureLine(feature: FeatureState): string {
const label = FEATURE_LABEL[feature.name] ?? feature.name;
const value = feature.enabled ? "开" : "关";
@@ -251,6 +337,8 @@ export function renderFeaturesText(document: FeaturesDocument): string {
const state = document.features;
const lines = [`当前模式:${state.mode}`];
for (const feature of state.features) lines.push(featureLine(feature));
for (const parameter of state.parameters ?? [])
lines.push(parameterLine(parameter));
lines.push(
"片段召回(episode_recall)只对带片段的记忆有用:先开启 session_episodes,之后提取的记忆才会带片段。",
);
@@ -258,7 +346,9 @@ export function renderFeaturesText(document: FeaturesDocument): string {
if (document.state === "preview") {
lines.push("将设置:");
for (const [name, value] of Object.entries(document.target)) {
lines.push(`- ${name} = ${value ? "开" : "关"}`);
lines.push(
`- ${name} = ${typeof value === "number" ? value : value ? "开" : "关"}`,
);
}
lines.push(`未执行任何改动。确认后运行:${document.next_step}`);
}
@@ -30,8 +30,7 @@ vi.mock("@one-memory/runtime-control", async (importOriginal) => ({
}));
function languageState(uiLanguage: string | null, extra = {}) {
const sdk =
uiLanguage === null || uiLanguage === "zh-Hans" ? "auto" : uiLanguage;
const sdk = uiLanguage === null ? "auto" : uiLanguage;
return {
ui_language: uiLanguage,
sdk_language: sdk,
@@ -95,7 +94,7 @@ describe("memhub settings language", () => {
});
expect(transport.put).not.toHaveBeenCalled();
const text = (await capturedRun(["settings", "language"])).stdout;
expect(text).toContain("界面语言:跟随系统(未选择)");
expect(text).toContain("界面语言:未设置(SDK 自动识别)");
expect(text).toContain("SDK 提示语言:auto");
});
+7 -6
View File
@@ -2,10 +2,11 @@
* `memhub settings language [<code>|system]`.
*
* The display language the App reports to the Runtime (`ui_language`), and
* the SDK prompt language it implies. zh-Hans and "system" (no explicit
* choice) pass no language, so the SDK keeps detecting Chinese or English as
* before; every other code, en included, makes extraction and the other SDK
* prompts use that language. A change applies at once: a write in flight
* the SDK prompt language it implies. Every code, zh-Hans and en included,
* makes extraction and the other SDK prompts use that language; "system"
* (no language set) passes none, so the SDK keeps detecting Chinese or
* English as before. The App sends the language it shows, so it is only
* unset on an install without the App. A change applies at once: a write in flight
* finishes in the old language, the next ones use the new one. The App sends
* its own choice again whenever it changes there.
*/
@@ -162,14 +163,14 @@ export function renderLanguageText(document: LanguageDocument): string {
const lines = [
`界面语言:${
state.ui_language === null
? "跟随系统(未选择)"
? "未设置(SDK 自动识别)"
: `${state.ui_language}(${NAMES[state.ui_language]})`
}`,
`SDK 提示语言:${sdkText(state.sdk_language)}`,
];
if (document.state === "ok") {
lines.push(
`可选:${UI_LANGUAGES.join("、")}、system。简体中文和 system 不指定语言,其余语言(包括 en)会让 SDK 使用该语言。`,
`可选:${UI_LANGUAGES.join("、")}、system。任一语言(包括 zh-Hans、en)都会让 SDK 使用该语言;system 不指定语言,SDK 自动识别中文或英文。`,
);
}
if (document.state === "unchanged") lines.push("没有需要改动的设置。");
+8 -4
View File
@@ -85,7 +85,7 @@ export interface PipelineSummary {
>;
graph_build: string | null;
/** SDK features (`memory_features`) whose value differs from the default. */
features: Record<string, boolean>;
features: Record<string, boolean | number>;
/** The App's display language; null = never chosen or "follow the system". */
ui_language: string | null;
/** The SDK prompt language: `auto` (zh/en detection) or the code passed. */
@@ -134,12 +134,13 @@ export function describePipeline(value: unknown): PipelineSummary | null {
};
}
}
const features: Record<string, boolean> = {};
const features: Record<string, boolean | number> = {};
if (item.features && typeof item.features === "object") {
for (const [name, value] of Object.entries(
item.features as Record<string, unknown>,
)) {
if (typeof value === "boolean") features[name] = value;
if (typeof value === "boolean" || typeof value === "number")
features[name] = value;
}
}
const graph =
@@ -357,7 +358,10 @@ export function pipelineLine(pipeline: PipelineSummary): string {
if (changed.length > 0) {
parts.push(
`;SDK 功能:${changed
.map(([name, value]) => `${name}=${value ? "开" : "关"}`)
.map(
([name, value]) =>
`${name}=${typeof value === "number" ? value : value ? "开" : "关"}`,
)
.join("、")}`,
);
}
+1 -1
View File
@@ -12,7 +12,7 @@ dependencies = [
"fastapi>=0.141.1",
"filelock>=3.32.4",
# Public SDK version validated against MemHub's permission and recall contracts.
"hy-memory==2.0.11",
"hy-memory==2.0.12",
# chromadb arrives through the HY SDK; locked here so an unrelated upgrade
# cannot move the SDK's store. Built-in embedding consumes numpy directly.
"chromadb==1.5.9",
+73 -19
View File
@@ -198,12 +198,17 @@ from one_memory.memory_evolution import (
)
from one_memory.memory_features import (
FEATURES,
PARAMETERS,
SETTING_NAMES,
FeatureCost,
FeatureOverrides,
FeatureReason,
FeatureSide,
MemoryFeatureName,
MemoryFeatures,
MemoryParameterName,
MemorySettingName,
SettingValue,
effective_features,
feature_activity,
non_default_features,
@@ -763,10 +768,11 @@ class PipelineStatus(BaseModel):
last_evolve_at: datetime | None = None
graph_build: GraphBuildState
#: The SDK features (`memory_features`) whose value differs from the SDK
#: default; empty while every feature is at its default.
features: dict[MemoryFeatureName, bool] = Field(default_factory=dict)
#: default; empty while every feature is at its default. A parameter
#: (`intention_dedup_threshold`) appears as its number.
features: dict[MemorySettingName, SettingValue] = Field(default_factory=dict)
#: The display language the App last reported (`ui_language`); null =
#: never chosen or "follow the system".
#: none set (the App sends the language it shows, even following the system).
ui_language: UiLanguage | None = None
#: The SDK prompt language: `auto` (the SDK detects zh/en) or a code.
sdk_language: str = SDK_LANGUAGE_AUTO
@@ -777,9 +783,9 @@ class UiLanguageState(BaseModel):
model_config = ConfigDict(extra="forbid")
#: What the App reported; null = never chosen or "follow the system".
#: What the App reported; null = none set (CLI/API-only, or `system`).
ui_language: UiLanguage | None
#: What SDK clients are built with: `auto` (zh-Hans or no choice: the SDK
#: What SDK clients are built with: `auto` (no language set: the SDK
#: detects zh/en, as before) or the code passed as `MemoryConfig.language`.
sdk_language: str
languages: tuple[UiLanguage, ...] = UI_LANGUAGES
@@ -824,6 +830,30 @@ class MemoryFeatureState(BaseModel):
description: str
class MemoryParameterState(BaseModel):
"""One numeric setting in `GET /api/v1/settings/memory-features`."""
model_config = ConfigDict(extra="forbid")
name: MemoryParameterName
#: What clients are built with: `configured`, else `default`.
value: float
#: What a person set; null = not set, the SDK default applies.
configured: float | None
#: The SDK default (its code default, or its own env var when set).
default: float
#: The range a `PUT` accepts, inclusive.
minimum: float
maximum: float
#: Whether it acts: exactly when `requires_feature` acts.
active: bool
reason: FeatureReason | None
requires_feature: MemoryFeatureName
sdk_field: str
env: str
description: str
class MemoryFeaturesState(BaseModel):
"""`GET /api/v1/settings/memory-features`."""
@@ -831,15 +861,16 @@ class MemoryFeaturesState(BaseModel):
mode: MemoryMode
features: tuple[MemoryFeatureState, ...]
parameters: tuple[MemoryParameterState, ...] = ()
#: Same as `pipeline.features`: the values that differ from the defaults.
non_default: dict[MemoryFeatureName, bool]
non_default: dict[MemorySettingName, SettingValue]
class MemoryFeaturesChange(MemoryFeaturesState):
"""`PUT /api/v1/settings/memory-features`: the new state and what changed."""
#: Features whose value changed; empty = nothing rebuilt.
changed: tuple[MemoryFeatureName, ...] = ()
#: Features and parameters whose value changed; empty = nothing rebuilt.
changed: tuple[MemorySettingName, ...] = ()
def memory_mode_effects(
@@ -4565,7 +4596,8 @@ def create_app(
"""Turn SDK features on or off; one global setting, not per user.
A key sets that feature, null resets it to the SDK default, an absent
key is left as it is; an unknown key or a non-boolean is 422. A
key is left as it is; an unknown key, a non-boolean feature or an
`intention_dedup_threshold` outside its range is 422. A
change rebuilds the SDK clients like a mode change: a write in flight
finishes with the old features, the next job and search use the new
ones. Nothing stored is migrated and no collection is renamed. See
@@ -4581,7 +4613,7 @@ def create_app(
current = _memory_features(app)
before = effective_features(previous, defaults)
after = effective_features(current, defaults)
changed = tuple(spec.name for spec in FEATURES if before[spec.name] != after[spec.name])
changed = tuple(name for name in SETTING_NAMES if before[name] != after[name])
if current != previous:
# Even a reset to the default value rebuilds: the client then
# carries no override at all, byte for byte the default config.
@@ -4616,9 +4648,9 @@ def create_app(
async def put_ui_language(request: UiLanguageUpdate) -> UiLanguageChange:
"""Record the App's display language; one global setting, not per user.
zh-Hans and null pass no language to the SDK, which keeps detecting
zh/en as before; every other code (en included) is passed as
`MemoryConfig.language`. A change of that SDK language rebuilds the
Every code (zh-Hans and en included) is passed as
`MemoryConfig.language`; only null passes no language, so the SDK
keeps detecting zh/en as before. A change of that SDK language rebuilds the
SDK clients like a feature change: a write in flight finishes in the
old language. Nothing stored is migrated and no collection is renamed.
"""
@@ -6066,7 +6098,7 @@ def _ui_language_state(app: FastAPI) -> UiLanguageState:
def _memory_features_state(
app: FastAPI, defaults: dict[str, bool] | None = None
app: FastAPI, defaults: dict[str, SettingValue] | None = None
) -> MemoryFeaturesState:
defaults = sdk_feature_defaults() if defaults is None else defaults
overrides = _memory_features(app)
@@ -6079,9 +6111,9 @@ def _memory_features_state(
features.append(
MemoryFeatureState(
name=spec.name,
enabled=effective[spec.name],
configured=configured.get(spec.name),
default=defaults[spec.name],
enabled=bool(effective[spec.name]),
configured=cast(bool | None, configured.get(spec.name)),
default=bool(defaults[spec.name]),
active=reason is None,
reason=reason,
side=spec.side,
@@ -6093,10 +6125,32 @@ def _memory_features_state(
description=spec.description,
)
)
parameters = []
for parameter in PARAMETERS:
reason = feature_activity(parameter.name, effective, mode)
parameters.append(
MemoryParameterState(
name=parameter.name,
value=float(effective[parameter.name]),
configured=cast(float | None, configured.get(parameter.name)),
default=float(defaults[parameter.name]),
minimum=parameter.minimum,
maximum=parameter.maximum,
active=reason is None,
reason=reason,
requires_feature=parameter.requires_feature,
sdk_field=parameter.sdk_field,
env=parameter.env,
description=parameter.description,
)
)
return MemoryFeaturesState(
mode=mode,
features=tuple(features),
non_default=cast(dict[MemoryFeatureName, bool], non_default_features(overrides, defaults)),
parameters=tuple(parameters),
non_default=cast(
dict[MemorySettingName, SettingValue], non_default_features(overrides, defaults)
),
)
@@ -6117,7 +6171,7 @@ def _pipeline_status(app: FastAPI) -> PipelineStatus | None:
last_evolve_at=max(finished, default=None),
graph_build=state.graph_build,
features=cast(
dict[MemoryFeatureName, bool],
dict[MemorySettingName, SettingValue],
non_default_features(_memory_features(app), sdk_feature_defaults()),
),
**_ui_language_state(app).model_dump(exclude={"languages"}),
@@ -14,7 +14,7 @@ from pathlib import Path
from typing import Literal, cast
HY_MEMORY_DISTRIBUTION = "hy-memory"
HY_MEMORY_VERSION = "2.0.11"
HY_MEMORY_VERSION = "2.0.12"
HY_MEMORY_NAMESPACE = "governed-v2"
DiagnosticLogLevel = Literal["error", "warning", "info", "debug"]
@@ -503,7 +503,7 @@ def _ensure_coding_schema(path: Path) -> None:
CodingMemoryStore,
)
# Relies on the pinned SDK's internals (hy-memory==2.0.11 is pinned exactly).
# Relies on the pinned SDK's internals (hy-memory==2.0.12 is pinned exactly).
store = CodingMemoryStore.__new__(CodingMemoryStore)
store._db_path = str(path)
store._conn = None
@@ -47,8 +47,10 @@ from one_memory.local_embedding import LocalEmbedder
from one_memory.log_file import confine_hy_sdk_logging
from one_memory.memory_features import (
FEATURES,
FEATURES_BY_NAME,
PARAMETERS,
SETTINGS_BY_NAME,
FeatureOverrides,
SettingValue,
feature_overrides,
)
from one_memory.model_profiles import (
@@ -321,21 +323,27 @@ def sdk_relevance_floor() -> float:
return min(1.0, max(0.0, value))
def sdk_feature_defaults() -> dict[str, bool]:
"""Each `memory_features` feature's SDK default, as a fresh config has it.
def sdk_feature_defaults() -> dict[str, SettingValue]:
"""Each `memory_features` setting's SDK default, as a fresh config has it.
That is the SDK's code default unless the process environment sets the
SDK's own variable (`FeatureSpec.env`), exactly what an unset feature
leaves on a client.
"""
config = MemoryConfig()
return {
defaults: dict[str, SettingValue] = {
spec.name: bool(getattr(getattr(config, spec.section), spec.field)) for spec in FEATURES
}
for parameter in PARAMETERS:
defaults[parameter.name] = float(
getattr(getattr(config, parameter.section), parameter.field)
)
return defaults
def apply_sdk_features(
config: MemoryConfig, features: Mapping[str, bool] | Iterable[tuple[str, bool]]
config: MemoryConfig,
features: Mapping[str, SettingValue] | Iterable[tuple[str, SettingValue]],
) -> MemoryConfig:
"""Set each feature a person chose on its `MemoryConfig` field.
@@ -346,7 +354,7 @@ def apply_sdk_features(
"""
values = dict(features.items() if isinstance(features, Mapping) else features)
for name, value in feature_overrides(values):
spec = FEATURES_BY_NAME[name]
spec = SETTINGS_BY_NAME[name]
setattr(getattr(config, spec.section), spec.field, value)
return config
@@ -367,8 +375,8 @@ def language_kwargs(language: str | None) -> LanguageKwargs:
def apply_sdk_language(config: MemoryConfig, language: str | None) -> MemoryConfig:
"""Set the SDK prompt language (`MemoryConfig.language`), when there is one.
None (zh-Hans, or no choice) sets nothing: the SDK detects zh/en as it
always did. Like a feature, the language never touches `vector_store`, so
None (no language set) sets nothing: the SDK detects zh/en as it always
did. Every display language, zh-Hans included, is set explicitly. Like a feature, the language never touches `vector_store`, so
the collection identity never depends on it.
"""
if language is not None:
@@ -383,7 +391,7 @@ def build_sdk_config(
*,
api_key: str | None,
data_dir: Path,
features: Mapping[str, bool] | Iterable[tuple[str, bool]] = (),
features: Mapping[str, SettingValue] | Iterable[tuple[str, SettingValue]] = (),
language: str | None = None,
) -> MemoryConfig:
"""Map a model snapshot and its embedding space to an SDK configuration.
@@ -209,6 +209,7 @@ class JsonlSourceAdapter:
file_predicate: Callable[[AuthorizedSourceFile], bool] | None = None,
suffixes: frozenset[str] = frozenset({".jsonl"}),
header_selector: Callable[[dict[str, JsonValue]], bool] | None = None,
header_gate: Callable[[dict[str, JsonValue] | None], bool] | None = None,
) -> None:
if descriptor.source_id != grant.source_id:
raise ValueError("Descriptor and authorized root source IDs must match")
@@ -219,6 +220,10 @@ class JsonlSourceAdapter:
self.file_predicate = file_predicate or (lambda _: True)
self.suffixes = suffixes
self.header_selector = header_selector
# False refuses the whole file before any record is read. It reports
# and leaves no cursor, so a release that learns the format reads the
# file from the top instead of finding it already behind a checkpoint.
self.header_gate = header_gate
self._header_cache: dict[str, tuple[str, dict[str, JsonValue] | None]] = {}
self._history_listing_cache: SourceListing | None = None
@@ -371,6 +376,9 @@ class JsonlSourceAdapter:
source_file, checkpoint, header = await asyncio.to_thread(
self._prepare, listed, options
)
if self.header_gate is not None and not self.header_gate(header):
yield ScanFailure(reason_code=ScanIssueCode.UNSUPPORTED_SCHEMA)
continue
_log.debug(
"import_file_read source=%s file=%d/%d file_bytes=%d planned_bytes=%d",
self.descriptor.source_id,
@@ -574,6 +582,9 @@ class JsonlSourceAdapter:
# resumed scan starts past the header, and the records after it need
# it just as much as the first batch did.
header = await _read_header(reader, source_file, self.header_selector)
if self.header_gate is not None and not self.header_gate(header):
yield ScanFailure(reason_code=ScanIssueCode.UNSUPPORTED_SCHEMA)
continue
last: SourceCursor = _start_cursor(source_file, options, checkpoint)
async for raw in iterate_in_worker(
partial(reader, source_file, checkpoint=checkpoint),
@@ -1,3 +1,4 @@
import re
from pathlib import PurePosixPath
from pydantic import JsonValue
@@ -37,6 +38,19 @@ DEEPSEEK_HARNESS_DESCRIPTOR = SourceDescriptor(
),
)
#: One session is one file, and the name carries the format generation it was
#: written in: `session.jsonl[.zstd]` for the first format, then
#: `session.v3.jsonl.zstd` and `session.v4.jsonl.zstd`. The version segment is
#: part of the published on-disk contract, so discovery must accept it — the
#: earlier exact-name match imported none of the versioned files.
SESSION_FILE = re.compile(r"^session(?:\.v[0-9]+)?\.jsonl(?:\.zstd)?$")
#: Session generations this parser has been verified against: the first format
#: (header `version: 0`), v3 and v4. Discovery is intentionally wider than
#: parsing: a future generation is found by pattern and then skipped from its
#: header, so it is reported as unsupported instead of silently vanishing.
SUPPORTED_SESSION_VERSIONS = frozenset({0, 3, 4})
def create_deepseek_harness_adapter(
grant: AuthorizedSourceRoot,
@@ -49,25 +63,43 @@ def create_deepseek_harness_adapter(
grant=grant,
parser=parse_deepseek_harness_record,
source_version=source_version,
file_predicate=lambda source_file: (
source_file.relative_path.name in {"session.jsonl", "session.jsonl.zstd"}
),
file_predicate=lambda source_file: bool(SESSION_FILE.match(source_file.relative_path.name)),
suffixes=frozenset({".jsonl", ".zstd"}),
header_selector=_is_session_header,
header_gate=_supported_session,
)
def _is_session_header(record: dict[str, JsonValue]) -> bool:
"""Harness writes the session's `cwd` once, in the first line only.
Verified against a session this machine produced: the header is
`{"type":"session","version":0,"id":...,"cwd":"/private/tmp/dsh-verify"}`
and no later record repeats it. Read per-record, `cwd` is therefore always
absent and every turn imports with no workspace.
Verified against sessions this machine produced: the header is
`{"type":"session","version":0|4,"id":...,"cwd":...}` and no later record
repeats it. Read per-record, `cwd` is therefore always absent and every turn
imports with no workspace.
"""
return record.get("type") == "session"
def _supported_session(header: dict[str, JsonValue] | None) -> bool:
"""Whether the session's declared format generation is one we can read.
A missing header, or a header without `version`, is the first format — the
earliest files this adapter already read. Any declared version outside
`SUPPORTED_SESSION_VERSIONS` is refused rather than interpreted with today's
field rules: a future format may change field semantics, and importing it
wrongly is harder to undo than not importing it yet.
"""
if header is None:
return True
version = header.get("version")
if version is None:
return True
if not isinstance(version, int) or isinstance(version, bool):
return False
return version in SUPPORTED_SESSION_VERSIONS
def parse_deepseek_harness_record(
record: dict[str, JsonValue],
context: SourceRecordContext,
@@ -80,6 +112,11 @@ def parse_deepseek_harness_record(
)
event_type = record.get("type")
data = as_record(record.get("data"))
if not _supported_session(context.header):
return ParsedSkip(
reason_code=ScanIssueCode.UNSUPPORTED_SCHEMA,
conversation_id=conversation_id,
)
if event_type == "session":
return ParsedSkip(reason_code=ScanIssueCode.UNKNOWN_RECORD)
if data is None:
@@ -148,11 +185,18 @@ def _tool_message(
"""`tool/call` carries name and arguments; `tool/result` a user-role message.
The same call also appears as a `tool-call` block in `assistant/message`;
only the event is read, so it is stored once.
only the event is read, so it is stored once. The first format and v3 wrap
the result in `tool-result` blocks; v4 writes plain `text` blocks, so both
shapes are read through the same clipping and credential-scrubbing path.
"""
message = as_record(data.get("message"))
if record.get("type") == "tool/result" and message is not None:
text = tool_blocks_evidence(message.get("content"), block_types=frozenset({"tool-result"}))
if text is None:
text = tool_blocks_evidence(
[{"type": "tool-result", "content": message.get("content")}],
block_types=frozenset({"tool-result"}),
)
message_id = first_string(message.get("id"), data.get("callId"))
else:
text = tool_evidence_text(data)
@@ -21,6 +21,11 @@ exercises (query rewrite needs `queries=[...]`, session narratives need
cross-encoder download, access write-back); and everything MemHub already
controls elsewhere (pipeline log, trace, memory operations, telemetry, mode).
Beside the on/off features there is one numeric parameter,
`intention_dedup_threshold` (`PARAMETERS`): the cosine similarity at which the
read-time intention dedup treats two intentions as copies. It is set, stored,
reset and keyed exactly like a feature.
No SDK import here: only `hy_sdk_runtime` and `hy_sdk_migration` import it.
`config_state` imports this module, so it imports nothing from there.
"""
@@ -31,7 +36,7 @@ from collections.abc import Mapping
from dataclasses import dataclass
from typing import Literal
from pydantic import BaseModel, ConfigDict, StrictBool
from pydantic import BaseModel, ConfigDict, Field, StrictBool
MemoryFeatureName = Literal[
"graph_rerank",
@@ -40,8 +45,13 @@ MemoryFeatureName = Literal[
"session_episodes",
"episode_summary",
"intention",
"intention_dedup",
"few_shot",
]
#: Numeric settings beside the on/off features.
MemoryParameterName = Literal["intention_dedup_threshold"]
#: Every key of the setting: a feature or a parameter.
MemorySettingName = MemoryFeatureName | MemoryParameterName
#: Read features change search; write features change what extraction stores.
FeatureSide = Literal["read", "write"]
#: none: no extra call. extra_query: one more store query per search.
@@ -49,9 +59,25 @@ FeatureSide = Literal["read", "write"]
#: a longer extraction prompt.
FeatureCost = Literal["none", "extra_query", "llm_call", "prompt_tokens"]
#: Why an enabled feature does nothing right now (`active: false`).
FeatureReason = Literal["disabled", "requires_pro", "requires_ultra", "requires_graph_rerank"]
FeatureReason = Literal[
"disabled",
"requires_pro",
"requires_ultra",
"requires_graph_rerank",
"requires_intention_dedup",
]
#: A feature is on or off; a parameter is a number.
type SettingValue = bool | float
#: A client's features as a hashable key: sorted (name, value) pairs, set ones only.
type FeatureOverrides = tuple[tuple[str, bool], ...]
type FeatureOverrides = tuple[tuple[str, SettingValue], ...]
#: The range a person may set `intention_dedup_threshold` to. With dedup on,
#: the SDK deletes every intention at or above it from the store at read time,
#: which cannot be undone; below 0.8 the embedding models MemHub uses score
#: different plans on one topic as that close, so a lower value would delete
#: intentions that are not copies. 1.0 keeps only exact copies' dedup.
INTENTION_DEDUP_THRESHOLD_MIN = 0.8
INTENTION_DEDUP_THRESHOLD_MAX = 1.0
_MODE_RANK: dict[str, int] = {"lite": 0, "pro": 1, "ultra": 2}
@@ -169,6 +195,23 @@ FEATURES: tuple[FeatureSpec, ...] = (
"No extra call."
),
),
FeatureSpec(
name="intention_dedup",
section="recall",
field="intention_dedup_enabled",
env="MEMORY_INTENTION_DEDUP_ENABLED",
side="read",
requires_mode="pro",
requires_feature=None,
cost="none",
description=(
"Treat same-day intentions (L7) with the same expiry and a cosine "
"similarity at or above intention_dedup_threshold as copies: a "
"search returns the earliest and deletes the others from the store. "
"On by default; off hides, drops and deletes no intention, at read "
"time or in a write batch. No extra call."
),
),
FeatureSpec(
name="few_shot",
section="llm",
@@ -189,12 +232,57 @@ FEATURE_NAMES: tuple[MemoryFeatureName, ...] = tuple(spec.name for spec in FEATU
FEATURES_BY_NAME: dict[str, FeatureSpec] = {spec.name: spec for spec in FEATURES}
@dataclass(frozen=True)
class ParameterSpec:
"""A numeric setting; it acts only while `requires_feature` acts."""
name: MemoryParameterName
section: Literal["recall"]
field: str
env: str
minimum: float
maximum: float
requires_feature: MemoryFeatureName
description: str
@property
def sdk_field(self) -> str:
return f"{self.section}.{self.field}"
PARAMETERS: tuple[ParameterSpec, ...] = (
ParameterSpec(
name="intention_dedup_threshold",
section="recall",
field="intention_dedup_threshold",
env="MEMORY_INTENTION_DEDUP_THRESHOLD",
minimum=INTENTION_DEDUP_THRESHOLD_MIN,
maximum=INTENTION_DEDUP_THRESHOLD_MAX,
requires_feature="intention_dedup",
description=(
"Cosine similarity at or above which intention_dedup treats two "
"intentions as copies. Higher keeps more. The SDK default is 0.95 "
"(MEMORY_DEDUP_THRESHOLD also sets it when its own env var is unset)."
),
),
)
PARAMETER_NAMES: tuple[MemoryParameterName, ...] = tuple(spec.name for spec in PARAMETERS)
PARAMETERS_BY_NAME: dict[str, ParameterSpec] = {spec.name: spec for spec in PARAMETERS}
#: Every key of the setting, features first, each in its catalog order.
SETTING_NAMES: tuple[MemorySettingName, ...] = (*FEATURE_NAMES, *PARAMETER_NAMES)
SETTINGS_BY_NAME: dict[str, FeatureSpec | ParameterSpec] = {
**FEATURES_BY_NAME,
**PARAMETERS_BY_NAME,
}
class MemoryFeatures(BaseModel):
"""`config.json` `memory_features`, and the `PUT` body.
Every key is optional; absent (or null) means the SDK default. In a `PUT`
an absent key is left as it is and null resets it. Unknown keys and
non-boolean values are refused (422).
an absent key is left as it is and null resets it. Unknown keys,
non-boolean feature values and a threshold that is not a number in its
range are refused (422).
"""
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
@@ -205,7 +293,14 @@ class MemoryFeatures(BaseModel):
session_episodes: StrictBool | None = None
episode_summary: StrictBool | None = None
intention: StrictBool | None = None
intention_dedup: StrictBool | None = None
few_shot: StrictBool | None = None
intention_dedup_threshold: float | None = Field(
default=None,
ge=INTENTION_DEDUP_THRESHOLD_MIN,
le=INTENTION_DEDUP_THRESHOLD_MAX,
allow_inf_nan=False,
)
def overrides(self) -> FeatureOverrides:
"""The features a person set, as the client key."""
@@ -221,24 +316,47 @@ class MemoryFeatures(BaseModel):
return MemoryFeatures(**{key: value for key, value in values.items() if value is not None})
def feature_overrides(values: Mapping[str, bool]) -> FeatureOverrides:
unknown = set(values) - set(FEATURES_BY_NAME)
def feature_overrides(values: Mapping[str, SettingValue]) -> FeatureOverrides:
unknown = set(values) - set(SETTINGS_BY_NAME)
if unknown:
raise ValueError("unknown_memory_feature")
return tuple(sorted((name, bool(value)) for name, value in values.items()))
return tuple(sorted((name, _setting_value(name, value)) for name, value in values.items()))
def _setting_value(name: str, value: SettingValue) -> SettingValue:
parameter = PARAMETERS_BY_NAME.get(name)
if parameter is None:
return bool(value)
if isinstance(value, bool) or not parameter.minimum <= float(value) <= parameter.maximum:
raise ValueError("invalid_memory_feature_value")
return float(value)
def effective_features(
overrides: FeatureOverrides, defaults: Mapping[str, bool]
) -> dict[str, bool]:
"""Every feature's value: what a person set, else the SDK default."""
values: dict[str, bool] = {spec.name: bool(defaults.get(spec.name, False)) for spec in FEATURES}
overrides: FeatureOverrides, defaults: Mapping[str, SettingValue]
) -> dict[str, SettingValue]:
"""Every setting's value: what a person set, else the SDK default."""
values: dict[str, SettingValue] = {
spec.name: bool(defaults.get(spec.name, False)) for spec in FEATURES
}
for parameter in PARAMETERS:
if parameter.name in defaults:
values[parameter.name] = float(defaults[parameter.name])
values.update(dict(overrides))
return values
def feature_activity(name: str, effective: Mapping[str, bool], mode: str) -> FeatureReason | None:
"""None when the feature acts in this mode; else why it does not."""
def feature_activity(
name: str, effective: Mapping[str, SettingValue], mode: str
) -> FeatureReason | None:
"""None when the feature acts in this mode; else why it does not.
A parameter acts exactly when the feature it tunes acts.
"""
parameter = PARAMETERS_BY_NAME.get(name)
if parameter is not None:
reason = feature_activity(parameter.requires_feature, effective, mode)
return "requires_intention_dedup" if reason == "disabled" else reason
spec = FEATURES_BY_NAME[name]
if not effective.get(name, False):
return "disabled"
@@ -252,11 +370,12 @@ def feature_activity(name: str, effective: Mapping[str, bool], mode: str) -> Fea
def non_default_features(
overrides: FeatureOverrides, defaults: Mapping[str, bool]
) -> dict[str, bool]:
"""The features whose value differs from the SDK default, for status."""
overrides: FeatureOverrides, defaults: Mapping[str, SettingValue]
) -> dict[str, SettingValue]:
"""The settings whose value differs from the SDK default, for status."""
baseline = effective_features((), defaults)
return {
name: value
for name, value in effective_features(overrides, defaults).items()
if value != bool(defaults.get(name, False))
if value != baseline.get(name)
}
@@ -74,9 +74,9 @@ class ConfigDocument(BaseModel):
#: SDK retrieval and extraction features a person set; an unset one keeps
#: the SDK default. See `one_memory.memory_features`.
memory_features: MemoryFeatures = Field(default_factory=MemoryFeatures)
#: The display language a person chose in the App; None = never chosen or
#: "follow the system". See `one_memory.ui_language` for what it does to
#: the SDK.
#: The display language the App shows (its choice, or the system language
#: it follows); None = none set. See `one_memory.ui_language` for what it
#: does to the SDK.
ui_language: UiLanguage | None = None
@field_validator("sources")
+16 -12
View File
@@ -3,14 +3,19 @@
The App owns the choice (its language selector) and tells Core whenever it
changes, so Core can build every SDK client with it. It is one global value in
`config.json` (`ui_language`), beside `memory_mode` and `memory_features`;
absent (never chosen, or "follow the system") means no explicit choice.
absent means no language was set (a CLI/API-only install, or
`settings language system`). An App that follows the system sends the
language it resolved and shows, not null.
The owner's rule for the SDK:
- zh-Hans, or no explicit choice: pass no language. The SDK keeps detecting
Chinese or English from the text, exactly as before this setting existed.
- Any other code, including en: pass it as `MemoryConfig.language`, so
extraction and the other prompts use that language.
- Any supported code, zh-Hans and en included: pass it as
`MemoryConfig.language`, so extraction and the other prompts use that
language. Every display language is passed explicitly (#243).
- No language at all (never set, as on a CLI/API-only install): pass no
language. The SDK keeps detecting Chinese or English from the text, exactly
as before this setting existed. The App does not leave it unset: it sends
the language it shows, including when it follows the system.
The language never names a collection; a change rebuilds the SDK handles the
way a mode or feature change does (#218 use count).
@@ -51,8 +56,6 @@ UI_LANGUAGES: tuple[UiLanguage, ...] = (
)
#: Codes earlier App builds stored, and the code each one is now.
LEGACY_UI_LANGUAGES: dict[str, UiLanguage] = {"zh-CN": "zh-Hans"}
#: Display languages that leave the SDK's own zh/en detection in charge.
AUTO_DETECTED: frozenset[str] = frozenset({"zh-Hans"})
#: What status shows when no language is passed to the SDK.
SDK_LANGUAGE_AUTO = "auto"
@@ -66,8 +69,9 @@ def normalize_ui_language(value: object) -> UiLanguage | None:
def sdk_language(ui_language: str | None) -> str | None:
"""The `MemoryConfig.language` for a display language; None = SDK auto-detect."""
language = normalize_ui_language(ui_language)
if language is None or language in AUTO_DETECTED:
return None
return language
"""The `MemoryConfig.language` for a display language; None = SDK auto-detect.
Every supported code is passed as is; only an unset (or unknown) value
leaves the SDK to detect zh/en.
"""
return normalize_ui_language(ui_language)
+2 -1
View File
@@ -25,6 +25,7 @@
| `test_c1_cross_source_session_isolation.py` | `contract` | Same session name in two sources must stay two conversations. |
| `test_c1_damage_per_source.py` | `contract` | Damage and unknown schema, per source: a bad record must not sink the import. |
| `test_c1_deepseek_profiles.py` | `contract` | DeepSeek Harness has two profiles; only the headless session form is importable. |
| `test_c1_deepseek_versioned_sessions.py` | `contract` | DeepSeek Harness versions its session file names; every generation must import. |
| `test_c1_import_event_matrix.py` | `contract` | C1 owned matrix: existing history, new file, append, truncate/replace, restart, revoke. |
| `test_c1_import_failure_injection.py` | `contract` | C1 failure injection: atomic receipt, disk-full, read-only source, rotation. |
| `test_c1_import_instrumentation.py` | `contract` | Instrumented import accounting: bytes read, opens, hashes, jobs, duplicates. |
@@ -318,4 +319,4 @@
| `test_workspace_recall.py` | `contract` | Workspace memories were unreachable from every host; these pin the way in. |
| `test_write_queue_lease_renewal.py` | `contract` | Rule 8: a lease must outlive the work it covers, and be renewed while it runs. |
共 313 个测试文件。
共 314 个测试文件。
@@ -14,8 +14,8 @@ from pathlib import Path
import pytest
PRIMARY_MARKERS = ("unit", "contract", "integration", "performance", "live")
EXPECTED_TEST_FILE_COUNT = 313
EXPECTED_TEST_FILES_SHA256 = "dcada5d5421767196a79e415dd47c2b6c6d67681972dbe81481b31867d318928"
EXPECTED_TEST_FILE_COUNT = 314
EXPECTED_TEST_FILES_SHA256 = "d745df3dfb964a8d2197c1ca3768728249d84ac4729305155ae1ef48428a19e4"
# Pure transformations, validation models, parity checks and state machines.
# This list is intentionally small: uncertain files default to contract.
@@ -0,0 +1,246 @@
"""DeepSeek Harness versions its session file names; every generation must import.
The first format writes `<session>/session.jsonl[.zstd]`; v3 and v4 write
`session.v3.jsonl.zstd` / `session.v4.jsonl.zstd`. Discovery used to match only
the two unversioned names, so every v3/v4 session was invisible to the import
job — `discovered 0` while the files sat on disk. These tests pin the file-name
contract, the header gate that keeps an unknown future version out of the
database, and the upgrade path where a library imported before the fix picks up
the versioned files on its next scan.
"""
import json
from pathlib import Path
import pytest
import zstandard
from one_memory.imports.adapters import ScanFailure, ScanIssueCode
from one_memory.imports.sources import deepseek_harness
from one_memory.imports.sources.deepseek_harness import (
DEEPSEEK_HARNESS_DESCRIPTOR,
create_deepseek_harness_adapter,
)
from tests.test_secondary_source_adapters import (
_cursors,
_evidence,
_evidence_text,
_grant,
_scan,
_skip_codes,
)
def _write_session(directory: Path, name: str, records: list[dict[str, object]]) -> None:
directory.mkdir(parents=True, exist_ok=True)
payload = "".join(f"{json.dumps(record)}\n" for record in records).encode()
(directory / name).write_bytes(zstandard.ZstdCompressor().compress(payload))
def _conversation(version: int | None, *, directory: str = "run-a") -> list[dict[str, object]]:
header: dict[str, object] = {
"type": "session",
"version": version,
"id": directory,
"cwd": "/private/versioned-project",
}
return [
header,
{
"type": "user/message",
"seq": 1,
"data": {
"id": "human",
"role": "user",
"source": {"kind": "user"},
"content": [{"type": "text", "text": "visible human"}],
},
},
{
"type": "assistant/message",
"seq": 2,
"data": {
"message": {
"id": "assistant",
"role": "assistant",
"content": [{"type": "text", "text": "visible assistant"}],
}
},
},
]
def _session_adapter(tmp_path: Path):
root = tmp_path / "dsh"
root.mkdir(parents=True, exist_ok=True)
return root, create_deepseek_harness_adapter(
_grant(DEEPSEEK_HARNESS_DESCRIPTOR.source_id, root, tmp_path)
)
def test_versioned_v4_session_file_is_discovered_and_imported(tmp_path: Path) -> None:
root, adapter = _session_adapter(tmp_path)
session = root / "run-v4"
records = _conversation(4, directory="run-v4")
records.append(
{
"type": "tool/result",
"seq": 3,
"time": 1793341068763,
"data": {
"callId": "call-1",
"message": {"role": "tool", "content": [{"type": "text", "text": "tool output"}]},
},
}
)
_write_session(session, "session.v4.jsonl.zstd", records)
# A rotated backup next to the live file must not be imported as a second copy.
(session / "session.v4.jsonl.zstd.orig-20261027").write_bytes(
zstandard.ZstdCompressor().compress(b'{"type":"session","version":4}\n')
)
events = _scan(adapter)
assert _evidence_text(events) == ["visible human", "visible assistant", "tool output"]
evidence = _evidence(events)
assert {event.evidence.project for event in evidence} == {"versioned-project"}
assert {event.evidence.conversation_id for event in evidence} == {"run-v4"}
def test_versioned_v3_session_file_is_discovered_and_imported(tmp_path: Path) -> None:
root, adapter = _session_adapter(tmp_path)
_write_session(root / "run-v3", "session.v3.jsonl.zstd", _conversation(3))
events = _scan(adapter)
assert _evidence_text(events) == ["visible human", "visible assistant"]
def _tool_result(content: list[dict[str, object]]) -> dict[str, object]:
return {
"type": "tool/result",
"seq": 3,
"data": {"callId": "call-1", "message": {"role": "tool", "content": content}},
}
def test_tool_output_imports_in_either_block_shape(tmp_path: Path) -> None:
"""`tool/result` output written as `text` blocks used to be dropped.
Only `tool-result` blocks were read, so a session that writes plain `text`
blocks lost every tool output. Both shapes must arrive, in any generation.
"""
root, adapter = _session_adapter(tmp_path)
v3 = _conversation(3, directory="run-v3-text")
v3.append(_tool_result([{"type": "text", "text": "v3 text output"}]))
_write_session(root / "run-v3-text", "session.v3.jsonl.zstd", v3)
v0 = _conversation(0, directory="run-v0-block")
v0.append(_tool_result([{"type": "tool-result", "content": "v0 block output"}]))
_write_session(root / "run-v0-block", "session.jsonl.zstd", v0)
texts = _evidence_text(_scan(adapter))
assert "v3 text output" in texts
assert "v0 block output" in texts
def test_text_tool_output_is_scrubbed_like_block_output(tmp_path: Path) -> None:
root, adapter = _session_adapter(tmp_path)
secret = "sk-" + "a" * 40
records = _conversation(4, directory="run-secret")
records.append(_tool_result([{"type": "text", "text": f"token {secret} " + "x" * 5000}]))
_write_session(root / "run-secret", "session.v4.jsonl.zstd", records)
tool = _evidence_text(_scan(adapter))[-1]
assert secret not in tool
assert len(tool) < 2000
def test_session_file_names_outside_the_contract_are_not_imported(tmp_path: Path) -> None:
root, adapter = _session_adapter(tmp_path)
for name in (
"session.v4.jsonl.zstd.orig-20261027",
"session.vx.jsonl.zstd",
"other.v4.jsonl.zstd",
"session.v4.json",
):
_write_session(root / name.replace(".", "-"), name, _conversation(4))
assert _evidence(_scan(adapter)) == []
def test_unknown_future_session_version_imports_nothing(tmp_path: Path) -> None:
root, adapter = _session_adapter(tmp_path)
records = _conversation(5)
records.append(
{
"type": "user/message",
"seq": 9,
"data": {
"id": "future",
"role": "user",
"source": {"kind": "user"},
"content": [{"type": "text", "text": "future generation payload"}],
},
}
)
_write_session(root / "run-v5", "session.v5.jsonl.zstd", records)
events = _scan(adapter)
assert _evidence(events) == []
assert ScanIssueCode.UNSUPPORTED_SCHEMA in _skip_codes(events)
def test_unknown_session_version_is_reported_and_read_once_supported(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Not importing a future format yet must stay "yet".
A cursor left behind by the refused scan would put the whole session behind
the checkpoint, so the release that learns the format would read nothing.
"""
root, adapter = _session_adapter(tmp_path)
_write_session(root / "run-v5", "session.v5.jsonl.zstd", _conversation(5))
refused = _scan(adapter)
assert _cursors(refused) == {}
assert [event.reason_code for event in refused if isinstance(event, ScanFailure)] == [
ScanIssueCode.UNSUPPORTED_SCHEMA
]
monkeypatch.setattr(deepseek_harness, "SUPPORTED_SESSION_VERSIONS", frozenset({0, 3, 4, 5}))
_, upgraded = _session_adapter(tmp_path)
assert _evidence_text(_scan(upgraded, cursors=_cursors(refused))) == [
"visible human",
"visible assistant",
]
def test_upgrade_scan_rediscovers_versioned_files_already_on_disk(tmp_path: Path) -> None:
"""A library imported before this fix must pick up the files on its next scan.
The first scan sees only the unversioned session that the old predicate
matched; after the upgrade, the versioned file next to it is discovered by
the next scan while the already imported session stays deduplicated by the
cursor it left behind.
"""
root, adapter = _session_adapter(tmp_path)
old = root / "run-old"
_write_session(old, "session.jsonl.zstd", _conversation(0, directory="run-old"))
first_scan = _scan(adapter)
assert _evidence_text(first_scan) == ["visible human", "visible assistant"]
assert _evidence(first_scan)[0].evidence.conversation_id == "run-old"
versioned = root / "run-v4"
_write_session(versioned, "session.v4.jsonl.zstd", _conversation(4, directory="run-v4"))
cursors = _cursors(first_scan)
assert cursors # the old session left a cursor behind
upgrade_scan = _scan(adapter, cursors=cursors)
assert _evidence_text(upgrade_scan) == ["visible human", "visible assistant"]
assert {event.evidence.conversation_id for event in _evidence(upgrade_scan)} == {"run-v4"}
@@ -193,7 +193,7 @@ def _qwenwork() -> Harness:
def _deepseek() -> Harness:
def write(path: Path, turns: list[Turn]) -> None:
# deepseek only accepts a file literally named session.jsonl, and nests
# deepseek only accepts files named session[.vN].jsonl[.zstd], and nests
# the turn under "data".
lines: list[dict] = [{"type": "session", "version": 0, "id": "s1", "cwd": "/w"}]
for index, (role, text, _session) in enumerate(turns):
@@ -225,7 +225,7 @@ def _deepseek() -> Harness:
from one_memory.imports.sources.deepseek_harness import create_deepseek_harness_adapter
# deepseek accepts only a file literally named session.jsonl.
# deepseek accepts only session[.vN].jsonl[.zstd]; the first format is used here.
return Harness(
"deepseek-harness",
write,
+166 -5
View File
@@ -28,6 +28,8 @@ from one_memory.memory_features import (
FEATURE_NAMES,
FEATURES,
FEATURES_BY_NAME,
PARAMETERS,
SETTING_NAMES,
MemoryFeatures,
effective_features,
feature_activity,
@@ -46,15 +48,20 @@ TODAY = {
"session_episodes": False,
"episode_summary": False,
"intention": True,
"intention_dedup": True,
"few_shot": False,
}
#: The same for the numeric settings.
TODAY_PARAMETERS = {"intention_dedup_threshold": 0.95}
@pytest.fixture(autouse=True)
def _clean_sdk_env(monkeypatch):
"""The SDK's own env vars feed its defaults; tests start without them."""
for spec in FEATURES:
for spec in (*FEATURES, *PARAMETERS):
monkeypatch.delenv(spec.env, raising=False)
# The threshold falls back to the SDK's shared dedup variable.
monkeypatch.delenv("MEMORY_DEDUP_THRESHOLD", raising=False)
monkeypatch.delenv("ONE_MEMORY_GRAPH_STORE", raising=False)
@@ -95,17 +102,25 @@ def _field(config, name: str) -> bool:
def test_the_document_names_exactly_the_catalog() -> None:
assert tuple(MemoryFeatures.model_fields) == FEATURE_NAMES
assert tuple(MemoryFeatures.model_fields) == SETTING_NAMES
assert set(TODAY) == set(FEATURE_NAMES)
# Each feature is a MemoryConfig field the SDK has; no env var is written.
defaults = hy_sdk_runtime.sdk_feature_defaults()
assert set(defaults) == set(FEATURE_NAMES)
assert set(defaults) == set(SETTING_NAMES)
def test_the_defaults_are_todays_behaviour() -> None:
assert hy_sdk_runtime.sdk_feature_defaults() == TODAY
everything = {**TODAY, **TODAY_PARAMETERS}
assert hy_sdk_runtime.sdk_feature_defaults() == everything
assert MemoryFeatures().overrides() == ()
assert effective_features((), TODAY) == TODAY
assert effective_features((), everything) == everything
@pytest.mark.parametrize("profile", PROFILES, ids=("builtin", "remote"))
def test_intention_dedup_defaults_to_on_at_095_in_the_built_config(tmp_path, profile) -> None:
config = _config(tmp_path, profile)
assert config.recall.intention_dedup_enabled is True
assert config.recall.intention_dedup_threshold == 0.95
def test_the_sdk_env_var_still_moves_the_default_of_an_unset_feature(monkeypatch) -> None:
@@ -126,6 +141,32 @@ def test_unknown_or_non_boolean_values_are_refused() -> None:
)
@pytest.mark.parametrize("bad", (0.79, 1.01, -1, 2, True, "0.9", float("nan"), float("inf")))
def test_an_intention_dedup_threshold_outside_its_range_is_refused(bad) -> None:
with pytest.raises(ValidationError):
MemoryFeatures.model_validate({"intention_dedup_threshold": bad})
def test_the_intention_dedup_threshold_range_is_inclusive() -> None:
for value in (0.8, 0.9, 1, 1.0):
document = MemoryFeatures.model_validate({"intention_dedup_threshold": value})
assert document.overrides() == (("intention_dedup_threshold", float(value)),)
with pytest.raises(ValueError, match="invalid_memory_feature_value"):
hy_sdk_runtime.build_sdk_config(
PROFILES[0],
api_key=None,
data_dir=Path("/tmp/unused"),
features={"intention_dedup_threshold": 0.5},
)
def test_the_sdk_env_vars_still_move_the_threshold_default(monkeypatch) -> None:
monkeypatch.setenv("MEMORY_DEDUP_THRESHOLD", "0.9")
assert hy_sdk_runtime.sdk_feature_defaults()["intention_dedup_threshold"] == 0.9
monkeypatch.setenv("MEMORY_INTENTION_DEDUP_THRESHOLD", "0.97")
assert hy_sdk_runtime.sdk_feature_defaults()["intention_dedup_threshold"] == 0.97
def test_merge_sets_resets_and_leaves_absent_keys_alone() -> None:
saved = MemoryFeatures(graph_rerank=True, few_shot=True)
update = MemoryFeatures.model_validate({"few_shot": None, "episode_recall": True})
@@ -165,6 +206,20 @@ def test_each_feature_reaches_the_built_memory_config(tmp_path, profile) -> None
assert _field(config, other.name) is TODAY[other.name], (spec.name, other.name)
@pytest.mark.parametrize("profile", PROFILES, ids=("builtin", "remote"))
def test_intention_dedup_on_off_and_threshold_reach_the_built_memory_config(
tmp_path, profile
) -> None:
off = _config(tmp_path, profile, {"intention_dedup": False})
assert off.recall.intention_dedup_enabled is False
assert off.recall.intention_dedup_threshold == 0.95
on = _config(tmp_path, profile, {"intention_dedup": True, "intention_dedup_threshold": 0.9})
assert on.recall.intention_dedup_enabled is True
assert on.recall.intention_dedup_threshold == 0.9
# Nothing else moves.
assert _field(on, "intention") is True and _field(on, "graph_rerank") is False
@pytest.mark.parametrize("profile", PROFILES, ids=("builtin", "remote"))
def test_nothing_set_is_the_config_of_before_byte_for_byte(tmp_path, profile) -> None:
before = repr(dataclasses.asdict(_config(tmp_path, profile)))
@@ -172,6 +227,8 @@ def test_nothing_set_is_the_config_of_before_byte_for_byte(tmp_path, profile) ->
assert repr(dataclasses.asdict(_config(tmp_path, profile, {}))) == before
# Setting every feature to its default value changes nothing either.
assert repr(dataclasses.asdict(_config(tmp_path, profile, TODAY))) == before
everything = {**TODAY, **TODAY_PARAMETERS}
assert repr(dataclasses.asdict(_config(tmp_path, profile, everything))) == before
@pytest.mark.parametrize("profile", PROFILES, ids=("builtin", "remote"))
@@ -190,6 +247,7 @@ def test_features_never_change_the_collection_identity(tmp_path, profile) -> Non
{name: True for name in FEATURE_NAMES},
{name: False for name in FEATURE_NAMES},
{"graph_rerank": True, "episode_recall": True},
{"intention_dedup": False, "intention_dedup_threshold": 0.8},
):
assert identity(_config(tmp_path, profile, values)) == baseline
@@ -243,6 +301,13 @@ def test_a_feature_needing_a_higher_mode_is_reported_inactive() -> None:
series = effective_features((("same_series_timeline", True), ("graph_rerank", True)), TODAY)
assert feature_activity("same_series_timeline", series, "pro") == "requires_ultra"
assert feature_activity("same_series_timeline", series, "ultra") is None
defaults = {**TODAY, **TODAY_PARAMETERS}
assert feature_activity("intention_dedup", defaults, "pro") is None
assert feature_activity("intention_dedup_threshold", defaults, "pro") is None
assert feature_activity("intention_dedup_threshold", defaults, "lite") == "requires_pro"
off = effective_features((("intention_dedup", False),), defaults)
assert feature_activity("intention_dedup", off, "pro") == "disabled"
assert feature_activity("intention_dedup_threshold", off, "pro") == "requires_intention_dedup"
# --- rebuilding handles -------------------------------------------------------
@@ -497,3 +562,99 @@ def test_features_api_get_put_reset_and_status(tmp_path, monkeypatch) -> None:
assert (await client.get("/api/v1/settings/memory-features")).json()["non_default"] == {}
run_app(tmp_path, monkeypatch, scenario)
@pytest.mark.fresh_sdk
def test_intention_dedup_api_on_off_threshold_and_422(tmp_path, monkeypatch) -> None:
built: list[tuple[bool, float]] = []
original = hy_sdk_runtime.build_sdk_config
def recording(*args, **kwargs):
config = original(*args, **kwargs)
built.append(
(config.recall.intention_dedup_enabled, config.recall.intention_dedup_threshold)
)
return config
monkeypatch.setattr(hy_sdk_runtime, "build_sdk_config", recording)
def built_now(app) -> tuple[bool, float]:
"""What a client built with the read handle's current key carries."""
recording(
hy_sdk_runtime.builtin_retrieval_snapshot(),
api_key=None,
data_dir=tmp_path,
features=app.state.sdk_client_handle.current_features(),
)
return built[-1]
async def scenario(app, client):
path = "/api/v1/settings/memory-features"
current = (await client.get(path)).json()
dedup = _by_name(current)["intention_dedup"]
assert dedup["enabled"] is True and dedup["default"] is True
assert dedup["configured"] is None and dedup["active"] is True
assert dedup["sdk_field"] == "recall.intention_dedup_enabled"
assert dedup["env"] == "MEMORY_INTENTION_DEDUP_ENABLED"
(threshold,) = current["parameters"]
assert threshold == {
"name": "intention_dedup_threshold",
"value": 0.95,
"configured": None,
"default": 0.95,
"minimum": 0.8,
"maximum": 1.0,
"active": True,
"reason": None,
"requires_feature": "intention_dedup",
"sdk_field": "recall.intention_dedup_threshold",
"env": "MEMORY_INTENTION_DEDUP_THRESHOLD",
"description": threshold["description"],
}
assert built_now(app) == (True, 0.95)
off = await client.put(path, json={"intention_dedup": False})
assert off.status_code == 200, off.text
body = off.json()
assert body["changed"] == ["intention_dedup"]
assert body["non_default"] == {"intention_dedup": False}
assert body["parameters"][0]["active"] is False
assert body["parameters"][0]["reason"] == "requires_intention_dedup"
assert app.state.sdk_write_coordinator.memory_features() == (("intention_dedup", False),)
assert built_now(app) == (False, 0.95)
on = (
await client.put(path, json={"intention_dedup": True, "intention_dedup_threshold": 0.9})
).json()
assert on["changed"] == ["intention_dedup", "intention_dedup_threshold"]
assert on["non_default"] == {"intention_dedup_threshold": 0.9}
assert on["parameters"][0]["value"] == 0.9 and on["parameters"][0]["active"] is True
expected = (("intention_dedup", True), ("intention_dedup_threshold", 0.9))
assert app.state.sdk_client_handle.current_features() == expected
assert built_now(app) == (True, 0.9)
processing = (await client.get("/api/v1/memory-processing")).json()
assert processing["pipeline"]["features"] == {"intention_dedup_threshold": 0.9}
saved = json.loads((tmp_path / "data" / "config.json").read_text())
assert saved["memory_features"] == {
"intention_dedup": True,
"intention_dedup_threshold": 0.9,
}
for bad in (0.5, 0.79, 1.5, -0.1, "0.9", True):
response = await client.put(path, json={"intention_dedup_threshold": bad})
assert response.status_code == 422, bad
assert (await client.put(path, json={"intention_dedup": "false"})).status_code == 422
# A refused body changes nothing.
assert app.state.sdk_client_handle.current_features() == expected
reset = (
await client.put(
path, json={"intention_dedup": None, "intention_dedup_threshold": None}
)
).json()
assert reset["changed"] == ["intention_dedup_threshold"]
assert reset["non_default"] == {}
assert app.state.sdk_client_handle.current_features() == ()
assert built_now(app) == (True, 0.95)
run_app(tmp_path, monkeypatch, scenario)
@@ -91,7 +91,7 @@ def test_bundle_contains_management_sdk_config_and_verified_manifest(tmp_path):
assert manifest["bundle_id"] == "migration-1"
assert manifest["sdk_namespace"] == "governed-v2"
assert manifest["runtime_build"] == "build-13"
assert manifest["snapshot_sdk_version"] == "2.0.11"
assert manifest["snapshot_sdk_version"] == "2.0.12"
paths = {item["path"]: item for item in manifest["files"]}
assert {
"management/one-memory.sqlite3",
+32 -17
View File
@@ -1,8 +1,8 @@
"""The App's display language, and the SDK prompt language it implies.
The owner's rule: zh-Hans, or no explicit choice, passes no language, so the
SDK keeps detecting zh/en exactly as before; every other code (en included)
is passed as `MemoryConfig.language` (hy-memory 2.0.11). A change rebuilds the
The owner's rule (#243): every display language, zh-Hans and en included, is
passed as `MemoryConfig.language` (hy-memory 2.0.11); only an unset language
passes none, so the SDK keeps detecting zh/en exactly as before. A change rebuilds the
handles the way a mode or feature change does, and the language never touches
the vector collection identity.
"""
@@ -28,8 +28,8 @@ from one_memory.secrets import InMemorySecretStore
from one_memory.ui_language import UI_LANGUAGES, normalize_ui_language, sdk_language
TOKEN = "ui-language-test"
#: Every code except zh-Hans is passed to the SDK.
PASSED = ("en", "zh-Hant", "ja", "es", "de", "pt", "fr", "ko", "ru", "id")
#: Every code is passed to the SDK, zh-Hans included.
PASSED = ("en", "zh-Hans", "zh-Hant", "ja", "es", "de", "pt", "fr", "ko", "ru", "id")
@pytest.fixture(autouse=True)
@@ -51,7 +51,7 @@ def _config(tmp_path: Path, language: str | None):
def test_eleven_codes_and_the_legacy_chinese_code() -> None:
assert ("en", "zh-Hans", *PASSED[1:]) == UI_LANGUAGES
assert PASSED == UI_LANGUAGES
assert len(UI_LANGUAGES) == 11
# Earlier App builds stored zh-CN; it is zh-Hans now.
assert normalize_ui_language("zh-CN") == "zh-Hans"
@@ -60,19 +60,20 @@ def test_eleven_codes_and_the_legacy_chinese_code() -> None:
assert normalize_ui_language(None) is None
def test_only_zh_hans_and_no_choice_leave_the_sdk_to_detect() -> None:
def test_only_an_unset_language_leaves_the_sdk_to_detect() -> None:
assert sdk_language(None) is None
assert sdk_language("zh-Hans") is None
assert sdk_language("zh-CN") is None
assert sdk_language("system") is None
assert sdk_language("xx") is None
# zh-Hans is passed like every other code; the legacy zh-CN maps to it.
assert sdk_language("zh-Hans") == "zh-Hans"
assert sdk_language("zh-CN") == "zh-Hans"
for code in PASSED:
assert sdk_language(code) == code
def test_zh_hans_and_no_choice_build_the_config_of_before(tmp_path) -> None:
before = repr(dataclasses.asdict(_config(tmp_path, None)))
def test_no_language_builds_the_config_of_before(tmp_path) -> None:
assert _config(tmp_path, None).language is None
assert repr(dataclasses.asdict(_config(tmp_path, sdk_language("zh-Hans")))) == before
assert _config(tmp_path, sdk_language("zh-Hans")).language == "zh-Hans"
@pytest.mark.parametrize("code", PASSED)
@@ -282,17 +283,31 @@ def test_ui_language_api_get_put_and_status(tmp_path, monkeypatch) -> None:
assert current["languages"] == list(UI_LANGUAGES)
assert reads.current_language() is None and writes.sdk_language() is None
# zh-Hans: recorded, but the SDK still detects zh/en; nothing rebuilt.
# zh-Hans is passed explicitly: Chinese prompts, handles rebuilt (#243).
body = (
await client.put("/api/v1/settings/ui-language", json={"ui_language": "zh-Hans"})
).json()
assert body == {**current, "ui_language": "zh-Hans", "rebuilt": False}
assert retired == [] and reads.current_language() is None
assert body == {
**current,
"ui_language": "zh-Hans",
"sdk_language": "zh-Hans",
"rebuilt": True,
}
assert reads.current_language() == "zh-Hans" and writes.sdk_language() == "zh-Hans"
assert retired == ["zh-Hans"]
processing = (await client.get("/api/v1/memory-processing")).json()
assert processing["pipeline"]["sdk_language"] == "zh-Hans"
# The same value again changes nothing.
body = (
await client.put("/api/v1/settings/ui-language", json={"ui_language": "zh-Hans"})
).json()
assert body["rebuilt"] is False and retired == ["zh-Hans"]
body = (await client.put("/api/v1/settings/ui-language", json={"ui_language": "ja"})).json()
assert body["sdk_language"] == "ja" and body["rebuilt"] is True
assert reads.current_language() == "ja" and writes.sdk_language() == "ja"
assert retired == ["ja"]
assert retired == ["zh-Hans", "ja"]
# An explicit English choice forces English prompts.
body = (await client.put("/api/v1/settings/ui-language", json={"ui_language": "en"})).json()
@@ -302,7 +317,7 @@ def test_ui_language_api_get_put_and_status(tmp_path, monkeypatch) -> None:
assert processing["pipeline"]["ui_language"] == "en"
assert processing["pipeline"]["sdk_language"] == "en"
# Back to "follow the system": auto again.
# Unset (CLI `settings language system`): auto again.
body = (await client.put("/api/v1/settings/ui-language", json={"ui_language": None})).json()
assert body["sdk_language"] == "auto" and body["rebuilt"] is True
assert reads.current_language() is None
+4 -4
View File
@@ -991,7 +991,7 @@ wheels = [
[[package]]
name = "hy-memory"
version = "2.0.11"
version = "2.0.12"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "chromadb" },
@@ -1008,9 +1008,9 @@ dependencies = [
{ name = "scikit-learn" },
{ name = "tiktoken" },
]
sdist = { url = "https://files.pythonhosted.org/packages/01/93/aec7d243259f6a315f38e8ebc21a9eea153a48fc13648fda149be7672788/hy_memory-2.0.11.tar.gz", hash = "sha256:96d6bd606d61052f127cd274aa6f8de8e7151d6250f1e89e4ef5b90e18ec7cb0", size = 1245738, upload-time = "2026-11-01T14:15:02.474Z" }
sdist = { url = "https://files.pythonhosted.org/packages/44/19/bcd0de44ae2011ee1ad70579996aad72e18f0ca292df22d1545db05db850/hy_memory-2.0.12.tar.gz", hash = "sha256:c1231596b4cf12595775541f81680d4819461cb69e4aa4dc449f876d4c3b6742", size = 1246969, upload-time = "2026-11-02T06:30:37.448Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/1a/85/1f5e6a13507a0cfcdce26f67c590df00d327a0f7d5c5b5483c3bd0fa2f85/hy_memory-2.0.11-py3-none-any.whl", hash = "sha256:c0173444a83c1197a49acaccb123f8286cea205b4838c1e83d106974f5bad259", size = 1315871, upload-time = "2026-11-01T14:14:58.764Z" },
{ url = "https://files.pythonhosted.org/packages/75/9e/b64c7643c1bad1ddca4623a39bb62423bed0c22e7fd0d86be1ff73b2a17a/hy_memory-2.0.12-py3-none-any.whl", hash = "sha256:7a2332288197fafb89d5037eac7fef97df4c80794ead18159d21da84cde431df", size = 1316922, upload-time = "2026-11-02T06:30:35.105Z" },
]
[[package]]
@@ -1837,7 +1837,7 @@ requires-dist = [
{ name = "fastapi", specifier = ">=0.141.1" },
{ name = "filelock", specifier = ">=3.32.4" },
{ name = "httpx", specifier = ">=0.28.1" },
{ name = "hy-memory", specifier = "==2.0.11" },
{ name = "hy-memory", specifier = "==2.0.12" },
{ name = "keyring", specifier = ">=25.7.0" },
{ name = "numpy", specifier = "==2.5.2" },
{ name = "onnxruntime", specifier = "==1.23.2" },
@@ -15,9 +15,13 @@ it("bakes fallback release identity when the packaging pipeline omits it", async
expect(config).toMatch(
/__ONE_MEMORY_BUILD_NUMBER__: JSON\.stringify\(\s*String\(releaseBuildNumber\)/,
);
expect(config).toMatch(
/process\.env\.ONE_MEMORY_COMMIT\?\.trim\(\) \|\| readSourceCommit\(\)/,
expect(config).toContain(
"const releaseCommit = resolveReleaseCommit(process.env.ONE_MEMORY_COMMIT)",
);
expect(config).toMatch(/if \(!trimmed\) return readSourceCommit\(\);/);
// A supplied commit must be the full 40-character form the runtime accepts.
expect(config).toContain("/^[0-9a-f]{40}$/i.test(trimmed)");
expect(config).toContain("return trimmed.toLowerCase();");
expect(config).toMatch(
/execFileSync\("git", \["rev-parse", "HEAD"\],[\s\S]*?encoding: "utf8"/,
);
@@ -1,4 +1,4 @@
import type { LanguageSnapshot } from "@one-memory/i18n";
import type { GuiLocale, LanguageSnapshot } from "@one-memory/i18n";
import { describe, expect, it, vi } from "vitest";
import { coreUiLanguage, installCoreLanguageSync } from "./core-language-sync";
@@ -21,11 +21,16 @@ function source(initial: LanguageSnapshot) {
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
describe("Core language sync", () => {
it("tells Core null for system and the code for an explicit choice", () => {
expect(coreUiLanguage("system")).toBeNull();
expect(coreUiLanguage("zh-Hans")).toBe("zh-Hans");
expect(coreUiLanguage("en")).toBe("en");
expect(coreUiLanguage("ja")).toBe("ja");
it("tells Core the language the GUI shows, system included", () => {
const shown = (
preference: LanguageSnapshot["preference"],
locale: GuiLocale,
) => coreUiLanguage({ preference, locale, revision: 0 });
expect(shown("system", "zh-Hans")).toBe("zh-Hans");
expect(shown("system", "en")).toBe("en");
expect(shown("zh-Hans", "zh-Hans")).toBe("zh-Hans");
expect(shown("en", "en")).toBe("en");
expect(shown("ja", "ja")).toBe("ja");
});
it("sends the stored choice once at launch, then every change", async () => {
@@ -38,29 +43,33 @@ describe("Core language sync", () => {
await settle();
language.change({ preference: "system", locale: "en", revision: 2 });
await settle();
expect(send.mock.calls).toEqual([["es"], ["ja"], [null]]);
expect(send.mock.calls).toEqual([["es"], ["ja"], ["en"]]);
dispose();
language.change({ preference: "de", locale: "de", revision: 3 });
await settle();
expect(send).toHaveBeenCalledTimes(3);
});
it("an untouched install sends null, which leaves the SDK on auto", async () => {
it("an untouched install sends the system language the GUI shows", async () => {
const language = source({
preference: "system",
locale: "ja",
locale: "zh-Hans",
revision: 0,
});
const send = vi.fn(async () => {});
installCoreLanguageSync({ language, send });
await settle();
expect(send.mock.calls).toEqual([[null]]);
expect(send.mock.calls).toEqual([["zh-Hans"]]);
// Choosing the language already shown changes nothing Core sees.
language.change({ preference: "zh-Hans", locale: "zh-Hans", revision: 1 });
await settle();
expect(send).toHaveBeenCalledTimes(1);
});
it("reports a failed send and retries it with the next change", async () => {
const language = source({ preference: "fr", locale: "fr", revision: 0 });
const send = vi
.fn<(value: string | null) => Promise<void>>()
.fn<(value: string) => Promise<void>>()
.mockRejectedValueOnce(new Error("core_unavailable"))
.mockResolvedValue(undefined);
const reportError = vi.fn();
+18 -16
View File
@@ -1,35 +1,37 @@
import type { GuiLocale, LanguagePreference } from "@one-memory/i18n";
import type { GuiLocale, LanguageSnapshot } from "@one-memory/i18n";
import type { NativeLanguageSource } from "./native-language";
/** What Core is told: a code, or null for "follow the system". */
export function coreUiLanguage(
preference: LanguagePreference,
): GuiLocale | null {
return preference === "system" ? null : preference;
/**
* What Core is told: the language the GUI shows. "Follow the system" sends
* the language it resolved to, so the memories match the interface a person
* sees; the App never leaves the SDK to detect zh/en (#243).
*/
export function coreUiLanguage(snapshot: LanguageSnapshot): GuiLocale {
return snapshot.locale;
}
/**
* Keep Core's `ui_language` setting on the display language a person chose.
* Keep Core's `ui_language` setting on the display language the GUI shows.
*
* Core builds every SDK client with it: zh-Hans and "follow the system" pass
* no language (the SDK keeps detecting zh/en), any other choice sets the SDK
* prompt language. Sent once when installed, so a choice made before this
* existed reaches Core, then on every committed change; a value Core already
* has is not sent again. Best effort: a failed send is reported and retried
* with the next change or launch, and never blocks the GUI.
* Core builds every SDK client with it and passes it, zh-Hans included, as
* the SDK prompt language. Sent once when installed, so a choice made before
* this existed, or the system language followed at this launch, reaches
* Core; then on every committed change. A value Core already has is not sent
* again. Best effort: a failed send is reported and retried with the next
* change or launch, and never blocks the GUI.
*/
export function installCoreLanguageSync(options: {
language: NativeLanguageSource;
send(uiLanguage: GuiLocale | null): Promise<void>;
send(uiLanguage: GuiLocale): Promise<void>;
reportError?(error: unknown): void;
}): () => void {
let closed = false;
let sent: GuiLocale | null | undefined;
let sent: GuiLocale | undefined;
let queue: Promise<void> = Promise.resolve();
const push = () => {
queue = queue.then(async () => {
if (closed) return;
const value = coreUiLanguage(options.language.read().preference);
const value = coreUiLanguage(options.language.read());
if (value === sent) return;
try {
await options.send(value);
@@ -526,7 +526,22 @@ describe("hourly isolated desktop launch", () => {
expect(resolvePackagedBuildNumber("-1")).toBeUndefined();
expect(resolvePackagedBuildNumber(undefined, "3907")).toBe(3907);
expect(resolvePackagedBuildNumber("3908", "3907")).toBe(3908);
expect(resolvePackagedCommit(undefined, "388fd0e9")).toBe("388fd0e9");
expect(resolvePackagedCommit("not-a-sha", "388fd0e9")).toBe("388fd0e9");
});
it("resolves only a full 40-character commit and lowercases it", () => {
// Every downstream check (packaged-runtime install, local install, release
// download, release scripts) requires 40 lowercase hex characters.
const embedded = "388fd0e9b3c41a2d5e6f7a8b9c0d1e2f3a4b5c6d";
expect(resolvePackagedCommit(undefined, embedded)).toBe(embedded);
expect(resolvePackagedCommit(embedded.toUpperCase())).toBe(embedded);
expect(
resolvePackagedCommit(` ${embedded.toUpperCase()} `, undefined),
).toBe(embedded);
expect(resolvePackagedCommit("388fd0e9", embedded)).toBe(embedded);
expect(resolvePackagedCommit("388fd0e9")).toBeUndefined();
expect(resolvePackagedCommit("not-a-sha", embedded)).toBe(embedded);
expect(resolvePackagedCommit(`${embedded}0`, embedded)).toBe(embedded);
expect(resolvePackagedCommit("g".repeat(40), embedded)).toBe(embedded);
expect(resolvePackagedCommit(undefined, "unknown")).toBeUndefined();
});
});
+7 -1
View File
@@ -143,6 +143,12 @@ export function resolvePackagedBuildNumber(
return undefined;
}
/**
* The packaged-runtime install, local install, release download and release
* scripts all require a full 40-character lowercase commit. Normalise here so
* that one format crosses this boundary: an uppercase full SHA is lowercased,
* and a short or malformed value is skipped so it cannot shadow the next source.
*/
export function resolvePackagedCommit(
environmentValue: unknown,
embeddedValue?: unknown,
@@ -150,7 +156,7 @@ export function resolvePackagedCommit(
for (const value of [environmentValue, embeddedValue]) {
if (typeof value !== "string") continue;
const trimmed = value.trim();
if (/^[0-9a-f]{7,40}$/i.test(trimmed)) return trimmed;
if (/^[0-9a-f]{40}$/i.test(trimmed)) return trimmed.toLowerCase();
}
return undefined;
}
+10 -4
View File
@@ -622,9 +622,11 @@ async function initialize(isQuitting: () => boolean): Promise<void> {
throw new Error("host_permission_store_unavailable");
}
if (isQuitting()) return;
const hosts = (await recallHosts(app.getPath("home"))).filter(
(host) => host.hostId !== "openclaw",
);
const scanHosts = async () =>
(await recallHosts(app.getPath("home"))).filter(
(host) => host.hostId !== "openclaw",
);
const hosts = await scanHosts();
readDiagnosticSummary = async () => {
const core = coreSupervisor;
if (!core) return {};
@@ -915,10 +917,14 @@ async function initialize(isQuitting: () => boolean): Promise<void> {
});
ipcMain.handle("one-memory:recall-hosts", async (event) => {
assertAllowedRenderer(event.senderFrame?.url);
// A Harness profile can appear at any time, and which ones exist is only
// knowable from the disk. In place, so `requireHost` sees it too. One
// directory read per list, next to an IPC round trip per host below.
hosts.splice(0, hosts.length, ...(await scanHosts()));
if (connectionClient?.host) {
const inspector = createConnectionClient({ dataDir });
const rows: unknown[] = [];
for (const host of hosts) {
for (const host of [...hosts]) {
const inspected = await inspector.host?.({
hostId: host.hostId,
operation: "inspect",
+14 -2
View File
@@ -11,8 +11,20 @@ const { resolveBuildNumber, resolveBuildVersion } =
};
const releaseVersion = resolveBuildVersion(process.env);
const releaseBuildNumber = resolveBuildNumber(process.env);
const releaseCommit =
process.env.ONE_MEMORY_COMMIT?.trim() || readSourceCommit();
const releaseCommit = resolveReleaseCommit(process.env.ONE_MEMORY_COMMIT);
// The runtime accepts only a full 40-character commit, so an explicitly
// supplied malformed value fails the build instead of being baked and skipped.
function resolveReleaseCommit(explicit: string | undefined): string {
const trimmed = explicit?.trim();
if (!trimmed) return readSourceCommit();
if (!/^[0-9a-f]{40}$/i.test(trimmed)) {
throw new Error(
`ONE_MEMORY_COMMIT must be a full 40-character hex commit, got ${JSON.stringify(trimmed)}`,
);
}
return trimmed.toLowerCase();
}
function readSourceCommit(): string {
try {
@@ -0,0 +1,185 @@
// @vitest-environment jsdom
/**
* #230: DeepSeek Harness has no single host, so the app page used to grey the
* switch out with `unsupported_host` and offered no other way to grant recall.
* The one switch now covers every detected profile.
*/
import type { SourceResponse } from "@one-memory/contracts";
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
within,
} from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { ApplicationDetail } from "./ApplicationDetail";
import { readConnectionPreferences } from "./connection-preferences";
import { resetConnectionReconcile } from "./connection-reconcile";
import { harnessBridge } from "./harness-profiles.test-fixture";
const source = {
source_id: "deepseek-harness",
display_name: "DeepSeek Harness",
authorized: true,
sync_enabled: true,
capabilities: {
historical_import: "implemented",
incremental_import: "implemented",
live_sync: "implemented",
recall: "implemented",
installer: "implemented",
verification: "real_replayed",
},
} as SourceResponse;
function renderDetail() {
return render(
<ApplicationDetail
source={source}
sources={[source]}
stale={false}
setSync={vi.fn()}
refresh={vi.fn().mockResolvedValue({ sources: [source] })}
onBack={vi.fn()}
/>,
);
}
function profileItems() {
return within(
screen.getByRole("list", { name: "DeepSeek Harness 的 Profile" }),
)
.getAllByRole("listitem")
.map((item) => item.textContent);
}
beforeEach(() => {
window.localStorage.clear();
resetConnectionReconcile();
});
afterEach(() => {
cleanup();
window.oneMemory = undefined;
window.localStorage.clear();
resetConnectionReconcile();
});
it("lists every detected profile with its own state", async () => {
harnessBridge({ desktop: "approved", web: "not-installed" });
renderDetail();
await waitFor(() =>
expect(profileItems()).toEqual(["desktop:已接入", "web:未接入"]),
);
const insertion = screen.getByRole("switch", { name: "一键插入应用" });
expect(insertion.hasAttribute("disabled")).toBe(false);
expect(screen.queryByText(/当前安装不支持一键插入/)).toBeNull();
});
it("turns every profile on with the one switch and remembers the choice", async () => {
const { api, state } = harnessBridge({
desktop: "not-installed",
web: "not-installed",
});
renderDetail();
const insertion = await screen.findByRole("switch", { name: "一键插入应用" });
await waitFor(() => expect(profileItems()).toHaveLength(2));
expect(insertion.getAttribute("aria-checked")).toBe("false");
fireEvent.click(insertion);
await waitFor(() =>
expect(profileItems()).toEqual(["desktop:已接入", "web:已接入"]),
);
expect(api.installRecall.mock.calls.map(([hostId]) => hostId)).toEqual([
"deepseek-harness:desktop",
"deepseek-harness:web",
]);
expect([...state.values()]).toEqual(["approved", "approved"]);
expect(insertion.getAttribute("aria-checked")).toBe("true");
// Not "未接通": the self-checks the grants recorded were read back.
await waitFor(() =>
expect(
screen.getByRole("button", { name: /已接通|未接通|检测中/ }).textContent,
).toBe("已接通"),
);
// Remembered, so a profile found on a later launch is connected too.
expect(readConnectionPreferences().hostSourceIds).toEqual([
"deepseek-harness",
]);
});
it("names the profile that failed and keeps the others on", async () => {
const { state } = harnessBridge(
{ desktop: "not-installed", web: "not-installed" },
{ failInstall: ["web"] },
);
renderDetail();
const insertion = await screen.findByRole("switch", { name: "一键插入应用" });
await waitFor(() => expect(profileItems()).toHaveLength(2));
fireEvent.click(insertion);
const alert = await screen.findByRole("alert");
expect(alert.textContent).toContain("以下 Profile 未能接入:web");
expect(alert.textContent).toContain("应用控制通道暂不可用");
await waitFor(() =>
expect(profileItems()).toEqual(["desktop:已接入", "web:未接入"]),
);
expect(state.get("deepseek-harness:desktop")).toBe("approved");
expect(insertion.getAttribute("aria-checked")).toBe("true");
});
it("turns every linked profile off with the one switch", async () => {
const { api, state } = harnessBridge({
desktop: "approved",
web: "approved",
});
renderDetail();
const insertion = await screen.findByRole("switch", { name: "一键插入应用" });
await waitFor(() =>
expect(insertion.getAttribute("aria-checked")).toBe("true"),
);
fireEvent.click(insertion);
await waitFor(() =>
expect(profileItems()).toEqual(["desktop:未接入", "web:未接入"]),
);
expect(api.uninstallRecall).toHaveBeenCalledTimes(2);
expect([...state.values()]).toEqual(["not-installed", "not-installed"]);
expect(insertion.getAttribute("aria-checked")).toBe("false");
expect(readConnectionPreferences().hostSourceIds).toEqual([]);
});
it("names the profile whose connection could not be removed", async () => {
harnessBridge(
{ desktop: "approved", web: "approved" },
{
failUninstall: ["desktop"],
},
);
renderDetail();
const insertion = await screen.findByRole("switch", { name: "一键插入应用" });
await waitFor(() =>
expect(insertion.getAttribute("aria-checked")).toBe("true"),
);
fireEvent.click(insertion);
// Removal failed but revocation went through: the grant is gone, the file
// is left for the person to check.
expect((await screen.findByRole("alert")).textContent).toContain(
"已撤销以下 Profile 的记忆权限,但连接文件没有全部移除,请核对:desktop",
);
});
it("says how to get a profile when none is detected", async () => {
harnessBridge({});
renderDetail();
expect(
await screen.findByText(
"还没有检测到 DeepSeek Harness 的 Profile。创建 Profile 后再回到此页。",
),
).toBeTruthy();
expect(
screen
.getByRole("switch", { name: "一键插入应用" })
.hasAttribute("disabled"),
).toBe(true);
});
+126 -8
View File
@@ -2,15 +2,21 @@ import type { SourceResponse } from "@one-memory/contracts";
import type { MessageKey } from "@one-memory/i18n";
import { useCallback, useEffect, useRef, useState } from "react";
import { AppMark } from "./app-mark";
import { connectionHostId, preferenceHasSource } from "./connection-hosts";
import {
connectionHostId,
isProfileSource,
preferenceHasSource,
profileName,
} from "./connection-hosts";
import {
readConnectionPreferences,
writeConnectionPreference,
} from "./connection-preferences";
import { noteUserHostChoice } from "./connection-reconcile";
import type { RecallLinkCheck } from "./global";
import type { RecallHostStatus, RecallLinkCheck } from "./global";
import {
disconnectHost,
disconnectProfiles,
enableHostConnection,
hostCapabilities,
hostConnectionApproved,
@@ -19,8 +25,11 @@ import {
hostWriteReason,
matchHost,
probeHost,
profileHosts,
profileWriteFailures,
refreshRecallHosts,
setHostMemoryPermission,
sourceConnectionApproved,
UNSUPPORTED_NOTE,
useRecallHosts,
} from "./host-state";
@@ -63,6 +72,24 @@ function connectionLabel(input: {
return "未开启关联";
}
/** The recorded self-check across the profiles that may use memory: wired
* only when every one of them is, otherwise the first one that is not. */
function profilesProbeState(profiles: RecallHostStatus[]) {
const linked = profiles.filter(hostConnectionApproved);
if (!linked.length) return null;
for (const host of linked) {
const state = host.selfCheck?.state ?? null;
if (state !== "wired") return state;
}
return "wired";
}
function profileList(hosts: readonly ProfileHost[]) {
return hosts.map((host) => profileName(host.hostId)).join(", ");
}
type ProfileHost = Pick<RecallHostStatus, "hostId">;
function SourceIcon({ source }: { source: SourceResponse }) {
return (
<AppMark
@@ -215,7 +242,10 @@ export function ApplicationDetail({
if (!mounted.current || version !== epoch.current) return;
setRead({ sourceId: id, state: "ready" });
setCheckedAt(new Date().toISOString());
if (matched?.installed) void probeLink(matched.hostId);
// A per-profile source has no single host to probe; its status comes
// from each profile's recorded self-check instead.
if (matched?.installed && !isProfileSource(id))
void probeLink(matched.hostId);
else setLink(null);
} catch {
if (mounted.current && version === epoch.current)
@@ -292,10 +322,14 @@ export function ApplicationDetail({
}
const current = read.sourceId === source.source_id ? read : null;
const host = matchHost(hosts, source.source_id);
const profileSource = isProfileSource(source.source_id);
const profiles = profileHosts(hosts, source.source_id);
const loading = !current || current.state === "loading";
const readFailed = current?.state === "error";
const approved = hostConnectionApproved(host);
const unsupported = hostConnectionUnsupported(host);
const approved = profileSource
? sourceConnectionApproved(hosts, source.source_id)
: hostConnectionApproved(host);
const unsupported = !profileSource && hostConnectionUnsupported(host);
const insertionChecked = insertionIntent ?? approved;
const memoryChecked = memoryIntent ?? host?.permission?.state === "approved";
const probing =
@@ -305,9 +339,10 @@ export function ApplicationDetail({
loading ||
readFailed ||
(stale && current?.state !== "ready");
const probeState =
link?.probe.state ??
(linkPending || linkFailed ? null : (host?.selfCheck?.state ?? null));
const probeState = profileSource
? profilesProbeState(profiles)
: (link?.probe.state ??
(linkPending || linkFailed ? null : (host?.selfCheck?.state ?? null)));
const stateText = connectionLabel({
approved,
insertionOn: insertionChecked,
@@ -326,10 +361,43 @@ export function ApplicationDetail({
? { reason: failureNote(installError.failure) }
: {}),
});
async function applyProfiles(enabled: boolean) {
if (enabled) {
try {
await enableHostConnection(source.source_id);
} finally {
// Each grant records its self-check on the desktop, and the status row
// reads those; nothing else re-reads them while this page is open.
await refreshRecallHosts().catch(() => {});
}
return;
}
const results = await disconnectProfiles(source.source_id);
const failed = results.filter((item) => item.outcome.state === "failed");
const retained = results.filter(
(item) =>
item.outcome.state === "revoked" || item.outcome.state === "review",
);
if (retained.length)
setInstallError({
key: "appProfilesRevokedRetained",
params: { profiles: profileList(retained) },
});
const first = failed[0]?.outcome;
if (first?.state === "failed")
throw Object.assign(Error("disconnect_failed"), {
profiles: failed.map((item) => profileName(item.hostId)),
failure: {
reason: first.reason,
rereadFailed: first.rereadFailed,
} satisfies HostFailure,
});
}
async function applyInsertion(enabled: boolean) {
const bridge = window.oneMemory;
if (!bridge) return;
setInstallError("");
if (profileSource) return applyProfiles(enabled);
if (enabled) {
await enableHostConnection(source.source_id);
void probeLink(hostId);
@@ -385,6 +453,30 @@ export function ApplicationDetail({
}
// A failed turn-on keeps the stored choice on; a failed turn-off
// shows the grant that is really still there after the re-read.
// Per-profile sources name the profiles that failed; the others
// keep what they got.
const failedProfiles =
profileWriteFailures(error) ??
(error as { profiles?: string[] }).profiles ??
null;
if (failedProfiles) {
setInstallError({
key: wanted
? "appProfilesConnectFailed"
: "appProfilesDisconnectFailed",
params: { profiles: failedProfiles.join(", ") },
failure: wanted
? {
reason: hostWriteReason(error),
rereadFailed: hostRereadFailed(error),
}
: ((error as { failure?: HostFailure }).failure ?? {
reason: null,
rereadFailed: false,
}),
});
continue;
}
setInstallError(
wanted
? {
@@ -561,6 +653,31 @@ export function ApplicationDetail({
<div>
<h2>{text("一键插入应用")}</h2>
<p>{text("安装记忆连接,并默认允许此应用使用已授权记忆。")}</p>
{profileSource &&
(profiles.length ? (
<>
<ul
className="r6-app-profiles"
aria-label={t("appProfilesLabel", {
name: source.display_name,
})}
>
{profiles.map((profile) => (
<li key={profile.hostId}>
{t(
hostConnectionApproved(profile)
? "appProfileOn"
: "appProfileOff",
{ profile: profileName(profile.hostId) },
)}
</li>
))}
</ul>
<p>{t("appProfilesHint")}</p>
</>
) : (
<p>{t("appProfilesNone", { name: source.display_name })}</p>
))}
{unsupported && (
<p>{`${source.display_name} ${text(UNSUPPORTED_NOTE)}`}</p>
)}
@@ -578,6 +695,7 @@ export function ApplicationDetail({
stale ||
appLocationNote !== null ||
unsupported ||
(profileSource && !profiles.length) ||
source.capabilities?.installer !== "implemented" ||
source.capabilities?.recall !== "implemented" ||
!hostCapabilities().install
+23 -18
View File
@@ -31,6 +31,8 @@ import {
hostBridgeAvailable,
hostConnectionApproved,
hostConnectionUnknown,
sourceConnectionApproved,
sourceConnectionIncomplete,
useRecallHosts,
} from "./host-state";
import { subscribePoll } from "./poll-scheduler";
@@ -737,12 +739,7 @@ export function ApplicationsHome({
failure.kind === "host"
? preferences.hostSourceIds.some((id) =>
sameConnectionHost(id, failure.sourceId),
) &&
!hosts.some(
(host) =>
hostConnectionApproved(host) &&
hostMatchesSource(failure.sourceId, host.hostId),
)
) && sourceConnectionIncomplete(hosts, failure.sourceId)
: preferences.syncSourceIds.includes(failure.sourceId) &&
!imports.sources.some(
(source) =>
@@ -754,14 +751,22 @@ export function ApplicationsHome({
const autoFailureText = autoFailures
.map((failure) =>
failure.kind === "host"
? t("apps.autoHostFailed", {
name: nameOf(failure.sourceId),
reason: failure.reason
? t("apps.failureReason", {
reason: localizeFailureReason(failure.reason),
})
: "",
})
? t(
failure.profiles
? "apps.autoHostProfilesFailed"
: "apps.autoHostFailed",
{
name: nameOf(failure.sourceId),
...(failure.profiles
? { profiles: failure.profiles.join(", ") }
: {}),
reason: failure.reason
? t("apps.failureReason", {
reason: localizeFailureReason(failure.reason),
})
: "",
},
)
: t("apps.autoSyncFailed", {
name: nameOf(failure.sourceId),
reason: localizeFailureReason(failure.reason),
@@ -1181,8 +1186,9 @@ export function ApplicationsHome({
t,
callState === "unavailable",
) || sourceSyncActivity(source.source_id, syncHealth, locale, t);
const host = hosts.find((item) =>
sourceMatchesHost(source.source_id, item.hostId),
const recallAllowed = sourceConnectionApproved(
hosts,
source.source_id,
);
return (
<div className="r6-home-app-row" key={source.source_id}>
@@ -1193,8 +1199,7 @@ export function ApplicationsHome({
<p>
{source.sync_enabled
? t("apps.syncEnabled")
: host?.installed &&
host.permission?.state === "approved"
: recallAllowed
? t("apps.recallAllowed")
: source.authorized
? t("apps.historyAllowed")
@@ -118,6 +118,14 @@
margin: 0;
overflow-wrap: anywhere;
}
.r6-app-profiles {
font-size: 13px;
color: #637786;
line-height: 1.8;
margin: 4px 0;
padding-left: 18px;
overflow-wrap: anywhere;
}
.r6-app-detail-actions {
display: flex;
gap: 12px;
+20 -2
View File
@@ -1,5 +1,6 @@
/** Mirrors desktop `SOURCE_HOST`. OpenClaw and DeepSeek Harness profiles
* are not accepted by one-click insertion. */
/** Mirrors desktop `SOURCE_HOST`. OpenClaw is not accepted by one-click
* insertion; DeepSeek Harness has no single host and goes through
* `PROFILE_SOURCES` instead. */
export const SOURCE_HOST: Readonly<Record<string, string>> = {
cursor: "cursor",
"claude-code": "claude-code",
@@ -14,6 +15,23 @@ export const SOURCE_HOST: Readonly<Record<string, string>> = {
export const ONE_CLICK_SOURCES = new Set(Object.keys(SOURCE_HOST));
/** Sources configured per profile. Each profile is its own host
* (`deepseek-harness:<profile>`, with its own patch, credential and grant), so
* the app's one switch covers every profile the desktop detected. */
export const PROFILE_SOURCES: ReadonlySet<string> = new Set([
"deepseek-harness",
]);
export function isProfileSource(sourceId: string) {
return PROFILE_SOURCES.has(sourceId);
}
/** `deepseek-harness:web` -> `web`. */
export function profileName(hostId: string) {
const colon = hostId.indexOf(":");
return colon < 0 ? hostId : hostId.slice(colon + 1);
}
export function connectionHostId(sourceId: string): string | null {
return SOURCE_HOST[sourceId] ?? null;
}
+38 -5
View File
@@ -1,6 +1,10 @@
import type { SourceResponse } from "@one-memory/contracts";
import { useQuery } from "@tanstack/react-query";
import { connectionHostId, sameConnectionHost } from "./connection-hosts";
import {
connectionHostId,
isProfileSource,
sameConnectionHost,
} from "./connection-hosts";
import {
readConnectionPreferences,
writeConnectionPreference,
@@ -8,11 +12,13 @@ import {
import {
cachedRecallHosts,
enableHostConnection,
hostConnectionApproved,
hostConnectionUnsupported,
hostWriteInFlight,
hostWriteReason,
matchHost,
profileHosts,
profileWriteFailures,
sourceConnectionIncomplete,
} from "./host-state";
import { onClientReset, queryClient } from "./query-client";
import { latestSource, sourceWriteInFlight } from "./source-state";
@@ -37,6 +43,8 @@ export type AutoConnectFailure = {
kind: "sync" | "host";
sourceId: string;
reason: string | null;
/** Which profiles of a per-profile source it was; the others are kept. */
profiles?: string[];
};
export type AutoConnectState = {
running: string[];
@@ -53,8 +61,10 @@ queryClient.setQueryDefaults(AUTO_KEY, {
});
let flight: Promise<AutoConnectFailure[]> | null = null;
const seenProfiles = new Map<string, Set<string>>();
onClientReset(() => {
flight = null;
seenProfiles.clear();
});
function autoState() {
@@ -148,8 +158,26 @@ export async function reconcileConnectionPreferences(
function hostNeedsApply(sourceId: string) {
const hosts = cachedRecallHosts();
if (hosts === undefined) return false;
const host = matchHost(hosts, sourceId);
return !hostConnectionApproved(host) && !hostConnectionUnsupported(host);
return sourceConnectionIncomplete(hosts, sourceId);
}
/** `attempted` holds one apply per source, which is right until a per-profile
* source grows a profile: that one was never tried, so the remembered switch
* gets one more apply. A profile that fails is not retried on every poll. */
function rearmNewProfiles(sourceIds: string[]) {
const hosts = cachedRecallHosts();
if (hosts === undefined) return;
for (const sourceId of sourceIds) {
if (!isProfileSource(sourceId)) continue;
const current = profileHosts(hosts, sourceId).map((host) => host.hostId);
const seen = seenProfiles.get(sourceId);
seenProfiles.set(sourceId, new Set([...(seen ?? []), ...current]));
if (!seen || current.every((hostId) => seen.has(hostId))) continue;
updateAuto((state) => ({
...state,
attempted: state.attempted.filter((key) => key !== hostKey(sourceId)),
}));
}
}
/** Whether a remembered host is still waiting for (or in) its one apply. */
@@ -191,6 +219,7 @@ export function autoReconcile(
if (hostConnectionUnsupported(matchHost(hosts, id)))
writeConnectionPreference("host", id, false);
const preferences = readConnectionPreferences();
rearmNewProfiles(preferences.hostSourceIds);
const { attempted } = autoState();
const only = options.only;
const wantedHosts = only
@@ -256,6 +285,7 @@ export function retryAutoReconcile(options: ReconcileOptions) {
export function resetConnectionReconcile() {
flight = null;
seenProfiles.clear();
queryClient.removeQueries({ queryKey: AUTO_KEY });
}
@@ -301,12 +331,15 @@ async function runReconcile(
// Per-app: other hosts keep going. Unsupported never succeeds on retry.
if (error instanceof Error && error.message === "host_unsupported")
writeConnectionPreference("host", sourceId, false);
else
else {
const profiles = profileWriteFailures(error);
failures.push({
kind: "host",
sourceId,
reason: hostWriteReason(error),
...(profiles ? { profiles } : {}),
});
}
}
}
return failures;
@@ -0,0 +1,120 @@
/** A fake desktop bridge holding DeepSeek Harness profile hosts, for tests. */
import { vi } from "vitest";
import type { RecallHostStatus, RecallPermissionStatus } from "./global";
type Bridge = NonNullable<typeof window.oneMemory>;
type Grant =
| "not-installed"
| "install-only"
| "approved"
| "revoked"
| "unsupported";
function permission(hostId: string, state: Grant): RecallPermissionStatus {
return {
hostId,
state,
reason: null,
receipt:
state === "not-installed" || state === "unsupported"
? null
: {
hostId,
installationId: `install-${hostId}`,
revision: 1,
status: state,
allowedTools: state === "approved" ? ["om_recall"] : [],
allowedScopes: state === "approved" ? ["all-apps"] : [],
},
};
}
/** A desktop that knows a set of Harness profiles and keeps their state. */
export function harnessBridge(
initial: Record<string, Grant>,
options: { failInstall?: string[]; failUninstall?: string[] } = {},
) {
const state = new Map(
Object.entries(initial).map(([profile, grant]) => [
`deepseek-harness:${profile}`,
grant,
]),
);
const hosts = (): RecallHostStatus[] =>
[...state].map(([hostId, grant]) => ({
hostId,
label: `DeepSeek Harness · ${hostId.split(":")[1]}`,
present: true,
installed: grant === "install-only" || grant === "approved",
permission: permission(hostId, grant),
// Recorded by the desktop when the grant lands, as on a real install.
selfCheck:
grant === "approved"
? { state: "wired", detail: "", probed_at: "2026-11-02" }
: null,
skillDrift: null,
}));
const failing = (hostId: string, list: string[] = []) =>
list.some((profile) => hostId === `deepseek-harness:${profile}`);
const api = {
getRecallHosts: vi.fn(async () => hosts()),
getRecallPermission: vi.fn(async (hostId: string) =>
permission(hostId, state.get(hostId) ?? "not-installed"),
),
previewRecallInstall: vi.fn(async (hostId: string) => ({
hostId,
hostLabel: hostId,
files: [],
fingerprint: `fp-${hostId}`,
})),
installRecall: vi.fn(async (hostId: string, _approved?: string) => {
if (failing(hostId, options.failInstall))
throw Error(
"Error invoking remote method 'one-memory:install-recall': Error: host_control_unavailable",
);
state.set(hostId, "install-only");
return {
hostId,
installed: true,
permission: permission(hostId, "install-only"),
};
}),
setRecallPermission: vi.fn(async (hostId: string, _input: unknown) => {
state.set(hostId, "approved");
return permission(hostId, "approved");
}),
revokeRecallPermission: vi.fn(async (hostId: string, _input: unknown) => {
state.set(hostId, "revoked");
return permission(hostId, "revoked");
}),
previewRecallUninstall: vi.fn(async (hostId: string) => ({
hostId,
hostLabel: hostId,
files: [],
review: [],
fingerprint: `fp-${hostId}`,
})),
uninstallRecall: vi.fn(async (hostId: string, _approved?: string) => {
if (failing(hostId, options.failUninstall))
throw Error(
"Error invoking remote method 'one-memory:uninstall-recall': Error: host_control_unavailable",
);
state.set(hostId, "not-installed");
return {
hostId,
installed: false,
permission: permission(hostId, "not-installed"),
};
}),
repairRecallCommands: vi.fn(async () => []),
};
window.oneMemory = api as unknown as Bridge;
return {
api,
state,
addProfile(profile: string) {
state.set(`deepseek-harness:${profile}`, "not-installed");
},
};
}
@@ -0,0 +1,210 @@
// @vitest-environment jsdom
/**
* DeepSeek Harness is configured per profile: every `deepseek-harness:<profile>`
* is its own host with its own patch, credential and grant. The app page has
* one switch for all of them (#230). These pin what that switch does: on
* installs and grants every detected profile, off removes and revokes every
* linked one, a failing profile is named without undoing the others, and a
* profile that appears later is picked up by the remembered switch.
*/
import { afterEach, describe, expect, it } from "vitest";
import { saveConnectionPreferences } from "./connection-preferences";
import {
autoReconcile,
resetConnectionReconcile,
} from "./connection-reconcile";
import { harnessBridge } from "./harness-profiles.test-fixture";
import {
disconnectProfiles,
enableHostConnection,
hostWriteReason,
ProfileWriteError,
profileHosts,
refreshRecallHosts,
sourceConnectionApproved,
sourceConnectionIncomplete,
} from "./host-state";
afterEach(() => {
window.oneMemory = undefined;
window.localStorage.clear();
resetConnectionReconcile();
});
describe("DeepSeek Harness profile hosts", () => {
it("lists only the profiles of the per-profile source", async () => {
harnessBridge({ desktop: "not-installed", web: "approved" });
const hosts = await refreshRecallHosts();
expect(
profileHosts(hosts, "deepseek-harness").map((host) => host.hostId),
).toEqual(["deepseek-harness:desktop", "deepseek-harness:web"]);
expect(profileHosts(hosts, "cursor")).toEqual([]);
// One approved profile reads as on; the other is still to do.
expect(sourceConnectionApproved(hosts, "deepseek-harness")).toBe(true);
expect(sourceConnectionIncomplete(hosts, "deepseek-harness")).toBe(true);
});
});
describe("turning the DeepSeek Harness switch on", () => {
it("installs and grants every profile that is not approved yet", async () => {
const { api, state } = harnessBridge({
desktop: "not-installed",
headless: "revoked",
web: "approved",
});
await refreshRecallHosts();
await enableHostConnection("deepseek-harness");
expect(api.installRecall.mock.calls.map(([hostId]) => hostId)).toEqual([
"deepseek-harness:desktop",
"deepseek-harness:headless",
]);
expect(api.setRecallPermission).toHaveBeenCalledWith(
"deepseek-harness:desktop",
expect.objectContaining({
allowedTools: ["om_recall", "om_conversations", "om_diagnostic_trace"],
allowedScopes: ["all-apps", "source:deepseek-harness"],
userConfirmed: true,
}),
);
expect([...state.values()]).toEqual(["approved", "approved", "approved"]);
});
it("keeps the profiles that worked and names the one that failed", async () => {
const { api, state } = harnessBridge(
{ desktop: "not-installed", web: "not-installed" },
{ failInstall: ["web"] },
);
await refreshRecallHosts();
const error = await enableHostConnection("deepseek-harness").catch(
(reason: unknown) => reason,
);
expect(error).toBeInstanceOf(ProfileWriteError);
expect((error as ProfileWriteError).profiles).toEqual(["web"]);
expect((error as Error).message).toContain("host_control_unavailable");
expect(state.get("deepseek-harness:desktop")).toBe("approved");
expect(state.get("deepseek-harness:web")).toBe("not-installed");
expect(api.setRecallPermission).toHaveBeenCalledTimes(1);
// The failure re-read lands the real state of every profile.
const hosts = await refreshRecallHosts();
expect(sourceConnectionApproved(hosts, "deepseek-harness")).toBe(true);
});
});
describe("turning the DeepSeek Harness switch off", () => {
it("removes and revokes every linked profile and leaves unlinked ones alone", async () => {
const { api, state } = harnessBridge({
desktop: "approved",
headless: "not-installed",
web: "approved",
});
await refreshRecallHosts();
const results = await disconnectProfiles("deepseek-harness");
expect(results.map((item) => [item.hostId, item.outcome.state])).toEqual([
["deepseek-harness:desktop", "removed"],
["deepseek-harness:web", "removed"],
]);
expect(api.uninstallRecall).toHaveBeenCalledTimes(2);
expect(state.get("deepseek-harness:desktop")).toBe("not-installed");
expect(state.get("deepseek-harness:web")).toBe("not-installed");
});
it("revokes a profile whose files cannot be removed and still reaches the rest", async () => {
const { api, state } = harnessBridge(
{ desktop: "approved", web: "approved" },
{ failUninstall: ["desktop"] },
);
await refreshRecallHosts();
const results = await disconnectProfiles("deepseek-harness");
expect(results.map((item) => item.outcome.state)).toEqual([
"revoked",
"removed",
]);
expect(api.revokeRecallPermission).toHaveBeenCalledWith(
"deepseek-harness:desktop",
expect.objectContaining({ userConfirmed: true }),
);
expect(state.get("deepseek-harness:desktop")).toBe("revoked");
expect(state.get("deepseek-harness:web")).toBe("not-installed");
});
});
describe("a profile created after the switch was turned on", () => {
it("is installed and granted by the remembered switch while the app is running", async () => {
saveConnectionPreferences({
syncSourceIds: [],
hostSourceIds: ["deepseek-harness"],
});
const harness = harnessBridge({ desktop: "not-installed" });
await refreshRecallHosts();
expect(await autoReconcile({ sources: [] })).toEqual([]);
expect(harness.api.installRecall).toHaveBeenCalledTimes(1);
// One attempt was already spent on this source; the new profile gets its own.
harness.addProfile("web");
await refreshRecallHosts();
expect(await autoReconcile({ sources: [] })).toEqual([]);
expect(harness.api.installRecall.mock.calls.at(-1)).toEqual([
"deepseek-harness:web",
"fp-deepseek-harness:web",
]);
expect(harness.state.get("deepseek-harness:web")).toBe("approved");
});
it("does not retry a failing profile on every poll", async () => {
saveConnectionPreferences({
syncSourceIds: [],
hostSourceIds: ["deepseek-harness"],
});
const harness = harnessBridge(
{ desktop: "approved", web: "not-installed" },
{ failInstall: ["web"] },
);
await refreshRecallHosts();
expect(await autoReconcile({ sources: [] })).toEqual([
{
kind: "host",
sourceId: "deepseek-harness",
reason: "应用控制通道暂不可用",
profiles: ["web"],
},
]);
await refreshRecallHosts();
expect(await autoReconcile({ sources: [] })).toBeNull();
expect(harness.api.installRecall).toHaveBeenCalledTimes(1);
});
it("stays out while the switch is off", async () => {
const harness = harnessBridge({ desktop: "not-installed" });
await refreshRecallHosts();
expect(await autoReconcile({ sources: [] })).toBeNull();
harness.addProfile("web");
await refreshRecallHosts();
expect(await autoReconcile({ sources: [] })).toBeNull();
expect(harness.api.installRecall).not.toHaveBeenCalled();
});
});
describe("a profile whose name MemHub cannot grant", () => {
it("is named with the real reason and does not hold up the others", async () => {
const { state } = harnessBridge({
My_Profile: "unsupported",
web: "not-installed",
});
await refreshRecallHosts();
const error = await enableHostConnection("deepseek-harness").catch(
(reason: unknown) => reason,
);
expect((error as ProfileWriteError).profiles).toEqual(["My_Profile"]);
expect(hostWriteReason(error)).toBe("appProfileNameUnsupported");
expect(state.get("deepseek-harness:web")).toBe("approved");
// Nothing is left for the remembered switch to keep trying.
expect(
sourceConnectionIncomplete(
await refreshRecallHosts(),
"deepseek-harness",
),
).toBe(false);
});
});
+187 -19
View File
@@ -1,5 +1,10 @@
import { MutationObserver, useQuery } from "@tanstack/react-query";
import { connectionHostId, hostMatchesSource } from "./connection-hosts";
import {
connectionHostId,
hostMatchesSource,
isProfileSource,
profileName,
} from "./connection-hosts";
import type {
RecallHostStatus,
RecallPermissionStatus,
@@ -226,6 +231,7 @@ export function matchHost(
const REASONS: Record<string, string> = {
host_unsupported: "它没有 MCP 通道,无法发放可撤销的记忆凭证",
profile_name_unsupported: "appProfileNameUnsupported",
unsupported_host: "当前安装不支持一键插入",
connection_client_unavailable: "桌面端的连接组件不可用",
noncanonical_data_dir_host_integration_disabled: "测试实例不接入应用",
@@ -350,18 +356,77 @@ export function hostWriteInFlight() {
return queryClient.isMutating({ mutationKey: HOST_WRITE }) > 0;
}
/** A per-profile source writes to every profile, so it waits on each of them. */
function sourceHost(sourceId: string) {
if (isProfileSource(sourceId))
return [
sourceId,
...profileHosts(cachedRecallHosts(), sourceId).map((host) => host.hostId),
];
return [connectionHostId(sourceId) ?? sourceId];
}
/** Every detected profile host of a per-profile source, e.g. DeepSeek Harness. */
export function profileHosts(
hosts: readonly RecallHostStatus[] | undefined,
sourceId: string,
) {
if (!isProfileSource(sourceId)) return [];
return (hosts ?? []).filter((host) => host.hostId.startsWith(`${sourceId}:`));
}
/** The app switch reads as on: its host, or for a per-profile source any
* profile, may use memory. A failed profile is reported, not hidden. */
export function sourceConnectionApproved(
hosts: readonly RecallHostStatus[] | undefined,
sourceId: string,
) {
if (isProfileSource(sourceId))
return profileHosts(hosts, sourceId).some(hostConnectionApproved);
return hostConnectionApproved(matchHost(hosts, sourceId));
}
/** Something the switch would still do: a host, or any profile, that is
* neither approved nor unsupported. */
export function sourceConnectionIncomplete(
hosts: readonly RecallHostStatus[] | undefined,
sourceId: string,
) {
const pending = (host: RecallHostStatus | null) =>
!hostConnectionApproved(host) && !hostConnectionUnsupported(host);
if (isProfileSource(sourceId))
return profileHosts(hosts, sourceId).some(pending);
return pending(matchHost(hosts, sourceId));
}
/** Some profiles of a per-profile source could not be written; the others
* were kept. The message keeps the first cause so `hostWriteReason` names it. */
export class ProfileWriteError extends Error {
readonly profiles: string[];
constructor(profiles: string[], cause: unknown) {
super(
`profile_write_failed ${cause instanceof Error ? cause.message : ""}`.trim(),
);
this.profiles = profiles;
}
}
/** The profile names a failed write left behind, if it was a profile write. */
export function profileWriteFailures(error: unknown): string[] | null {
return error instanceof ProfileWriteError ? error.profiles : null;
}
type Connected = {
hostId: string;
installed: boolean;
permission?: RecallPermissionStatus;
};
async function connect(sourceId: string): Promise<Connected | null> {
const hostId = connectionHostId(sourceId);
type Bridge = NonNullable<ReturnType<typeof bridge>>;
async function connect(sourceId: string): Promise<Connected[]> {
const profiles = isProfileSource(sourceId);
const hostId = profiles ? sourceId : connectionHostId(sourceId);
const api = bridge();
if (
!hostId ||
@@ -371,12 +436,65 @@ async function connect(sourceId: string): Promise<Connected | null> {
!api.setRecallPermission
)
throw Error("unsupported_host");
const existing = matchHost(await refreshRecallHosts(), sourceId);
if (hostConnectionUnsupported(existing)) throw Error("host_unsupported");
if (hostConnectionApproved(existing)) {
await api.repairRecallCommands?.();
return null;
const hosts = await refreshRecallHosts();
if (profiles) return connectProfiles(api, sourceId, hosts);
const result = await grantHost(
api,
hostId,
sourceId,
matchHost(hosts, sourceId),
);
await api.repairRecallCommands?.();
return result ? [result] : [];
}
/** One switch, every detected profile. A profile that fails does not undo
* the ones that worked; the error names it. Profiles already approved are
* left alone, so turning the switch on again only reaches what is missing. */
async function connectProfiles(
api: Bridge,
sourceId: string,
hosts: RecallHostStatus[],
): Promise<Connected[]> {
const profiles = profileHosts(hosts, sourceId);
if (!profiles.length) throw Error("profiles_not_found");
const connected: Connected[] = [];
const failed: string[] = [];
let cause: unknown;
for (const host of profiles) {
try {
const result = await grantHost(api, host.hostId, sourceId, host);
if (result) connected.push(result);
} catch (error) {
failed.push(profileName(host.hostId));
// Harness speaks MCP, so "unsupported" can only mean the id grammar
// refused this name; "no MCP channel" would send the person astray.
cause ??= hostConnectionUnsupported(host)
? Error("profile_name_unsupported")
: error;
}
}
if (failed.length < profiles.length) await api.repairRecallCommands?.();
if (failed.length) throw new ProfileWriteError(failed, cause);
return connected;
}
/** Installs and grants one host; null when it was already approved. */
async function grantHost(
api: Bridge,
hostId: string,
sourceId: string,
existing: RecallHostStatus | null,
): Promise<Connected | null> {
if (
!api.previewRecallInstall ||
!api.installRecall ||
!api.getRecallPermission ||
!api.setRecallPermission
)
throw Error("unsupported_host");
if (hostConnectionUnsupported(existing)) throw Error("host_unsupported");
if (hostConnectionApproved(existing)) return null;
const preview = await api.previewRecallInstall(hostId);
const installed = await api.installRecall(hostId, preview.fingerprint);
let permission =
@@ -394,19 +512,19 @@ async function connect(sourceId: string): Promise<Connected | null> {
}
if (permission.receipt?.status !== "approved")
throw Error("permission_not_approved");
await api.repairRecallCommands?.();
return { hostId, installed: true, permission };
}
function landConnected(result: Connected | null) {
if (result)
function landConnected(results: Connected[]) {
for (const result of results)
landHost(result.hostId, {
installed: result.installed,
permission: result.permission,
});
}
/** Installs and grants one host; resolves only once the grant is approved. */
/** Installs and grants one host (or every profile of a per-profile source);
* resolves only once the grants are approved. */
export const enableHostConnection = hostWrite(
sourceHost,
connect,
@@ -479,6 +597,22 @@ async function disconnect(hostId: string): Promise<Disconnected> {
}
}
function landDisconnected({
hostId,
outcome,
}: {
hostId: string;
outcome: DisconnectOutcome;
}) {
if (outcome.state === "removed")
landHost(hostId, {
installed: false,
...(outcome.permission ? { permission: outcome.permission } : {}),
});
else if (outcome.state !== "failed" && outcome.permission)
landHost(hostId, { permission: outcome.permission });
}
export const disconnectHost = hostWrite(
(hostId: string) => [hostId],
async (
@@ -489,14 +623,48 @@ export const disconnectHost = hostWrite(
const rereadFailed = !(await rereadOnce());
return { hostId, outcome: { ...result, rereadFailed } };
},
({ hostId, outcome }) => {
if (outcome.state === "removed")
landHost(hostId, {
installed: false,
...(outcome.permission ? { permission: outcome.permission } : {}),
landDisconnected,
);
export type ProfileDisconnect = { hostId: string; outcome: DisconnectOutcome };
/** Linked to MemHub at all: installed, or holding a receipt that is not yet
* revoked. A profile that never was has nothing to remove. */
function profileLinked(host: RecallHostStatus) {
const status = host.permission?.receipt?.status;
return host.installed || (status !== undefined && status !== "revoked");
}
/** Turn a per-profile source off: each linked profile is removed and its grant
* revoked, exactly as one host would be. One failure does not stop the rest;
* every outcome is returned so the page can name the profile it concerns. */
export const disconnectProfiles = hostWrite(
sourceHost,
async (sourceId: string): Promise<ProfileDisconnect[]> => {
const profiles = profileHosts(await refreshRecallHosts(), sourceId).filter(
profileLinked,
);
const results: ProfileDisconnect[] = [];
let anyFailed = false;
for (const host of profiles) {
const outcome = await disconnect(host.hostId);
anyFailed ||= outcome.state === "failed";
results.push({
hostId: host.hostId,
outcome:
outcome.state === "failed"
? { ...outcome, rereadFailed: false }
: outcome,
});
else if (outcome.state !== "failed" && outcome.permission)
landHost(hostId, { permission: outcome.permission });
}
if (anyFailed && !(await rereadOnce()))
for (const result of results)
if (result.outcome.state === "failed")
result.outcome = { ...result.outcome, rereadFailed: true };
return results;
},
(results) => {
for (const result of results) landDisconnected(result);
},
);
+8 -1
View File
@@ -91,7 +91,14 @@ describe("single state layer", () => {
});
it("reads and writes host connections only through host-state", () => {
expect(offenders(hostUses, ["host-state.ts", "global.d.ts"])).toEqual([]);
expect(
offenders(hostUses, [
"host-state.ts",
"global.d.ts",
// Test support: it is the fake bridge, and only tests import it.
"harness-profiles.test-fixture.ts",
]),
).toEqual([]);
});
it("reads and writes sources only through source-state", () => {
+1 -1
View File
@@ -282,7 +282,7 @@ Support is declared per immutable GitHub Release manifest:
- Linux x64/arm64 Runtime on native GHA runners.
- macOS arm64/x64 App/Runtime: Developer ID, notarization, native acceptance.
- Windows is not supported.
- `hy-memory==2.0.11` is the current stable SDK dependency; the release
- `hy-memory==2.0.12` is the current stable SDK dependency; the release
lock and [`../MEMORY.md`](../MEMORY.md) are authoritative when the pin changes.
See [`INSTALLATION.md`](INSTALLATION.md).
+5 -5
View File
@@ -177,7 +177,7 @@ node apps/cli/dist/one-memory.cjs settings features reset
```
- 全局设置,不分用户;没设置的功能保持 SDK 默认值,什么都不设时与以前完全一样(App 不变)。
- 可设:`graph_rerank`(图谱重排,仅 ultra)、`same_series_timeline`(需 graph_rerank)、`episode_recall`(片段召回,pro 即可)、`session_episodes`(片段写入)、`episode_summary`(片段摘要,每个片段一次模型调用)、`intention`(默认开)、`few_shot`。
- 可设:`graph_rerank`(图谱重排,仅 ultra)、`same_series_timeline`(需 graph_rerank)、`episode_recall`(片段召回,pro 即可)、`session_episodes`(片段写入)、`episode_summary`(片段摘要,每个片段一次模型调用)、`intention`(默认开)、`intention_dedup`(意图判重,默认开;关闭后检索和写入都不判重、不删除意图)、`few_shot`;以及数值 `intention_dedup_threshold`(意图判重的余弦阈值,默认 0.95,可设 0.8–1.0,例如 `settings features set intention_dedup_threshold=0.9 --yes`)。
- 片段召回只对带片段的记忆有用:同时开 `session_episodes`,之后提取的记忆才按会话归入片段。
- 在当前模式下不生效的功能照样保存,并注明原因(如 `graph_rerank` 在 pro 下「需要 ultra」)。
- 修改会重建 SDK 客户端:正在写的一批按旧设置写完,之后的写入和检索用新设置;不迁移数据,不改集合名。
@@ -189,14 +189,14 @@ node apps/cli/dist/one-memory.cjs settings features reset
```bash
node apps/cli/dist/one-memory.cjs settings language # 界面语言和 SDK 提示语言
node apps/cli/dist/one-memory.cjs settings language ja # 设为日语,立即生效
node apps/cli/dist/one-memory.cjs settings language system # 跟随系统(不指定 SDK 语言)
node apps/cli/dist/one-memory.cjs settings language system # 清除设置(不指定 SDK 语言)
```
- 可选 11 种:`en`、`zh-Hans`、`zh-Hant`、`ja`、`es`、`de`、`pt`、`fr`、`ko`、`ru`、`id`,以及 `system`;旧代码 `zh-CN` 按 `zh-Hans` 处理。
- App 切换语言时会自动设置(Desktop 启动时也会同步一次已保存的选择)。全局设置,存于 `config.json` 的 `ui_language`;从未选择时不写入。
- `zh-Hans` 和 `system` 不向 SDK 传语言,SDK 照旧自动识别中文或英文;其余语言(包括 `en`)作为 `MemoryConfig.language` 传给 SDK,提取等提示使用该语言。
- App 切换语言时会自动设置;Desktop 每次启动也会同步一次界面实际显示的语言(App 选“跟随系统”时,发送它按系统语言解析出的语言,例如 `zh-Hans`)。全局设置,存于 `config.json` 的 `ui_language`;从未设置时不写入。
- 所有语言(包括 `zh-Hans` 和 `en`)都作为 `MemoryConfig.language` 传给 SDK,提取等提示使用该语言;只有未设置(`system`,或只用 CLI/API、从未打开 App 的安装)时不向 SDK 传语言,SDK 照旧自动识别中文或英文。
- 修改会像功能开关一样重建 SDK 客户端;不迁移数据,不改集合名(需要 hy-memory 2.0.11 的 `MemoryConfig.language`)。
- `status --json` 的 `pipeline.ui_language` / `pipeline.sdk_language`(`auto` 或语言代码)。API:`GET`/`PUT /api/v1/settings/ui-language`。
- `status --json` 的 `pipeline.ui_language` / `pipeline.sdk_language`(`auto` 或语言代码;`zh-Hans` 用户显示 `zh-Hans`)。API:`GET`/`PUT /api/v1/settings/ui-language`。
## 8. 召回(recall)
+73 -17
View File
@@ -32,6 +32,7 @@ prompt and no extra call.
| `session_episodes` | `recall.session_episode_enabled` (`MEMORY_SESSION_EPISODE_ENABLED`) | off | pro or ultra | none |
| `episode_summary` | `recall.episode_summary_enabled` (`MEMORY_EPISODE_SUMMARY_ENABLED`) | off | pro or ultra | LLM: one call per closed episode of 3+ memories |
| `intention` | `llm.enable_intention` (`MEMORY_ENABLE_INTENTION`) | **on** | pro or ultra | none (off shortens the prompt) |
| `intention_dedup` | `recall.intention_dedup_enabled` (`MEMORY_INTENTION_DEDUP_ENABLED`) | **on** | pro or ultra | none |
| `few_shot` | `llm.few_shot_enabled` (`MEMORY_FEW_SHOT_ENABLED`) | off | pro or ultra | tokens (extraction and reconcile) |
- **Graph rerank (usage A).** It propagates support over the graph edges
@@ -52,8 +53,32 @@ prompt and no extra call.
write half of episodes, and both are off by default. Usage B only helps once
episodes are being written. The SDK's session narrative (L3, `finalize_session`)
is a separate feature and is not exposed (section 2).
- **`intention`** is the only feature that is on by default. Turning it off
stops L7 intention memories from being extracted.
- **`intention`** is on by default. Turning it off stops L7 intention
memories from being extracted.
- **`intention_dedup`** (hy-memory 2.0.12) is on by default, which is what
every earlier version did. A search treats intentions of one user and agent
with the same `memory_at` day, the same `valid_until` day and a cosine
similarity at or above `intention_dedup_threshold` as copies: it returns the
earliest and deletes the others from the store. Off, no intention dedup
runs, at read time or within a write batch, and nothing is hidden, dropped
or deleted.
### Parameters
Numeric settings beside the features. Each tunes one feature and acts only
while that feature acts.
| Name | SDK field (env) | Default | Range | Tunes |
|---|---|---|---|---|
| `intention_dedup_threshold` | `recall.intention_dedup_threshold` (`MEMORY_INTENTION_DEDUP_THRESHOLD`, else `MEMORY_DEDUP_THRESHOLD`) | 0.95 | 0.8–1.0 inclusive | `intention_dedup` (read time only) |
Why 0.8–1.0: with dedup on, every intention at or above the threshold is
deleted from the store at read time, and that cannot be undone. Below about
0.8 the embedding models MemHub ships or connects score different plans on
one topic as that close, so a lower value would delete intentions that are
not copies. Cosine similarity cannot exceed 1.0, and 1.0 keeps dedup for
exact copies only. Someone who wants no dedup turns `intention_dedup` off
rather than picking a threshold.
### Left out, and why
@@ -81,11 +106,12 @@ prompt and no extra call.
holds only the features they set:
```json
{"memory_mode": "pro", "memory_features": {"episode_recall": true, "session_episodes": true}}
{"memory_mode": "pro", "memory_features": {"episode_recall": true, "intention_dedup_threshold": 0.9}}
```
The values are strict booleans and unknown keys are refused, so a hand-edited
file with an unknown feature fails to load (`config_invalid`), like any other
Feature values are strict booleans, a parameter is a number in its range, and
unknown keys are refused. So a hand-edited file with an unknown feature or an
out-of-range threshold fails to load (`config_invalid`), like any other
malformed setting.
## 3. How a setting reaches the SDK
@@ -104,7 +130,8 @@ malformed setting.
- Each client's features are fixed when it is built, like its mode. Both the
write handles (`SdkWriteCoordinator`) and the read handle
(`ActiveProfileReadHandle`) are keyed by (profile, revision, mode,
features).
features). The features part of the key is the sorted (name, value) pairs
a person set, parameters included, so a new threshold is a new key.
- A change runs `retire_stale_handles`, the #218 use count. An idle write
handle closes at once, and a write in flight finishes with the features it
started with. The next read builds a client with the new key. The old read
@@ -135,6 +162,22 @@ malformed setting.
"description": "Usage A: propagate support over knowledge-graph edges ..."
}
],
"parameters": [
{
"name": "intention_dedup_threshold",
"value": 0.95,
"configured": null,
"default": 0.95,
"minimum": 0.8,
"maximum": 1.0,
"active": true,
"reason": null,
"requires_feature": "intention_dedup",
"sdk_field": "recall.intention_dedup_threshold",
"env": "MEMORY_INTENTION_DEDUP_THRESHOLD",
"description": "Cosine similarity at or above which ..."
}
],
"non_default": {"graph_rerank": true}
}
```
@@ -143,27 +186,32 @@ malformed setting.
- `configured` is null when unset.
- `default` is the SDK default: its code default, or its own env var when set.
- `active` is false with a `reason` when the feature does nothing right now.
The reason is one of `disabled`, `requires_pro` (lite), `requires_ultra`, or
`requires_graph_rerank` (for `same_series_timeline`).
The reason is one of `disabled`, `requires_pro` (lite), `requires_ultra`,
`requires_graph_rerank` (for `same_series_timeline`), or
`requires_intention_dedup` (for the threshold while `intention_dedup` is off).
- `cost` is one of `none`, `extra_query`, `llm_call`, `prompt_tokens`.
- `features` always lists every feature, in the table's order.
- `parameters` lists every parameter. `value` is what clients are built with;
`minimum` and `maximum` are the range a `PUT` accepts. A parameter is
active exactly when the feature it tunes is.
## 5. `PUT /api/v1/settings/memory-features`
The body has any of the feature names as keys:
- `true` or `false` sets that feature.
- A JSON number sets a parameter, if it is in range (inclusive).
- `null` resets it to the default.
- An absent key is left as it is.
- Anything else answers `422`, including a non-boolean, `"true"`, `1`, or an
unknown name.
- Anything else answers `422`, including a non-boolean feature, `"true"`, `1`,
an unknown name, or a threshold outside 0.8–1.0, a string, or a boolean.
```json
{"graph_rerank": true, "episode_recall": true, "few_shot": null}
{"graph_rerank": true, "intention_dedup_threshold": 0.9, "few_shot": null}
```
The answer is the state of section 4, plus `changed`: the features whose
effective value changed, in the table's order. When the set of configured
The answer is the state of section 4, plus `changed`: the features and then
the parameters whose effective value changed, in the tables' order. When the set of configured
features changes, the SDK clients are rebuilt (section 3). That includes a
reset to a value equal to the default, after which the client carries no
override at all.
@@ -172,10 +220,11 @@ override at all.
`pipeline` in `GET /api/v1/memory-processing` (memory-mode contract §7) gains
`features`, which lists the features whose effective value differs from the
default. It is `{}` while every feature is at its default:
default, and the parameters (as numbers) likewise. It is `{}` while every
setting is at its default:
```json
{"pipeline": {"mode": "pro", "...": "...", "features": {"episode_recall": true, "intention": false}}}
{"pipeline": {"mode": "pro", "...": "...", "features": {"episode_recall": true, "intention_dedup_threshold": 0.9}}}
```
`memhub status --json` and `memhub progress --json` carry it as
@@ -188,14 +237,19 @@ to the memory-mode line.
memhub settings features # list them
memhub settings features set episode_recall=true session_episodes=true # plan only
memhub settings features set episode_recall=true session_episodes=true --yes
memhub settings features set intention_dedup=false --yes # no intention dedup
memhub settings features set intention_dedup_threshold=0.9 --yes # a looser dedup
memhub settings features reset few_shot # back to the default
memhub settings features reset # every set feature
```
`set` prints its plan and needs `--yes`, like `settings mode`, because some
features spend model calls. `reset` only returns features to their defaults,
so it applies at once. Unknown names or values other than `true` / `false` are
a usage error (exit 2) before the Runtime is asked.
so it applies at once. Unknown names, feature values other than `true` /
`false`, and a threshold that is not a plain decimal in 0.8–1.0 are a usage
error (exit 2) before the Runtime is asked. Against an older Runtime that does
not list the threshold, `set` answers `rejected` /
`memory_feature_unsupported` without sending it.
## 8. Rules kept
@@ -216,6 +270,8 @@ a usage error (exit 2) before the Runtime is asked.
| session_episodes | 片段写入:同一会话中提取的记忆归入同一片段。 | Episodes per conversation: memories extracted from one conversation share one episode. | Episodios por conversación: las memorias extraídas de una conversación comparten un episodio. |
| episode_summary | 片段摘要:片段结束时总结一次(每个片段一次模型调用)。 | Episode summaries: each finished episode is summarized once (one model call per episode). | Resúmenes de episodio: cada episodio terminado se resume una vez (una llamada al modelo por episodio). |
| intention | 意图提取:随事实一起记住你提到的计划和意图。 | Intentions: remembers the plans and intentions you mention, along with facts. | Intenciones: recuerda los planes e intenciones que mencionas, junto con los hechos. |
| intention_dedup | 意图去重:同一天里几乎相同的意图只保留最早一条,其余删除。 | Intention dedup: of near-identical intentions from one day, keeps the earliest and deletes the rest. | Deduplicación de intenciones: de las intenciones casi idénticas de un mismo día, conserva la más antigua y borra las demás. |
| intention_dedup_threshold | 去重阈值:越高,越少的意图被视为重复。 | Dedup threshold: the higher it is, the fewer intentions count as copies. | Umbral de deduplicación: cuanto más alto, menos intenciones cuentan como copias. |
| few_shot | 提取示例:在提取提示中加入示例,可帮助较弱的模型(输入更长)。 | Extraction examples: adds examples to the extraction prompt, which can help a weaker model (longer input). | Ejemplos de extracción: añade ejemplos a la instrucción de extracción, lo que puede ayudar a un modelo más débil (entrada más larga). |
| default | 默认 | Default | Predeterminado |
| requires_ultra | 当前模式下不生效,需要 ultra。 | Has no effect in this mode; needs ultra. | No tiene efecto en este modo; requiere ultra. |
+1 -1
View File
@@ -40,7 +40,7 @@ Preview 不会弹出给用户;开关点击本身被视为确认。关闭时通
| [Qwen Code](qwen-code.md) | 开放 | MCP + Skill | 无自动 Hook | `$QWEN_HOME/projects` 扫描 |
| [Pi](pi.md) | 开放 | CLI Skill,不使用 MCP | JS Capture Extension | Pi session 扫描 + Extension 实时入口 |
| [OpenClaw](openclaw.md) | 正式产品冻结 | 当前没有;仅有未开放的底层 MCP 写入器 | 没有 Hook、Plugin 或 Prefetch | Adapter 也被冻结,开关不可用 |
| [DeepSeek Harness](deepseek-harness.md) | 详情页排除,来源管理页按 Profile 接入 | Profile 级 MCP Patch | 无自动 Hook | `$DSH_HOME/sessions` 扫描 |
| [DeepSeek Harness](deepseek-harness.md) | 开放;一个开关覆盖全部已检测 Profile | Profile 级 MCP Patch | 无自动 Hook | `$DSH_HOME/sessions` 扫描 |
## 同步开关的统一精确语义
+37 -26
View File
@@ -1,28 +1,45 @@
# DeepSeek Harness 一键插入支持
更新日期:2026-10-18
更新日期:2026-11-02
## 结论
DeepSeek Harness 的 Profile 级 MCP 安装器已经实现,Profile Scoped Host ID(`deepseek-harness:<profile>`)在权限层按不透明标签处理,可正常走完 Preview 与安装。
DeepSeek Harness 按 Profile 配置 MCP:每个 Profile 是一个独立 Host(`deepseek-harness:<profile>`),有自己的 `cordis.patch.yml`、Credential 与 Grant。应用详情页只有一个“一键插入应用”开关,它一次覆盖桌面检测到的全部 Profile:打开时逐个安装并授权,关闭时逐个移除并撤销。
## 接入方式和产品状态
| 项目 | DeepSeek Harness 当前实现 |
|---|---|
| 应用详情页一键插入 | 有意排除,因为无法选择 Profile |
| 来源管理页 Profile 安装 | 可用;每个 Profile 独立 Patch、Credential 与 Grant |
| 应用详情页一键插入 | 可用;一个开关覆盖全部已检测 Profile,并列出每个 Profile 的状态 |
| 首次导入批量连接 | 排除;在应用详情页打开开关 |
| Harness 查询 MemHub | 通过 Profile 级 Cordis MCP Client |
| Skill | 没有 |
| Prompt 前自动 Prefetch | 没有 |
| Capture Hook/Plugin | 没有 |
| Harness 新会话进入 MemHub | Core 扫描 `$DSH_HOME/sessions` |
| Harness 新会话进入 MemHub | Core 扫描 `$DSH_HOME/sessions`,按 `session[.vN].jsonl[.zstd]` 识别会话文件 |
会话文件按写入时的格式版本命名:首版为 `session.jsonl` / `session.jsonl.zstd`,v3/v4 起为 `session.v3.jsonl.zstd` / `session.v4.jsonl.zstd`。来源扫描接受带版本号的名称;解析前再读文件头 `version` 字段,只导入已验证的 v0/v3/v4,未来未知版本不会被解析:整个文件以 `unsupported_schema` 报告,且不留下读取进度,将来支持该版本的发布会从头读取(错误导入比暂时漏导更难回滚)。`tool/result` 的输出无论写成 `tool-result` 块还是纯 `text` 块,都按同一条裁剪与凭据清洗路径导入。
## 两个开关分别做什么
### “一键插入应用”
### 打开“一键插入应用”
应用详情页不可用。来源管理页对每个 Profile 写 `cordis.patch.yml`、创建独立 Credential 并授权;Host ID 形如 `deepseek-harness:<profile>`,冒号只作为标签存在,权限层的安装目录按 Host ID 摘要生成,不参与路径拼接。
应用详情页对每个已检测、尚未获批的 Profile:
1. 预览并写入该 Profile 的 `cordis.patch.yml` 受管块,创建独立 Credential;
2. 授予 `om_recall`、`om_conversations`、`om_diagnostic_trace`,范围为 `all-apps` 与 `source:deepseek-harness`(与其他应用的一键插入相同)。
已获批的 Profile 不会重装。某个 Profile 失败时,其他 Profile 的结果保留,页面提示失败的 Profile 名称;开关只要有一个 Profile 获批就显示为开。Host ID 里的冒号只作为标签存在,权限层的安装目录按 Host ID 摘要生成,不参与路径拼接。
### 关闭“一键插入应用”
对每个已接入的 Profile 先撤销 Credential,再删除受管块(与其他应用的关闭语义相同)。受管块被改过、无法删除时仍会撤销授权,页面列出需要核对的 Profile;撤销也失败的 Profile 会单独列出,它仍可使用记忆。从未接入的 Profile 不受影响。
### 之后新建的 Profile
桌面每次刷新应用接入状态时都会重新枚举 Profile(`$DSH_HOME/profiles/<profile>/cordis.yml`),应用首页打开时每 3 秒刷新一次;常驻的 Runtime 收到未知的 Profile Host ID 时也会重新读盘。开关的选择会被记住:开关为开时,新出现的 Profile 由应用首页自动安装并授权,不需要重启 MemHub。
每个新 Profile 触发一次自动尝试;失败时应用首页会指明 Profile,不会每次轮询都重试,下次启动或点击重试时再试一次。开关为关时不会自动接入任何 Profile。
### 打开“同步开关”
@@ -32,12 +49,10 @@ DeepSeek Harness 的 Profile 级 MCP 安装器已经实现,Profile Scoped Host
Core 停止扫描和 pending Job claim,running Job可结束,已有 Memory 保留。它不会修改任何 Profile 的 `cordis.patch.yml` 或 Credential。
### 修复一键安装后的组合语义
### 组合语义
未来修复 Profile Host ID 后:
- 某个 Profile 的一键插入只决定该 Profile 是否能查询 MemHub;
- 全局同步开关决定 MemHub 是否继续读取整个 DeepSeek Harness 的 Session;
- 一键插入决定已检测 Profile 是否能查询 MemHub;
- 同步开关决定 MemHub 是否继续读取整个 DeepSeek Harness 的 Session;
- 没有自动 Prefetch,也没有 Capture Hook。
## Profile 粒度
@@ -58,7 +73,7 @@ deepseek-harness:headless
...
```
理论上每个 Profile 拥有独立 Patch、Journal、Credential 和 Grant;Core 会话同步仍按统一的 `deepseek-harness` 来源扫描 `$DSH_HOME/sessions`。
每个 Profile 拥有独立 Patch、Journal、Credential 和 Grant;Core 会话同步仍按统一的 `deepseek-harness` 来源扫描 `$DSH_HOME/sessions`。
## MCP Patch
@@ -85,13 +100,15 @@ DeepSeek Harness 不安装 Skill,也不安装 Capture Hook;新会话进入 M
## UI 状态
- 应用详情页排除 DeepSeek Harness,因为单一来源页无法选择 Profile。
- 首次导入批量连接也排除它。
- 来源管理页会列出每个 Profile,并显示独立安装按钮。
- 应用详情页的“一键插入应用”下方列出每个已检测 Profile 及其“已接入 / 未接入”状态;没有检测到 Profile 时开关不可用,并提示创建 Profile 后回到此页。
- Host ID 只接受小写字母、数字和连字符(最长 32 个字符)。名称不符合的 Profile 仍会列出,但无法授权,页面会指明它和原因,不影响其他 Profile。
- 连接状态取各已接入 Profile 记录的自检结果:全部接通才显示“已接通”。
- 首次导入批量连接排除 DeepSeek Harness。
- CLI 的 `memhub host install deepseek-harness:<profile>` 只安装,不授权(状态停在 `install-only`);授权入口只有应用详情页的开关,CLI 没有授权命令。
## 已修复:Profile Host ID 校验
此前来源管理页安装会在写入 `cordis.patch.yml` 和创建 Credential 之前失败,原因是:
此前 Profile 安装会在写入 `cordis.patch.yml` 和创建 Credential 之前失败,原因是:
```text
系统生成 hostId = deepseek-harness:<profile>
@@ -101,18 +118,12 @@ HostGrantStore 也不接受冒号
Host ID 是不可解释的标签:安装目录对它取摘要,不会把它拼进路径。现在权限层与 Grant 存储都接受一个可选的 `:<profile>` 段,因此 Profile 安装可以正常走完。这不是 DeepSeek Harness 不支持 MCP 的问题,而是 Profile Host ID 格式与权限校验不一致,现已对齐。
## 修复后的权限语义风险
## 已修复:应用详情页返回 `unsupported_host`
来源管理页当前默认授权选择可能包含:
- `om_recall`、`om_conversations`、`om_diagnostic_trace`(`om_ask` 已随 `MemHub_ask` 移除,旧授权仍可读取但不再授权任何工具);
- `all-apps`;
- 所有已授权 Source 和 Workspace。
这比应用详情页通用授权更宽。Host ID 修复后仍应确认是否希望每个 Profile 默认获得如此宽的权限。
此前应用详情页按“一个来源对应一个 Host”接入,而 DeepSeek Harness 没有不带 Profile 的 Host,开关因此置灰并返回 `unsupported_host`,安装后的 Profile 也只能停在 `install-only`(#230)。现在开关直接作用于全部 `deepseek-harness:<profile>` Host,复用与其他应用相同的安装、授权、撤销与卸载接口。
## 重复安装与卸载
底层 Patch 安装是幂等的:已有受管块时替换,不追加第二份。相同 Row ID 出现在 MemHub 哨兵块外时默认拒绝接管。
正常卸载设计是先撤销该 Profile Credential,再删除受管块并保留其他 Patch;如果删完没有其他 Row,恢复 `[]`。用户修改过受管块时不强删。
卸载先撤销该 Profile Credential,再删除受管块并保留其他 Patch;如果删完没有其他 Row,恢复 `[]`。用户修改过受管块时不强删。
@@ -927,6 +927,23 @@ const baseEnglishMessages = {
"Memory access was revoked, so {name} can no longer look up memories. Full removal could not be confirmed; review these paths manually: {paths}.",
appRemovalReview:
"Full connection removal could not be confirmed. Review these paths manually: {paths}.",
appProfilesLabel: "{name} profiles",
appProfileOn: "{profile}: connected",
appProfileOff: "{profile}: not connected",
appProfilesHint:
"The switch installs the memory connection and grants access for every detected profile, and revokes them all when turned off. While it is on, new profiles are connected automatically.",
appProfilesNone:
"No {name} profile was detected. Create a profile, then come back to this page.",
appProfilesConnectFailed:
"These profiles could not be connected: {profiles}. The other profiles were kept. {reason}",
appProfilesDisconnectFailed:
"These profiles could not be disconnected and can still use memories: {profiles}. Please retry. {reason}",
appProfilesRevokedRetained:
"Memory access was revoked for these profiles, but not all of their connection files were removed; review them: {profiles}.",
appProfileNameUnsupported:
"profile names may only use lowercase letters, digits and hyphens, up to 32 characters",
"apps.autoHostProfilesFailed":
"{name} could not connect these profiles automatically ({profiles}){reason}.",
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
"Cursor's connection credential changed. Fully quit and reopen Cursor before starting a new conversation.",
连接其他工具: "Connect other tools",
@@ -298,6 +298,23 @@ export const settingsSpanishMessages = {
"Se revocó el permiso; {name} ya no puede consultar memorias. No se pudo confirmar la eliminación completa de la conexión. Comprueba manualmente: {paths}.",
appRemovalReview:
"No se pudo confirmar la eliminación completa de la conexión. Comprueba manualmente: {paths}.",
appProfilesLabel: "Perfiles de {name}",
appProfileOn: "{profile}: conectado",
appProfileOff: "{profile}: sin conectar",
appProfilesHint:
"El interruptor instala la conexión de memorias y concede acceso a cada perfil detectado, y los revoca todos al apagarlo. Mientras esté activado, los perfiles nuevos se conectan automáticamente.",
appProfilesNone:
"No se detectó ningún perfil de {name}. Crea un perfil y vuelve a esta página.",
appProfilesConnectFailed:
"No se pudieron conectar estos perfiles: {profiles}. Los demás perfiles se mantienen.{reason}",
appProfilesDisconnectFailed:
"No se pudieron desconectar estos perfiles y aún pueden usar memorias: {profiles}. Reintenta.{reason}",
appProfilesRevokedRetained:
"Se revocó el acceso a memorias de estos perfiles, pero no se eliminaron todos sus archivos de conexión; revísalos: {profiles}.",
appProfileNameUnsupported:
"los nombres de perfil solo admiten minúsculas, dígitos y guiones, hasta 32 caracteres",
"apps.autoHostProfilesFailed":
"No se pudieron conectar automáticamente estos perfiles de {name} ({profiles}){reason}. ",
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
"Las credenciales de conexión de Cursor se actualizaron. Cierra completamente Cursor y vuelve a abrirlo; después, inicia una conversación nueva.",
连接其他工具: "Conectar otras herramientas",
@@ -350,6 +367,23 @@ const chineseOverrides: Partial<
appRevokedReview:
"已撤销记忆权限,{name} 已查不到记忆。但无法确认连接已全部移除,需要你手动核对:{paths}。",
appRemovalReview: "无法确认连接已全部移除,需要你手动核对:{paths}。",
appProfilesLabel: "{name} 的 Profile",
appProfileOn: "{profile}:已接入",
appProfileOff: "{profile}:未接入",
appProfilesHint:
"开关会为每个已检测到的 Profile 安装记忆连接并授权,关闭时全部撤销。开关开启期间,新建的 Profile 会自动接入。",
appProfilesNone:
"还没有检测到 {name} 的 Profile。创建 Profile 后再回到此页。",
appProfilesConnectFailed:
"以下 Profile 未能接入:{profiles}。其他 Profile 已保留。{reason}",
appProfilesDisconnectFailed:
"以下 Profile 的连接未能移除,记忆权限也未能撤销,仍可使用记忆:{profiles}。请重试。{reason}",
appProfilesRevokedRetained:
"已撤销以下 Profile 的记忆权限,但连接文件没有全部移除,请核对:{profiles}。",
appProfileNameUnsupported:
"Profile 名称只能包含小写字母、数字和连字符,最长 32 个字符",
"apps.autoHostProfilesFailed":
"{name} 的以下 Profile 未能自动接入({profiles}){reason}。",
};
export const settingsChineseMessages = Object.fromEntries(
Object.keys(settingsSpanishMessages).map((key) => [
@@ -1105,6 +1105,23 @@ export const germanMessages: Record<MessageKey, string> = {
"Der Erinnerungszugriff wurde widerrufen; {name} kann keine Erinnerungen mehr abfragen. Die vollständige Entfernung konnte nicht bestätigt werden; prüfen Sie diese Pfade manuell: {paths}.",
appRemovalReview:
"Vollständige Entfernung der Verbindung konnte nicht bestätigt werden. Prüfen Sie diese Pfade manuell: {paths}.",
appProfilesLabel: "Profile von {name}",
appProfileOn: "{profile}: verbunden",
appProfileOff: "{profile}: nicht verbunden",
appProfilesHint:
"Der Schalter installiert für jedes erkannte Profil die Erinnerungsverbindung und erteilt den Zugriff; beim Ausschalten wird er für alle widerrufen. Solange er eingeschaltet ist, werden neue Profile automatisch verbunden.",
appProfilesNone:
"Es wurde kein Profil von {name} erkannt. Legen Sie ein Profil an und kehren Sie dann zu dieser Seite zurück.",
appProfilesConnectFailed:
"Diese Profile konnten nicht verbunden werden: {profiles}. Die übrigen Profile bleiben erhalten. {reason}",
appProfilesDisconnectFailed:
"Diese Profile konnten nicht getrennt werden und können weiterhin Erinnerungen nutzen: {profiles}. Bitte versuchen Sie es erneut. {reason}",
appProfilesRevokedRetained:
"Der Erinnerungszugriff dieser Profile wurde widerrufen, aber nicht alle Verbindungsdateien wurden entfernt; prüfen Sie sie: {profiles}.",
appProfileNameUnsupported:
"Profilnamen dürfen nur Kleinbuchstaben, Ziffern und Bindestriche enthalten, höchstens 32 Zeichen",
"apps.autoHostProfilesFailed":
"Diese Profile von {name} konnten nicht automatisch verbunden werden ({profiles}){reason}.",
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
"Die Verbindungs-Anmeldedaten von Cursor haben sich geändert. Beenden Sie Cursor vollständig und öffnen Sie es erneut, bevor Sie eine neue Unterhaltung beginnen.",
连接其他工具: "Andere Tools verbinden",
@@ -1118,6 +1118,23 @@ export const frenchMessages: Record<MessageKey, string> = {
"L’accès aux mémoires a été révoqué : {name} ne peut plus rechercher de mémoires. La suppression complète n’a pas pu être confirmée ; vérifiez manuellement ces chemins : {paths}.",
appRemovalReview:
"La suppression complète de la connexion n’a pas pu être confirmée. Vérifiez manuellement ces chemins : {paths}.",
appProfilesLabel: "Profils de {name}",
appProfileOn: "{profile} : connecté",
appProfileOff: "{profile} : non connecté",
appProfilesHint:
"L’interrupteur installe la connexion aux mémoires et accorde l’accès à chaque profil détecté, puis les révoque tous lorsqu’il est désactivé. Tant qu’il est activé, les nouveaux profils sont connectés automatiquement.",
appProfilesNone:
"Aucun profil de {name} n’a été détecté. Créez un profil, puis revenez sur cette page.",
appProfilesConnectFailed:
"Ces profils n’ont pas pu être connectés : {profiles}. Les autres profils sont conservés. {reason}",
appProfilesDisconnectFailed:
"Ces profils n’ont pas pu être déconnectés et peuvent encore utiliser les mémoires : {profiles}. Réessayez. {reason}",
appProfilesRevokedRetained:
"L’accès aux mémoires de ces profils a été révoqué, mais tous leurs fichiers de connexion n’ont pas été supprimés ; vérifiez-les : {profiles}.",
appProfileNameUnsupported:
"les noms de profil ne peuvent contenir que des minuscules, des chiffres et des tirets, 32 caractères au maximum",
"apps.autoHostProfilesFailed":
"Ces profils de {name} n’ont pas pu être connectés automatiquement ({profiles}){reason}.",
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
"L’identifiant de connexion de Cursor a changé. Quittez complètement Cursor et rouvrez-le avant de démarrer une nouvelle conversation.",
连接其他工具: "Connecter d’autres outils",
@@ -1088,6 +1088,23 @@ export const indonesianMessages: Record<MessageKey, string> = {
"Akses memori telah dicabut, sehingga {name} tidak dapat lagi mencari memori. Penghapusan penuh belum dapat dikonfirmasi; tinjau jalur berikut secara manual: {paths}.",
appRemovalReview:
"Penghapusan koneksi penuh belum dapat dikonfirmasi. Tinjau jalur berikut secara manual: {paths}.",
appProfilesLabel: "Profil {name}",
appProfileOn: "{profile}: terhubung",
appProfileOff: "{profile}: belum terhubung",
appProfilesHint:
"Sakelar ini memasang koneksi memori dan memberi akses untuk setiap profil yang terdeteksi, lalu mencabut semuanya saat dimatikan. Selama sakelar menyala, profil baru akan terhubung otomatis.",
appProfilesNone:
"Tidak ada profil {name} yang terdeteksi. Buat profil, lalu kembali ke halaman ini.",
appProfilesConnectFailed:
"Profil berikut tidak dapat dihubungkan: {profiles}. Profil lainnya tetap dipertahankan. {reason}",
appProfilesDisconnectFailed:
"Profil berikut tidak dapat diputuskan dan masih dapat memakai memori: {profiles}. Coba lagi. {reason}",
appProfilesRevokedRetained:
"Akses memori untuk profil berikut telah dicabut, tetapi tidak semua file koneksinya dihapus; tinjau: {profiles}.",
appProfileNameUnsupported:
"nama profil hanya boleh berisi huruf kecil, angka, dan tanda hubung, maksimal 32 karakter",
"apps.autoHostProfilesFailed":
"Profil {name} berikut tidak dapat terhubung otomatis ({profiles}){reason}.",
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
"Kredensial koneksi Cursor telah berubah. Keluar sepenuhnya lalu buka kembali Cursor sebelum memulai percakapan baru.",
连接其他工具: "Hubungkan alat lain",
@@ -1084,6 +1084,23 @@ export const japaneseMessages: Record<MessageKey, string> = {
"記憶へのアクセスを取り消したため、{name} は記憶を照会できなくなりました。接続が完全に削除されたか確認できませんでした。次のパスを手動で確認してください:{paths}。",
appRemovalReview:
"接続が完全に削除されたか確認できませんでした。次のパスを手動で確認してください:{paths}。",
appProfilesLabel: "{name} のプロファイル",
appProfileOn: "{profile}:接続済み",
appProfileOff: "{profile}:未接続",
appProfilesHint:
"このスイッチは検出されたすべてのプロファイルに記憶の接続をインストールしてアクセスを許可し、オフにするとすべて取り消します。オンの間は、新しいプロファイルも自動的に接続されます。",
appProfilesNone:
"{name} のプロファイルが検出されませんでした。プロファイルを作成してから、このページに戻ってください。",
appProfilesConnectFailed:
"次のプロファイルを接続できませんでした:{profiles}。ほかのプロファイルはそのまま維持されます。{reason}",
appProfilesDisconnectFailed:
"次のプロファイルの接続を解除できず、引き続き記憶を使用できます:{profiles}。もう一度お試しください。{reason}",
appProfilesRevokedRetained:
"次のプロファイルの記憶へのアクセスを取り消しましたが、接続ファイルの一部は削除されていません。確認してください:{profiles}。",
appProfileNameUnsupported:
"プロファイル名に使えるのは小文字、数字、ハイフンのみで、32 文字までです",
"apps.autoHostProfilesFailed":
"{name} の次のプロファイルを自動的に接続できませんでした({profiles}){reason}。",
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
"Cursor の接続の認証情報が更新されました。Cursor を完全に終了して開き直してから、新しい会話を始めてください。",
连接其他工具: "ほかのツールを接続",
@@ -1061,6 +1061,23 @@ export const koreanMessages: Record<MessageKey, string> = {
"기억 접근 권한이 취소되어 {name}은(는) 더 이상 기억을 조회할 수 없습니다. 완전히 제거되었는지 확인할 수 없으니 다음 경로를 직접 확인하세요: {paths}.",
appRemovalReview:
"연결이 완전히 제거되었는지 확인할 수 없습니다. 다음 경로를 직접 확인하세요: {paths}.",
appProfilesLabel: "{name} 프로필",
appProfileOn: "{profile}: 연결됨",
appProfileOff: "{profile}: 연결 안 됨",
appProfilesHint:
"이 스위치는 감지된 모든 프로필에 기억 연결을 설치하고 접근을 허용하며, 끄면 모두 취소합니다. 켜져 있는 동안 새 프로필은 자동으로 연결됩니다.",
appProfilesNone:
"{name} 프로필이 감지되지 않았습니다. 프로필을 만든 뒤 이 페이지로 돌아오세요.",
appProfilesConnectFailed:
"다음 프로필을 연결하지 못했습니다: {profiles}. 다른 프로필은 유지됩니다. {reason}",
appProfilesDisconnectFailed:
"다음 프로필의 연결을 해제하지 못해 여전히 기억을 사용할 수 있습니다: {profiles}. 다시 시도하세요. {reason}",
appProfilesRevokedRetained:
"다음 프로필의 기억 접근 권한을 취소했지만 연결 파일이 모두 제거되지는 않았습니다. 확인하세요: {profiles}.",
appProfileNameUnsupported:
"프로필 이름에는 소문자, 숫자, 하이픈만 사용할 수 있으며 최대 32자입니다",
"apps.autoHostProfilesFailed":
"{name}의 다음 프로필을 자동으로 연결하지 못했습니다({profiles}){reason}.",
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
"Cursor의 연결 자격 증명이 변경되었습니다. 새 대화를 시작하기 전에 Cursor를 완전히 종료했다가 다시 여세요.",
连接其他工具: "다른 도구 연결",
@@ -1109,6 +1109,23 @@ export const portugueseMessages: Record<MessageKey, string> = {
"O acesso às memórias foi revogado, então {name} não pode mais consultar memórias. Não foi possível confirmar a remoção completa; revise estes caminhos manualmente: {paths}.",
appRemovalReview:
"Não foi possível confirmar a remoção completa da conexão. Revise estes caminhos manualmente: {paths}.",
appProfilesLabel: "Perfis de {name}",
appProfileOn: "{profile}: conectado",
appProfileOff: "{profile}: não conectado",
appProfilesHint:
"O interruptor instala a conexão de memórias e concede acesso a cada perfil detectado, e revoga todos ao ser desligado. Enquanto estiver ligado, novos perfis são conectados automaticamente.",
appProfilesNone:
"Nenhum perfil de {name} foi detectado. Crie um perfil e volte a esta página.",
appProfilesConnectFailed:
"Não foi possível conectar estes perfis: {profiles}. Os outros perfis foram mantidos. {reason}",
appProfilesDisconnectFailed:
"Não foi possível desconectar estes perfis, que ainda podem usar memórias: {profiles}. Tente novamente. {reason}",
appProfilesRevokedRetained:
"O acesso às memórias foi revogado para estes perfis, mas nem todos os arquivos de conexão foram removidos; revise-os: {profiles}.",
appProfileNameUnsupported:
"nomes de perfil só podem usar letras minúsculas, dígitos e hifens, até 32 caracteres",
"apps.autoHostProfilesFailed":
"Não foi possível conectar automaticamente estes perfis de {name} ({profiles}){reason}.",
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
"A credencial de conexão do Cursor mudou. Feche o Cursor por completo e abra novamente antes de iniciar uma nova conversa.",
连接其他工具: "Conectar outras ferramentas",
@@ -1093,6 +1093,23 @@ export const russianMessages: Record<MessageKey, string> = {
"Доступ к памяти отозван: {name} больше не может искать записи памяти. Полное удаление не подтверждено; проверьте эти пути вручную: {paths}.",
appRemovalReview:
"Полное удаление подключения не подтверждено. Проверьте эти пути вручную: {paths}.",
appProfilesLabel: "Профили {name}",
appProfileOn: "{profile}: подключён",
appProfileOff: "{profile}: не подключён",
appProfilesHint:
"Переключатель устанавливает подключение к памяти и выдаёт доступ каждому найденному профилю, а при выключении отзывает доступ у всех. Пока он включён, новые профили подключаются автоматически.",
appProfilesNone:
"Профили {name} не найдены. Создайте профиль и вернитесь на эту страницу.",
appProfilesConnectFailed:
"Не удалось подключить профили: {profiles}. Остальные профили сохранены. {reason}",
appProfilesDisconnectFailed:
"Не удалось отключить профили, они всё ещё могут использовать память: {profiles}. Повторите попытку. {reason}",
appProfilesRevokedRetained:
"Доступ к памяти для этих профилей отозван, но не все файлы подключения удалены; проверьте их: {profiles}.",
appProfileNameUnsupported:
"имя профиля может содержать только строчные буквы, цифры и дефисы, не более 32 символов",
"apps.autoHostProfilesFailed":
"Не удалось автоматически подключить эти профили {name} ({profiles}){reason}.",
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
"Учётные данные подключения Cursor изменились. Полностью закройте и снова откройте Cursor, прежде чем начинать новый диалог.",
连接其他工具: "Подключить другие инструменты",
@@ -991,6 +991,22 @@ export const traditionalChineseMessages: Record<MessageKey, string> = {
appRevokedReview:
"已撤銷記憶權限,{name} 已無法查詢記憶。但無法確認連線已全部移除,請手動核對以下路徑:{paths}。",
appRemovalReview: "無法確認連線已全部移除,請手動核對以下路徑:{paths}。",
appProfilesLabel: "{name} 的 Profile",
appProfileOn: "{profile}:已串接",
appProfileOff: "{profile}:未串接",
appProfilesHint:
"開關會為每個已偵測到的 Profile 安裝記憶連線並授權,關閉時全部撤銷。開關開啟期間,新建立的 Profile 會自動串接。",
appProfilesNone: "尚未偵測到 {name} 的 Profile。建立 Profile 後請回到此頁。",
appProfilesConnectFailed:
"以下 Profile 未能串接:{profiles}。其他 Profile 已保留。{reason}",
appProfilesDisconnectFailed:
"以下 Profile 的連線未能移除,記憶權限也未能撤銷,仍可使用記憶:{profiles}。請重試。{reason}",
appProfilesRevokedRetained:
"已撤銷以下 Profile 的記憶權限,但連線檔案沒有全部移除,請核對:{profiles}。",
appProfileNameUnsupported:
"Profile 名稱只能包含小寫字母、數字和連字號,最長 32 個字元",
"apps.autoHostProfilesFailed":
"{name} 的以下 Profile 未能自動串接({profiles}){reason}。",
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
"Cursor 的連線憑證已更新。請完全結束並重新開啟 Cursor,再開始新對話。",
连接其他工具: "連線其他工具",
@@ -21,6 +21,7 @@ interface Options {
permissions: HostPermissions;
layouts: ReadonlyMap<string, RecallHostLayout>;
hosts?: readonly RecallHostDescriptor[];
discoverHosts?: () => Promise<readonly RecallHostDescriptor[]>;
}
/** Constructed inside the Runtime with its existing permission owner. */
@@ -28,6 +29,7 @@ export function createConnectionControlService(options: Options) {
const hostControl = createHostControlService({
permissions: options.permissions,
hosts: options.hosts ?? [],
...(options.discoverHosts ? { discover: options.discoverHosts } : {}),
});
let controller: Promise<ConnectionController | null> | null = null;
let pinned: string | null = null;
@@ -194,6 +194,39 @@ it.each([
expect(f.effects).toEqual([]);
},
);
it("finds a Harness profile created after the Runtime started, and only a profile", async () => {
const f = await fixture();
const hostId = "deepseek-harness:later";
const later = {
hostId,
label: "DeepSeek Harness · later",
layout: { ...f.layout, hostId, hostLabel: "DeepSeek Harness · later" },
presencePath: f.root,
};
const discover = vi.fn(async () => [...f.hosts, later]);
const service = createHostControlService({
permissions: f.permissions as unknown as HostPermissions,
hosts: f.hosts,
discover,
});
await service.handle({ hostId, operation: "getPermission", args: [] });
expect(f.methods.getPermission).toHaveBeenCalledWith(later.layout);
// Remembered: the disk is read once per new profile, not once per call.
await service.handle({ hostId, operation: "getPermission", args: [] });
expect(discover).toHaveBeenCalledTimes(1);
await expect(
service.handle({
hostId: "deepseek-harness:absent",
operation: "getPermission",
args: [],
}),
).rejects.toThrow();
expect(discover).toHaveBeenCalledTimes(2);
await expect(
service.handle({ hostId: "unknown", operation: "getPermission", args: [] }),
).rejects.toThrow();
expect(discover).toHaveBeenCalledTimes(2);
});
it("clones nested arguments and trusted layout before an asynchronous owner observes them", async () => {
const f = await fixture();
let release!: () => void;
@@ -149,6 +149,8 @@ function validateArgs(operation: HostControlOperation, args: unknown[]): void {
export function createHostControlService(options: {
permissions: HostPermissions;
hosts: readonly RecallHostDescriptor[];
/** Re-reads the disk for a profile host created since this service started. */
discover?: () => Promise<readonly RecallHostDescriptor[]>;
}) {
const permissions = options.permissions;
const hosts = new Map<string, RecallHostDescriptor>();
@@ -158,6 +160,17 @@ export function createHostControlService(options: {
fail();
hosts.set(source.hostId, structuredClone(source));
}
/** Only a profile id can appear after start; every other host is a fixed
* path, so an unknown one is refused without touching the disk. */
async function discovered(hostId: string) {
if (!options.discover || !hostId.includes(":")) return undefined;
const found = (await options.discover()).find(
(source) =>
source.hostId === hostId && source.layout.hostId === source.hostId,
);
if (found) hosts.set(hostId, structuredClone(found));
return found;
}
return {
async handle(input: unknown): Promise<unknown> {
const request = exact(input, ["hostId", "operation", "args"]);
@@ -169,7 +182,10 @@ export function createHostControlService(options: {
!Array.isArray(request.args)
)
fail();
const host = hosts.get(request.hostId);
// A known host must not yield here: its arguments are cloned below,
// before the caller's next tick can change them.
const host =
hosts.get(request.hostId) ?? (await discovered(request.hostId));
if (!host) fail();
const operation = request.operation as HostControlOperation;
if (
@@ -749,12 +749,14 @@ export async function createRuntimeService(
verifyHostRuntime,
config.hostRuntime?.manifestSha256 ?? "daily",
);
const hosts = (
await recallHosts(config.hostHome ?? os.homedir(), {
...process.env,
ONE_MEMORY_HOST_HOME: config.hostHome,
})
).filter((host) => host.hostId !== "openclaw");
const scanHosts = async () =>
(
await recallHosts(config.hostHome ?? os.homedir(), {
...process.env,
ONE_MEMORY_HOST_HOME: config.hostHome,
})
).filter((host) => host.hostId !== "openclaw");
const hosts = await scanHosts();
await verifyHostRuntime().then(
async () => {
// Every Runtime start after an upgrade, the App's or `memhub
@@ -784,6 +786,9 @@ export async function createRuntimeService(
connection,
permissions,
hosts,
// The Runtime outlives the App: a Harness profile created after it
// started must not make every later host read fail.
discoverHosts: scanHosts,
layouts: new Map(
hosts.flatMap((host) =>
host.hostId === "claude-code"
+1 -1
View File
@@ -36,7 +36,7 @@ MEMMY_LICENSE = (
MEMMY_PROVENANCE = MEMMY_LICENSE.with_name("PROVENANCE.md")
MEMMY_PIN = "25acd5f29fc7df73b943713abe61f1b2f9839887"
HY_MEMORY_NAME = "hy-memory"
HY_MEMORY_VERSION = "2.0.11"
HY_MEMORY_VERSION = "2.0.12"
class SbomError(RuntimeError):
+1 -1
View File
@@ -12,7 +12,7 @@ test("installation docs disclose publication and lifecycle boundaries", async ()
"utf8",
);
assert.match(readme, /`hy-memory==2\.0\.11`/);
assert.match(readme, /`hy-memory==2\.0\.12`/);
assert.match(readme, /`v1\.0\.6` 的发行目标是 Linux x64\/arm64 Runtime/);
assert.match(readme, /Linux 制品由 GitHub Actions/);
assert.match(readme, /macOS.*Developer ID 签名、公证/s);
@@ -80,6 +80,8 @@ CONFIG_FIELDS = {
"dynamic_episode_enabled",
"episode_capsule_context_enabled",
"local_rerank_enabled",
"intention_dedup_enabled",
"intention_dedup_threshold",
],
}
+3 -3
View File
@@ -13,7 +13,7 @@ spec.loader.exec_module(module)
def test_hy_memory_notice_comes_from_the_installed_dist_info(tmp_path: Path) -> None:
dist_info = tmp_path / "hy_memory-2.0.11.dist-info"
dist_info = tmp_path / "hy_memory-2.0.12.dist-info"
licenses = dist_info / "licenses"
licenses.mkdir(parents=True)
(dist_info / "METADATA").write_text(
@@ -21,7 +21,7 @@ def test_hy_memory_notice_comes_from_the_installed_dist_info(tmp_path: Path) ->
(
"Metadata-Version: 2.4",
"Name: hy-memory",
"Version: 2.0.11",
"Version: 2.0.12",
"License-Expression: Apache-2.0",
"",
)
@@ -38,7 +38,7 @@ def test_hy_memory_notice_comes_from_the_installed_dist_info(tmp_path: Path) ->
notice = module.hy_memory_notice(dist_info)
assert notice["name"] == "hy-memory"
assert notice["version"] == "2.0.11"
assert notice["version"] == "2.0.12"
assert notice["license"] == "Apache-2.0"
assert notice["copyright"] == "Copyright (C) 2026 Tencent. All rights reserved."
assert "Licensed under the Apache License" in notice["text"]
+346
View File
@@ -0,0 +1,346 @@
# -*- coding: utf-8 -*-
"""
Intention(L7)读侧判重开关(issue #241)。
覆盖:
1. 默认开启:行为不变,复本只返回最早一条,其余异步删库;
2. 关闭:不隐藏、不删除,两条意图都返回;
3. 阈值生效:cosine 低于阈值不判重,高于阈值判重;
4. reader 按 client 的 MemoryConfig.recall 读取开关/阈值,而非调用时的 env;
5. MemoryConfig 默认值与 env 回退;
6. 写入侧批内判重同样受开关控制;阈值不影响写入侧;
7. 关闭时不为判重补拉 embedding;配置阈值非法时不影响召回。
"""
from __future__ import annotations
import uuid
from datetime import datetime
import pytest
from hy_memory.config import MemoryConfig
from hy_memory.pipelines.base import ReadRequest
from hy_memory.pipelines._retrieval.intention import recall_intentions
from tests.test_intention_dedup import (
_FakeVectorStore,
_make_intention_node,
_run,
)
_MA = datetime(2025, 8, 6)
_VU = datetime(2025, 8, 31, 23, 59)
_NOW = datetime(2025, 8, 6, 12, 0)
def _unit(vec):
n = sum(x * x for x in vec) ** 0.5 or 1.0
return [x / n for x in vec]
def _seed_project_pair(vs, *, emb_a, emb_b):
"""A / B 两个项目的近似意图:同 user/agent/同天/同截止日。A 更早写入。"""
a = _make_intention_node(
"A 项目每周一触发发布前校验流程", memory_at=_MA, valid_until=_VU,
gmt_created=datetime(2025, 8, 1), embedding=emb_a,
)
b = _make_intention_node(
"B 项目每周一触发发布前校验流程", memory_at=_MA, valid_until=_VU,
gmt_created=datetime(2025, 8, 2), embedding=emb_b,
)
_run(vs.upsert(a))
_run(vs.upsert(b))
return a, b
# ============================================================================
# recall_intentions 参数
# ============================================================================
def test_default_on_keeps_earliest_and_deletes_duplicate():
vs = _FakeVectorStore()
emb = _unit([1.0, 0.0])
a, b = _seed_project_pair(vs, emb_a=emb, emb_b=list(emb))
stats = {}
result = _run(recall_intentions(
vs, emb, user_ids=["u1"], limit=10, now=_NOW, stats_out=stats,
))
assert [h["node_id"] for h in result] == [a.node_id]
assert vs.delete_calls == [b.node_id]
assert stats["dedup_enabled"] is True
assert stats["dedup_dropped"] == 1
def test_off_returns_both_and_deletes_nothing():
vs = _FakeVectorStore()
emb = _unit([1.0, 0.0])
a, b = _seed_project_pair(vs, emb_a=emb, emb_b=list(emb))
stats = {}
result = _run(recall_intentions(
vs, emb, user_ids=["u1"], limit=10, now=_NOW, stats_out=stats,
dedup_enabled=False,
))
assert {h["node_id"] for h in result} == {a.node_id, b.node_id}
assert vs.delete_calls == []
assert stats["dedup_enabled"] is False
assert stats["dedup_dropped"] == 0
def test_threshold_respected():
# cosine(a, b) = 0.9
emb_a = _unit([1.0, 0.0])
emb_b = _unit([0.9, (1 - 0.81) ** 0.5])
# 默认 0.95 → 0.9 不算复本
vs = _FakeVectorStore()
_seed_project_pair(vs, emb_a=emb_a, emb_b=emb_b)
result = _run(recall_intentions(
vs, emb_a, user_ids=["u1"], limit=10, now=_NOW, dedup_threshold=0.95,
))
assert len(result) == 2
assert vs.delete_calls == []
# 调低到 0.85 → 判重,删较晚的 B
vs = _FakeVectorStore()
a, b = _seed_project_pair(vs, emb_a=emb_a, emb_b=emb_b)
stats = {}
result = _run(recall_intentions(
vs, emb_a, user_ids=["u1"], limit=10, now=_NOW,
dedup_threshold=0.85, stats_out=stats,
))
assert [h["node_id"] for h in result] == [a.node_id]
assert vs.delete_calls == [b.node_id]
assert stats["dedup_threshold"] == 0.85
def test_explicit_threshold_wins_over_env(monkeypatch):
monkeypatch.setenv("MEMORY_DEDUP_THRESHOLD", "0.5")
emb_a = _unit([1.0, 0.0])
emb_b = _unit([0.9, (1 - 0.81) ** 0.5])
vs = _FakeVectorStore()
_seed_project_pair(vs, emb_a=emb_a, emb_b=emb_b)
result = _run(recall_intentions(
vs, emb_a, user_ids=["u1"], limit=10, now=_NOW, dedup_threshold=0.95,
))
assert len(result) == 2
assert vs.delete_calls == []
def test_off_skips_embedding_backfill():
vs = _FakeVectorStore()
emb = _unit([1.0, 0.0])
_seed_project_pair(vs, emb_a=emb, emb_b=list(emb))
backfill_calls = []
async def _get_embeddings(ids):
backfill_calls.append(ids)
return {}
vs.get_embeddings = _get_embeddings
for n in vs._nodes.values():
n.embedding = None
result = _run(recall_intentions(
vs, emb, user_ids=["u1"], limit=10, now=_NOW, dedup_enabled=False,
))
assert len(result) == 2
assert backfill_calls == []
def test_invalid_threshold_degrades_to_env_default(monkeypatch):
monkeypatch.delenv("MEMORY_DEDUP_THRESHOLD", raising=False)
vs = _FakeVectorStore()
emb = _unit([1.0, 0.0])
a, b = _seed_project_pair(vs, emb_a=emb, emb_b=list(emb))
stats = {}
result = _run(recall_intentions(
vs, emb, user_ids=["u1"], limit=10, now=_NOW, stats_out=stats,
dedup_threshold="not-a-number",
))
assert [h["node_id"] for h in result] == [a.node_id]
assert stats["dedup_threshold"] == 0.95
# ============================================================================
# 写入侧批内判重
# ============================================================================
class _SameVectorEmbed:
"""所有文本同一向量:cosine=1,开启判重时必判为复本。"""
async def embed_batch(self, texts):
return [_unit([1.0, 0.0]) for _ in texts]
async def embed_queued(self, text):
return _unit([1.0, 0.0])
def _store_batch(config_recall):
from hy_memory.pipelines.base import WriteRequest
from hy_memory.pipelines.writer import MemoryWriter
cfg = MemoryConfig.from_dict({"recall": config_recall})
vs = _FakeVectorStore()
writer = MemoryWriter(cfg, embed_service=_SameVectorEmbed(), vector_store=vs)
req = WriteRequest(
content="", messages=[], user_id="u1", agent_id="a1",
session_id="s1", request_id=uuid.uuid4().hex,
)
intentions = [
{"content": "A 项目每周一触发发布前校验流程", "tags": [], "valid_until": None},
{"content": "B 项目每周一触发发布前校验流程", "tags": [], "valid_until": None},
]
return _run(writer._store_intentions(intentions, req, vs, req.request_id)), vs
def test_write_batch_dedup_default_on_unchanged():
ids, vs = _store_batch({})
assert len(ids) == 1
assert [n.content for n in vs._nodes.values()] == [
"A 项目每周一触发发布前校验流程",
]
def test_write_batch_dedup_off_stores_both():
ids, vs = _store_batch({"intention_dedup_enabled": False})
assert len(ids) == 2
assert len(vs._nodes) == 2
def test_read_threshold_does_not_change_write_batch_dedup(monkeypatch):
"""intention_dedup_threshold 只管读侧;写入侧仍取 MEMORY_DEDUP_THRESHOLD。"""
monkeypatch.delenv("MEMORY_DEDUP_THRESHOLD", raising=False)
ids, _ = _store_batch({"intention_dedup_threshold": 1.5})
assert len(ids) == 1
# ============================================================================
# MemoryConfig
# ============================================================================
def test_config_defaults(monkeypatch):
for k in (
"MEMORY_INTENTION_DEDUP_ENABLED",
"MEMORY_INTENTION_DEDUP_THRESHOLD",
"MEMORY_DEDUP_THRESHOLD",
):
monkeypatch.delenv(k, raising=False)
cfg = MemoryConfig()
assert cfg.recall.intention_dedup_enabled is True
assert cfg.recall.intention_dedup_threshold == 0.95
def test_config_env_fallbacks(monkeypatch):
monkeypatch.setenv("MEMORY_INTENTION_DEDUP_ENABLED", "false")
monkeypatch.setenv("MEMORY_DEDUP_THRESHOLD", "0.9")
monkeypatch.delenv("MEMORY_INTENTION_DEDUP_THRESHOLD", raising=False)
cfg = MemoryConfig()
assert cfg.recall.intention_dedup_enabled is False
# 未设专用阈值 → 回退共享 MEMORY_DEDUP_THRESHOLD(兼容旧部署)
assert cfg.recall.intention_dedup_threshold == 0.9
monkeypatch.setenv("MEMORY_INTENTION_DEDUP_THRESHOLD", "0.8")
assert MemoryConfig().recall.intention_dedup_threshold == 0.8
def test_config_from_dict_overrides_env(monkeypatch):
monkeypatch.setenv("MEMORY_INTENTION_DEDUP_ENABLED", "true")
cfg = MemoryConfig.from_dict({"recall": {
"intention_dedup_enabled": False,
"intention_dedup_threshold": 0.99,
}})
assert cfg.recall.intention_dedup_enabled is False
assert cfg.recall.intention_dedup_threshold == 0.99
assert cfg.to_dict()["recall"]["intention_dedup_enabled"] is False
# ============================================================================
# reader:按 client 配置,而不是调用时的 env
# ============================================================================
def _reader_for(enabled: bool, vs):
from hy_memory.pipelines.reader_hybrid import HybridReadPipeline
cfg = MemoryConfig.from_dict({
"vector_store": {
"provider": "chroma",
"collection_name": f"t_intent_sw_{uuid.uuid4().hex[:8]}",
"embedding_dims": 2,
},
"recall": {"intention_dedup_enabled": enabled},
})
reader = HybridReadPipeline(cfg, vector_store=vs)
reader._vector_store = vs
reader._vector_store_initialized = True
return reader
async def _no_keyword_hits(**kw):
return []
def _read_project_pair(enabled: bool):
"""经 reader 完整读路径召回 A/B 两条近似意图;返回 (返回的意图 id, 删库调用, a, b)。"""
vs = _FakeVectorStore()
vs.keyword_search = _no_keyword_hits
emb = _unit([1.0, 0.0])
a, b = _seed_project_pair(vs, emb_a=emb, emb_b=list(emb))
# 读路径用真实 now:让两条都未过期且同一天
today = datetime.now()
for n in (a, b):
n.memory_at = today
n.valid_until = None
reader = _reader_for(enabled, vs)
_run(reader.initialize())
resp = _run(reader.read(ReadRequest(
query="发布前校验", query_embedding=emb,
user_ids=["u1"], agent_ids=["a1"], limit=10, intention_limit=5,
)))
ids = {
m["memory_id"] for m in resp.memories
if m.get("layer") == "l7_intention"
}
return ids, list(vs.delete_calls), a, b
@pytest.mark.parametrize("env_value", ["true", "false"])
def test_reader_uses_per_client_config_not_env(monkeypatch, env_value):
"""调用时的 env 与 client 配置无关:两个 client 一开一关,各自生效。"""
monkeypatch.setenv("MEMORY_INTENTION_DEDUP_ENABLED", env_value)
monkeypatch.setenv("MEMORY_DEDUP_THRESHOLD", "0.0")
ids_on, deleted_on, a, b = _read_project_pair(True)
assert ids_on == {a.node_id}
assert deleted_on == [b.node_id]
ids_off, deleted_off, a, b = _read_project_pair(False)
assert ids_off == {a.node_id, b.node_id}
assert deleted_off == []
def test_reader_passes_client_threshold(monkeypatch):
monkeypatch.setenv("MEMORY_DEDUP_THRESHOLD", "0.1")
seen = []
async def _spy(*args, **kwargs):
seen.append(kwargs)
return []
monkeypatch.setattr("hy_memory.pipelines.reader_base.recall_intentions", _spy)
vs = _FakeVectorStore()
vs.keyword_search = _no_keyword_hits
reader = _reader_for(True, vs)
reader.config.recall.intention_dedup_threshold = 0.97
_run(reader.initialize())
_run(reader.read(ReadRequest(
query="发布前校验", query_embedding=_unit([1.0, 0.0]),
user_ids=["u1"], agent_ids=["a1"], limit=10, intention_limit=5,
)))
assert seen and seen[0]["dedup_enabled"] is True
assert seen[0]["dedup_threshold"] == 0.97