[Bug]: entities category guidance is language-branched and freely invented, splitting one topic into multiple category directories
Issue Origin
Observed or reproduced in a real environment
Bug Description
In a single-user store, entities cards for the same real-world topic end up under several
different category directories, because the category value is produced by the extraction
model from a loose, {{ language }}-branched instruction, and it is then used directly as a
path segment:
entities.yaml:11 filename_template: "{{ category|lower }}/{{ name|lower }}.md" entities.yaml:31 Category written in {{ language }}. entities.yaml:32 {% if language == 'en' %}Use lowercase with underscores, max 3 words.{% else %}Keep it concise and natural in {{ language }}.{% endif %}
Two independent multipliers:
- Language.
{{ language }}is per-session — see theLanguage policyline already used incases.yaml: "use the current task user's primary language as{{ language }}; if unclear, use the latest user message language". A bilingual user therefore gets at least two directories per topic, one per instruction branch. - No canonical vocabulary. Nothing tells the model to reuse an existing category, so every synonym becomes a new directory.
Measured in one real store (single user, entities extraction enabled by default, zh/en):
- 87 category directories before a local mitigation, including
academic_paper/学术论文/论文,tooling/tool/工具/工具包,软件/software/软件包/软件组件. - Even after the local mitigation (which only blocks new splits — it cannot rewrite history),
37 categories remain, 8 of them ASCII synonyms coexisting with a Chinese equivalent:
concept/学术概念,document/工程文档,project/工程项目,software/软件环境,software_plugin,software_project,software_tool/软件工具,tool/工具链.
Impact:
- The same object has several near-duplicate cards; retrieval returns a partial or stale card depending on which category the query happens to match.
categoryandnamearemerge_op: immutable, so a later extraction cannot rename or merge a duplicate into the canonical path — the divergence is permanent without manual migration (this is the write-path half that #3526 asks for).- Cross-file
linkspoint into one directory variant, so the other variants fall out of the link graph. - Nothing is logged; the divergence is silent and only surfaces as degraded retrieval.
Note on the analogous preferences case (#4043): that issue states entities never splits
because it has no user layer. Entities does split — through category — by the same
mechanism: an LLM-filled field interpolated as a directory path segment. The |lower filters
now on main only normalize ASCII case; they do not merge alias or language variants, and for
CJK values |lower is a no-op.
Steps to Reproduce
-
Run OpenViking with the default memory templates and entities extraction enabled, used by a bilingual (zh/en) user, so that
{{ language }}alternates between sessions. -
In Chinese sessions, discuss a real object (a paper, a piece of software, a project). In later English sessions, discuss the same object.
-
List the category directories:
ov ls viking://user/default/memories/entitiesand, for peer scopes:
ov ls viking://user/default/peers/<peer>/memories/entities -
Observe that one topic appears under both a Chinese and an ASCII category, and that near-synonyms accumulate as sessions continue.
Expected Behavior
One real-world topic resolves to exactly one canonical category directory, and switching the session language does not create a new directory for the same topic.
Category values are either drawn from a normalized vocabulary or canonicalized against the existing category set before the path is built. Normalization must cover non-ASCII and alias variants, not only ASCII case.
Actual Behavior
Multiple per-language and per-synonym category directories; the same object gets several cards
that the extractor cannot merge afterwards, because category and name are
merge_op: immutable. No error or warning is logged, so the divergence is invisible until
retrieval quality degrades.
Minimal Reproducible Example
# Detects language/synonym category splits in an entities tree.
# Point it at an instance that has been used in both zh and en sessions.
from pathlib import Path
root = Path.home() / ".openviking/data/viking/default/user/default"
cats = {p.name for p in (root / "memories/entities").iterdir() if p.is_dir()}
for peer in (root / "peers").glob("*/memories/entities"):
cats |= {p.name for p in peer.iterdir() if p.is_dir()}
ascii_cats = sorted(c for c in cats if c.isascii())
print(f"{len(cats)} categories, {len(ascii_cats)} ASCII")
for c in ascii_cats:
print(" ", c)
# On a single-language store with a stable vocabulary this prints 0 ASCII categories
# (or only deliberate proper nouns). Observed on the reporting instance:
# 37 categories, 9 ASCII
# concept
# document
# OpenViking <- legitimate proper noun
# project
# software
# software_plugin
# software_project
# software_tool
# tool
# i.e. 8 of the 9 are synonyms of an existing Chinese category.
Error Logs
No error or warning is logged — the divergence is silent. The only observable evidence is the
resulting directory layout:
$ ov ls viking://user/default/memories/entities
viking://user/default/memories/entities/本机环境
viking://user/default/memories/entities/程序脚本
viking://user/default/memories/entities/工具链
viking://user/default/memories/entities/工作流
viking://user/default/memories/entities/学术概念
...
# and, in peer scopes, the coexisting ASCII variants:
$ ov ls viking://user/default/peers/<peer>/memories/entities
.../concept
.../document
.../project
.../software
.../software_tool
.../tool
OpenViking Version
0.4.23
Python Version
3.12.14
Operating System
Windows
Model Backend
OpenAI
Additional Context
Also present on main at commit 20f9c1136 (2026-10-09), so this is not fixed by upgrading.
Related issues:
- #3526 asks for type-aware entity canonicalization and an entity category allowlist at write time. That is the deeper fix; this report is the template-text half, which is much cheaper to land and already stops the bleeding.
- #4043 is the same mechanism for
preferences.user. Its write-up notes that entities has nouserlayer and therefore never splits — that is not the case: entities splits throughcategory. The|lowerfilters now present on main inpreferences.yamllook like a partial mitigation for #4043; they do not address alias or language variants.
Suggested fixes, cheapest first:
- Template text (one-file change). Drop the
{{ language }}branch from the entitiescategoryinstruction and state a stable category language plus an explicit reuse rule, e.g. "if a suitable category directory already exists, reuse it exactly; never create a synonym; never use a different language for a category that already exists".cases.yamlalready carries aLanguage policyline that could be reused instead of branching on{{ language }}. - Write-path canonicalization. Before building the path, map the model's proposed
categoryonto the existing category set (exact match, then normalized match, then a configured alias map); when two candidates are synonyms, merge instead of creating. - Hardening for the general mechanism. Avoid interpolating an LLM-filled field as a
leading directory segment without normalization. The same pattern affects
preferences.user(#4043) andpreferences.topic, which takes the same "lowercase with underscores / concise and natural" instruction;topicis notimmutable, so topic drift also creates new files.
Local mitigation currently in use — does not fix upstream, only prevents new splits:
memory.custom_templates_dir pointing at a copy of entities.yaml whose category
instruction requires a 2-6 character Chinese topic word and lists the existing categories to
reuse. It cannot clean directories that already exist.
@chenjw 关于 #5828 补充一句,正好对上大佬你在 #4043 里的取舍:我认同"身份别名不自动判断、两个目录都召回、交给在线模型"这个设计,并不要求上游自动合并历史数据。但 entities 的 category 是分类标签,不存在"张三是不是当前用户"那种身份歧义——它分裂是因为官方指引本身按 {{ language }} 分支(entities.yaml:31-32),双语用户描述同一主题必然生成中英两份,又没有"复用既有类目"的约束,同义词也各自成目录(实测单库 37 个类目、8 个与中文同义并存)。#3526 里 stone16 的 #4070 已在 8-19 合并,只小写化路径段,堵的是大小写这一种机械变异,盖不住语言与同义词,所以 #5828 仍成立。请求只有写入侧一步:去掉 category 指引的 {{ language }} 分支,改成"必须复用已存在的类目、同一主题不得另造同义词或换语言";历史存量我按 discussion #3570 的方向自己用 ov compile --from/--to --skill memory_consolidation 收敛。
Hi! I'd like to take this one.
Root cause: the category field instruction in openviking/prompts/templates/memory/entities.yaml is branched on {{ language }} and never requires reusing an existing category, while category is interpolated directly as a path segment ({{ category|lower }}/{{ name|lower }}.md). Bilingual sessions and synonyms therefore each create a new category directory, and the split is permanent because category/name are immutable.
Plan (template-text half only, per the issue's suggested fix 1):
- Remove the
{{ language }}branch from thecategoryinstruction and pin categories to a stable lowercase English snake_case vocabulary, independent of the session language. - Add an explicit reuse rule: before proposing a new category, check the existing category directories and reuse an existing category exactly when it fits; never create a synonym or a translated variant for the same topic.
The write-path canonicalization requested in #3526 stays out of scope, and existing split directories are not migrated by this change.
Hi! I'd like to take this one. 嗨!我想接手这个任务。
Root cause: the
categoryfield instruction inopenviking/prompts/templates/memory/entities.yamlis branched on{{ language }}and never requires reusing an existing category, whilecategoryis interpolated directly as a path segment ({{ category|lower }}/{{ name|lower }}.md). Bilingual sessions and synonyms therefore each create a new category directory, and the split is permanent becausecategory/nameare immutable.根本原因:openviking/prompts/templates/memory/entities.yaml中的category字段指令基于{{ language }}进行分支,且从未要求复用现有类别,同时category被直接插值为路径段({{ category|lower }}/{{ name|lower }}.md)。因此,双语会话和同义词都会各自创建新的类别目录,且由于category/name是不可变的,这种拆分是永久性的。Plan (template-text half only, per the issue's suggested fix 1):计划(仅针对模板文本部分,按该问题建议的修复方案1执行):
- Remove the
{{ language }}branch from thecategoryinstruction and pin categories to a stable lowercase English snake_case vocabulary, independent of the session language.从{{ language }}分支中移除category指令,并将类别固定为稳定的小写英文蛇形命名法,与会话语言无关。- Add an explicit reuse rule: before proposing a new category, check the existing category directories and reuse an existing category exactly when it fits; never create a synonym or a translated variant for the same topic.添加一条明确的复用规则:在提出新类别之前,先查看现有的类别目录,若现有类别完全适用则直接复用;绝不为同一主题创建同义词或翻译变体。
The write-path canonicalization requested in #3526 stays out of scope, and existing split directories are not migrated by this change.#3526 中请求的写入路径规范化不在本次变更范围内,且现有拆分目录不会通过此变更进行迁移。
Hi @zzx04-cool Thank you for your suggestion. Memory currently uses the primary language of the user’s session, because most users want their memories—including directory names—to be readable in a language they understand. However, we cannot know a user’s preferred language in advance. There are a few ways to address this: (1)Users can already explicitly specify the language used to store memories in ov.conf. (2)Users can periodically reorganize the memory directory by explicitly running ov compile --skill memory. (3)The memory directory can be reorganized automatically when memories are updated. Option (3) is already implemented, but it doesn’t trigger frequently enough yet. We’ll continue to improve this.
Thanks @chenjw for the clear explanation — that makes sense.
Given that session-language directory names are intentional for readability, and that option (1) already covers users who want a fixed storage language, hardcoding English snake_case as the default (as in #6033) would work against the intended design, so I'll close that PR.
If making option (3) auto-reorganization trigger more often is something you'd like external help with — ideally as a small, bounded change — I'd be happy to take a look if you can point me at the owning module or a tracking issue. No worries if not.
Thanks again for the detailed guidance!
@zzx04-cool Thanks! There’s still a lot we can improve in (3). Currently, in extract_loop, we allow the model to generate Python code that deletes old files and creates new ones to merge or split files. However, the prompts don’t yet specify when these operations should be performed. If you’re interested, we’d love your help testing and improving this.
Thanks @chenjw — happy to take this on.
I'll start by mapping the extract_loop path where the model generates Python code to delete/recreate files (merge/split), together with the prompts/tools that govern it, then evaluate how reliably those operations are triggered in practice (I'll use scenario-based runs with a provider double, since I can't drive a real model on every case). I'll post concrete findings — where the prompts stay silent on when to merge/split, and what the trigger reliability looks like — before proposing any prompt change.
Evaluation: how reliably merge/split are triggered in the online extract_loop
Thanks for the pointer. As promised, I evaluated path (3) before touching any prompts. Below are findings; no implementation is proposed yet.
Method
- Static audit of the real prompt assembly for the online path:
SessionExtractContextProvider.instruction()+PythonExtractionOutputProtocol.render_reference_rules()/render_contract()(viaExtractLoop). - Deterministic visibility/trigger simulation of the prefetch chain (fixture stores, parameterized embedding recall, 300 trials/scenario), with a policy-compliant scripted model that acts whenever the condition is actually visible. This measures the system-side ceiling; real-model compliance is a separate axis and needs API access to a configured model. The harness is ~250 lines of stdlib-only Python — happy to add it under
test_scripts/if you want it in-tree.
What the online path actually does
- Prefetch runs one semantic search (query derived from the new conversation), top-5 URIs, scoped to the schema directories. Runtime tools are read-only (
["read"];[]with eager prefetch) — there is nolsorsearchat runtime, so the model cannot widen visibility. - The merge/split conditions exist in
MEMORY_MERGE_POLICY("merge only when same identity … or explicit alias"; "split when a memory … mixes multiple identities"), and the mechanics exist in "Memory Object Rules" (fold unique facts → duplicate.delete(replacement=canonical)).
Findings
-
Conditions exist but there is no active trigger. The instruction says stored facts "may be preserved, normalized, merged, split … when required by their schemas" — permission, not a task. There is no "before returning new memories, actively reconcile the visible cards" instruction. A model focused on extracting new facts treats reorganization as optional.
-
Visibility is the dominant limiter — and matches "not triggered frequently enough". Both cards of a duplicate pair must land in the same top-5 recall window. Simulated trigger rates (optimistic → realistic → pessimistic cross-language recall):
scenario optimistic realistic pessimistic cross-language duplicate 70% 34% 15% same-language alias / synonym category 93% 84% 59% conflated card (split) 96% 91% 79% duplicate exists, new conversation unrelated 4% 0% 0% -
When the new conversation does not mention the topic, the trigger effectively never fires (0–4%): prefetch is a single topical search, so option (3) currently only self-heals when a later session happens to recall both variants.
-
No rule for suspected-but-not-visible duplicates (nothing tells the model to note an unresolved alias or request more recall), and split mechanics are only implicit (create two cards, fold facts, then pure-delete the old bound object with no replacement).
Candidate interventions (for discussion, not implemented)
- (a) Prompt-only, ~10 lines: convert the permission into an active trigger — before returning new memories, compare the pre-fetched bindings and merge/split whenever the identity conditions hold; explicitly state what to do when an alias is suspected but the counterpart is not readable.
- (b) Prefetch changes: add a second search in the alternate/alias language and raise top-N (simulated cross-language trigger 34% → 51%; same-language roughly unchanged).
- (c) Bounded inventory: a scoped
ls/recall limited to the category directories named in the search hits, instead of the full 500-node cap (simulated 100% with bounded context). - (d) Server-side hint: when duplicate detection runs server-side, surface it via the existing
memory_maintenance_noticechannel so the prompt only has to act on it.
My read is that (a) is necessary regardless, and (b) or (c) is needed for the cross-language case to actually fire often. Which direction would you like — and if you have a canonical model configuration for this path, I can extend the harness to measure real-model compliance rather than only the system-side ceiling.