Skip to content

Commit 284f0a7

Browse files
committed
fix(inject): emoji 代理对截断与会话时间注入恢复(issues #334 #333)
issue #334:注入路径 4 处截断点(热上下文查询/回复 500/800、 lastUserQuery 500、记忆条目 injectContentMaxChars)UTF-16 slice 切在代理对中间留下孤立高位代理项,序列化成非法 UTF-8 后 DeepSeek API 每轮 400,且畸形文本永久写入会话历史。新增 safeSlice(尾字符 为高位代理即丢弃),4 处截断点全部换用;测试以「孤立代理项不存在」 锁语义,附变异阴性对照。 issue #333(issue #34 恢复):injectTimePrefix 于 v0.7.11 面板 大改版时随一次批量删除静默消失(CHANGELOG 无登记,同刀的 escapePromptVars 已随 #162/#165 恢复、本函数漏了)。按 v0.7.2 语义原样恢复:键名/默认值/格式不变,per-session 闩锁每会话一次, 时间前缀排记忆块最前(时间 → 热上下文 → 长期记忆)。settings 白名单、面板双语、FEATURE_GROUPS、配置计数锁同步。 全量 1429/1428/0。
1 parent 365e46b commit 284f0a7

12 files changed

Lines changed: 273 additions & 27 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-3E63DD?style=flat-square" alt="license"></a>
1111
<a href="https://github.com/slow-stack/mneme/actions"><img src="https://img.shields.io/github/actions/workflow/status/slow-stack/mneme/ci.yml?style=flat-square&label=CI" alt="CI"></a>
1212
<a href="https://nodejs.org"><img src="https://img.shields.io/badge/node-22%2B-3E63DD?style=flat-square&logo=nodedotjs&logoColor=white" alt="node"></a>
13-
<a href="https://github.com/slow-stack/mneme"><img src="https://img.shields.io/badge/tests-1405%20passed-3E63DD?style=flat-square" alt="tests"></a>
13+
<a href="https://github.com/slow-stack/mneme"><img src="https://img.shields.io/badge/tests-1429%20passed-3E63DD?style=flat-square" alt="tests"></a>
1414
<a href="https://codecov.io/gh/slow-stack/mneme"><img src="https://img.shields.io/codecov/c/github/slow-stack/mneme/main?style=flat-square" alt="coverage"></a>
1515
<a href="https://github.com/awesome-dsh-plugin/awesome-dsh-plugin"><img src="https://awesome-dsh-plugin.com/badge.svg" alt="Awesome"></a>
1616
</p>
@@ -183,7 +183,7 @@ dsh web
183183

184184
```bash
185185
cd dsh-mneme && npm install
186-
npm test # 1405 个测试
186+
npm test # 1429 个测试
187187
npm run stress # 三轴线压测
188188
npm run sync # src → lib 同步
189189
```
@@ -366,7 +366,7 @@ The plugin ships a zero-dependency stdio MCP server (standalone npm package **`m
366366

367367
```bash
368368
cd dsh-mneme && npm install
369-
npm test # 1405 tests
369+
npm test # 1429 tests
370370
npm run stress # three-axis stress test
371371
npm run sync # src → lib sync
372372
```

‎dsh-mneme/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@
4040

4141
## 🐛 修复
4242

43+
- **注入路径 4 处截断点切开 emoji 代理对 → 会话级 400(issue #334)**:UTF-16 `slice` 切在代理对中间会留下孤立高位代理项,序列化成非法 UTF-8,DeepSeek API 对每个请求回 400;畸形文本随注入消息被永久写进会话历史,此后每一轮都带着它(换话题/重启都不恢复)。新增 `safeSlice`(尾字符是高位代理即丢弃),热上下文查询/回复、lastUserQuery、记忆条目 4 处截断点全部换用;回归测试以「孤立代理项不存在」锁语义,配阴性对照。
44+
45+
- **恢复 v0.7.11 误删的对话开始时间注入(issue #34,报告 #333)**:`injectTimePrefix` 于 v0.7.2 引入(issue #34),v0.7.11 面板大改版时随一次批量删除静默消失、CHANGELOG 无登记(同刀误删的 `escapePromptVars` 已随 #162/#165 恢复,本函数漏了)——用户按 CHANGELOG 开着开关实际什么都不会发生。本次按 v0.7.2 语义原样恢复:键名/默认值(false)/格式 `[当前时间: YYYY-MM-DD 周X HH:MM]` 不变,存量 feature_flags 恢复即生效;per-session 闩锁保证每个新会话只注入一次。
46+
4347
- **saveWithDedupe 透传显式 epistemic_status(trustEpistemicWeighting 写入通路缺口)**:创建路径此前丢弃显式字段,store 回退内容标记推断(中文正则)——英文/无标记内容一律落 subjective,EPISTEMIC_WEIGHTS 对整池均匀 ×0.7,`trustEpistemicWeighting` 的重排对工具主路径写入的记忆**整体空转**(v0.4.5 起消费者在、写入通路断;patch 路径 store.update 本来就通)。E 系列四臂实验现场抓到(重排臂与对照臂注入序逐条相同)。修复后 undefined 保持推断行为(存量零变化),显式值优先(契约同 resolveEpistemicStatus);回归测试锁「observation 加权前后分数不变——字段丢失则全体缩放当场红」。
4448

4549
## [0.8.8] - 2026-09-27

‎dsh-mneme/README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
[![npm version](https://img.shields.io/npm/v/@modusensus/dsh-mneme?color=blue&label=npm)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
66
[![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
77
[![Awesome](https://awesome-dsh-plugin.com/badge.svg)](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin)
8-
[![tests](https://img.shields.io/badge/tests-1405%20passed-success)](https://github.com/slow-stack/mneme)
8+
[![tests](https://img.shields.io/badge/tests-1429%20passed-success)](https://github.com/slow-stack/mneme)
99
[![CI](https://img.shields.io/github/actions/workflow/status/slow-stack/mneme/ci.yml)](https://github.com/slow-stack/mneme/actions)
1010
[![node](https://img.shields.io/badge/node-22%2B-blue)](https://nodejs.org)
1111
[![npm downloads](https://img.shields.io/npm/d18m/@modusensus/dsh-mneme.svg?color=blue&label=downloads)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
@@ -584,7 +584,7 @@ src/
584584
├── api.js # HTTP 路由(Web 面板数据通道,含 /conflicts 冲突队列)
585585
└── index.js # 插件接线
586586
lib/ # src 的同步分发产物(npm run sync;发布前由 root prepack 的 check-sync.js 校验一致性;唯一手写例外 lib/client.js——Web 面板 bundle,sync 不覆盖)
587-
test/ # 1405 个 node:test 测试(审计与三轴线压测不变量;src↔lib 一致性由 scripts/check-sync.js 发布闸门校验)
587+
test/ # 1429 个 node:test 测试(审计与三轴线压测不变量;src↔lib 一致性由 scripts/check-sync.js 发布闸门校验)
588588
scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压测 · sync-lib.js 同步 · check-sync.js 发布闸门 · benchmark-recall.js / benchmark-embed.js / benchmark-rerank.js 基准 · sync-test-badge.mjs 测试徽章 · build-runtime-manifest.mjs 运行时清单
589589
```
590590
@@ -593,7 +593,7 @@ scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压
593593
```bash
594594
cd dsh-mneme
595595
npm install # 安装 peer 依赖(以 devDependencies 形式,用于本地测试)
596-
npm test # 运行 1405 个测试
596+
npm test # 运行 1429 个测试
597597
npm run stress # 三轴线压测:长会话检索 / 冲突仲裁 / 多 Agent 并发(离线 mock LLM)
598598
npm run sync # 把 src/ 同步到 lib/(发布时由 prepack 钩子自动执行)
599599
```

‎dsh-mneme/lib/client.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,8 @@ window.__ModuleLoader__.load({
415415
"memory.features.autoSummarize.hint": "对话结束自动提炼记忆条目",
416416
"memory.features.hotMemoryEnabled": "热记忆",
417417
"memory.features.hotMemoryEnabled.hint": "最近几轮对话原文随注入携带,不写入长期记忆",
418+
"memory.features.injectTimePrefix": "对话开始注入当前时间",
419+
"memory.features.injectTimePrefix.hint": "每次新会话的首轮注入一次日期与星期(默认关)",
418420
"memory.features.entityExtractionEnabled": "实体抽取",
419421
"memory.features.entityExtractionEnabled.hint": "从记忆中提取人物/项目/概念,图谱随之生长",
420422
"memory.features.entityExtractionProvider": "实体抽取 Provider",
@@ -846,6 +848,8 @@ window.__ModuleLoader__.load({
846848
"memory.features.autoSummarize.hint": "Distill memory entries when a conversation ends",
847849
"memory.features.hotMemoryEnabled": "Hot memory",
848850
"memory.features.hotMemoryEnabled.hint": "Carry the last few turns verbatim; never written to long-term memory",
851+
"memory.features.injectTimePrefix": "Inject current time at conversation start",
852+
"memory.features.injectTimePrefix.hint": "Adds the date and weekday once at each new session's first turn (off by default)",
849853
"memory.features.entityExtractionEnabled": "Entity extraction",
850854
"memory.features.entityExtractionEnabled.hint": "Extract people / projects / concepts so the graph grows by itself",
851855
"memory.features.entityExtractionProvider": "Entity extraction provider",
@@ -2085,7 +2089,7 @@ window.__ModuleLoader__.load({
20852089
// test/inject-parent-gate.test.js 钉住。
20862090
const FEATURE_CHILDREN = { autoInject: ["injectGuidanceEnabled", "continuityRescueEnabled"] };
20872091
const FEATURE_GROUPS = [
2088-
{ key: "group.core", items: ["autoInject", "autoSummarize", "hotMemoryEnabled", "memoryQualityFilter.enabled", "llmAudit.enabled", "writeAdmission.enabled", "writeAdmission.enforce"] },
2092+
{ key: "group.core", items: ["autoInject", "autoSummarize", "hotMemoryEnabled", "injectTimePrefix", "memoryQualityFilter.enabled", "llmAudit.enabled", "writeAdmission.enabled", "writeAdmission.enforce"] },
20892093
{ key: "group.enhance", items: ["entityExtractionEnabled", "codingRetrospect", "rerankEnabled", "resilientModelDownload", "searchSemanticDedup", "bm25SearchEnabled", "heatEnabled", "documentMemoryEnabled"] },
20902094
{ key: "group.dream", items: ["autoDream", "sleepModeEnabled"] },
20912095
// v0.8.0 A4(issue #17):作用域隔离组——标注总开关 + 严格硬过滤。

‎dsh-mneme/lib/config.js‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,9 @@ export const Config = z.object({
7171
// 提示:上限/原长/全文 memory_get 指引(BUDGET_EXCEEDED 原则——绝不静默)。
7272
// 默认 300 = 与既有行为一致。
7373
injectContentMaxChars: z.natural().min(60).max(4000).default(300),
74+
// Issue #34(v0.7.2 引入;v0.7.11 误删后随 #333 恢复):对话开始注入一次当前
75+
// 时间。默认关 = 与既有行为一致;格式与键名不变,存量 feature_flags 恢复即生效。
76+
injectTimePrefix: z.boolean().default(false),
7477
importanceThreshold: z.natural().min(1).max(5).default(3),
7578
// Issue #239(第 5 项):注入条数的查询自适应(默认关)。确定性强的话题收缩注入
7679
// 条数(减半、下限 1),模糊话题(回指/时间线索,或极短查询)维持

‎dsh-mneme/lib/inject.js‎

Lines changed: 65 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,23 @@ export function getInjectionSnapshot() {
1616
return injectionSnapshot;
1717
}
1818

19+
// Issue #334:UTF-16 截断切开 emoji 代理对会留下孤立代理项(如 🔴 = D83D DD34
20+
// 在 800 处切,D83D 留下、DD34 被切走)。DSH 把它序列化成非法 UTF-8,DeepSeek
21+
// API 对每个请求回 400 INVALID_REQUEST——而且畸形文本随注入消息被永久写进会话
22+
// 历史,此后**每一轮**都带着它,表现为会话从某一轮起连续 400、换话题/重启都不
23+
// 恢复(会话级不可逆损坏)。防法是「少一个字符都行,绝不留半个」:尾字符是
24+
// 高位代理(0xD800–0xDBFF)说明它的低位搭档被切走了,把这个高位代理整个丢掉。
25+
// (反过来尾字符是低位代理不可能孤立——它的搭档必然紧邻在前、同在切点之内。)
26+
// ASCII-only 的文本零开销(length 相等直接短路)。
27+
function safeSlice(text, limit) {
28+
const s = String(text);
29+
if (s.length <= limit) return s;
30+
let cut = s.slice(0, limit);
31+
const tail = cut.charCodeAt(cut.length - 1);
32+
if (tail >= 0xd800 && tail <= 0xdbff) cut = cut.slice(0, -1);
33+
return cut;
34+
}
35+
1936
// Best-effort extraction of the current user's latest message text from the
2037
// live session, for semantic-first injection (Bug4). The system-prompt
2138
// interpolator renders synchronously, so this walks the already-materialized
@@ -36,11 +53,14 @@ function lastUserQuery(ctx) {
3653
if (kind !== undefined && kind !== "user") continue;
3754
const parts = event.data?.content;
3855
if (!Array.isArray(parts) || parts.length === 0) continue;
39-
return parts
40-
.map((p) => (typeof p === "string" ? p : p?.text ?? ""))
41-
.filter(Boolean)
42-
.join("\n")
43-
.slice(0, 500);
56+
return safeSlice(
57+
parts
58+
.map((p) => (typeof p === "string" ? p : p?.text ?? ""))
59+
.filter(Boolean)
60+
.join("\n")
61+
.slice(0, 500),
62+
500
63+
);
4464
}
4565
} catch { /* session internals unavailable: degrade to no query */ }
4666
return "";
@@ -85,7 +105,7 @@ function extractRounds(ctx, maxRounds) {
85105
const isUser = event?.type === "user/message" && (kind === undefined || kind === "user");
86106
if (isUser) {
87107
if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
88-
pendingQuery = textOf(event).slice(0, 500);
108+
pendingQuery = safeSlice(textOf(event), 500);
89109
continue;
90110
}
91111
// Only assistant-originated events close a round; tool/system events
@@ -94,7 +114,7 @@ function extractRounds(ctx, maxRounds) {
94114
|| kind === "assistant";
95115
const body = isAssistant ? textOf(event) : "";
96116
if (!body || !pendingQuery) continue;
97-
rounds.push({ query: pendingQuery, response: body.slice(0, 800) });
117+
rounds.push({ query: pendingQuery, response: safeSlice(body, 800) });
98118
pendingQuery = null;
99119
}
100120
if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
@@ -171,7 +191,7 @@ export function createInjector(ctx, service, settings, config) {
171191
function injectMemory(m, maxLength = maxContent) {
172192
const text = String(m?.content ?? "");
173193
if (text.length <= maxLength) return text;
174-
return `${text.slice(0, maxLength)}…${STR.truncatedHint[language](maxLength, text.length, m.id)}`;
194+
return `${safeSlice(text, maxLength)}…${STR.truncatedHint[language](maxLength, text.length, m.id)}`;
175195
}
176196

177197
// Prompt-variable brace escaping (issue #162, restored from v0.7.4 #40):
@@ -192,6 +212,37 @@ export function createInjector(ctx, service, settings, config) {
192212
return String(text).replace(/[{}]{2,}/g, (run) => run.split("").join("\\"));
193213
}
194214

215+
// Time-prefix injection (issue #34,恢复于 #333): opt-in, off by default.
216+
// When enabled the current date/time is injected once per conversation — at
217+
// the first prompt assembly of a new session — so the model can sense what
218+
// time/day it is. A per-session latch means later assemblies in the same
219+
// session never re-inject; a bare render ctx (no session id) falls back to
220+
// once per injector lifetime.
221+
// v0.7.11 面板大改版(ce4658e)时这段随一次批量删除被静默移除,CHANGELOG 无
222+
// 登记(#162 的 escapePromptVars 同刀误删、后来恢复,本函数漏了)——用户按
223+
// CHANGELOG 开着开关,实际什么都不会发生。本次按 v0.7.2 语义原样恢复:键名、
224+
// 默认值(false)、格式 `[当前时间: YYYY-MM-DD 周X HH:MM]` 全部不变,存量
225+
// feature_flags 里的配置恢复即生效。
226+
const WEEKDAYS = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
227+
let timePrefixSession = null;
228+
229+
function renderTimePrefix(ctx) {
230+
if (config.injectTimePrefix !== true) return "";
231+
const sessionId = ctx?.agent?.session?.id;
232+
if (sessionId === undefined) {
233+
if (timePrefixSession !== null) return "";
234+
timePrefixSession = true;
235+
} else {
236+
if (sessionId === timePrefixSession) return "";
237+
timePrefixSession = sessionId;
238+
}
239+
const now = new Date();
240+
const pad = (n) => String(n).padStart(2, "0");
241+
const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
242+
const time = `${pad(now.getHours())}:${pad(now.getMinutes())}`;
243+
return escapePromptVars(`[当前时间: ${date} ${WEEKDAYS[now.getDay()]} ${time}]`);
244+
}
245+
195246
// Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
196247
// the materialized event log on every render — stateless, so it survives
197248
// session switches and never persists anywhere.
@@ -335,7 +386,12 @@ export function createInjector(ctx, service, settings, config) {
335386
// separate context) keeps the prompt assembly stable at two blocks.
336387
const hotText = renderHotContext(ctx);
337388
const body = render(candidates, pinnedStats);
338-
const finalBody = !hotText ? body : body ? `${hotText}\n\n${body}` : hotText;
389+
// #333(issue #34 恢复):时间前缀只在会话首轮出现(per-session 闩锁),
390+
// 排在整个记忆块的最前——模型先知道「今天几号」,再看热上下文与长期记忆。
391+
const timePrefix = renderTimePrefix(ctx);
392+
// 拼接次序:时间 → 热上下文 → 长期记忆(三者都可能为空,逐级判空拼接)。
393+
const withHot = !hotText ? body : body ? `${hotText}\n\n${body}` : hotText;
394+
const finalBody = !timePrefix ? withHot : withHot ? `${timePrefix}\n\n${withHot}` : timePrefix;
339395
// Issue #179:旁路缓存一帧——面板「注入预览」卡据此展示构成与体积。
340396
// chars 为条目内容的截断后近似值(与 render 同一函数计长),totalChars
341397
// 是本次实际返回块的精确长度。maxItems 反映自适应收缩后的生效值。

‎dsh-mneme/lib/settings.js‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ const FEATURE_FLAG_BOOLEANS = [
4343
"autoInject",
4444
"autoSummarize",
4545
"hotMemoryEnabled",
46+
// Issue #34(v0.7.2 引入;v0.7.11 误删后随 #333 恢复):对话开始注入当前时间。
47+
// 顶层扁平键,随白名单回面板(FEATURE_GROUPS 的 group.core)。
48+
"injectTimePrefix",
4649
// Issue #239 第 5 项:注入条数的查询自适应(确定性强则收缩注入条数,默认关)。
4750
"injectUncertaintyAdaptive",
4851
// Issue #249:能力说明(工具描述判断指引 + order 150 总则段)。第二批起它是

‎dsh-mneme/src/config.js‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,9 @@ export const Config = z.object({
7171
// 提示:上限/原长/全文 memory_get 指引(BUDGET_EXCEEDED 原则——绝不静默)。
7272
// 默认 300 = 与既有行为一致。
7373
injectContentMaxChars: z.natural().min(60).max(4000).default(300),
74+
// Issue #34(v0.7.2 引入;v0.7.11 误删后随 #333 恢复):对话开始注入一次当前
75+
// 时间。默认关 = 与既有行为一致;格式与键名不变,存量 feature_flags 恢复即生效。
76+
injectTimePrefix: z.boolean().default(false),
7477
importanceThreshold: z.natural().min(1).max(5).default(3),
7578
// Issue #239(第 5 项):注入条数的查询自适应(默认关)。确定性强的话题收缩注入
7679
// 条数(减半、下限 1),模糊话题(回指/时间线索,或极短查询)维持

0 commit comments

Comments
 (0)