Skip to content

Commit d30fe18

Browse files
fix(memory): normalize REM concept topics at their owner (#117248)
Share canonical concept normalization across extraction and REM; reject numeric noise, preserve protected technical terms, and avoid duplicate normalized counts. Co-authored-by: Peter Steinberger <[email protected]>
1 parent ad08481 commit d30fe18

5 files changed

Lines changed: 63 additions & 87 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,7 @@ Docs: https://docs.openclaw.ai
235235
- **Plugin session catalogs:** reject unknown catalog filters, report catalogs as plugin capabilities, and preserve them in SDK registration captures instead of silently returning empty results or classifying catalog-only plugins as capability-free.
236236
- **Gateway service audit:** treat POSIX shell `-c` wrappers as opaque for the gateway-subcommand check, avoiding false missing-command warnings for shell-wrapped macOS LaunchAgents without parsing inner commands or ports. Fixes #81751. (#81778) Thanks @liaoandi.
237237
- **Memory filename search:** index paths separately from chunk bodies so exact full-path, basename, and stem queries rank the intended memory file first without changing body BM25 scores, snippets, or embeddings. (#96052, #94102) Thanks @Pick-cat.
238+
- **Memory REM topics:** share canonical concept normalization across new extraction and stored-tag reflections, reject numeric/date noise, and count normalized spellings once per memory while preserving multilingual and short technical terms. (#117248) Thanks @synthalorian.
238239
- **Outbound channel bootstrap:** suppress repeated failed plugin activation for the same channel, config, and registry generation while retrying after config or registry reloads. (#100377) Thanks @xialonglee.
239240
- **OpenAI Realtime client-secret deadlines:** bound voice and transcription secret acquisition to 30 seconds through the guarded fetch boundary while preserving authentication and bounded response parsing. (#102860) Thanks @Alix-007.
240241
- **Gateway client watchdog:** keep transport-stall detection active for unbounded and mixed pending requests so dead sockets reject pending requests, reconnect, and never replay rejected requests. (#103407) Thanks @NianJiuZst.

‎extensions/memory-core/src/concept-vocabulary.test.ts‎

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -25,29 +25,28 @@ describe("concept vocabulary", () => {
2525
expect(tags).not.toContain("2026-04-04.md");
2626
});
2727

28-
it("preserves short protected-glossary terms past the latin minimum-length gate", () => {
29-
const tags = deriveConceptTags({
30-
path: "memory/2026-04-04.md",
31-
snippet: "Store the session in kv and back up to s3 nightly.",
32-
});
33-
34-
// "kv" and "s3" are 2-char latin glossary entries that the generic min-length-3 gate would drop.
35-
expect(tags).toContain("kv");
36-
expect(tags).toContain("s3");
28+
it.each([
29+
["Store the session in kv and back up to s3 nightly.", ["kv", "s3"], []],
30+
["Played the mkv recording and tuned the css3 layout.", ["mkv", "css3"], ["kv", "s3"]],
31+
["kv𐐀 𐐀kv s3𐐀 𐐀s3", ["kv𐐨", "𐐨kv", "s3𐐨", "𐐨s3"], ["kv", "s3"]],
32+
])("preserves short glossary terms only as whole words: %s", (snippet, present, absent) => {
33+
const tags = deriveConceptTags({ path: "memory/2026-04-04.md", snippet });
34+
expect(tags).toEqual(expect.arrayContaining(present));
35+
for (const tag of absent) {
36+
expect(tags).not.toContain(tag);
37+
}
3738
});
3839

39-
it("does not surface short glossary terms that only appear inside longer words", () => {
40-
const tags = deriveConceptTags({
41-
path: "memory/2026-04-04.md",
42-
snippet: "Played the mkv recording and tuned the css3 layout.",
43-
});
44-
45-
// "kv"/"s3" are substrings of "mkv"/"css3"; whole-word matching must not emit them as tags.
46-
expect(tags).not.toContain("kv");
47-
expect(tags).not.toContain("s3");
48-
expect(tags).toContain("mkv");
49-
expect(tags).toContain("css3");
50-
});
40+
it.each(["42", "1.00", "51-54", "1.00", "51-54", "2026-04-04", "2026-04-04.md"])(
41+
"rejects numeric and date noise without losing technical tags: %s",
42+
(noise) => {
43+
const tags = deriveConceptTags({
44+
path: "memory/2026-04-04.md",
45+
snippet: `${noise} kv s3 router`,
46+
});
47+
expect(tags).toStrictEqual(["kv", "router", "s3"]);
48+
},
49+
);
5150

5251
it("extracts protected and segmented CJK concept tags", () => {
5352
const tags = deriveConceptTags({

‎extensions/memory-core/src/concept-vocabulary.ts‎

Lines changed: 25 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Memory Core plugin module implements concept vocabulary behavior.
22
import path from "node:path";
33
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
4+
import { escapeRegExp } from "openclaw/plugin-sdk/text-utility-runtime";
45

56
export const MAX_CONCEPT_TAGS = 8;
67

@@ -290,10 +291,6 @@ const HANGUL_RE = /\p{Script=Hangul}/u;
290291
const DEFAULT_WORD_SEGMENTER =
291292
typeof Intl.Segmenter === "function" ? new Intl.Segmenter("und", { granularity: "word" }) : null;
292293

293-
function containsLetterOrNumber(value: string): boolean {
294-
return LETTER_OR_NUMBER_RE.test(value);
295-
}
296-
297294
function classifyConceptTagScript(tag: string): ConceptTagScriptFamily {
298295
const normalized = tag.normalize("NFKC");
299296
const hasLatin = LATIN_RE.test(normalized);
@@ -329,27 +326,28 @@ function isKanaOnlyToken(value: string): boolean {
329326
);
330327
}
331328

332-
function normalizeConceptToken(rawToken: string, fromGlossary = false): string | null {
329+
export function normalizeConceptToken(rawToken: string): string | null {
333330
const normalized = normalizeLowercaseStringOrEmpty(
334331
rawToken
335332
.normalize("NFKC")
336333
.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "")
337334
.replaceAll("_", "-"),
338335
);
339-
if (!normalized || !containsLetterOrNumber(normalized) || normalized.length > 32) {
336+
if (!normalized || !LETTER_OR_NUMBER_RE.test(normalized) || normalized.length > 32) {
340337
return null;
341338
}
342339
if (
343-
/^\d+$/.test(normalized) ||
344-
/^\d{4}-\d{2}-\d{2}$/u.test(normalized) ||
340+
/^\p{N}+(?:[./-]\p{N}+)*$/u.test(normalized) ||
345341
/^\d{4}-\d{2}-\d{2}\.[\p{L}\p{N}]+$/u.test(normalized)
346342
) {
347343
return null;
348344
}
349345
const script = classifyConceptTagScript(normalized);
350-
// Glossary entries are an explicit allowlist of short technical terms (e.g. "kv", "s3"); they
351-
// bypass the per-script minimum length that would otherwise discard them.
352-
if (!fromGlossary && normalized.length < minimumTokenLengthForScript(script)) {
346+
// Recognize the glossary here so extraction and stored REM tags share the same short-token policy.
347+
if (
348+
normalized.length < minimumTokenLengthForScript(script) &&
349+
!PROTECTED_GLOSSARY.includes(normalized)
350+
) {
353351
return null;
354352
}
355353
if (isKanaOnlyToken(normalized) && normalized.length < 3) {
@@ -367,34 +365,18 @@ function normalizeConceptToken(rawToken: string, fromGlossary = false): string |
367365
// Precomputed so derive() does not reclassify on every call.
368366
const GLOSSARY_ENTRIES = PROTECTED_GLOSSARY.map((entry) => ({
369367
entry,
370-
wholeWord: entry.length < minimumTokenLengthForScript(classifyConceptTagScript(entry)),
368+
// Unicode boundaries must inspect code points, not half of an astral letter or number.
369+
wholeWord:
370+
entry.length < minimumTokenLengthForScript(classifyConceptTagScript(entry))
371+
? new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(entry)}(?![\\p{L}\\p{N}])`, "u")
372+
: undefined,
371373
}));
372374

373-
function isAlphanumericAt(source: string, index: number): boolean {
374-
const ch = source[index];
375-
return ch !== undefined && LETTER_OR_NUMBER_RE.test(ch);
376-
}
377-
378-
// True when `entry` occurs as a delimiter-bounded token, not inside a longer word. Keeps short
379-
// glossary entries like "kv"/"s3" from firing inside "mkv"/"css3" once they bypass the length gate.
380-
function includesStandaloneTerm(source: string, entry: string): boolean {
381-
let from = source.indexOf(entry);
382-
while (from !== -1) {
383-
if (!isAlphanumericAt(source, from - 1) && !isAlphanumericAt(source, from + entry.length)) {
384-
return true;
385-
}
386-
from = source.indexOf(entry, from + 1);
387-
}
388-
return false;
389-
}
390-
391375
function collectGlossaryMatches(source: string): string[] {
392376
const normalizedSource = normalizeLowercaseStringOrEmpty(source.normalize("NFKC"));
393377
const matches: string[] = [];
394378
for (const { entry, wholeWord } of GLOSSARY_ENTRIES) {
395-
const present = wholeWord
396-
? includesStandaloneTerm(normalizedSource, entry)
397-
: normalizedSource.includes(entry);
379+
const present = wholeWord ? wholeWord.test(normalizedSource) : normalizedSource.includes(entry);
398380
if (present) {
399381
matches.push(entry);
400382
}
@@ -415,22 +397,6 @@ function collectSegmentTokens(source: string): string[] {
415397
return source.split(/[^\p{L}\p{N}]+/u).filter(Boolean);
416398
}
417399

418-
function pushNormalizedTag(
419-
tags: string[],
420-
rawToken: string,
421-
limit: number,
422-
fromGlossary = false,
423-
): void {
424-
const normalized = normalizeConceptToken(rawToken, fromGlossary);
425-
if (!normalized || tags.includes(normalized)) {
426-
return;
427-
}
428-
tags.push(normalized);
429-
if (tags.length > limit) {
430-
tags.splice(limit);
431-
}
432-
}
433-
434400
export function deriveConceptTags(params: {
435401
path: string;
436402
snippet: string;
@@ -448,14 +414,18 @@ export function deriveConceptTags(params: {
448414
}
449415

450416
const tags: string[] = [];
451-
const tokenSources: Array<{ tokens: string[]; fromGlossary: boolean }> = [
452-
{ tokens: collectGlossaryMatches(source), fromGlossary: true },
453-
{ tokens: collectCompoundTokens(source), fromGlossary: false },
454-
{ tokens: collectSegmentTokens(source), fromGlossary: false },
417+
const tokenSources = [
418+
collectGlossaryMatches(source),
419+
collectCompoundTokens(source),
420+
collectSegmentTokens(source),
455421
];
456-
for (const { tokens, fromGlossary } of tokenSources) {
422+
for (const tokens of tokenSources) {
457423
for (const rawToken of tokens) {
458-
pushNormalizedTag(tags, rawToken, limit, fromGlossary);
424+
const normalized = normalizeConceptToken(rawToken);
425+
if (!normalized || tags.includes(normalized)) {
426+
continue;
427+
}
428+
tags.push(normalized);
459429
if (tags.length >= limit) {
460430
return tags;
461431
}

‎extensions/memory-core/src/dreaming-phases.test.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1855,7 +1855,12 @@ describe("memory-core dreaming phases", () => {
18551855
expect(corpus).not.toContain("Run the memory sync");
18561856
});
18571857

1858-
it("ignores chat scaffolding tags when building rem reflections", () => {
1858+
it.each([
1859+
["assistant", "the"],
1860+
["1.00", "51-54"],
1861+
["1.00", "51-54"],
1862+
["2026-04-16", "2026-04-16.txt"],
1863+
])("normalizes stored concept tags and rejects %s / %s in rem reflections", (...noise) => {
18591864
const preview = previewRemDreaming({
18601865
entries: [
18611866
{
@@ -1874,17 +1879,18 @@ describe("memory-core dreaming phases", () => {
18741879
lastRecalledAt: "2026-04-16T18:00:00.000Z",
18751880
queryHashes: ["q1"],
18761881
recallDays: ["2026-04-16"],
1877-
conceptTags: ["assistant", "the", "ollama", "provider"],
1882+
conceptTags: [...noise, "Ollama", "provider", "kv", "KV", "s3", "备份"],
18781883
},
18791884
],
1880-
limit: 5,
1885+
limit: 20,
18811886
minPatternStrength: 0,
18821887
});
18831888

1884-
expect(preview.reflections.join("\n")).toContain("`ollama`");
1885-
expect(preview.reflections.join("\n")).toContain("`provider`");
1886-
expect(preview.reflections.join("\n")).not.toContain("`assistant`");
1887-
expect(preview.reflections.join("\n")).not.toContain("`the`");
1889+
expect(preview.reflections.filter((line) => line.startsWith("- Theme:"))).toEqual(
1890+
["kv", "ollama", "provider", "s3", "备份"].map(
1891+
(tag) => `- Theme: \`${tag}\` kept surfacing across 1 memories.`,
1892+
),
1893+
);
18881894
});
18891895

18901896
it("does not reread unchanged dreaming-generated transcripts after checkpointing skip state", async () => {

‎extensions/memory-core/src/dreaming-phases.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
} from "openclaw/plugin-sdk/memory-core-host-status";
1818
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
1919
import { normalizeStringEntries, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
20+
import { normalizeConceptToken } from "./concept-vocabulary.js";
2021
import { isPromotionOriginBlocked } from "./dreaming-consolidation-candidates.js";
2122
import { appendFailedDreamingEvent } from "./dreaming-events.js";
2223
import {
@@ -194,8 +195,6 @@ type DailySnippetChunk = {
194195
identitySnippet?: string;
195196
};
196197

197-
const REM_REFLECTION_TAG_BLACKLIST = new Set(["assistant", "user", "system", "subagent", "the"]);
198-
199198
function buildDailyChunkSnippet(heading: string | null, chunkLines: string[]): string {
200199
const body = chunkLines.join(" ").trim();
201200
const prefixed = heading ? `${heading}: ${body}` : body;
@@ -1260,8 +1259,9 @@ function buildRemReflections(
12601259
): string[] {
12611260
const tagStats = new Map<string, { count: number; evidence: Set<string> }>();
12621261
for (const entry of entries) {
1263-
for (const tag of entry.conceptTags) {
1264-
if (!tag || REM_REFLECTION_TAG_BLACKLIST.has(tag.toLowerCase())) {
1262+
// Stored spellings may normalize to one topic; each memory contributes only once.
1263+
for (const tag of new Set(entry.conceptTags.map(normalizeConceptToken))) {
1264+
if (!tag) {
12651265
continue;
12661266
}
12671267
const stat = tagStats.get(tag) ?? { count: 0, evidence: new Set<string>() };

0 commit comments

Comments
 (0)