Skip to content

Commit eb6dde4

Browse files
committed
fix(profile): 评审修复——update 缺 content 不再写成 undefined 正文
新鲜眼睛评审(0d612cb..5e6d280 全量 diff)的 P1/P2/P3 收口: - P1:op 形状谓词抽成单一份(isValidFactOps,路由 400 闸与解析层共用), update 与 add 同样必须带非空 content——此前 update 缺 content 时 String(undefined) 会把「undefined」写进事实正文并从此每帧注入。 - P2:applyOps 的去重集合跟上 update 的新值——同批 [update A→B, add B] 此前会落两条相同事实且 dupsSkipped 仍为 0。 - P2:功能开关卡保存成功广播 mneme:features-changed,事实卡监听重读总闸 快照——开关即改即存,不监听的话按提示开了「自动事实」还得关面板重开 才解禁。切卡时维护轮结局一并清(跨卡残留)。 - P3:/apply 同步异常补 500 兜底;collectInputRows 首行保底(单行超预算 不再永久 noop);事务内逐 op 吞错的取舍落注释。 回归锁:update 缺 content 的 400 闸、同批 update+add 去重、features-changed 两端接线。全量 npm test 2828/2827 pass/0 fail/1 skipped。
1 parent 5e6d280 commit eb6dde4

7 files changed

Lines changed: 149 additions & 42 deletions

File tree

‎dsh-mneme/lib/api.js‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import { timingSafeEqual, randomBytes } from "node:crypto";
77
import { TYPES } from "./store.js";
88
import { TYPE_FILE, renderMirrorText, renderFileHeader, parseHumanEdits, MIRROR_READONLY_TYPES } from "./mirror.js";
99
import { langOf } from "./lang.js";
10+
// op 形状谓词单一份(评审 P3:两份皮会让形状修洞漏一边)。
11+
import { isValidFactOps } from "./profile-facts.js";
1012
import { computeHeat } from "./heat.js";
1113
import { EFFORT_REJECT_RE, describeStreamFailure, resolveRoute, withEffortFallback } from "./dream.js";
1214
// Issue #521:面板要按归一化原因显示 skipped,归一化只有一份实现(住在
@@ -656,13 +658,18 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
656658
const agent = typeof body.agent === "string" ? body.agent.trim() : "";
657659
const ops = Array.isArray(body.ops) ? body.ops : [];
658660
if (!ops.length) return sendJson(res, 400, { error: "ops required" });
659-
if (!ops.every((o) => o && typeof o === "object"
660-
&& (o.op === "add" || o.op === "update" || o.op === "archive")
661-
&& (o.op !== "add" || (typeof o.content === "string" && o.content.trim()))
662-
&& (o.op === "add" || typeof o.id === "string" && o.id.trim()))) {
663-
return sendJson(res, 400, { error: "invalid ops" });
661+
// 形状谓词与解析层共用一份(isValidFactOps):update 与 add 同样必须带
662+
// content——缺了会把「undefined」写进事实正文并从此每帧注入。
663+
if (!isValidFactOps(ops)) return sendJson(res, 400, { error: "invalid ops" });
664+
let result;
665+
try {
666+
result = facts.applyManualOps(agent, ops);
667+
} catch (error) {
668+
// /run 有完整的错误映射,这条写路径也不能把同步异常(SQLite I/O)裸抛
669+
// 给宿主——500 + 一句 internal,与 GET 分支的 try/catch 同款。
670+
ctx.logger?.warn?.(`dsh-mneme: profile-facts apply failed: ${String(error?.message ?? error)}`);
671+
return sendJson(res, 500, { error: "internal" });
664672
}
665-
const result = facts.applyManualOps(agent, ops);
666673
sendJson(res, 200, {
667674
applied: result.applied,
668675
failures: result.failures,

‎dsh-mneme/lib/client.js‎

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3815,6 +3815,10 @@ window.__ModuleLoader__.load({
38153815
}
38163816
setState(await res.json());
38173817
setSaveError("");
3818+
// 功能开关即改即存:别的卡在读同一份 effective 快照(画像事实卡的
3819+
// 「立即更新」按钮禁用态)——广播让它们重读,不然按提示开了开关还得
3820+
// 关面板重开才解禁,正是本车道广播工作项要消灭的那类体验。
3821+
try { window.dispatchEvent(new CustomEvent("mneme:features-changed")); } catch { /* 非浏览器环境 */ }
38183822
announce(t("memory.features.restartHint"));
38193823
setSavedTick(true);
38203824
setTimeout(() => setSavedTick(false), 1800);
@@ -4716,26 +4720,34 @@ window.__ModuleLoader__.load({
47164720
}
47174721
}, []);
47184722
// 切卡先清行再取:上一张卡的事实留在屏上会被当成这张的(同 loadPreview 的
4719-
// 单一所有者纪律——这里没有直接写数据,都交给 loadFacts)。
4723+
// 单一所有者纪律——这里没有直接写数据,都交给 loadFacts)。维护轮结局一并
4724+
// 清:A 卡跑完的「已更新 N 条」不该显示在 B 卡下(评审 P3:跨卡残留)。
47204725
react.useEffect(() => {
47214726
setFactsRows(null);
47224727
setFactsEditId(null);
47234728
setFactsEditDraft("");
47244729
setFactsNotice(null);
4730+
setFactsRunEnd(null);
47254731
loadFacts(factsAgent);
47264732
}, [factsAgent, loadFacts]);
4727-
// 总闸快照:features 由功能开关卡管写,这里只读不写、失败不猜。
4733+
// 总闸快照:features 由功能开关卡管写,这里只读不写、失败不猜。功能开关卡
4734+
// 即改即存并广播 mneme:features-changed——不监听的话,按提示开了「自动事实」
4735+
// 还得关面板重开才解禁(正是广播工作项要消灭的那类体验)。
47284736
react.useEffect(() => {
47294737
let cancelled = false;
4730-
apiFetch("/api/dsh-mneme/features")
4731-
.then((res) => (res.ok ? res.json() : null))
4732-
.then((j) => {
4733-
if (cancelled) return;
4734-
const eff = (j && j.effective) || {};
4735-
setFactsFlag(eff.profileFactsEnabled === true);
4736-
})
4737-
.catch(() => {}); // 读失败保持 null:按钮不锁死,409 兜底
4738-
return () => { cancelled = true; };
4738+
const loadFlag = () => {
4739+
apiFetch("/api/dsh-mneme/features")
4740+
.then((res) => (res.ok ? res.json() : null))
4741+
.then((j) => {
4742+
if (cancelled) return;
4743+
const eff = (j && j.effective) || {};
4744+
setFactsFlag(eff.profileFactsEnabled === true);
4745+
})
4746+
.catch(() => {}); // 读失败保持 null:按钮不锁死,409 兜底
4747+
};
4748+
loadFlag();
4749+
window.addEventListener("mneme:features-changed", loadFlag);
4750+
return () => { cancelled = true; window.removeEventListener("mneme:features-changed", loadFlag); };
47394751
}, []);
47404752
// 人工修正统一入口:一张卡上的小批量 ops 一次 POST,回来重取 GET 让账本跟上,
47414753
// 并刷新注入预览(事实段是注入文本的一部分,预览别停在编辑前)。

‎dsh-mneme/lib/profile-facts.js‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,24 @@ export class ProfileFactsError extends Error {
4848
}
4949
}
5050

51+
/**
52+
* 单个 op 的形状谓词;批量口径(路由层 400 闸)与解析层共用这一份——两处各抄
53+
* 一遍的话,改形状就会漏一边(评审 P3:同一谓词两份皮,P1 的洞因此要修两处)。
54+
* add 与 update 都必须带非空 content:update 缺 content 时 `String(undefined)`
55+
* 会把「undefined」三个字母写进事实正文并从此每帧注入(评审 P1 实测复现的洞)。
56+
*/
57+
function isValidFactOp(o) {
58+
return !!o && typeof o === "object"
59+
&& (o.op === "add" || o.op === "update" || o.op === "archive")
60+
&& (o.op !== "add" && o.op !== "update" || (typeof o.content === "string" && o.content.trim()))
61+
&& (o.op === "add" || typeof o.id === "string" && o.id.trim());
62+
}
63+
64+
/** 批量口径:待写入的 op 批必须非空且逐个形状合格(空批走「没什么可改」,不进这条)。 */
65+
export function isValidFactOps(ops) {
66+
return Array.isArray(ops) && ops.length > 0 && ops.every(isValidFactOp);
67+
}
68+
5169
/**
5270
* 从模型输出里取 ops 数组。先剥 markdown 围栏,再退到「第一个 [ 或 { 到最后一个
5371
* ] 或 }」的宽取——与 parseProfileDraft 同款两步。形状校验:op 只认 add/update/
@@ -73,13 +91,9 @@ export function parseFactOps(text) {
7391
continue;
7492
}
7593
const ops = Array.isArray(value) ? value : (value && typeof value === "object" && Array.isArray(value.ops) ? value.ops : null);
76-
if (!ops) continue;
77-
if (!ops.every((o) => o && typeof o === "object"
78-
&& (o.op === "add" || o.op === "update" || o.op === "archive")
79-
&& (o.op !== "add" || (typeof o.content === "string" && o.content.trim()))
80-
&& (o.op === "add" || typeof o.id === "string" && o.id.trim()))) {
81-
continue;
82-
}
94+
// 空 ops 是合法的「没什么可改」(runFor 会以 ok + opsApplied:0 收尾),所以
95+
// 这里只验逐 op 形状、不要求非空——非空是批量写入口径(isValidFactOps)。
96+
if (!ops || !ops.every(isValidFactOp)) continue;
8397
return ops;
8498
}
8599
return null;
@@ -95,7 +109,9 @@ function collectInputRows(store, agentKey, cursor) {
95109
const content = String(row.content ?? "").slice(0, DEFAULT_ROW_CHARS);
96110
if (content.length < String(row.content ?? "").length) truncated = true;
97111
const size = `${row.type} ${row.title} ${content}`.length;
98-
if (chars + size > DEFAULT_TOTAL_CHARS) {
112+
// 首行保底:单行就超总预算时也收进来(截断已如实标记)——否则游标永远
113+
// 推不进、这张卡变成永久 noop(评审 P3:首行即超预算的死角)。
114+
if (rows.length && chars + size > DEFAULT_TOTAL_CHARS) {
99115
truncated = true;
100116
break;
101117
}
@@ -183,12 +199,20 @@ export function createProfileFacts({ ctx, service, store, config, logger }) {
183199
at, agentKey, runId, factId: prev.id, op: op.op,
184200
before: prev.content, after: op.op === "update" ? nextContent : null, actor
185201
});
186-
if (op.op === "update") activeContents.delete(String(prev.content ?? "").trim());
202+
if (op.op === "update") {
203+
// 去重集合要跟上新值:同批 [update A→B, add B] 不收新值的话会落两条
204+
// 相同的活跃事实,而 dupsSkipped 还是 0(评审 P2 实测复现)。
205+
activeContents.delete(String(prev.content ?? "").trim());
206+
activeContents.add(nextContent);
207+
}
187208
applied += 1;
188209
} else {
189210
failures.push({ op: op.op ?? null, id: op.id ?? null, reason: "unsupported op" });
190211
}
191212
} catch (error) {
213+
// 逐 op 吞错是刻意的:一条 journal 写失败不该把整批已落的事实回滚掉
214+
// (失败进 failures 由回执如实报)。代价是与「单事务」注释的原子粒度
215+
// 有出入——真故障通常连 COMMIT 一起失败,这里只是收窄那道缝。
192216
failures.push({ op: op.op ?? null, id: op.id ?? null, reason: String(error?.message ?? error) });
193217
}
194218
}

‎dsh-mneme/src/api.js‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import { timingSafeEqual, randomBytes } from "node:crypto";
77
import { TYPES } from "./store.js";
88
import { TYPE_FILE, renderMirrorText, renderFileHeader, parseHumanEdits, MIRROR_READONLY_TYPES } from "./mirror.js";
99
import { langOf } from "./lang.js";
10+
// op 形状谓词单一份(评审 P3:两份皮会让形状修洞漏一边)。
11+
import { isValidFactOps } from "./profile-facts.js";
1012
import { computeHeat } from "./heat.js";
1113
import { EFFORT_REJECT_RE, describeStreamFailure, resolveRoute, withEffortFallback } from "./dream.js";
1214
// Issue #521:面板要按归一化原因显示 skipped,归一化只有一份实现(住在
@@ -656,13 +658,18 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
656658
const agent = typeof body.agent === "string" ? body.agent.trim() : "";
657659
const ops = Array.isArray(body.ops) ? body.ops : [];
658660
if (!ops.length) return sendJson(res, 400, { error: "ops required" });
659-
if (!ops.every((o) => o && typeof o === "object"
660-
&& (o.op === "add" || o.op === "update" || o.op === "archive")
661-
&& (o.op !== "add" || (typeof o.content === "string" && o.content.trim()))
662-
&& (o.op === "add" || typeof o.id === "string" && o.id.trim()))) {
663-
return sendJson(res, 400, { error: "invalid ops" });
661+
// 形状谓词与解析层共用一份(isValidFactOps):update 与 add 同样必须带
662+
// content——缺了会把「undefined」写进事实正文并从此每帧注入。
663+
if (!isValidFactOps(ops)) return sendJson(res, 400, { error: "invalid ops" });
664+
let result;
665+
try {
666+
result = facts.applyManualOps(agent, ops);
667+
} catch (error) {
668+
// /run 有完整的错误映射,这条写路径也不能把同步异常(SQLite I/O)裸抛
669+
// 给宿主——500 + 一句 internal,与 GET 分支的 try/catch 同款。
670+
ctx.logger?.warn?.(`dsh-mneme: profile-facts apply failed: ${String(error?.message ?? error)}`);
671+
return sendJson(res, 500, { error: "internal" });
664672
}
665-
const result = facts.applyManualOps(agent, ops);
666673
sendJson(res, 200, {
667674
applied: result.applied,
668675
failures: result.failures,

‎dsh-mneme/src/profile-facts.js‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,24 @@ export class ProfileFactsError extends Error {
4848
}
4949
}
5050

51+
/**
52+
* 单个 op 的形状谓词;批量口径(路由层 400 闸)与解析层共用这一份——两处各抄
53+
* 一遍的话,改形状就会漏一边(评审 P3:同一谓词两份皮,P1 的洞因此要修两处)。
54+
* add 与 update 都必须带非空 content:update 缺 content 时 `String(undefined)`
55+
* 会把「undefined」三个字母写进事实正文并从此每帧注入(评审 P1 实测复现的洞)。
56+
*/
57+
function isValidFactOp(o) {
58+
return !!o && typeof o === "object"
59+
&& (o.op === "add" || o.op === "update" || o.op === "archive")
60+
&& (o.op !== "add" && o.op !== "update" || (typeof o.content === "string" && o.content.trim()))
61+
&& (o.op === "add" || typeof o.id === "string" && o.id.trim());
62+
}
63+
64+
/** 批量口径:待写入的 op 批必须非空且逐个形状合格(空批走「没什么可改」,不进这条)。 */
65+
export function isValidFactOps(ops) {
66+
return Array.isArray(ops) && ops.length > 0 && ops.every(isValidFactOp);
67+
}
68+
5169
/**
5270
* 从模型输出里取 ops 数组。先剥 markdown 围栏,再退到「第一个 [ 或 { 到最后一个
5371
* ] 或 }」的宽取——与 parseProfileDraft 同款两步。形状校验:op 只认 add/update/
@@ -73,13 +91,9 @@ export function parseFactOps(text) {
7391
continue;
7492
}
7593
const ops = Array.isArray(value) ? value : (value && typeof value === "object" && Array.isArray(value.ops) ? value.ops : null);
76-
if (!ops) continue;
77-
if (!ops.every((o) => o && typeof o === "object"
78-
&& (o.op === "add" || o.op === "update" || o.op === "archive")
79-
&& (o.op !== "add" || (typeof o.content === "string" && o.content.trim()))
80-
&& (o.op === "add" || typeof o.id === "string" && o.id.trim()))) {
81-
continue;
82-
}
94+
// 空 ops 是合法的「没什么可改」(runFor 会以 ok + opsApplied:0 收尾),所以
95+
// 这里只验逐 op 形状、不要求非空——非空是批量写入口径(isValidFactOps)。
96+
if (!ops || !ops.every(isValidFactOp)) continue;
8397
return ops;
8498
}
8599
return null;
@@ -95,7 +109,9 @@ function collectInputRows(store, agentKey, cursor) {
95109
const content = String(row.content ?? "").slice(0, DEFAULT_ROW_CHARS);
96110
if (content.length < String(row.content ?? "").length) truncated = true;
97111
const size = `${row.type} ${row.title} ${content}`.length;
98-
if (chars + size > DEFAULT_TOTAL_CHARS) {
112+
// 首行保底:单行就超总预算时也收进来(截断已如实标记)——否则游标永远
113+
// 推不进、这张卡变成永久 noop(评审 P3:首行即超预算的死角)。
114+
if (rows.length && chars + size > DEFAULT_TOTAL_CHARS) {
99115
truncated = true;
100116
break;
101117
}
@@ -183,12 +199,20 @@ export function createProfileFacts({ ctx, service, store, config, logger }) {
183199
at, agentKey, runId, factId: prev.id, op: op.op,
184200
before: prev.content, after: op.op === "update" ? nextContent : null, actor
185201
});
186-
if (op.op === "update") activeContents.delete(String(prev.content ?? "").trim());
202+
if (op.op === "update") {
203+
// 去重集合要跟上新值:同批 [update A→B, add B] 不收新值的话会落两条
204+
// 相同的活跃事实,而 dupsSkipped 还是 0(评审 P2 实测复现)。
205+
activeContents.delete(String(prev.content ?? "").trim());
206+
activeContents.add(nextContent);
207+
}
187208
applied += 1;
188209
} else {
189210
failures.push({ op: op.op ?? null, id: op.id ?? null, reason: "unsupported op" });
190211
}
191212
} catch (error) {
213+
// 逐 op 吞错是刻意的:一条 journal 写失败不该把整批已落的事实回滚掉
214+
// (失败进 failures 由回执如实报)。代价是与「单事务」注释的原子粒度
215+
// 有出入——真故障通常连 COMMIT 一起失败,这里只是收窄那道缝。
192216
failures.push({ op: op.op ?? null, id: op.id ?? null, reason: String(error?.message ?? error) });
193217
}
194218
}

‎dsh-mneme/test/client.test.js‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2633,6 +2633,13 @@ test("profile facts card ships management UI, run outcomes and never touches the
26332633
// 只在 run 后刷新会让「改完一条、预览还是旧的」。
26342634
assert.ok(factsSlice.includes("loadPreview(personaEditing)"),
26352635
"both apply and run success paths must refresh the injected preview");
2636+
// 总闸快照要跟着功能开关走:FeaturesCard 即改即存并广播 mneme:features-changed,
2637+
// 事实卡监听重读——不然按提示开了「自动事实」,按钮还得关面板重开才解禁
2638+
// (评审 P2:快照 effect 是 [] 依赖,监听缺失等于回到「重开才生效」的老病)。
2639+
assert.ok(clientSource.includes('new CustomEvent("mneme:features-changed")'),
2640+
"FeaturesCard must broadcast a features-changed event when a save lands");
2641+
assert.ok(clientSource.includes('addEventListener("mneme:features-changed", loadFlag)'),
2642+
"the facts card must re-read its flag snapshot when features change");
26362643
});
26372644

26382645
// 复制的竞态(CodeRabbit #559 第二轮):剪贴板是异步的,回调属于哪一份草稿必须能认出来。

0 commit comments

Comments
 (0)