dsh-shiori 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client/index.js CHANGED
@@ -60,6 +60,7 @@ window.__ModuleLoader__.load({
60
60
  ".dshi_badge{border:1px solid var(--dshi-gold-ink,#c98a1b);color:var(--dshi-gold-ink,#c98a1b);border-radius:999px;padding:0 8px;font-size:10px;white-space:nowrap}" +
61
61
  ".dshi_badgeWarn{border-color:var(--dsw-alias-state-error-primary,#f85149);color:var(--dsw-alias-state-error-primary,#f85149)}" +
62
62
  ".dshi_badgeDim{border-color:var(--dsw-alias-border-l2,#dce2eb);color:var(--dsw-alias-label-tertiary)}" +
63
+ ".dshi_badgeStale{border-color:var(--dshi-warn);color:var(--dshi-warn)}" +
63
64
  ".dshi_btn{border:1px solid var(--dsw-alias-border-l2,#dce2eb);background:var(--dsw-alias-bg-layer-3,#fff);color:var(--dsw-alias-label-primary);border-radius:8px;padding:5px 12px;font:inherit;font-size:12px;cursor:pointer}" +
64
65
  ".dshi_btn:hover:not(:disabled){border-color:var(--dshi-accent-a,#e5484d)}" +
65
66
  ".dshi_btn:disabled{opacity:.5;cursor:default}" +
@@ -80,6 +81,7 @@ window.__ModuleLoader__.load({
80
81
  ".dshi_graphWrap{border:1px solid var(--dsw-alias-border-l2,#dce2eb);border-radius:10px;overflow:hidden;position:relative;user-select:none;cursor:grab;background:var(--dsw-alias-bg-layer-2,transparent)}" +
81
82
  ".dshi_graphSvg{display:block;width:100%;height:380px;touch-action:none}" +
82
83
  ".dshi_graphNode{cursor:pointer}" +
84
+ ".dshi_graphNode:focus-visible{outline:2px solid var(--dshi-accent,#e5484d);outline-offset:2px}" +
83
85
  ".dshi_nodeEvergreen{fill:var(--dsw-alias-state-success-primary,#1a7f37)}" +
84
86
  ".dshi_nodeEphemeral{fill:var(--dsw-alias-state-business-primary,#3964fe)}" +
85
87
  ".dshi_nodeDim{fill:var(--dsw-alias-label-tertiary,#8b93a1)}" +
@@ -167,7 +169,26 @@ window.__ModuleLoader__.load({
167
169
  ".dshi_roBanner{border:1px solid var(--dshi-warn);background:rgba(180,83,9,.10);color:var(--dshi-warn);border-radius:8px;padding:8px 12px;font-size:12px;line-height:1.5;word-break:break-word}" +
168
170
  ".dshi_roHint{font-size:11px;color:var(--dshi-warn);border:1px solid var(--dshi-warn);border-radius:8px;padding:4px 8px;word-break:break-word}" +
169
171
  ".dshi_tlScan{font-size:11px;color:var(--dshi-warn)}" +
170
- ".dshi_tlDedupe{border-color:var(--dshi-l3);color:var(--dshi-l3)}";
172
+ ".dshi_tlDedupe{border-color:var(--dshi-l3);color:var(--dshi-l3)}" +
173
+ // U5 整理与遗忘页:筛选条(chips)、搜索框、kind 分组组头、就地预览 diff 区。
174
+ // 只引用 --dshi-* token;diff 区最小高度 240px、可滚动、字号不小于 12px。
175
+ ".dshi_filterBar{display:flex;align-items:center;gap:var(--dshi-space-xs);flex-wrap:wrap}" +
176
+ ".dshi_filterChip{border:1px solid var(--dsw-alias-border-l2,#dce2eb);background:var(--dshi-bg-card);color:var(--dshi-text-dim);border-radius:var(--dshi-radius-pill);padding:2px 10px;font:inherit;font-size:var(--dshi-font-xs);cursor:pointer}" +
177
+ ".dshi_filterChip:hover{color:var(--dshi-text)}" +
178
+ ".dshi_filterChipOn{border-color:transparent;background:linear-gradient(135deg,var(--dshi-accent-a),var(--dshi-accent-b));color:#fff;font-weight:600}" +
179
+ ".dshi_searchInput{flex:1;min-width:160px;max-width:240px}" +
180
+ ".dshi_groupHead{display:flex;align-items:center;gap:var(--dshi-space-xs);cursor:pointer;border:none;background:none;padding:2px 0;font:inherit;font-size:var(--dshi-font-sm);font-weight:600;color:var(--dshi-text);text-align:left}" +
181
+ ".dshi_groupHead:hover{color:var(--dshi-accent)}" +
182
+ ".dshi_groupCount{font-size:var(--dshi-font-xs);font-weight:400;color:var(--dshi-text-dim)}" +
183
+ ".dshi_diffBox{display:flex;flex-direction:column;gap:var(--dshi-space-sm);min-height:240px;max-height:480px;overflow:auto;border:var(--dshi-stroke);border-radius:var(--dshi-radius-sm);padding:var(--dshi-space-sm)}" +
184
+ ".dshi_diffBox .dshi_pre{font-size:var(--dshi-font-sm)}" +
185
+ ".dshi_kindGroup{display:flex;flex-direction:column;gap:var(--dshi-space-xs)}" +
186
+ ".dshi_advanced{display:flex;flex-direction:column;gap:var(--dshi-space-xs);margin-top:var(--dshi-space-xs)}" +
187
+ // U5-e:过期候选——行内徽章(warn 色沿用 --dshi-warn)、顶部提示条与重析按钮
188
+ //(底色沿用 dshi_roBanner 的 rgba(180,83,9,.10),不引入新色系)。
189
+ ".dshi_staleBar{display:flex;align-items:center;gap:var(--dshi-space-xs);flex-wrap:wrap;border:1px solid var(--dshi-warn);background:rgba(180,83,9,.10);color:var(--dshi-warn);border-radius:var(--dshi-radius-sm);padding:var(--dshi-space-xs) var(--dshi-space-sm);font-size:var(--dshi-font-sm)}" +
190
+ ".dshi_staleBarBtn{border:1px solid var(--dshi-warn);background:none;color:var(--dshi-warn);font:inherit;font-size:var(--dshi-font-xs);border-radius:var(--dshi-radius-sm);padding:2px 10px;cursor:pointer}" +
191
+ ".dshi_staleBarBtn:disabled{opacity:.5;cursor:default}";
171
192
  function ensureStyle() {
172
193
  try {
173
194
  if (document.getElementById("dsh-shiori-style")) return;
@@ -504,6 +525,29 @@ window.__ModuleLoader__.load({
504
525
  function stableStringify(value) {
505
526
  return JSON.stringify(value, null, 2) ?? "null";
506
527
  }
528
+ // C4(审计 P2-4):候选/计划行的「原始数据(JSON)」details 在整表重渲时逐行重跑
529
+ // JSON.stringify——搜索框逐键输入即对全部候选全量重序列化。这里按数据引用记忆化:
530
+ // 同一份 DTO 快照渲染多少次都只序列化一次。
531
+ // 失效条件(等价正确性论证,改动时逐条核对):
532
+ // 1. 键是对象引用:服务端每次响应都产生新对象,新数据必然重新序列化;
533
+ // 2. 面板把 RPC 响应当不可变快照,从不在原地改写 item/plan(改动一律整表重拉,
534
+ // 生成新对象)——所以「引用相同 ⇒ 内容相同」成立;凡是会被原地改写的对象
535
+ // (如 core 编辑区的 pristineLinks 对比)必须继续用 stableStringify,不得换本函数;
536
+ // 3. WeakMap 弱键随 DTO 对象一起被 GC,缓存不延长快照生命周期;条目数超上限
537
+ // 整体清空(换队列后旧键本可自然回收,清空只是防极端驻留的兜底);
538
+ // 4. 原始值(string/number/boolean/null/undefined)不缓存——序列化本身 O(1);
539
+ // 序列化抛错(循环引用等)不缓存、照常向上抛(与 stableStringify 同语义)。
540
+ var STABLE_STRINGIFY_CACHE_MAX = 512;
541
+ var stableStringifyCache = typeof WeakMap === "function" ? new WeakMap() : null;
542
+ function stableStringifyCached(value) {
543
+ if (stableStringifyCache === null || value === null || typeof value !== "object") return stableStringify(value);
544
+ var hit = stableStringifyCache.get(value);
545
+ if (hit !== undefined) return hit;
546
+ var text = stableStringify(value);
547
+ if (stableStringifyCache.size >= STABLE_STRINGIFY_CACHE_MAX) stableStringifyCache.clear();
548
+ stableStringifyCache.set(value, text);
549
+ return text;
550
+ }
507
551
  // Q-C(owner work order):diagnostics 里 P 本轮会新增 codec/transport 等字段,
508
552
  // 未来还可能继续加。状态 tab 必须容错:未知字段照常展示(key: value),值为
509
553
  // undefined 的键忽略(不显示 undefined / 伪装成 null),序列化抛错(循环引用等)
@@ -777,7 +821,14 @@ window.__ModuleLoader__.load({
777
821
 
778
822
  function ErrorBox(error) {
779
823
  if (!error) return null;
780
- return h("div", { className: "dshi_error" }, (error.code ? "[" + error.code + "] " : "") + (error.message || String(error)));
824
+ // U5:人话提示在盒子正文;服务端原始错误收进默认折叠的 details(排查用),
825
+ // 不再把原始大红字直接顶出来。detail 由 candidateActionError 等映射层携带。
826
+ var detail = error.detail !== undefined && error.detail !== null ? String(error.detail) : null;
827
+ return h("div", { className: "dshi_error" },
828
+ (error.code ? "[" + error.code + "] " : "") + (error.message || String(error)),
829
+ detail ? h("details", { className: "dshi_details" },
830
+ h("summary", { className: "dshi_hint" }, "原始错误信息"),
831
+ h("pre", { className: "dshi_pre" }, detail)) : null);
781
832
  }
782
833
 
783
834
  // U3 水位三档具名常量:ratio < WATER_WARN_RATIO 正常、达到 WATER_WARN_RATIO 警示、
@@ -880,6 +931,34 @@ window.__ModuleLoader__.load({
880
931
  hint ? h("span", { className: "dshi_hint" }, hint) : null);
881
932
  }
882
933
 
934
+ // ── P1-2:tab 级会话守卫(CandidatesTab 现成 mark/isStale 思路的本文件局部
935
+ // 抽用;不新增全局、不改导出面)────────────────────────────────────────────
936
+ // 六个数据 tab(Status / Memory / Graph / Topics / Flashbacks / Timeline)的
937
+ // load 都是异步的:响应回来时若用户已切换会话,旧响应会把别的作用域的数据
938
+ // 写进当前页。holder 由调用方用 useState 存一个可变对象(跨渲染持久、充当
939
+ // ref 使用,不占渲染状态语义);track() 在渲染体里调用(早于任何 load 发起,
940
+ // 不依赖 effect 是否真的执行),mark() 给本次加载发戳,isStale() 判过期。
941
+ function makeTabSessionGuard(props, holder) {
942
+ var track = function () {
943
+ if (holder.sessionId !== props.sessionId) {
944
+ holder.sessionId = props.sessionId;
945
+ holder.gen += 1;
946
+ }
947
+ };
948
+ return {
949
+ track: track,
950
+ mark: function () {
951
+ track();
952
+ // origin 记闭包自己的 props.sessionId(不是 holder):旧闭包的 props
953
+ // 停在旧会话,即使 holder 已 gen+1 也能按 sessionId 判过期。
954
+ return { sessionId: props.sessionId, gen: holder.gen };
955
+ },
956
+ isStale: function (origin) {
957
+ return holder.sessionId !== origin.sessionId || holder.gen !== origin.gen;
958
+ },
959
+ };
960
+ }
961
+
883
962
  // ── F1b:语义召回只读状态 + 重建向量按钮 ─────────────────────────────
884
963
  // 数据源:getStatus.diagnostics.semantic(wire 的 diagnostics 块是
885
964
  // additionalProperties:true,服务端纯增量注入;客户端不做结构假设——
@@ -887,7 +966,8 @@ window.__ModuleLoader__.load({
887
966
  // 触发通道:executeTool 的保留名 semantic_rebuild(不是宿主工具,服务端
888
967
  // dispatchTool 内部拦截;单飞:重建中再点只返回进度快照)。
889
968
  // 进度:点击后本地起一个轮询循环(getStatus 每 1.5s),直到 rebuild 不在
890
- // running;会话切换 / 组件销毁由 sessionId 比对终止,不依赖 unmount 回调。
969
+ // running;会话切换由渲染体同步的 sessionId 镜像 ref 比对终止,组件卸载由
970
+ // 挂载 effect 的 cleanup 置停(P1-1)。
891
971
  var SEMANTIC_REBUILD_TOOL = "semantic_rebuild";
892
972
  var REBUILD_POLL_MS = 1500;
893
973
  var SEMANTIC_PHASE_LABELS = {
@@ -946,11 +1026,32 @@ window.__ModuleLoader__.load({
946
1026
  var rebuildState = useState(null);
947
1027
  var rebuildProgress = rebuildState[0];
948
1028
  var setRebuildProgress = rebuildState[1];
1029
+ // P1-2:本 tab 的会话守卫 holder(新 state 一律追加在既有 state 之后)。
1030
+ var tabGuardState = useState({ sessionId: props.sessionId, gen: 0 });
1031
+ var tabGuard = makeTabSessionGuard(props, tabGuardState[0]);
1032
+ tabGuard.track(); // 每次渲染同步:会话一换,在途响应即刻过期
1033
+ // P1-1(重建轮询串会话):当前 sessionId 的镜像 ref——渲染体同步,轮询每轮
1034
+ // 与发起时的 sid 比对。旧实现比对创建闭包里的 props.sessionId,props 对象
1035
+ // 不随重渲染更新,切换会话后比对恒等、轮询永不停止。pollAliveRef 由挂载
1036
+ // effect 置真、cleanup 置假,组件卸载即停,不依赖会话切换。
1037
+ var sidRef = useRef(props.sessionId);
1038
+ sidRef.current = props.sessionId;
1039
+ var pollAliveRef = useRef(false);
1040
+ useEffect(function () {
1041
+ pollAliveRef.current = true;
1042
+ return function () { pollAliveRef.current = false; };
1043
+ }, []);
949
1044
  var load = async function () {
1045
+ var origin = tabGuard.mark();
950
1046
  setError(null);
951
1047
  try {
952
- setStatus(await props.dsh.call("getStatus", props.sessionId, {}));
953
- } catch (e) { setStatus(null); if (!reportSessionUnavailable(e, props, setError)) setError(e); }
1048
+ var result = await props.dsh.call("getStatus", props.sessionId, {});
1049
+ if (tabGuard.isStale(origin)) return; // P1-2:会话已切换,丢弃旧响应
1050
+ setStatus(result);
1051
+ } catch (e) {
1052
+ if (tabGuard.isStale(origin)) return;
1053
+ setStatus(null); if (!reportSessionUnavailable(e, props, setError)) setError(e);
1054
+ }
954
1055
  };
955
1056
  useEffect(function () { load(); }, [props.sessionId]);
956
1057
  var semantic = status && status.diagnostics && typeof status.diagnostics === "object" && !Array.isArray(status.diagnostics)
@@ -959,7 +1060,7 @@ window.__ModuleLoader__.load({
959
1060
  var rebuildRunning = rebuildProgress !== null && rebuildProgress.running === true;
960
1061
  // 「重建向量」:后台分批补(服务端每批 20 张、批间让出事件循环),进度
961
1062
  // 写在 diagnostics.semantic.rebuild,这里轮询读取并原地显示。会话切换
962
- // (props.sessionId 变化)即停轮询,不依赖组件卸载回调。
1063
+ // (sidRef 镜像比对)与卸载(pollAliveRef cleanup)都会停轮询(P1-1)。
963
1064
  var startRebuild = async function () {
964
1065
  if (!semantic || !semantic.enabled || rebuildRunning) return;
965
1066
  var sid = props.sessionId;
@@ -972,7 +1073,9 @@ window.__ModuleLoader__.load({
972
1073
  return;
973
1074
  }
974
1075
  for (;;) {
975
- if (props.sessionId !== sid) return; // 会话已切换:停止轮询
1076
+ // P1-1:每轮比对镜像 ref(渲染体同步的当前会话);组件已卸载(cleanup
1077
+ // 置假)同样停轮询。读闭包里的 props 判断不出会话切换,这里必须走 ref。
1078
+ if (!pollAliveRef.current || sidRef.current !== sid) return; // 会话已切换 / 已卸载:停止轮询
976
1079
  var fresh;
977
1080
  try {
978
1081
  fresh = await props.dsh.call("getStatus", sid, {});
@@ -1083,6 +1186,12 @@ window.__ModuleLoader__.load({
1083
1186
  : null);
1084
1187
  }
1085
1188
 
1189
+ // 0.3:记忆占用上限的常量兜底(仅当 DTO 连 hardCap / budget 都没带时才用)。
1190
+ // L1 与状态页同口径按硬顶显示(getStatus occupancy.l1HardCap 的服务端默认
1191
+ // 环境即 14000);L0 维持人设卡 maxChars 的历史常量。
1192
+ var MEMORY_L1_HARDCAP_FALLBACK = 14000;
1193
+ var MEMORY_L0_BUDGET_FALLBACK = 12000;
1194
+
1086
1195
  function MemoryTab(props) {
1087
1196
  var state = useState(null);
1088
1197
  var view = state[0];
@@ -1109,18 +1218,48 @@ window.__ModuleLoader__.load({
1109
1218
  var saveErrorState = useState(null);
1110
1219
  var saveError = saveErrorState[0];
1111
1220
  var setSaveError = saveErrorState[1];
1221
+ // P1-2:本 tab 的会话守卫 holder(新 state 一律追加在既有 state 之后)。
1222
+ var tabGuardState = useState({ sessionId: props.sessionId, gen: 0 });
1223
+ var tabGuard = makeTabSessionGuard(props, tabGuardState[0]);
1224
+ tabGuard.track(); // 每次渲染同步:会话一换,在途响应即刻过期
1112
1225
  // F7:只读态(另一实例在写)写按钮置灰 + 页内黄字说明原因。
1113
1226
  var ro = props.readOnly === true;
1114
1227
  var load = async function () {
1228
+ var origin = tabGuard.mark();
1115
1229
  setError(null);
1116
1230
  try {
1117
- setView(await props.dsh.call("getMemoryView", props.sessionId, {}));
1118
- } catch (e) { setView(null); if (!reportSessionUnavailable(e, props, setError)) setError(e); }
1231
+ var result = await props.dsh.call("getMemoryView", props.sessionId, {});
1232
+ if (tabGuard.isStale(origin)) return; // P1-2:会话已切换,丢弃旧响应
1233
+ setView(result);
1234
+ } catch (e) {
1235
+ if (tabGuard.isStale(origin)) return;
1236
+ setView(null); if (!reportSessionUnavailable(e, props, setError)) setError(e);
1237
+ }
1119
1238
  };
1120
1239
  useEffect(function () { load(); }, [props.sessionId]);
1121
1240
  var l0 = view && (view.l0 || view.persona);
1122
1241
  var l1 = view && (view.l1 || view.core);
1123
1242
  var budgets = (view && view.budgets) || props.budgets || {};
1243
+ // 0.3:占用上限与状态页同源同口径——统一按硬顶显示。getMemoryView DTO
1244
+ // (src/plugin/management.mjs getMemoryView)在 l1 上带 hardCap(=
1245
+ // settings.budgets.core.hardCapChars,与 getStatus occupancy.l1HardCap 同一
1246
+ // 真值);旧宿主 DTO 缺字段时按 l1.budget → budgets.core.hardCapChars →
1247
+ // 常量兜底。不再用 budgets.core.targetChars(软目标,状态页不显示它,
1248
+ // 之前正是两页 14000 / 8000 对不上的根因)。L0 同理取 l0.budget,不再走
1249
+ // budgets.persona 兜底。
1250
+ var l0BudgetOf = function (layer) {
1251
+ var value = layer && typeof layer === "object" ? layer.budget : undefined;
1252
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : MEMORY_L0_BUDGET_FALLBACK;
1253
+ };
1254
+ var l1HardCapOf = function (layer) {
1255
+ var hardCap = layer && typeof layer === "object" ? layer.hardCap : undefined;
1256
+ if (typeof hardCap === "number" && Number.isFinite(hardCap) && hardCap > 0) return hardCap;
1257
+ var budget = layer && typeof layer === "object" ? layer.budget : undefined;
1258
+ if (typeof budget === "number" && Number.isFinite(budget) && budget > 0) return budget;
1259
+ var core = budgets && budgets.core ? budgets.core : {};
1260
+ if (typeof core.hardCapChars === "number" && Number.isFinite(core.hardCapChars) && core.hardCapChars > 0) return core.hardCapChars;
1261
+ return MEMORY_L1_HARDCAP_FALLBACK;
1262
+ };
1124
1263
 
1125
1264
  // 编辑初值:L1 的 text 是服务端渲染视图(core 正文 + 派生主题索引),整段写回
1126
1265
  // 会把索引固化进 core,必须用 body(磁盘正文)。L0 没有派生部分,照旧用 text。
@@ -1282,8 +1421,8 @@ window.__ModuleLoader__.load({
1282
1421
  // 空状态:说明记忆怎么组织、从哪里开始写第一条、需要先配置什么,不留白。
1283
1422
  var renderEmptyLayer = function (kind, title) {
1284
1423
  var guide = kind === "l0"
1285
- ? "人设卡(L0)还是空的。记忆按层组织:L0 是每轮对话常驻注入的身份与规则卡,L1 是记忆核心,更细的事实记录在 L2/L3(由记忆工具与候选整理维护)。写第一条:点下方「编辑」,写下这份人设的身份、语气与边界,保存后下一轮对话即生效。开始前请先确认面板处于 active 模式,并在「预算配置」里设置人设卡最大字符数。"
1286
- : "记忆核心(L1)还是空的。它是长期记忆的正文区,服务端渲染时会自动在正文后附加主题索引,不用手写。写第一条:点下方「编辑」,用一段话记录值得长期记住的事实或偏好,保存即生效。开始前请先确认面板处于 active 模式,并在「预算配置」里设置记忆核心的目标字符数与硬上限。";
1424
+ ? "人设卡(L0)还是空的。记忆按层组织:L0 是每轮对话常驻注入的身份与规则卡,L1 是记忆核心,更细的事实记录在 L2/L3(由记忆工具与候选整理维护)。写第一条:点下方「编辑」,写下这份人设的身份、语气与边界,保存后下一轮对话即生效。开始前请先确认面板处于 active 模式,并在「记忆预算」里设置人设卡最大字符数。"
1425
+ : "记忆核心(L1)还是空的。它是长期记忆的正文区,服务端渲染时会自动在正文后附加主题索引,不用手写。写第一条:点下方「编辑」,用一段话记录值得长期记住的事实或偏好,保存即生效。开始前请先确认面板处于 active 模式,并在「记忆预算」里设置记忆核心的目标字符数与硬上限。";
1287
1426
  return h("div", { className: "dshi_card" },
1288
1427
  h("div", { className: "dshi_row" },
1289
1428
  h("span", { className: "dshi_cardTitle" }, title),
@@ -1341,10 +1480,10 @@ window.__ModuleLoader__.load({
1341
1480
  okText ? h("div", { className: "dshi_ok" }, okText) : null,
1342
1481
  view ? h(fragment, null,
1343
1482
  h("div", { className: "dshi_grid2" },
1344
- Bar("人设卡 L0(UTF-16)", l0 && (l0.chars ?? l0.length ?? (l0.text ? l0.text.length : 0)), (budgets.persona && budgets.persona.maxChars) ?? 12000),
1345
- Bar("记忆核心 L1(UTF-16)", l1 && (l1.chars ?? l1.length ?? (l1.text ? l1.text.length : 0)), (budgets.core && budgets.core.targetChars) ?? 8000)),
1483
+ Bar("人设卡 L0(UTF-16)", l0 && (l0.chars ?? l0.length ?? (l0.text ? l0.text.length : 0)), l0BudgetOf(l0)),
1484
+ Bar("记忆核心 L1(UTF-16)", l1 && (l1.chars ?? l1.length ?? (l1.text ? l1.text.length : 0)), l1HardCapOf(l1))),
1346
1485
  renderLayer("l0", "人设卡(L0 persona)", l0,
1347
- "每轮对话常驻的身份与规则。编辑后保存立即生效;上限由「预算配置」的人设卡最大字符数决定。"),
1486
+ "每轮对话常驻的身份与规则。编辑后保存立即生效;上限由「记忆预算」的人设卡最大字符数决定。"),
1348
1487
  renderLayer("l1", "记忆核心(L1 core)", l1,
1349
1488
  "上方预览是完整渲染结果(正文 + 派生主题索引);点编辑后文本框里只有磁盘正文,主题索引由服务端自动生成,不用手写。保存带 revision 校验,若别处刚改过会提示冲突,刷新后重试。"),
1350
1489
  h("details", null,
@@ -1392,6 +1531,465 @@ window.__ModuleLoader__.load({
1392
1531
  return map;
1393
1532
  }
1394
1533
 
1534
+ // 实体聚类的实体名:取 raw.entities[0],字符串直接用;对象取 name/id/key。
1535
+ // 拿不到(undefined / 空数组 / 空串)返回 null → 中性色。
1536
+ function entityKeyOf(node) {
1537
+ var entities = node && node.raw && node.raw.entities;
1538
+ if (!Array.isArray(entities) || entities.length === 0) return null;
1539
+ var first = entities[0];
1540
+ var key = first && typeof first === "object" ? (first.name ?? first.id ?? first.key) : first;
1541
+ if (key === undefined || key === null) return null;
1542
+ var text = String(key);
1543
+ return text === "" ? null : text;
1544
+ }
1545
+
1546
+ // FNV-1a 稳定哈希 → 固定 6 色调色板下标。同一实体名永远同色,无随机。
1547
+ // 调色板走 circle 内联 style(reviewer q-1ba8addcbcd85a30:不新增 dshi_* 类名)。
1548
+ var CLUSTER_PALETTE = ["#4c8bf5", "#d29922", "#8250df", "#1a7f37", "#bf3989", "#0969da"];
1549
+ var NEUTRAL_FILL = "var(--dsw-alias-label-secondary,#6b7280)";
1550
+ function clusterIndexOf(text) {
1551
+ var hash = 0x811c9dc5;
1552
+ for (var i = 0; i < text.length; i++) {
1553
+ hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193) >>> 0;
1554
+ }
1555
+ return hash % 6;
1556
+ }
1557
+ function clusterFillOf(node) {
1558
+ var entityKey = entityKeyOf(node);
1559
+ return entityKey === null ? NEUTRAL_FILL : CLUSTER_PALETTE[clusterIndexOf(entityKey)];
1560
+ }
1561
+ // 存续类型描边色:evergreen 绿、ephemeral 蓝、非 active 灰(填充让位给聚类色)。
1562
+ function vitalityStrokeOf(node) {
1563
+ return node.state !== "active" ? "var(--dsw-alias-label-tertiary,#8b93a1)"
1564
+ : node.vitality === "evergreen" ? "var(--dsw-alias-state-success-primary,#1a7f37)"
1565
+ : "var(--dsw-alias-state-business-primary,#3964fe)";
1566
+ }
1567
+
1568
+ // 节点半径按重要度:r = 10 + min(8, 2*degree),degree 缺失或非数字按 0。
1569
+ function nodeRadiusOf(node) {
1570
+ var raw = node && node.raw;
1571
+ var degree = raw ? Number(raw.degree) : 0;
1572
+ if (!Number.isFinite(degree) || degree < 0) degree = 0;
1573
+ return 10 + Math.min(8, 2 * degree);
1574
+ }
1575
+
1576
+ // 手写 Fruchterman–Reingold 力导向布局(不引依赖、不加构建)。
1577
+ // 初始位置按节点稳定顺序摆到圆上(不用 Math.random,同一份数据两次调用结果完全一致);
1578
+ // 120 轮迭代:点对斥力 k=sqrt(W*H/n)、边为弹簧、中心回归力,温度从 W/8 线性降到 0,
1579
+ // 位移限幅后夹在 [pad, W-pad] × [pad, H-pad] 内。
1580
+ // 迭代后:包围盒等比归一化到 [2*pad, W-2*pad] × [2*pad, H-2*pad] 并居中(防全图贴边),
1581
+ // 再做 ≤30 轮确定性分离收尾(两两距离拉到 r_i+r_j+6 以上,保证不重合、标签不叠),
1582
+ // 全程坐标保证有限值。(收敛三层修复见 review-rework a1:中心回归 / 归一化 / 分离。)
1583
+ // C3(审计 P2-3):全流程是 O(n²)(120 轮点对斥力 + ≤60 轮两两分离),节点数无上限
1584
+ // 时大库会在主线程冻结秒级以上。超过上限即降级为「圆形静布」:直接返回初始圆环
1585
+ // 位置(确定性、无迭代、O(n)),GraphTab 顶部给出提示。阈值取 500 的依据:
1586
+ // - 主线程耗时预算:斥力 ≈ 120×n²/2 点对、分离 ≈ ≤60×n²/2 点对。n=500 时合计
1587
+ // ≈2×10⁷ 次点对计算,主线程一次性开销约 0.1~0.3s,且布局 useMemo 只在图变化时
1588
+ // 重跑一次,可接受;n=1000 时计算量翻 4 倍起,进入秒级冻结区。
1589
+ // - 几何上限:800×380 画布、半径 ≥10 的圆,两两不重叠最多放几百个,超过后
1590
+ // 「不重合、标签不叠」的布局承诺本就放不下,力导向的精度优势失去意义。
1591
+ // - 既有 60/200 节点布局承诺(R8 用例)留有 2.5 倍余量,不受影响。
1592
+ var FORCE_LAYOUT_MAX_NODES = 500;
1593
+ function forceLayout(nodes, edges) {
1594
+ var W = 800;
1595
+ var H = 380;
1596
+ var PAD = 30;
1597
+ var ITERATIONS = 120;
1598
+ var positions = {};
1599
+ var count = nodes.length;
1600
+ if (count === 0) return positions;
1601
+ for (var i = 0; i < count; i++) {
1602
+ var angle = (2 * Math.PI * i) / count - Math.PI / 2;
1603
+ positions[nodes[i].id] = { x: 400 + 260 * Math.cos(angle), y: 190 + 140 * Math.sin(angle) };
1604
+ }
1605
+ // C3 降级路径:超上限跳过全部 O(n²) 迭代与分离,直接用初始圆环(确定性静布)。
1606
+ if (count > FORCE_LAYOUT_MAX_NODES) return positions;
1607
+ if (count === 1) { positions[nodes[0].id] = { x: 400, y: 190 }; return positions; }
1608
+ // 半径预计算:分离收尾按 r_i + r_j + 6 判定
1609
+ var radii = [];
1610
+ for (var r0 = 0; r0 < count; r0++) radii.push(nodeRadiusOf(nodes[r0]));
1611
+ var k = Math.sqrt((W * H) / count);
1612
+ // 边去重:同一对节点的多条边只算一根弹簧,保证布局稳定
1613
+ var pairSeen = {};
1614
+ var springs = [];
1615
+ for (var e = 0; e < edges.length; e++) {
1616
+ var from = edges[e].from;
1617
+ var to = edges[e].to;
1618
+ if (from === to || !positions[from] || !positions[to]) continue;
1619
+ var pair = from < to ? from + "\u0000" + to : to + "\u0000" + from;
1620
+ if (pairSeen[pair]) continue;
1621
+ pairSeen[pair] = true;
1622
+ springs.push({ from: from, to: to });
1623
+ }
1624
+ var disp = {};
1625
+ for (var iter = 0; iter < ITERATIONS; iter++) {
1626
+ var temp = (W / 8) * (1 - iter / ITERATIONS); // W/8 线性降到 0
1627
+ for (var a = 0; a < count; a++) disp[nodes[a].id] = { x: 0, y: 0 };
1628
+ // 斥力:所有点对
1629
+ for (var u = 0; u < count; u++) {
1630
+ for (var v = u + 1; v < count; v++) {
1631
+ var pu = positions[nodes[u].id];
1632
+ var pv = positions[nodes[v].id];
1633
+ var dx = pu.x - pv.x;
1634
+ var dy = pu.y - pv.y;
1635
+ var dist = Math.sqrt(dx * dx + dy * dy);
1636
+ if (!Number.isFinite(dist) || dist < 0.01) {
1637
+ // 完全重合:给一个确定性的方向(按对下标取奇偶),避免 NaN 与随机
1638
+ dx = (u + v) % 2 === 0 ? 1 : -1;
1639
+ dy = (u * 3 + v * 7) % 2 === 0 ? 1 : -1;
1640
+ dist = 1;
1641
+ }
1642
+ var force = (k * k) / dist;
1643
+ var fx = (dx / dist) * force;
1644
+ var fy = (dy / dist) * force;
1645
+ disp[nodes[u].id].x += fx;
1646
+ disp[nodes[u].id].y += fy;
1647
+ disp[nodes[v].id].x -= fx;
1648
+ disp[nodes[v].id].y -= fy;
1649
+ }
1650
+ }
1651
+ // 引力:边为弹簧
1652
+ for (var s = 0; s < springs.length; s++) {
1653
+ var pf = positions[springs[s].from];
1654
+ var pt = positions[springs[s].to];
1655
+ var sdx = pt.x - pf.x;
1656
+ var sdy = pt.y - pf.y;
1657
+ var sdist = Math.sqrt(sdx * sdx + sdy * sdy);
1658
+ if (!Number.isFinite(sdist) || sdist < 0.01) continue;
1659
+ var attract = (sdist * sdist) / k;
1660
+ var ax = (sdx / sdist) * attract;
1661
+ var ay = (sdy / sdist) * attract;
1662
+ disp[springs[s].from].x += ax;
1663
+ disp[springs[s].from].y += ay;
1664
+ disp[springs[s].to].x -= ax;
1665
+ disp[springs[s].to].y -= ay;
1666
+ }
1667
+ // 中心回归力:把成分往画布中心轻轻拉,避免整图被斥力推到四边后被夹取压成一摞
1668
+ for (var c = 0; c < count; c++) {
1669
+ var cid = nodes[c].id;
1670
+ disp[cid].x += 0.02 * (W / 2 - positions[cid].x);
1671
+ disp[cid].y += 0.02 * (H / 2 - positions[cid].y);
1672
+ }
1673
+ // 限幅位移 + 夹取到画布内
1674
+ for (var b = 0; b < count; b++) {
1675
+ var id = nodes[b].id;
1676
+ var d = disp[id];
1677
+ var len = Math.sqrt(d.x * d.x + d.y * d.y);
1678
+ if (Number.isFinite(len) && len > temp && len > 0) {
1679
+ d.x = (d.x / len) * temp;
1680
+ d.y = (d.y / len) * temp;
1681
+ }
1682
+ var p = positions[id];
1683
+ p.x = Math.min(W - PAD, Math.max(PAD, p.x + (Number.isFinite(d.x) ? d.x : 0)));
1684
+ p.y = Math.min(H - PAD, Math.max(PAD, p.y + (Number.isFinite(d.y) ? d.y : 0)));
1685
+ }
1686
+ }
1687
+ // 迭代后归一化:包围盒等比缩放到 [2*PAD, W-2*PAD] × [2*PAD, H-2*PAD] 并居中,
1688
+ // 消掉「全图贴边」;退化(宽高都为 0 的单点团)直接置画布中心。
1689
+ var minX = Infinity;
1690
+ var minY = Infinity;
1691
+ var maxX = -Infinity;
1692
+ var maxY = -Infinity;
1693
+ for (var n1 = 0; n1 < count; n1++) {
1694
+ var p1 = positions[nodes[n1].id];
1695
+ if (p1.x < minX) minX = p1.x;
1696
+ if (p1.x > maxX) maxX = p1.x;
1697
+ if (p1.y < minY) minY = p1.y;
1698
+ if (p1.y > maxY) maxY = p1.y;
1699
+ }
1700
+ var bw = maxX - minX;
1701
+ var bh = maxY - minY;
1702
+ if (bw === 0 && bh === 0) {
1703
+ for (var z = 0; z < count; z++) {
1704
+ positions[nodes[z].id] = { x: W / 2, y: H / 2 };
1705
+ }
1706
+ } else {
1707
+ var scaleW = bw > 0 ? (W - 4 * PAD) / bw : Infinity;
1708
+ var scaleH = bh > 0 ? (H - 4 * PAD) / bh : Infinity;
1709
+ var scale = Math.min(scaleW, scaleH);
1710
+ var offsetX = bw > 0 ? (W - bw * scale) / 2 : W / 2;
1711
+ var offsetY = bh > 0 ? (H - bh * scale) / 2 : H / 2;
1712
+ for (var n2 = 0; n2 < count; n2++) {
1713
+ var pn = positions[nodes[n2].id];
1714
+ pn.x = bw > 0 ? (pn.x - minX) * scale + offsetX : W / 2;
1715
+ pn.y = bh > 0 ? (pn.y - minY) * scale + offsetY : H / 2;
1716
+ }
1717
+ }
1718
+ // 确定性分离收尾:≤30 轮,把距离 < (r_i + r_j + 6) 的点对沿连线各推一半
1719
+ // (dist≈0 给确定性方向),推完夹回画布。保证两两中心距离 > 6、圆面不叠。
1720
+ // 奇偶轮交替扫描方向(升序/降序都由下标决定,仍无随机),避免同一批最紧
1721
+ // 点对每轮都被后面的推挤侵蚀。
1722
+ var SEPARATION_ROUNDS = 30;
1723
+ for (var round = 0; round < SEPARATION_ROUNDS; round++) {
1724
+ var moved = false;
1725
+ var forward = round % 2 === 0;
1726
+ for (var u2 = 0; u2 < count; u2++) {
1727
+ var ui = forward ? u2 : count - 1 - u2;
1728
+ for (var v2 = ui + 1; v2 < count; v2++) {
1729
+ var qu = positions[nodes[ui].id];
1730
+ var qv = positions[nodes[v2].id];
1731
+ var qx = qu.x - qv.x;
1732
+ var qy = qu.y - qv.y;
1733
+ var qdist = Math.sqrt(qx * qx + qy * qy);
1734
+ var needed = radii[ui] + radii[v2] + 6;
1735
+ if (Number.isFinite(qdist) && qdist >= needed) continue;
1736
+ if (!Number.isFinite(qdist) || qdist < 0.01) {
1737
+ qx = (ui + v2) % 2 === 0 ? 1 : -1;
1738
+ qy = (ui * 3 + v2 * 7) % 2 === 0 ? 1 : -1;
1739
+ qdist = 1;
1740
+ }
1741
+ var push = (needed - qdist) / 2;
1742
+ var ux2 = (qx / qdist) * push;
1743
+ var uy2 = (qy / qdist) * push;
1744
+ qu.x += ux2;
1745
+ qu.y += uy2;
1746
+ qv.x -= ux2;
1747
+ qv.y -= uy2;
1748
+ moved = true;
1749
+ }
1750
+ }
1751
+ for (var c2 = 0; c2 < count; c2++) {
1752
+ var pc = positions[nodes[c2].id];
1753
+ pc.x = Math.min(W - PAD, Math.max(PAD, pc.x));
1754
+ pc.y = Math.min(H - PAD, Math.max(PAD, pc.y));
1755
+ }
1756
+ if (!moved) break;
1757
+ }
1758
+ // 末段兜底:只保「两两距离 > 6」的硬下限。r_i+r_j+6 的间距在超密图(数百节点)
1759
+ // 里几何上放不下,主分离跑完后仍可能有个别点对被挤穿 6——这里用小阈值继续
1760
+ // 纯推挤(固定 ≤30 轮、同款确定性方向与夹取),把下限顶回 6 以上。
1761
+ var FLOOR_ROUNDS = 30;
1762
+ for (var round2 = 0; round2 < FLOOR_ROUNDS; round2++) {
1763
+ var moved2 = false;
1764
+ var forward2 = round2 % 2 === 0;
1765
+ for (var w = 0; w < count; w++) {
1766
+ var wi = forward2 ? w : count - 1 - w;
1767
+ for (var w2 = wi + 1; w2 < count; w2++) {
1768
+ var rw = positions[nodes[wi].id];
1769
+ var rw2 = positions[nodes[w2].id];
1770
+ var wx = rw.x - rw2.x;
1771
+ var wy = rw.y - rw2.y;
1772
+ var wdist = Math.sqrt(wx * wx + wy * wy);
1773
+ if (Number.isFinite(wdist) && wdist >= 7) continue;
1774
+ if (!Number.isFinite(wdist) || wdist < 0.01) {
1775
+ wx = (wi + w2) % 2 === 0 ? 1 : -1;
1776
+ wy = (wi * 3 + w2 * 7) % 2 === 0 ? 1 : -1;
1777
+ wdist = 1;
1778
+ }
1779
+ var wpush = (7 - wdist) / 2;
1780
+ var wdx = (wx / wdist) * wpush;
1781
+ var wdy = (wy / wdist) * wpush;
1782
+ rw.x += wdx;
1783
+ rw.y += wdy;
1784
+ rw2.x -= wdx;
1785
+ rw2.y -= wdy;
1786
+ moved2 = true;
1787
+ }
1788
+ }
1789
+ for (var c3 = 0; c3 < count; c3++) {
1790
+ var pc3 = positions[nodes[c3].id];
1791
+ pc3.x = Math.min(W - PAD, Math.max(PAD, pc3.x));
1792
+ pc3.y = Math.min(H - PAD, Math.max(PAD, pc3.y));
1793
+ }
1794
+ if (!moved2) break;
1795
+ }
1796
+ return positions;
1797
+ }
1798
+
1799
+ // ── 标签去重叠(0.2.3 实测反馈:节点被力导向挤在中间后,十来个标签全叠在一起)──
1800
+ // forceLayout 之后、渲染之前算一次确定性排布:无 Math.random、同一份数据两次
1801
+ // 调用结果完全一致。输入 nodes + layout + nodeRadiusOf(+ 强制画标签的节点 id
1802
+ // 清单),输出 id → { x, y, anchor, text, forced } 或 null(四锚皆撞不画)。
1803
+ // 字号 10px(.dshi_nodeLabel):ASCII 按 6px、CJK/全角(以及其余非 ASCII)按
1804
+ // 10px 估宽,再加 4px 余量;高度按 12px。
1805
+ var LABEL_CHAR_WIDE = 10;
1806
+ var LABEL_CHAR_NARROW = 6;
1807
+ var LABEL_MARGIN = 4;
1808
+ var LABEL_HEIGHT = 12;
1809
+ var LABEL_MAX_WIDTH = 120;
1810
+ var LABEL_GAP = 2; // 标签矩形之间至少留 2px 间距
1811
+ var LABEL_NODE_PAD = 2; // 节点圆用 (x±(r+2), y±(r+2)) 方框近似
1812
+ // 0.3:SVG viewBox 尺寸唯一事实来源(GraphTab 的 viewBox 与标签画布判定共用,
1813
+ // 之前 800×380 只写在 viewBox 字符串里,标签排布不知道画布边界,四角标签被裁)。
1814
+ var GRAPH_VIEW_W = 800;
1815
+ var GRAPH_VIEW_H = 380;
1816
+
1817
+ // 标签矩形是否完整落在画布内(viewBox 外的部分会被 SVG 裁掉,等于看不见)。
1818
+ function labelRectInCanvas(rect) {
1819
+ return rect.x >= 0 && rect.y >= 0
1820
+ && rect.x + rect.w <= GRAPH_VIEW_W && rect.y + rect.h <= GRAPH_VIEW_H;
1821
+ }
1822
+ // 把矩形平移钳回画布内(只平移、不缩放:标签最宽 120px / 高 12px,画布
1823
+ // 800×380 装得下,异常入参保守返回 null)。返回新矩形,不改入参。
1824
+ function clampLabelRectToCanvas(rect) {
1825
+ if (rect.w > GRAPH_VIEW_W || rect.h > GRAPH_VIEW_H) return null;
1826
+ var x = Math.min(Math.max(rect.x, 0), GRAPH_VIEW_W - rect.w);
1827
+ var y = Math.min(Math.max(rect.y, 0), GRAPH_VIEW_H - rect.h);
1828
+ if (x === rect.x && y === rect.y) return rect;
1829
+ return { x: x, y: y, w: rect.w, h: rect.h };
1830
+ }
1831
+ // 从(可能被钳回后的)矩形反推文本锚点坐标:与 labelRectOf 的展开方向互逆。
1832
+ function labelAnchorFromRect(rect, anchorKind) {
1833
+ return {
1834
+ x: anchorKind === "end" ? rect.x + rect.w : anchorKind === "middle" ? rect.x + rect.w / 2 : rect.x,
1835
+ y: rect.y + rect.h / 2,
1836
+ anchor: anchorKind
1837
+ };
1838
+ }
1839
+
1840
+ function estimateLabelWidth(text) {
1841
+ var width = LABEL_MARGIN;
1842
+ for (var i = 0; i < text.length; i++) {
1843
+ width += text.charCodeAt(i) < 0x80 ? LABEL_CHAR_NARROW : LABEL_CHAR_WIDE;
1844
+ }
1845
+ return width;
1846
+ }
1847
+
1848
+ // 估算宽度超过 120px 时按字符累加截断并补「…」;高代理项不收尾,避免在半个字上切。
1849
+ function truncateLabelText(title) {
1850
+ if (estimateLabelWidth(title) <= LABEL_MAX_WIDTH) return title;
1851
+ var kept = "";
1852
+ for (var i = 0; i < title.length; i++) {
1853
+ var code = title.charCodeAt(i);
1854
+ if (code >= 0xd800 && code <= 0xdbff) continue;
1855
+ if (estimateLabelWidth(title.slice(0, i + 1) + "…") > LABEL_MAX_WIDTH) break;
1856
+ kept = title.slice(0, i + 1);
1857
+ }
1858
+ return kept + "…";
1859
+ }
1860
+
1861
+ // 标签矩形:锚点 y 视作垂直居中(上下各 6px),x 按 text-anchor 方向展开。
1862
+ function labelRectOf(anchor, width) {
1863
+ var x = anchor.anchor === "end" ? anchor.x - width
1864
+ : anchor.anchor === "middle" ? anchor.x - width / 2 : anchor.x;
1865
+ return { x: x, y: anchor.y - LABEL_HEIGHT / 2, w: width, h: LABEL_HEIGHT };
1866
+ }
1867
+
1868
+ // 矩形相交;gap>0 时两矩形净距不足 gap 也算相交(标签之间的 2px 间距)。
1869
+ function rectsCollide(a, b, gap) {
1870
+ return !(a.x >= b.x + b.w + gap || b.x >= a.x + a.w + gap
1871
+ || a.y >= b.y + b.h + gap || b.y >= a.y + a.h + gap);
1872
+ }
1873
+
1874
+ // 度数读取口径与 nodeRadiusOf 一致(raw.degree,非数字按 0)。
1875
+ function nodeDegreeOf(node) {
1876
+ var raw = node && node.raw;
1877
+ var degree = raw ? Number(raw.degree) : 0;
1878
+ return Number.isFinite(degree) && degree > 0 ? degree : 0;
1879
+ }
1880
+
1881
+ // 四个候选锚点:右侧(左对齐)、左侧(end 对齐)、下方(居中)、上方(居中)。
1882
+ function labelAnchorsOf(position, radius) {
1883
+ return [
1884
+ { x: position.x + radius + 4, y: position.y + 4, anchor: "start" },
1885
+ { x: position.x - radius - 4, y: position.y + 4, anchor: "end" },
1886
+ { x: position.x, y: position.y + radius + 14, anchor: "middle" },
1887
+ { x: position.x, y: position.y - radius - 8, anchor: "middle" }
1888
+ ];
1889
+ }
1890
+
1891
+ function labelLayoutOf(nodes, layout, radiusOf, forcedIds) {
1892
+ var placements = {};
1893
+ var count = Array.isArray(nodes) ? nodes.length : 0;
1894
+ if (count === 0) return placements;
1895
+ var forced = {};
1896
+ if (Array.isArray(forcedIds)) {
1897
+ for (var f = 0; f < forcedIds.length; f++) {
1898
+ if (forcedIds[f] !== null && forcedIds[f] !== undefined) forced[String(forcedIds[f])] = true;
1899
+ }
1900
+ }
1901
+ // 所有节点圆的方框近似都参与碰撞判定
1902
+ var nodeBoxes = [];
1903
+ for (var n0 = 0; n0 < count; n0++) {
1904
+ var pos0 = layout[nodes[n0].id];
1905
+ if (!pos0) continue;
1906
+ var pad0 = radiusOf(nodes[n0]) + LABEL_NODE_PAD;
1907
+ nodeBoxes.push({ x: pos0.x - pad0, y: pos0.y - pad0, w: pad0 * 2, h: pad0 * 2 });
1908
+ }
1909
+ // 排序:度降序,再 id 升序——度大的节点先挑位,标签顺序与数据顺序解耦
1910
+ var order = nodes.slice().sort(function (a, b) {
1911
+ var byDegree = nodeDegreeOf(b) - nodeDegreeOf(a);
1912
+ if (byDegree !== 0) return byDegree;
1913
+ var ai = String(a.id);
1914
+ var bi = String(b.id);
1915
+ return ai < bi ? -1 : ai > bi ? 1 : 0;
1916
+ });
1917
+ var placedRects = [];
1918
+ for (var i = 0; i < order.length; i++) {
1919
+ var node = order[i];
1920
+ var id = String(node.id);
1921
+ if (forced[id]) continue; // 强制标签最后单独画,不占普通排布
1922
+ var position = layout[node.id];
1923
+ if (!position) { placements[id] = null; continue; }
1924
+ var radius = radiusOf(node);
1925
+ var text = truncateLabelText(node.title);
1926
+ var width = estimateLabelWidth(text);
1927
+ var anchors = labelAnchorsOf(position, radius);
1928
+ var chosen = null;
1929
+ for (var a = 0; a < anchors.length && chosen === null; a++) {
1930
+ var rect = labelRectOf(anchors[a], width);
1931
+ // 0.3:画布边界纳入锚点判定——viewBox 外的矩形再干净也看不见。
1932
+ // 每个锚点先试原位(须完整在画布内),不行再试平移钳回画布后的位置;
1933
+ // 两条路都过碰撞检查,「标签两两不相交、不压节点圆」的承诺不变。
1934
+ var candidates = [];
1935
+ if (labelRectInCanvas(rect)) candidates.push({ rect: rect, anchor: anchors[a] });
1936
+ var clamped = clampLabelRectToCanvas(rect);
1937
+ if (clamped !== null && clamped !== rect) candidates.push({ rect: clamped, anchor: labelAnchorFromRect(clamped, anchors[a].anchor) });
1938
+ for (var c = 0; c < candidates.length; c++) {
1939
+ var candRect = candidates[c].rect;
1940
+ var hit = false;
1941
+ for (var p = 0; p < placedRects.length; p++) {
1942
+ if (rectsCollide(candRect, placedRects[p], LABEL_GAP)) { hit = true; break; }
1943
+ }
1944
+ for (var b = 0; !hit && b < nodeBoxes.length; b++) {
1945
+ if (rectsCollide(candRect, nodeBoxes[b], 0)) { hit = true; break; }
1946
+ }
1947
+ if (!hit) { chosen = candidates[c]; break; }
1948
+ }
1949
+ }
1950
+ if (!chosen) { placements[id] = null; continue; } // 四锚(含钳回位置)皆撞:不渲染该标签
1951
+ placedRects.push(chosen.rect);
1952
+ placements[id] = {
1953
+ x: chosen.anchor.x, y: chosen.anchor.y, anchor: chosen.anchor.anchor,
1954
+ text: text, width: width, forced: false
1955
+ };
1956
+ }
1957
+ // hover / 选中节点的标签永远画:强制右侧、不参与碰撞判定、渲染在最上层。
1958
+ // 0.3:贴右缘时同样把矩形钳回画布内(只平移),不参与碰撞判定的口径不变。
1959
+ for (var j = 0; j < order.length; j++) {
1960
+ var node2 = order[j];
1961
+ var id2 = String(node2.id);
1962
+ if (!forced[id2]) continue;
1963
+ var position2 = layout[node2.id];
1964
+ if (!position2) { placements[id2] = null; continue; }
1965
+ var radius2 = radiusOf(node2);
1966
+ var text2 = truncateLabelText(node2.title);
1967
+ var width2 = estimateLabelWidth(text2);
1968
+ var anchor2 = { x: position2.x + radius2 + 4, y: position2.y + 4, anchor: "start" };
1969
+ var rect2 = clampLabelRectToCanvas(labelRectOf(anchor2, width2));
1970
+ var anchorOut = rect2 === null ? anchor2 : labelAnchorFromRect(rect2, "start");
1971
+ placements[id2] = {
1972
+ x: anchorOut.x, y: anchorOut.y, anchor: "start",
1973
+ text: text2, width: width2, forced: true
1974
+ };
1975
+ }
1976
+ return placements;
1977
+ }
1978
+
1979
+ // hover 邻居高亮的邻接表:id → 直接邻居 id 集合。
1980
+ function adjacencyOf(normalized) {
1981
+ var adj = {};
1982
+ for (var i = 0; i < normalized.nodes.length; i++) adj[normalized.nodes[i].id] = {};
1983
+ for (var j = 0; j < normalized.edges.length; j++) {
1984
+ var from = normalized.edges[j].from;
1985
+ var to = normalized.edges[j].to;
1986
+ if (from === to || !adj[from] || !adj[to]) continue;
1987
+ adj[from][to] = true;
1988
+ adj[to][from] = true;
1989
+ }
1990
+ return adj;
1991
+ }
1992
+
1395
1993
  function GraphTab(props) {
1396
1994
  var state = useState(null);
1397
1995
  var graph = state[0];
@@ -1405,6 +2003,21 @@ window.__ModuleLoader__.load({
1405
2003
  var viewState = useState({ x: 0, y: 0, k: 1 });
1406
2004
  var view = viewState[0];
1407
2005
  var setView = viewState[1];
2006
+ // hover 邻居高亮:当前悬停的节点 id(离开即置 null)。
2007
+ var hoverState = useState(null);
2008
+ var hoverId = hoverState[0];
2009
+ var setHoverId = hoverState[1];
2010
+ // 搜索定位:输入框文本 + 无匹配提示。
2011
+ var searchState = useState("");
2012
+ var search = searchState[0];
2013
+ var setSearch = searchState[1];
2014
+ var searchMissState = useState(false);
2015
+ var searchMiss = searchMissState[0];
2016
+ var setSearchMiss = searchMissState[1];
2017
+ // P1-2:本 tab 的会话守卫 holder(新 state 一律追加在既有 state 之后)。
2018
+ var tabGuardState = useState({ sessionId: props.sessionId, gen: 0 });
2019
+ var tabGuard = makeTabSessionGuard(props, tabGuardState[0]);
2020
+ tabGuard.track(); // 每次渲染同步:会话一换,在途响应即刻过期
1408
2021
  var dragRef = useRef(null);
1409
2022
  var wrapRef = useRef(null);
1410
2023
  // F7:只读态(另一实例在写)写按钮置灰;F4:时间线跳转目标(type 必须是 spark)。
@@ -1446,22 +2059,30 @@ window.__ModuleLoader__.load({
1446
2059
  };
1447
2060
  }, [graph]);
1448
2061
  var load = async function () {
2062
+ var origin = tabGuard.mark();
1449
2063
  setError(null);
1450
2064
  try {
1451
- setGraph(await props.dsh.call("getGraph", props.sessionId, {}));
1452
- } catch (e) { setGraph(null); if (!reportSessionUnavailable(e, props, setError)) setError(e); }
2065
+ var result = await props.dsh.call("getGraph", props.sessionId, {});
2066
+ if (tabGuard.isStale(origin)) return; // P1-2:会话已切换,丢弃旧响应
2067
+ setGraph(result);
2068
+ } catch (e) {
2069
+ if (tabGuard.isStale(origin)) return;
2070
+ setGraph(null); if (!reportSessionUnavailable(e, props, setError)) setError(e);
2071
+ }
1453
2072
  };
1454
2073
  useEffect(function () { load(); }, [props.sessionId]);
1455
2074
  var normalized = useMemo(function () { return graph ? normalizeGraph(graph) : { nodes: [], edges: [] }; }, [graph]);
1456
- var layout = useMemo(function () {
1457
- var positions = {};
1458
- var count = normalized.nodes.length;
1459
- for (var i = 0; i < count; i++) {
1460
- var angle = (2 * Math.PI * i) / Math.max(1, count) - Math.PI / 2;
1461
- positions[normalized.nodes[i].id] = { x: 400 + 260 * Math.cos(angle), y: 190 + 140 * Math.sin(angle) };
1462
- }
1463
- return positions;
1464
- }, [normalized]);
2075
+ // 力导向布局:normalized 不变就不重算。邻居表只服务 hover 高亮。
2076
+ var layout = useMemo(function () { return forceLayout(normalized.nodes, normalized.edges); }, [normalized]);
2077
+ var adjacency = useMemo(function () { return adjacencyOf(normalized); }, [normalized]);
2078
+ // 标签去重叠排布:normalized 不变就不重算;hover / 选中变化只重排一次
2079
+ // (强制标签不参与碰撞,普通标签位置不受 hover 抖动影响——只受障碍集影响)。
2080
+ var labelLayout = useMemo(function () {
2081
+ var forcedIds = [];
2082
+ if (hoverId !== null && hoverId !== undefined) forcedIds.push(hoverId);
2083
+ if (selected && selected.id !== hoverId) forcedIds.push(selected.id);
2084
+ return labelLayoutOf(normalized.nodes, layout, nodeRadiusOf, forcedIds);
2085
+ }, [normalized, layout, hoverId, selected]);
1465
2086
  // F4 时间线跳转:目标卡在图里 → 选中节点;不在(已删 / 已归档)→ 降级提示,
1466
2087
  // 不报错、不发必然失败的 RPC。deps 带 normalized:图谱刷新到货后重跑。
1467
2088
  // 跳转目标消费一次(consumed 标记,审查 P3①):同一 seq 只处理一次,用户
@@ -1496,10 +2117,28 @@ window.__ModuleLoader__.load({
1496
2117
  var zoomBy = function (factor) {
1497
2118
  setView({ x: view.x, y: view.y, k: Math.min(3, Math.max(0.3, view.k * factor)) });
1498
2119
  };
2120
+ // 节点类名沿用既有三态(evergreen/ephemeral/非 active/选中),颜色表达改走 circle
2121
+ // 内联 style(聚类填充 + 存续描边,reviewer q-1ba8addcbcd85a30:不新增类名)。
1499
2122
  var nodeClass = function (node) {
1500
2123
  var base = node.state !== "active" ? "dshi_nodeDim" : node.vitality === "evergreen" ? "dshi_nodeEvergreen" : "dshi_nodeEphemeral";
1501
2124
  return base + (selected && selected.id === node.id ? " dshi_nodeSel" : "");
1502
2125
  };
2126
+ // 搜索定位:忽略大小写匹配 title 与 id,回车选中第一个匹配并把它居中
2127
+ // (换算 view 让节点落在 800×380 中心,缩放保持);无匹配只提示,不动图。
2128
+ var runSearch = function () {
2129
+ var query = String(search || "").trim().toLowerCase();
2130
+ if (!query) return;
2131
+ var found = null;
2132
+ for (var i = 0; i < normalized.nodes.length; i++) {
2133
+ var node = normalized.nodes[i];
2134
+ if (node.title.toLowerCase().indexOf(query) >= 0 || node.id.toLowerCase().indexOf(query) >= 0) { found = node; break; }
2135
+ }
2136
+ if (!found) { setSearchMiss(true); return; }
2137
+ setSearchMiss(false);
2138
+ setSelected(found);
2139
+ var position = layout[found.id];
2140
+ if (position) setView({ x: 400 - position.x * view.k, y: 190 - position.y * view.k, k: view.k });
2141
+ };
1503
2142
  return h("div", { className: "dshi_card" },
1504
2143
  h("div", { className: "dshi_row" },
1505
2144
  h("span", { className: "dshi_cardTitle" }, "Spark 图谱(active)"),
@@ -1508,15 +2147,30 @@ window.__ModuleLoader__.load({
1508
2147
  h("button", { className: "dshi_btn", onClick: function () { zoomBy(1 / 1.2); } }, "缩小 −"),
1509
2148
  h("button", { className: "dshi_btn", onClick: function () { setView({ x: 0, y: 0, k: 1 }); } }, "复位")),
1510
2149
  h("div", { className: "dshi_legend" },
1511
- h("span", null, h("i", { className: "dshi_dot", style: { background: "var(--dsw-alias-state-success-primary,#1a7f37)" } }), "evergreen"),
1512
- h("span", null, h("i", { className: "dshi_dot", style: { background: "var(--dsw-alias-state-business-primary,#3964fe)" } }), "ephemeral"),
1513
- h("span", null, h("i", { className: "dshi_dot", style: { background: "var(--dsw-alias-label-tertiary,#8b93a1)" } }), "非 active"),
2150
+ h("span", null, h("i", { className: "dshi_dot", style: { background: "transparent", border: "2px solid var(--dsw-alias-state-success-primary,#1a7f37)" } }), "evergreen"),
2151
+ h("span", null, h("i", { className: "dshi_dot", style: { background: "transparent", border: "2px solid var(--dsw-alias-state-business-primary,#3964fe)" } }), "ephemeral"),
2152
+ h("span", null, h("i", { className: "dshi_dot", style: { background: "transparent", border: "2px solid var(--dsw-alias-label-tertiary,#8b93a1)" } }), "非 active"),
2153
+ h("span", { className: "dshi_hint" }, "填充=实体聚类,描边=存续类型"),
1514
2154
  h("span", { className: "dshi_hint" }, "滚轮缩放 / 拖拽平移 / 点击节点查看详情与编辑")),
1515
2155
  ErrorBox(error),
1516
2156
  focusMiss ? h("div", { className: "dshi_roHint" }, "时间线跳转:卡片「" + shortId(focusTarget.id) + "」不在当前图谱(可能已删除或已归档)。") : null,
1517
2157
  ro ? h("div", { className: "dshi_roHint" }, READONLY_HINT_TEXT) : null,
1518
2158
  normalized.nodes.length === 0 && !error ? h("div", { className: "dshi_loading" }, graph ? "当前 scope 无 active 卡" : "加载中…") : null,
1519
- normalized.nodes.length > 0 ? h("div", {
2159
+ // C3 降级提示:超上限改用圆形静布(不再跑 O(n²) 力导向),如实告知用户。
2160
+ normalized.nodes.length > FORCE_LAYOUT_MAX_NODES ? h("div", { className: "dshi_hint" },
2161
+ "节点数 " + normalized.nodes.length + " 超过力导向布局上限(" + FORCE_LAYOUT_MAX_NODES + "),已改用圆形静布以保证面板不冻结;要恢复精细布局请缩小 scope 或归档旧卡后刷新。") : null,
2162
+ normalized.nodes.length > 0 ? h("div", { style: { display: "flex", flexDirection: "column", gap: "8px" } },
2163
+ h("div", { className: "dshi_row" },
2164
+ h("input", {
2165
+ className: "dshi_input",
2166
+ placeholder: "搜索:按标题或 id 定位",
2167
+ value: search,
2168
+ onChange: function (event) { setSearch(event.target.value); setSearchMiss(false); },
2169
+ onKeyDown: function (event) { if (event && event.key === "Enter") runSearch(); }
2170
+ }),
2171
+ h("button", { className: "dshi_btn", onClick: function () { setSearch(""); setSearchMiss(false); } }, "清除"),
2172
+ searchMiss ? h("span", { className: "dshi_hint" }, "没有匹配的卡片") : null),
2173
+ h("div", {
1520
2174
  className: "dshi_graphWrap",
1521
2175
  ref: wrapRef,
1522
2176
  onPointerDown: onPointerDown,
@@ -1524,27 +2178,74 @@ window.__ModuleLoader__.load({
1524
2178
  onPointerUp: onPointerUp,
1525
2179
  onPointerLeave: onPointerUp
1526
2180
  },
1527
- h("svg", { className: "dshi_graphSvg", viewBox: "0 0 800 380" },
2181
+ h("svg", { className: "dshi_graphSvg", viewBox: "0 0 " + GRAPH_VIEW_W + " " + GRAPH_VIEW_H },
1528
2182
  h("g", { transform: "translate(" + view.x + "," + view.y + ") scale(" + view.k + ")" },
1529
2183
  normalized.edges.map(function (edge, index) {
1530
2184
  var from = layout[edge.from];
1531
2185
  var to = layout[edge.to];
1532
2186
  if (!from || !to) return null;
1533
- return h("line", { key: "e" + index, className: "dshi_edge", x1: from.x, y1: from.y, x2: to.x, y2: to.y });
2187
+ // hover 高亮:高亮集 = 悬停节点 + 直接邻居;两端都在集内的边保持原样,
2188
+ // 其余淡出(内联 opacity + 过渡,reviewer q-1ba8addcbcd85a30)。
2189
+ var inHighlight = function (id) { return id === hoverId || Boolean(adjacency[hoverId] && adjacency[hoverId][id]); };
2190
+ var dimmed = Boolean(hoverId && !(inHighlight(edge.from) && inHighlight(edge.to)));
2191
+ return h("line", {
2192
+ key: "e" + index,
2193
+ className: "dshi_edge",
2194
+ x1: from.x, y1: from.y, x2: to.x, y2: to.y,
2195
+ style: { opacity: dimmed ? 0.25 : 1, transition: "opacity .15s" }
2196
+ });
1534
2197
  }),
1535
2198
  normalized.nodes.map(function (node) {
1536
2199
  var position = layout[node.id] || { x: 400, y: 190 };
2200
+ var nodeDim = Boolean(hoverId && hoverId !== node.id && !(adjacency[hoverId] && adjacency[hoverId][node.id]));
2201
+ var isSelected = Boolean(selected && selected.id === node.id);
2202
+ var placement = labelLayout[node.id];
1537
2203
  return h("g", {
1538
2204
  key: node.id,
1539
2205
  className: "dshi_graphNode",
2206
+ style: { opacity: nodeDim ? 0.25 : 1, transition: "opacity .15s" },
2207
+ // C8(审计 P2-8):键盘可达——Tab 聚焦、Enter/Space 选中(与 pointer-up
2208
+ // 同走 setSelected)、role/aria-label 给出可访问名称(完整标题,不取
2209
+ // 截断后的可见标签)。鼠标交互(pointer 三件套与 hover 语义)不动。
2210
+ tabIndex: 0,
2211
+ role: "button",
2212
+ "aria-label": node.title,
2213
+ onPointerEnter: function () { setHoverId(node.id); },
2214
+ onPointerLeave: function () { setHoverId(null); },
1540
2215
  onPointerUp: function () {
1541
2216
  if (dragRef.current && dragRef.current.moved) return;
1542
2217
  setSelected(node);
2218
+ },
2219
+ onKeyDown: function (event) {
2220
+ if (!event) return;
2221
+ if (event.key !== "Enter" && event.key !== " " && event.key !== "Spacebar") return;
2222
+ if (typeof event.preventDefault === "function") event.preventDefault();
2223
+ setSelected(node);
1543
2224
  }
1544
2225
  },
1545
- h("circle", { className: nodeClass(node), cx: position.x, cy: position.y, r: 14 }),
1546
- h("text", { className: "dshi_nodeLabel", x: position.x + 18, y: position.y + 4 }, node.title.slice(0, 24)));
1547
- }))))
2226
+ h("circle", {
2227
+ className: nodeClass(node),
2228
+ cx: position.x, cy: position.y, r: nodeRadiusOf(node),
2229
+ // 填充=实体聚类(哈希→6 色,无实体中性色);描边=存续类型,选中时让位红描边
2230
+ style: {
2231
+ fill: clusterFillOf(node),
2232
+ stroke: isSelected ? "var(--dsw-alias-state-error-primary,#f85149)" : vitalityStrokeOf(node),
2233
+ strokeWidth: isSelected ? 2 : 2.5
2234
+ }
2235
+ }),
2236
+ // 去重叠后的标签:完整标题进 <title>(SVG 原生 tooltip),可见文本
2237
+ // 是截断后的 text;四锚皆撞的节点(placement 为 null)不渲染标签。
2238
+ placement && !placement.forced ? h("text",
2239
+ { className: "dshi_nodeLabel", x: placement.x, y: placement.y, textAnchor: placement.anchor },
2240
+ h("title", null, node.title), placement.text) : null);
2241
+ }),
2242
+ // hover / 选中节点的标签强制画在最上层:右侧锚点、不参与碰撞判定。
2243
+ normalized.nodes.map(function (node) {
2244
+ var placement = labelLayout[node.id];
2245
+ if (!placement || !placement.forced) return null;
2246
+ return h("text", { key: "label-" + node.id, className: "dshi_nodeLabel", x: placement.x, y: placement.y, textAnchor: placement.anchor },
2247
+ h("title", null, node.title), placement.text);
2248
+ })))))
1548
2249
  : null,
1549
2250
  selected ? h(NodeDetail, { node: selected, nodes: normalized.nodes, edges: normalized.edges, dsh: props.dsh, sessionId: props.sessionId, readOnly: ro, onClose: function () { setSelected(null); }, onSaved: load }) : null);
1550
2251
  }
@@ -1553,6 +2254,14 @@ window.__ModuleLoader__.load({
1553
2254
  var STATE_LABELS = { active: "生效中", archived: "已归档", superseded: "已被替代" };
1554
2255
 
1555
2256
  // spark_read / spark_update 的 links 形状:[{ target, rel }],target 是另一张卡的 id。
2257
+ // rel 归一:null/undefined/空串(含纯空白)一律归成 "related"——服务端要求
2258
+ // rel 是 1..64 字符串,历史脏数据在读取时就地修好,保存时自然带上合法关系名;
2259
+ // 任何一条连线都不许静默丢掉。
2260
+ function normalizeLinkRel(rel) {
2261
+ var text = rel === undefined || rel === null ? "" : String(rel);
2262
+ text = text.trim();
2263
+ return text === "" ? "related" : text;
2264
+ }
1556
2265
  function cardLinksOf(card) {
1557
2266
  var raw = card && card.links;
1558
2267
  if (!Array.isArray(raw)) return [];
@@ -1560,10 +2269,10 @@ window.__ModuleLoader__.load({
1560
2269
  for (var i = 0; i < raw.length; i++) {
1561
2270
  var item = raw[i];
1562
2271
  if (!item) continue;
1563
- if (typeof item === "string") { out.push({ target: item, rel: null }); continue; }
2272
+ if (typeof item === "string") { out.push({ target: item, rel: "related" }); continue; }
1564
2273
  var target = String(item.target ?? item.id ?? "");
1565
2274
  if (!target) continue;
1566
- out.push({ target: target, rel: item.rel === undefined ? null : item.rel });
2275
+ out.push({ target: target, rel: normalizeLinkRel(item.rel) });
1567
2276
  }
1568
2277
  return out;
1569
2278
  }
@@ -1697,7 +2406,8 @@ window.__ModuleLoader__.load({
1697
2406
  var duplicated = false;
1698
2407
  for (var i = 0; i < links.length; i++) if (links[i].target === target) duplicated = true;
1699
2408
  if (duplicated) return;
1700
- var next = links.concat([{ target: target, rel: linkRel ? String(linkRel) : null }]);
2409
+ // 空关系名不再发 null:留空按 related 落库(服务端要求 rel 是 1..64 字符串)。
2410
+ var next = links.concat([{ target: target, rel: normalizeLinkRel(linkRel) }]);
1701
2411
  setCard(function (prev) {
1702
2412
  var base = prev && typeof prev === "object" ? prev : {};
1703
2413
  return assign({}, base, { links: next });
@@ -1716,11 +2426,19 @@ window.__ModuleLoader__.load({
1716
2426
  };
1717
2427
  var saveLinks = async function () {
1718
2428
  if (!card) return;
2429
+ // 提交前本地校验:rel 去首尾空白后为空填 related;超过 64 个 UTF-16 字
2430
+ // 不发请求,直接给人话错误(服务端要求 rel 是 1..64 字符串)。
2431
+ var checked = [];
2432
+ for (var i = 0; i < links.length; i++) {
2433
+ var rel = normalizeLinkRel(links[i].rel);
2434
+ if (rel.length > 64) { setLinksError(new Error("关系名最多 64 个字")); return; }
2435
+ checked.push({ target: links[i].target, rel: rel });
2436
+ }
1719
2437
  setLinksBusy(true);
1720
2438
  setLinksError(null);
1721
2439
  setLinksOk(null);
1722
2440
  try {
1723
- var args = { id: node.id, patch: { links: links } };
2441
+ var args = { id: node.id, patch: { links: checked } };
1724
2442
  if (card.revision !== undefined && card.revision !== null) args.expectedRevision = card.revision;
1725
2443
  await props.dsh.call("executeTool", props.sessionId, { name: "spark_update", args: args });
1726
2444
  setLinksOk("连线已保存");
@@ -1823,15 +2541,15 @@ window.__ModuleLoader__.load({
1823
2541
  })),
1824
2542
  h("input", {
1825
2543
  className: "dshi_input",
1826
- placeholder: "关系名(可空,如 related)",
2544
+ placeholder: "关系名(留空自动记为 related)",
1827
2545
  value: linkRel,
1828
2546
  onChange: function (event) { setLinkRel(event.target.value); }
1829
2547
  }),
1830
2548
  h("button", { className: "dshi_btn", disabled: !linkTarget || ro, onClick: addLink }, "添加连线"),
1831
2549
  h("button", { className: "dshi_btn dshi_btnPrimary", disabled: linksBusy || !card || ro, onClick: saveLinks }, linksBusy ? "保存中…" : "保存连线"))),
1832
2550
 
1833
- // 卡片内容:只改 spark 卡片本身。人设卡 / 记忆核心在「记忆 L0/L1」页,
1834
- // 主题在「L3/topic 记忆管理」页——这里不再混进那四个记忆工具。
2551
+ // 卡片内容:只改 spark 卡片本身。人设卡 / 记忆核心在「记忆内容」页,
2552
+ // 主题在「专题」页——这里不再混进那四个记忆工具。
1835
2553
  h("div", { className: "dshi_card" },
1836
2554
  h("div", { className: "dshi_row" },
1837
2555
  h("span", { className: "dshi_cardTitle" }, "卡片内容"),
@@ -1860,64 +2578,38 @@ window.__ModuleLoader__.load({
1860
2578
  : null,
1861
2579
  h("option", { value: "evergreen" }, "长期卡(evergreen)"),
1862
2580
  h("option", { value: "ephemeral" }, "短期卡(ephemeral)"))),
1863
- h("div", { className: "dshi_hint" }, "保存走版本校验:别处刚改过这张卡会提示冲突,点「重新读取」再改。人设卡 / 记忆核心在「记忆 L0/L1」页改,主题在「L3/topic 记忆管理」页改。"))));
2581
+ h("div", { className: "dshi_hint" }, "保存走版本校验:别处刚改过这张卡会提示冲突,点「重新读取」再改。人设卡 / 记忆核心在「记忆内容」页改,主题在「专题」页改。"))));
1864
2582
  }
1865
2583
 
1866
- // ── Q-A:cluster 候选「合并进主题」辅助 ──────────────────────────────────
2584
+ // ── 遗忘页辅助 ──────────────────────────────────────────────────────────
1867
2585
  // revision token:executeTool memory_list_topics / memory_read 返回
1868
2586
  // `shiori-r1.<base64url>.<sha256>`(src/service/index.mjs tokenFor/parseToken)。
1869
- // legacy 主题只读(updated === "legacy-unknown",服务端拒 UNSUPPORTED),必须过滤。
1870
- var LEGACY_TOPIC_UPDATED = "legacy-unknown";
1871
- function isLegacyTopicRow(row) {
1872
- if (!row || typeof row !== "object") return true;
1873
- return String(row.updated) === LEGACY_TOPIC_UPDATED;
1874
- }
2587
+ // (U6 收尾:legacy 主题概念整体删除——数据层第一批起不再产生 legacy 行,
2588
+ // isLegacyTopicRow / LEGACY_TOPIC_UPDATED 及各处过滤、提示均为死分支,已清。
2589
+ // 0.3 起合并流程裁撤:mergeBodyDraft / validateMergeFormLocal /
2590
+ // validateOrganizeProposalLocal / proposalSkeleton 一并删除。)
1875
2591
  function topicRevisionPrefix(token) {
1876
2592
  var text = String(token ?? "");
1877
2593
  return text.length > 28 ? text.slice(0, 28) + "…" : text;
1878
2594
  }
1879
- // 合并正文默认草稿:候选 evidence(sharedTerm/field)+ 源卡 id 清单;用户可编辑。
1880
- // 服务端会在 after 末尾自动追加 shiori-p3-sources 源保全块(queue.mjs buildMergeTopicDraft)。
1881
- function mergeBodyDraft(candidate) {
1882
- var evidence = candidate && typeof candidate.evidence === "object" && candidate.evidence ? candidate.evidence : {};
1883
- var term = typeof evidence.sharedTerm === "string" && evidence.sharedTerm
1884
- ? evidence.sharedTerm
1885
- : (typeof evidence.field === "string" && evidence.field ? evidence.field : "合并记忆");
1886
- var ids = Array.isArray(candidate && candidate.sources)
1887
- ? candidate.sources.map(function (s) { return String(s && s.id); }).filter(Boolean) : [];
1888
- return "\n\n## 合并记忆:" + term + "\n\n本节由面板合并流程生成,收录 " + ids.length + " 张关联记忆卡(" + ids.join(", ") + ")。请按需编辑正文。\n";
1889
- }
1890
- // 发送前的轻量预检(服务端 buildMergeTopicDraft / validatePlanTopic 仍是权威):
1891
- // 只拦 UI 能明确给出人话的常见错误,避免用户吃裸 INVALID_INPUT。
1892
- function validateMergeFormLocal(form) {
1893
- if (!form || typeof form !== "object") return "合并表单未初始化。";
1894
- if (!String(form.key || "")) return "缺少目标主题 key。";
1895
- if (!String(form.expectedRevision || "")) return "缺少主题 revision token(请重新拉取主题列表)。";
1896
- if (!String(form.title || "").trim()) return "标题不能为空。";
1897
- var summary = String(form.summary ?? "");
1898
- if (summary.includes("\n") || summary.includes("\r")) return "摘要必须单行(不得含换行)。";
1899
- if (summary.length > 60) return "摘要过长(最多 60 字符,当前 " + summary.length + ")。";
1900
- var before = String(form.before ?? "");
1901
- var after = String(form.after ?? "");
1902
- if (!after.startsWith(before)) return "合并后正文必须保留原正文(append-only):after 必须以 before 开头。";
1903
- if (after.length === before.length) return "合并后正文与原正文相同(没有任何变化),服务端会拒绝。";
1904
- return null;
1905
- }
1906
- // Q-B:候选/计划脏数据的人话错误(保留原 code,便于排查)。
2595
+ // Q-B:候选/计划脏数据的人话错误(保留原 code 便于排查)。
2596
+ // U5:服务端原文不再拼进 message 顶大红字——放 detail 字段,ErrorBox 收进
2597
+ // 默认折叠的 details。0.3 起本页只做遗忘、不再有「分析整理候选」按钮:
2598
+ // 候选操作出错指向「刷新」,计划执行冲突指向计划行的「预览遗忘计划」。
1907
2599
  function candidateActionError(error) {
1908
2600
  var code = error && error.code ? String(error.code) : "";
1909
2601
  var detail = (error && error.message) || String(error);
1910
2602
  if (code === "NOT_FOUND") {
1911
- return { code: code, message: "该候选或计划已过期:源卡可能已被合并 / 归档,或计划已不存在。请点「刷新」重新分析后再试。(原始信息:" + detail + ")" };
2603
+ return { code: code, message: "该候选已不存在:该候选或计划已过期(源卡可能已被合并 / 归档,或计划已不存在)。请点「刷新」重新读取后再试。", detail: detail };
1912
2604
  }
1913
2605
  if (code === "INVALID_INPUT") {
1914
- return { code: code, message: "服务端拒绝了这次操作:数据可能已过期(请点「刷新」重新分析),或参数未通过服务端校验。(原始信息:" + detail + ")" };
2606
+ return { code: code, message: "服务端拒绝了这次操作:候选内容可能已变化,请点「刷新」重新读取后再试。", detail: detail };
1915
2607
  }
1916
2608
  if (code === "REVISION_CONFLICT") {
1917
- return { code: code, message: "revision 冲突:该计划可能已被执行,或主题 / 队列在此期间被修改。请刷新后重新预览,不要重试旧预览。(原始信息:" + detail + ")" };
2609
+ return { code: code, message: "revision 冲突:队列已更新,不要重试旧预览(该计划可能已被执行,或专题 / 队列在此期间被修改);计划请从行内「预览遗忘计划」重新生成预览后再执行。", detail: detail };
1918
2610
  }
1919
2611
  if (code === "UNSUPPORTED") {
1920
- return { code: code, message: "服务端不支持该操作(例如 legacy 主题只读,不能作为合并目标)。(原始信息:" + detail + ")" };
2612
+ return { code: code, message: "服务端不支持该操作。", detail: detail };
1921
2613
  }
1922
2614
  return error;
1923
2615
  }
@@ -1941,8 +2633,78 @@ window.__ModuleLoader__.load({
1941
2633
  // 未知 kind / status 保留原文,绝不吞掉服务端新增的分类。
1942
2634
  var CANDIDATE_KIND_LABELS = { cluster: "集群", isolated: "孤立卡", link: "可建链接" };
1943
2635
  var CANDIDATE_STATUS_LABELS = { pending: "待处理", reviewed: "已阅", dismissed: "已忽略" };
2636
+ // U5:状态筛选条(筛选只是前端视图,协议仍发 decision=reviewed / dismissed),
2637
+ // 「已阅」分组可切回。0.3 起 kind 分组随整理三组裁撤,只剩状态筛选。
2638
+ var CANDIDATE_FILTERS = [["all", "全部"], ["pending", "待处理"], ["reviewed", "已阅"], ["dismissed", "已忽略"]];
1944
2639
  var PLAN_STATE_LABELS = { open: "待执行", executed: "已执行", superseded: "已作废" };
1945
2640
  var PLAN_KIND_LABELS = { organize: "整理", forgetting: "遗忘" };
2641
+ // U5b:预览卡标题按计划类型翻成人话;未知类型原样显示,绝不吞掉、不崩。
2642
+ // 0.2.2 归档入口(rework a2):planView.kind 恒为家族名 "organize"(服务端
2643
+ // protocol.mjs enum 只有 organize / forgetting),"archive-topic" 不在 kind enum
2644
+ // 里——专题归档卡由渲染处用发起时钉定的 preview.archiveTopic 直接给标题
2645
+ // 「专题归档」(方向在正文说明)。
2646
+ // 0.2.3 计划类型细分:planView 新增可选 proposalKind(link / merge-topic /
2647
+ // archive-topic),真实计划类型从它读;旧服务端不带该字段时回退
2648
+ // plan.kind(旧行为)。planKindOf 是唯一取值口,标题 / 正文 / 按钮一律经它。
2649
+ // (thin-core 已在 0.2.3 裁掉;link / merge-topic 标题随整理流程于 0.3 删除,
2650
+ // 遗忘预览补上人话标题。)
2651
+ var PLAN_PREVIEW_TITLES = { "forgetting": "遗忘归档" };
2652
+ function planKindOf(plan) {
2653
+ var proposal = plan && plan.proposalKind !== undefined && plan.proposalKind !== null
2654
+ ? String(plan.proposalKind) : "";
2655
+ if (proposal !== "") return proposal;
2656
+ return plan && plan.kind !== undefined && plan.kind !== null ? String(plan.kind) : "";
2657
+ }
2658
+ function planPreviewTitle(kind) {
2659
+ var text = String(kind ?? "");
2660
+ return PLAN_PREVIEW_TITLES[text] ?? text;
2661
+ }
2662
+ // U5b:候选行「理由」小字——把 evidence 翻成人话(纯展示)。evidence 缺失 /
2663
+ // 形状不对 / 未知 kind 返回 null:调用方不渲染该行,行本身绝不消失、绝不抛错。
2664
+ // 词条一律按纯文本拼接(React 文本节点,无 HTML 注入面)。
2665
+ function candidateReasonOf(candidate) {
2666
+ var kind = candidate && candidate.kind !== undefined && candidate.kind !== null ? String(candidate.kind) : "";
2667
+ var evidence = candidate && candidate.evidence
2668
+ && typeof candidate.evidence === "object" && !Array.isArray(candidate.evidence)
2669
+ ? candidate.evidence : null;
2670
+ if (evidence === null) return null;
2671
+ // 字段缺失按「空」处理;字段存在但不是数组按「形状不对」处理(返回 null)。
2672
+ var wordList = function (value) {
2673
+ if (value === undefined || value === null) return [];
2674
+ if (!Array.isArray(value)) return null;
2675
+ return value
2676
+ .filter(function (t) { return t !== null && t !== undefined && String(t) !== ""; })
2677
+ .map(function (t) { return String(t); });
2678
+ };
2679
+ var quoteList = function (words) {
2680
+ return words.map(function (w) { return "「" + w + "」"; }).join("");
2681
+ };
2682
+ if (kind === "link") {
2683
+ var entities = wordList(evidence.sharedEntities);
2684
+ var triggers = wordList(evidence.sharedTriggers);
2685
+ if (entities === null || triggers === null) return null;
2686
+ var parts = [];
2687
+ if (entities.length > 0) parts.push("两张卡都提到实体" + quoteList(entities));
2688
+ if (triggers.length > 0) parts.push("都带触发词" + quoteList(triggers));
2689
+ return parts.length > 0 ? parts.join(";") : "两张卡有共同关键词";
2690
+ }
2691
+ if (kind === "cluster") {
2692
+ var sources = candidate && Array.isArray(candidate.sources) ? candidate.sources : null;
2693
+ var field = evidence.field;
2694
+ var term = evidence.sharedTerm;
2695
+ if (sources === null || (field !== "entities" && field !== "triggers")) return null;
2696
+ if (term === undefined || term === null || String(term) === "") return null;
2697
+ var noun = field === "triggers" ? "触发词" : "实体";
2698
+ return sources.length + " 张卡都共享" + noun + "「" + String(term) + "」,可以合并成一个主题";
2699
+ }
2700
+ if (kind === "isolated") {
2701
+ var retired = wordList(evidence.ignoredRetiredTargets);
2702
+ if (retired === null) return null;
2703
+ var base = "这张卡没有和任何卡相连";
2704
+ return retired.length > 0 ? base + "(另有 " + retired.length + " 条指向已退休卡的旧连线)" : base;
2705
+ }
2706
+ return null;
2707
+ }
1946
2708
  function candidateKindLabel(kind) {
1947
2709
  var text = String(kind ?? "");
1948
2710
  return CANDIDATE_KIND_LABELS[text] ?? text;
@@ -1958,80 +2720,8 @@ window.__ModuleLoader__.load({
1958
2720
  var text = String(kind ?? "");
1959
2721
  return PLAN_KIND_LABELS[text] ?? text;
1960
2722
  }
1961
- // Q-B:preview organize 发送前的本地校验(服务端 protocol.mjs organizeProposal
1962
- // 仍是权威):拦下必然失败的死 payload(如空 links),给出中文指引,
1963
- // 不把注定 INVALID_INPUT 的请求交给服务端。形状按协议 additionalProperties:false
1964
- // 加严:多余键、rel 类型、link/merge-topic 键集齐全都本地拦下。
1965
- function validateOrganizeProposalLocal(proposal) {
1966
- if (!proposal || typeof proposal !== "object" || Array.isArray(proposal)) {
1967
- return "proposal 必须是 JSON 对象。";
1968
- }
1969
- if (proposal.kind !== "link" && proposal.kind !== "merge-topic") {
1970
- return "proposal.kind 必须是 link / merge-topic(当前 " + JSON.stringify(proposal.kind ?? null) + ")。cluster 候选可直接用「合并进主题」自动构造。";
1971
- }
1972
- if (proposal.kind === "link") {
1973
- var linkExtra = Object.keys(proposal).filter(function (k) { return k !== "kind" && k !== "links"; });
1974
- if (linkExtra.length > 0) return "proposal.link 存在多余键:" + linkExtra.join(", ") + "(协议只允许 kind / links)。";
1975
- if (!Array.isArray(proposal.links) || proposal.links.length === 0) {
1976
- return "proposal.link.links 至少需要 1 项:请先补 link 项,或改用 cluster 候选的「合并进主题」流程。";
1977
- }
1978
- for (var i = 0; i < proposal.links.length; i++) {
1979
- var link = proposal.links[i];
1980
- if (!link || typeof link !== "object" || Array.isArray(link)) {
1981
- return "proposal.links[" + i + "] 必须是对象({ id, after })。";
1982
- }
1983
- var entryExtra = Object.keys(link).filter(function (k) { return k !== "id" && k !== "after"; });
1984
- if (entryExtra.length > 0) return "proposal.links[" + i + "] 存在多余键:" + entryExtra.join(", ") + "(协议只允许 id / after)。";
1985
- if (!String(link.id ?? "")) return "proposal.links[" + i + "].id 不能为空。";
1986
- if (!Array.isArray(link.after) || link.after.length === 0) {
1987
- return "proposal.links[" + i + "].after 至少需要 1 项({ target, rel })。";
1988
- }
1989
- for (var j = 0; j < link.after.length; j++) {
1990
- var edge = link.after[j];
1991
- if (!edge || typeof edge !== "object" || Array.isArray(edge)) {
1992
- return "proposal.links[" + i + "].after[" + j + "] 必须是对象({ target, rel })。";
1993
- }
1994
- var edgeExtra = Object.keys(edge).filter(function (k) { return k !== "target" && k !== "rel"; });
1995
- if (edgeExtra.length > 0) return "proposal.links[" + i + "].after[" + j + "] 存在多余键:" + edgeExtra.join(", ") + "(协议只允许 target / rel)。";
1996
- if (!String(edge.target ?? "")) return "proposal.links[" + i + "].after[" + j + "].target 不能为空。";
1997
- if (edge.rel !== undefined && edge.rel !== null && typeof edge.rel !== "string") {
1998
- return "proposal.links[" + i + "].after[" + j + "].rel 必须是字符串或 null。";
1999
- }
2000
- }
2001
- }
2002
- }
2003
- if (proposal.kind === "merge-topic") {
2004
- var topicExtra = Object.keys(proposal).filter(function (k) { return k !== "kind" && k !== "topic"; });
2005
- if (topicExtra.length > 0) return "proposal.merge-topic 存在多余键:" + topicExtra.join(", ") + "(协议只允许 kind / topic)。";
2006
- var topic = proposal.topic;
2007
- if (!topic || typeof topic !== "object" || Array.isArray(topic)) {
2008
- return "proposal.merge-topic 必须带 topic 对象(7 键:key/expectedRevision/before/after/title/summary/updated)。";
2009
- }
2010
- var TOPIC_KEYS = ["key", "expectedRevision", "before", "after", "title", "summary", "updated"];
2011
- var missing = TOPIC_KEYS.filter(function (k) { return !Object.prototype.hasOwnProperty.call(topic, k); });
2012
- if (missing.length > 0) return "proposal.topic 缺少键:" + missing.join(", ") + "(7 键缺一不可)。";
2013
- var topicOnlyExtra = Object.keys(topic).filter(function (k) { return TOPIC_KEYS.indexOf(k) === -1; });
2014
- if (topicOnlyExtra.length > 0) return "proposal.topic 存在多余键:" + topicOnlyExtra.join(", ") + "。";
2015
- if (!String(topic.key ?? "")) return "proposal.topic.key 不能为空。";
2016
- if (!String(topic.title ?? "")) return "proposal.topic.title 不能为空。";
2017
- if (topic.expectedRevision !== null && typeof topic.expectedRevision !== "string") {
2018
- return "proposal.topic.expectedRevision 必须是字符串或 null(服务端签发的 token)。";
2019
- }
2020
- if (!String(topic.after ?? "").startsWith(String(topic.before ?? ""))) {
2021
- return "proposal.topic.after 必须保留 before 全文(append-only)。";
2022
- }
2023
- }
2024
- return null;
2025
- }
2026
- // B-Q2:按候选 kind 预填可提交的 proposal 骨架(带候选真实源卡 id)。
2027
- // cluster 候选不预填——merge-topic 需要服务端签发的 revision token,
2028
- // 文本框手写必然失败,应走「合并进主题」一键流程。
2029
- function proposalSkeleton(candidate) {
2030
- var sources = candidate && Array.isArray(candidate.sources) ? candidate.sources : [];
2031
- var first = sources[0] && sources[0].id ? String(sources[0].id) : "<源卡 id>";
2032
- var second = sources[1] && sources[1].id ? String(sources[1].id) : "<另一张卡 id>";
2033
- return JSON.stringify({ kind: "link", links: [{ id: first, after: [{ target: second, rel: "related" }] }] }, null, 2);
2034
- }
2723
+ // (0.3:validateOrganizeProposalLocal / proposalSkeleton 已随整理流程删除——
2724
+ // organize proposal 的本地校验与骨架生成不再有调用方,协议校验仍以服务端为准。)
2035
2725
 
2036
2726
  function CandidatesTab(props) {
2037
2727
  var state = useState(null);
@@ -2043,8 +2733,9 @@ window.__ModuleLoader__.load({
2043
2733
  var busyState = useState(false);
2044
2734
  var busy = busyState[0];
2045
2735
  var setBusy = busyState[1];
2046
- // B-Q2:默认留空——必红死值(空 links)等于换个地方红;点「preview organize」
2047
- // 时按候选 kind 预填可用骨架(带真实源卡 id)或指引走合并流程。
2736
+ // B-Q2 槽位保留:手动 proposal 高级调试区已随整理流程一并裁撤(0.3 只做遗忘),
2737
+ // 此 state 不再读写;下标冻结以维持老测试的 states 布局
2738
+ //(data/error/busy/proposal/preview/previewError/guard)。
2048
2739
  var proposalState = useState("");
2049
2740
  var proposal = proposalState[0];
2050
2741
  var setProposal = proposalState[1];
@@ -2060,26 +2751,24 @@ window.__ModuleLoader__.load({
2060
2751
  // 变化时 gen+1 使一切在途异步结果作废,并清空会话绑定状态。
2061
2752
  var guardState = useState({ sessionId: props.sessionId, gen: 0 });
2062
2753
  var sessionGuard = guardState[0];
2063
- // ── Q-A:合并进主题流程(新增 hook 全部排在既有 7 个之后,老测试的
2064
- // states[0..6] 布局不变)──────────────────────────────────────────────
2065
- // merge:当前走合并流程的候选 { candidateId };topics:主题列表
2066
- // { loading, error, topics, total };mergeForm:合并表单;newTopic:新建主题表单。
2067
- var mergeState = useState(null);
2068
- var merge = mergeState[0];
2069
- var setMerge = mergeState[1];
2754
+ // 0.3:整理流程裁撤后本页只做遗忘。topics 是「专题索引归档(手动)」卡的
2755
+ // 专题列表 { loading, error, topics, total }(取数逻辑沿用原合并流程,
2756
+ // 合并表单 / 新建主题不再存在)。
2070
2757
  var topicsState = useState(null);
2071
2758
  var topics = topicsState[0];
2072
2759
  var setTopics = topicsState[1];
2073
- var mergeFormState = useState(null);
2074
- var mergeForm = mergeFormState[0];
2075
- var setMergeForm = mergeFormState[1];
2076
- var newTopicState = useState({ topic: "", title: "", summary: "", busy: false, error: null });
2077
- var newTopic = newTopicState[0];
2078
- var setNewTopic = newTopicState[1];
2079
2760
  // R7 追加:候选卡片 id → 标题映射(拉不到图谱时保持空对象,行内退化成短 id)。
2080
2761
  var titlesState = useState({});
2081
2762
  var titles = titlesState[0];
2082
2763
  var setTitles = titlesState[1];
2764
+ // U5:filter:状态筛选(pending 默认——「稍后再说」后该行立即离开当前分组);
2765
+ // search:纯前端搜索(标题 / 短 id)。kind 分组折叠已随整理三组裁撤。
2766
+ var filterState = useState("pending");
2767
+ var filter = filterState[0];
2768
+ var setFilter = filterState[1];
2769
+ var searchState = useState("");
2770
+ var search = searchState[0];
2771
+ var setSearch = searchState[1];
2083
2772
  // F7:只读态(另一实例在写)——analyze / review / preview / execute 与合并
2084
2773
  // 流程全部置灰(服务端 assertHostWritable 同口径),页内黄字说明原因。
2085
2774
  var ro = props.readOnly === true;
@@ -2100,10 +2789,8 @@ window.__ModuleLoader__.load({
2100
2789
  setPreviewError(null);
2101
2790
  setError(null);
2102
2791
  setBusy(false);
2103
- // Q-A:合并流程是会话绑定的(主题列表 / 表单 / revision token 都按 scope 解析)
2104
- setMerge(null);
2792
+ // 专题列表是会话(scope)绑定的:切会话即清,等「专题索引归档」卡重新拉取
2105
2793
  setTopics(null);
2106
- setMergeForm(null);
2107
2794
  }
2108
2795
  }, [props.sessionId]);
2109
2796
 
@@ -2114,6 +2801,12 @@ window.__ModuleLoader__.load({
2114
2801
  // DTO 守卫:items / plans 只按数组渲染(对象形态不调 .length/.map)。
2115
2802
  var items = Array.isArray(data && data.items) ? data.items : [];
2116
2803
  var plans = Array.isArray(data && data.plans) ? data.plans : [];
2804
+ // 0.3:本页只做遗忘——整理类计划不再展示(「预览整理计划 / 合并进主题」
2805
+ // 入口已裁撤,遗留的 open organize 计划对用户不可执行,收起来不添乱)。
2806
+ var isForgettingPlan = function (p) {
2807
+ return Boolean(p) && (p.kind === undefined || String(p.kind) === "forgetting");
2808
+ };
2809
+ var visiblePlans = plans.filter(isForgettingPlan);
2117
2810
 
2118
2811
  var load = async function () {
2119
2812
  var origin = mark();
@@ -2190,59 +2883,31 @@ window.__ModuleLoader__.load({
2190
2883
  setBusy(false);
2191
2884
  }
2192
2885
  };
2193
- var doPreviewOrganize = function (candidateId) {
2194
- // B-Q2:空 proposal(默认态)不发送——按候选 kind 预填:link 候选给带真实
2195
- // 源卡 id 的骨架;cluster 候选指引走「合并进主题」(merge-topic 需服务端
2196
- // 签发的 revision token,文本框手写必然失败)。
2197
- var candidate = null;
2198
- for (var i = 0; i < items.length; i++) {
2199
- var c = queueItemCandidate(items[i]);
2200
- if (c && c.id !== undefined && c.id !== null && String(c.id) === String(candidateId)) {
2201
- candidate = c;
2202
- break;
2203
- }
2204
- }
2205
- var text = String(proposal ?? "");
2206
- if (text.trim() === "") {
2207
- setPreview(null);
2208
- if (candidate && String(candidate.kind) === "cluster") {
2209
- setPreviewError({ code: "ui/use-merge-flow", message: "cluster 候选请使用「合并进主题」一键流程(自动选/建主题并带服务端签发的 revision token);手动 merge-topic 需要真实 token,不在文本框手写。" });
2210
- return;
2211
- }
2212
- setProposal(proposalSkeleton(candidate));
2213
- setPreviewError({ code: "ui/proposal-prefilled", message: "已按该候选预填 link 骨架(源卡 id 来自候选)。请确认 target 是另一张真实卡 id 后,再点「preview organize」发送。" });
2214
- return;
2215
- }
2216
- var parsed;
2217
- try {
2218
- parsed = JSON.parse(text);
2219
- } catch (e) {
2220
- setPreview(null);
2221
- setPreviewError({ code: "ui/invalid-json", message: "proposal JSON 解析失败:" + e.message });
2222
- return;
2223
- }
2224
- // Q-B:死 payload(如空 links)在本地拦下,不发必然失败的 RPC。
2225
- var problem = validateOrganizeProposalLocal(parsed);
2226
- if (problem) {
2227
- setPreview(null);
2228
- setPreviewError({ code: "ui/invalid-proposal", message: problem });
2229
- return;
2230
- }
2886
+ var doPreviewForgetting = function (planId) {
2231
2887
  setPreviewError(null);
2232
2888
  var origin = mark();
2233
2889
  guardPreview(async function () {
2234
- var result = await props.dsh.call("previewPlan", props.sessionId, withRevision({ kind: "organize", candidateId: candidateId, proposal: parsed, operationId: newId() }));
2890
+ var result = await props.dsh.call("previewPlan", props.sessionId, { kind: "forgetting", planId: planId });
2235
2891
  if (isStale(origin)) return;
2236
- setPreview({ sessionId: props.sessionId, plan: result });
2892
+ setPreview({ sessionId: props.sessionId, plan: result, targetId: String(planId) });
2237
2893
  });
2238
2894
  };
2239
- var doPreviewForgetting = function (planId) {
2895
+ // 0.2.2 归档入口:专题行「移出索引 / 恢复到索引」共用 archive-topic 计划
2896
+ // (服务端 previewPlan 新入参 { kind:'archive-topic', topicKey, archive },返回与
2897
+ // organize 相同的 plan 视图;本组件不发明新 RPC)。预览落既有 preview 状态,
2898
+ // targetId 用 topicKey;方向与 topicKey 随调用钉进 preview(服务端 plan 视图不保证
2899
+ // 回显入参),供确认卡文案与 doExecute 成功后的列表刷新使用。出错走 guardPreview
2900
+ // 既有的 ErrorBox 路径。该调用不涉及候选队列,不带 expectedQueueRevision / operationId。
2901
+ var doArchiveTopicPreview = function (row, archive) {
2902
+ var key = String((row && row.key) ?? "");
2903
+ if (!key) return;
2904
+ var archiveFlag = archive === true;
2240
2905
  setPreviewError(null);
2241
2906
  var origin = mark();
2242
2907
  guardPreview(async function () {
2243
- var result = await props.dsh.call("previewPlan", props.sessionId, { kind: "forgetting", planId: planId });
2908
+ var result = await props.dsh.call("previewPlan", props.sessionId, { kind: "archive-topic", topicKey: key, archive: archiveFlag });
2244
2909
  if (isStale(origin)) return;
2245
- setPreview({ sessionId: props.sessionId, plan: result });
2910
+ setPreview({ sessionId: props.sessionId, plan: result, targetId: key, topicKey: key, archiveTopic: archiveFlag });
2246
2911
  });
2247
2912
  };
2248
2913
  // R4:确认执行前校验 preview 钉住的来源会话与当前会话一致,不一致拒绝发送
@@ -2260,349 +2925,363 @@ window.__ModuleLoader__.load({
2260
2925
  return Promise.resolve();
2261
2926
  }
2262
2927
  var plan = preview.plan;
2928
+ // 0.2.2 归档入口(rework a2):planView.kind 恒为家族名 "organize",不能用
2929
+ // plan.kind === "archive-topic" 判定;改用发起时钉定的 preview.archiveTopic
2930
+ //(发起入口 doArchiveTopicPreview 无条件钉定,false 也算钉定——恢复方向)。
2931
+ var wasArchivePreview = Boolean(preview.archiveTopic !== undefined && preview.archiveTopic !== null);
2263
2932
  return guard(async function () {
2264
2933
  await props.dsh.call("executePlan", props.sessionId, { planId: plan.planId, planDigest: plan.planDigest, operationId: newId(), confirmed: true });
2265
- // 执行成功:收起合并流程(guard 随后 load() 刷新队列 revision / 候选 / 计划;
2266
- // 图谱与记忆 L1 视图在切到对应 tab 时按会话重新拉取)。
2267
- setMerge(null);
2268
- setMergeForm(null);
2934
+ // 0.2.2 归档入口:专题归档执行成功后专题的 archived 状态已变,重新拉
2935
+ // memory_list_topics 刷新列表,并清掉预览(失败路径不走这里,错误由 guard
2936
+ // 的 catch 经 ErrorBox 展示,预览保留)。普通 forgetting 预览不刷新专题
2937
+ // 列表,行为与既往一致。
2938
+ if (wasArchivePreview) {
2939
+ loadTopics();
2940
+ setPreview(null);
2941
+ }
2269
2942
  });
2270
2943
  };
2271
2944
  var actionsDisabled = busy || !loaded || ro;
2272
2945
 
2273
- // ── Q-A:cluster 候选「合并进主题」流程 ────────────────────────────────
2274
- // 全部 RPC 经 props.dsh.call(ctx.get('remote.shiori'));会话级失败沿用
2275
- // reportSessionUnavailable(面板层缓存,不刷 tab 红字)。
2946
+ // ── 专题索引归档(手动):原合并流程的专题列表取数保留,供「移出索引 /
2947
+ // 恢复到索引」使用;合并表单 / 新建主题不再存在(0.3 起本页只做遗忘)。
2276
2948
  var loadTopics = function () {
2277
2949
  var origin = mark();
2278
2950
  setTopics({ loading: true, error: null, topics: [], total: 0 });
2279
2951
  props.dsh.call("executeTool", props.sessionId, { name: "memory_list_topics", args: {} }).then(function (result) {
2280
2952
  if (isStale(origin)) return;
2281
2953
  var rows = Array.isArray(result && result.topics) ? result.topics : [];
2282
- setTopics({ loading: false, error: null, topics: rows.filter(function (t) { return !isLegacyTopicRow(t); }), total: rows.length });
2954
+ setTopics({ loading: false, error: null, topics: rows, total: rows.length });
2283
2955
  }, function (e) {
2284
2956
  if (isStale(origin)) return;
2285
2957
  setTopics({ loading: false, error: candidateActionError(e), topics: [], total: 0 });
2286
2958
  });
2287
2959
  };
2288
- var openMerge = function (candidateId) {
2289
- setMerge({ candidateId: String(candidateId) });
2290
- setMergeForm(null);
2291
- setPreviewError(null);
2292
- loadTopics();
2293
- };
2294
- var closeMerge = function () {
2295
- setMerge(null);
2296
- setMergeForm(null);
2297
- setNewTopic({ topic: "", title: "", summary: "", busy: false, error: null });
2298
- };
2299
- // 选中主题:memory_read 拿当前正文(before)与服务端权威 revision token。
2300
- // before 绝不传空串——执行端以 plan.topic.after 整体替换正文(executor 锁内
2301
- // 重读 after 一致性校验),空 before 会截断既有正文。
2302
- var openTopicForMerge = function (row) {
2303
- if (!merge) return;
2304
- var origin = mark();
2305
- var key = String(row && row.key);
2306
- setNewTopic({ topic: "", title: "", summary: "", busy: false, error: null });
2307
- props.dsh.call("executeTool", props.sessionId, { name: "memory_read", args: { topic: key } }).then(function (result) {
2308
- if (isStale(origin)) return;
2309
- var before = result && typeof result.content === "string" ? result.content : "";
2310
- var token = result && typeof result.revision === "string" && result.revision
2311
- ? result.revision
2312
- : (row && typeof row.revision === "string" ? row.revision : "");
2313
- var candidate = null;
2314
- for (var i = 0; i < items.length; i++) {
2315
- var c = queueItemCandidate(items[i]);
2316
- if (c && c.id !== undefined && c.id !== null && String(c.id) === merge.candidateId) {
2317
- candidate = c;
2318
- break;
2319
- }
2320
- }
2321
- if (candidate === null) candidate = {};
2322
- setMergeForm({
2323
- key: key,
2324
- expectedRevision: token,
2325
- tokenSource: result && result.revision ? "memory_read" : "memory_list_topics",
2326
- before: before,
2327
- after: before + mergeBodyDraft(candidate),
2328
- title: String((row && row.title) ?? ""),
2329
- summary: String((row && row.summary) ?? "").split("\n")[0].slice(0, 60),
2330
- updated: new Date().toISOString()
2331
- });
2332
- }, function (e) {
2333
- if (isStale(origin)) return;
2334
- setTopics({ loading: false, error: candidateActionError(e), topics: topics ? topics.topics : [], total: topics ? topics.total : 0 });
2335
- });
2960
+ // ── U5:筛选 / 搜索 / 就地预览(纯前端推导,协议与守卫不变)───
2961
+ // 候选人话标题:集群说共享词 + 卡数,链接说「A ↔ B」,孤立卡直接给源卡标题;
2962
+ // 都没有时退化成短 id(titles 拉不到图谱时为空对象)。
2963
+ var candidateTitleOf = function (candidate) {
2964
+ var sourceIds = candidate && Array.isArray(candidate.sources)
2965
+ ? candidate.sources.map(function (s) { return String(s && s.id); }).filter(Boolean) : [];
2966
+ var sourceTitles = sourceIds.map(function (id) { return titles[id] || shortId(id); });
2967
+ var evidence = candidate && candidate.evidence && typeof candidate.evidence === "object" ? candidate.evidence : {};
2968
+ var candidateKind = candidate && candidate.kind ? String(candidate.kind) : "";
2969
+ if (candidateKind === "cluster") {
2970
+ var sharedTerm = evidence.sharedTerm || evidence.field;
2971
+ return sharedTerm
2972
+ ? "合并「" + String(sharedTerm) + "」相关的 " + sourceIds.length + " 张卡"
2973
+ : "合并 " + sourceIds.length + " 张卡";
2974
+ }
2975
+ if (candidateKind === "link" && sourceTitles.length >= 2) return "连接:" + sourceTitles.join(" ↔ ");
2976
+ if (sourceTitles.length === 1) return sourceTitles[0];
2977
+ if (sourceTitles.length > 1) return sourceTitles.join("、");
2978
+ return null;
2336
2979
  };
2337
- // 新建主题:topic_create 成功后重新 memory_list_topics 取服务端权威 token,
2338
- // 再自动进入合并表单(不猜 token 形状)。
2339
- var submitNewTopic = function () {
2340
- if (!merge) return;
2341
- var key = String(newTopic.topic || "").trim();
2342
- var title = String(newTopic.title || "").trim();
2343
- var summary = String(newTopic.summary || "").trim();
2344
- if (!key || !title || !summary) {
2345
- setNewTopic({ topic: newTopic.topic, title: newTopic.title, summary: newTopic.summary, busy: false, error: { code: "ui/invalid-topic", message: "key / 标题 / 摘要 都必填。" } });
2346
- return;
2980
+ // 预览正文按计划类型翻人话(planKindOf:proposalKind 优先,回退 plan.kind);
2981
+ // 未知类型返回空数组(原始 diff 都在「原始信息」里)。
2982
+ // 0.2.2 归档入口(rework a2):planView.kind 恒为家族名 "organize"(服务端
2983
+ // enum 无 "archive-topic"),专题归档卡改用第二参 previewInfo(发起时钉进
2984
+ // preview 状态)里的 archiveTopic 作判据:有钉定即走归档分支。0.2.3 起
2985
+ // proposalKind === "archive-topic" 也算归档;方向永远取 archiveTopic
2986
+ //(未钉定时按 false=恢复处理);topicKey 同样取钉定值,缺失时退化为通用句,
2987
+ // 绝不抛错。0.3 起本页只做遗忘:link / merge-topic 的人话分支随整理流程裁撤。
2988
+ var previewBodyLines = function (plan, previewInfo) {
2989
+ var info = previewInfo && typeof previewInfo === "object" ? previewInfo : null;
2990
+ var isArchivePreview = Boolean(info && info.archiveTopic !== undefined && info.archiveTopic !== null);
2991
+ var kind = planKindOf(plan);
2992
+ var lines = [];
2993
+ if (isArchivePreview || kind === "archive-topic") {
2994
+ var archiveDir = info.archiveTopic === true;
2995
+ var archiveKey = info.topicKey !== undefined && info.topicKey !== null
2996
+ ? String(info.topicKey)
2997
+ : String((plan && plan.topicKey) ?? "");
2998
+ var archiveVerb = archiveDir ? "移出" : "恢复到";
2999
+ lines.push(archiveKey !== ""
3000
+ ? "把专题『" + archiveKey + "』" + archiveVerb + " L1 索引"
3001
+ : "把专题" + archiveVerb + " L1 索引(明细见下方「原始信息」)");
3002
+ lines.push("正文长度不变,随时可读。");
3003
+ return lines;
2347
3004
  }
2348
- if (summary.includes("\n") || summary.includes("\r") || summary.length > 60) {
2349
- setNewTopic({ topic: newTopic.topic, title: newTopic.title, summary: newTopic.summary, busy: false, error: { code: "ui/invalid-topic", message: "摘要必须单行且不超过 60 字符。" } });
2350
- return;
3005
+ // forgetting 预览:要归档哪些卡在「原始信息」的 diff 里逐张可见。
3006
+ if (kind === "forgetting") {
3007
+ lines.push("按衰减分数把旧卡归档(每张卡的明细见下方「原始信息」)。");
3008
+ return lines;
2351
3009
  }
2352
- var origin = mark();
2353
- setNewTopic({ topic: key, title: title, summary: summary, busy: true, error: null });
2354
- props.dsh.call("executeTool", props.sessionId, { name: "topic_create", args: { topic: key, title: title, summary: summary, operationId: newId() } }).then(function () {
2355
- return props.dsh.call("executeTool", props.sessionId, { name: "memory_list_topics", args: {} });
2356
- }).then(function (listing) {
2357
- if (isStale(origin)) return;
2358
- var rows = Array.isArray(listing && listing.topics) ? listing.topics : [];
2359
- var usable = rows.filter(function (t) { return !isLegacyTopicRow(t); });
2360
- setTopics({ loading: false, error: null, topics: usable, total: rows.length });
2361
- setNewTopic({ topic: "", title: "", summary: "", busy: false, error: null });
2362
- var fresh = usable.find(function (t) { return String(t && t.key) === key; });
2363
- if (!fresh) {
2364
- setNewTopic({ topic: key, title: title, summary: summary, busy: false, error: { code: "shiori/ui-topic-missing", message: "主题已创建,但未能在主题列表中找到它(" + key + ");请刷新主题列表后手动选择。" } });
2365
- return;
2366
- }
2367
- openTopicForMerge(fresh);
2368
- }, function (e) {
2369
- if (isStale(origin)) return;
2370
- setNewTopic({ topic: key, title: title, summary: summary, busy: false, error: candidateActionError(e) });
2371
- });
3010
+ return lines;
2372
3011
  };
2373
- // 合并预览:自动构造 merge-topic proposal(7 键),带 candidateId +
2374
- // expectedQueueRevision + operationId 走 previewPlan;diff 由既有 preview 卡渲染。
2375
- var doMergePreview = function () {
2376
- if (!merge || !mergeForm) return;
2377
- var form = mergeForm;
2378
- var problem = validateMergeFormLocal(form);
2379
- if (problem) {
2380
- setPreview(null);
2381
- setPreviewError({ code: "ui/invalid-proposal", message: problem });
2382
- return;
3012
+ var statusOfItem = function (item) {
3013
+ return item && item.status ? String(item.status) : "pending";
3014
+ };
3015
+ var searchQuery = String(search ?? "").trim().toLowerCase();
3016
+ var rowVisible = function (item, candidate) {
3017
+ if (filter !== "all" && statusOfItem(item) !== filter) return false;
3018
+ if (searchQuery) {
3019
+ var id = candidate && candidate.id !== undefined && candidate.id !== null ? String(candidate.id) : "";
3020
+ var hay = ((candidateTitleOf(candidate) || "") + " " + id + " " + (id ? shortId(id) : "")).toLowerCase();
3021
+ if (hay.indexOf(searchQuery) === -1) return false;
2383
3022
  }
2384
- setPreviewError(null);
2385
- var origin = mark();
2386
- guardPreview(async function () {
2387
- var proposal = { kind: "merge-topic", topic: { key: form.key, expectedRevision: form.expectedRevision, before: form.before, after: form.after, title: form.title, summary: form.summary, updated: form.updated } };
2388
- var result = await props.dsh.call("previewPlan", props.sessionId, withRevision({ kind: "organize", candidateId: merge.candidateId, proposal: proposal, operationId: newId() }));
2389
- if (isStale(origin)) return;
2390
- setPreview({ sessionId: props.sessionId, plan: result, queueRevision: queueRevision });
3023
+ return true;
3024
+ };
3025
+ var statusCounts = { all: items.length, pending: 0, reviewed: 0, dismissed: 0 };
3026
+ items.forEach(function (item) {
3027
+ var status = statusOfItem(item);
3028
+ if (status === "pending" || status === "reviewed" || status === "dismissed") statusCounts[status] += 1;
3029
+ });
3030
+ // 预览钉定的目标(计划 id):有 targetId 且目标计划行可见 → 就地展开在
3031
+ // 该行正下方;targetId 缺失(旧状态 / 专题归档)或目标行已消失 → 回落到底部卡。
3032
+ var previewTargetId = preview && preview.targetId !== undefined && preview.targetId !== null
3033
+ ? String(preview.targetId) : null;
3034
+ var previewTargetVisible = false;
3035
+ if (previewTargetId !== null) {
3036
+ previewTargetVisible = visiblePlans.some(function (p) {
3037
+ var pid = p && p.planId !== undefined && p.planId !== null
3038
+ ? String(p.planId)
3039
+ : (p && p.id !== undefined && p.id !== null ? String(p.id) : null);
3040
+ return pid !== null && pid === previewTargetId;
2391
3041
  });
3042
+ }
3043
+ var showBottomPreview = preview !== null && preview.sessionId === props.sessionId
3044
+ && (previewTargetId === null || !previewTargetVisible);
3045
+ // 就地预览确认卡:U5b 起标题 / 正文翻人话(planPreviewTitle / previewBodyLines),
3046
+ // planId / planDigest / summary / 原始 diff 收进默认折叠的「原始信息」details
3047
+ // (link 的 JSON 不再默认铺开);确认按钮文案按 kind 区分(link 不用 danger 红)。
3048
+ // doExecute 与 queueRevision / executed / superseded 守卫一字不动。
3049
+ var renderPreviewCard = function (key) {
3050
+ if (!preview || preview.sessionId !== props.sessionId) return null;
3051
+ var plan = preview.plan;
3052
+ var planKind = planKindOf(plan);
3053
+ var planIdText = plan && plan.planId !== undefined && plan.planId !== null ? String(plan.planId) : "";
3054
+ var planDigestText = plan && plan.planDigest !== undefined && plan.planDigest !== null ? String(plan.planDigest) : "";
3055
+ var bodyLines = previewBodyLines(plan, preview);
3056
+ // Q-B:预览对应的计划若已在 plans 列表里标记 executed / superseded,执行按钮禁用
3057
+ var rowLocked = (function () {
3058
+ var row = plans.find(function (p) { return String(p && p.planId) === String(plan && plan.planId); });
3059
+ return Boolean(row && (row.executed === true || row.superseded === true));
3060
+ })();
3061
+ // 0.2.2 归档入口(rework a2):planView.kind 恒为家族名 "organize",专题归档卡
3062
+ // 以 preview.archiveTopic 是否被钉定为判据(false 也算钉定——恢复方向)。
3063
+ // 0.2.3 起 proposalKind === "archive-topic" 同样算归档卡。两者都不满足
3064
+ //(普通 organize / forgetting 预览)绝不出现归档文案。归档可逆——移出
3065
+ // 方向明示「可随时恢复」,恢复方向短句。
3066
+ var isArchivePreview = Boolean(preview && preview.archiveTopic !== undefined && preview.archiveTopic !== null);
3067
+ var isArchiveCard = isArchivePreview || planKind === "archive-topic";
3068
+ var confirmLabel = isArchiveCard ? (preview.archiveTopic === true ? "确认移出索引(可随时恢复)" : "确认恢复")
3069
+ : "确认执行";
3070
+ return h("div", { key: key, className: "dshi_itemMerge", style: { minWidth: 0 } },
3071
+ h("div", { className: "dshi_confirm", style: { marginLeft: 12 } },
3072
+ h("div", { className: "dshi_cardTitle" }, isArchiveCard ? "专题归档" : planPreviewTitle(planKind)),
3073
+ bodyLines.map(function (line, index) {
3074
+ return h("div", { key: index, className: "dshi_hint" }, line);
3075
+ }),
3076
+ // 未知 kind:翻不了人话,summary(服务端原始摘要)兜底展示,不空屏。
3077
+ bodyLines.length === 0 && plan && plan.summary ? h("div", { className: "dshi_hint" }, String(plan.summary)) : null,
3078
+ rowLocked ? h("div", { className: "dshi_hint" }, "该计划已执行或已被新预览作废(plans 列表标记),执行按钮已禁用。") : null,
3079
+ // planId / planDigest / summary / 原始 diff:默认折叠,点开才见。
3080
+ h("details", { className: "dshi_details" },
3081
+ h("summary", { className: "dshi_hint" }, "原始信息"),
3082
+ planIdText !== "" ? h("div", { className: "dshi_hint dshi_mono" }, "planId " + planIdText) : null,
3083
+ planDigestText !== "" ? h("div", { className: "dshi_hint dshi_mono" }, "planDigest " + planDigestText) : null,
3084
+ plan && plan.summary ? h("div", { className: "dshi_hint" }, String(plan.summary)) : null,
3085
+ Array.isArray(plan && plan.diff) && plan.diff.length > 0 ? h("div", { className: "dshi_diffBox" }, plan.diff.map(function (entry, index) {
3086
+ return h("div", { key: index, className: "dshi_item" },
3087
+ h("div", { className: "dshi_mono" }, String((entry && entry.path) ?? index)),
3088
+ h("div", { className: "dshi_hint" }, "old"),
3089
+ h("pre", { className: "dshi_pre" }, String((entry && entry.oldText) ?? "")),
3090
+ h("div", { className: "dshi_hint" }, "new"),
3091
+ h("pre", { className: "dshi_pre" }, String((entry && entry.newText) ?? "")));
3092
+ })) : h("div", { className: "dshi_hint" }, "(无 diff 条目)")),
3093
+ h("div", { className: "dshi_row" },
3094
+ h("button", {
3095
+ className: "dshi_btn dshi_btnDanger",
3096
+ disabled: busy || ro || rowLocked,
3097
+ onClick: doExecute
3098
+ }, confirmLabel),
3099
+ h("button", { className: "dshi_btn", disabled: busy, onClick: function () { setPreview(null); } }, "取消"))));
2392
3100
  };
2393
- var updateMergeForm = function (patch) {
2394
- setMergeForm(mergeForm ? assign({}, mergeForm, patch) : mergeForm);
3101
+ var renderCandidateRow = function (item, index, candidate) {
3102
+ var businessId = candidate && candidate.id !== undefined && candidate.id !== null
3103
+ ? String(candidate.id) : null;
3104
+ var key = businessId !== null ? businessId : String(index);
3105
+ var rowDisabled = actionsDisabled || businessId === null;
3106
+ var candidateTitle = candidateTitleOf(candidate);
3107
+ // U5b:标题下「理由」小字——evidence 缺失 / 形状不对 / 未知 kind 时为 null,
3108
+ // 不渲染该行(行本身绝不消失),不抛错。
3109
+ var candidateReason = candidateReasonOf(candidate);
3110
+ // U5-e:过期候选就地标注——队列是快照,源卡在面板外被改动后 revision 前进,
3111
+ // 服务端在队列 item 上投影 stale 布尔(旧扁平形状兼容读 candidate.stale)。
3112
+ // 「稍后再说」「忽略」只改 status 不校验 revision,保持可用。
3113
+ var staleRow = item.stale === true || Boolean(candidate && candidate.stale === true);
3114
+ // 0.3:整理流程裁撤后行内只剩审阅动作(协议仍发 decision=reviewed / dismissed)。
3115
+ return h("div", { key: key, className: "dshi_item" },
3116
+ h("div", { className: "dshi_itemHead" },
3117
+ h("span", null, candidateTitle || "(未识别的卡片)"),
3118
+ h("span", { className: "dshi_mono" }, businessId !== null ? shortId(businessId) : "(缺少 candidate.id)"),
3119
+ candidate && candidate.kind ? h("span", { className: "dshi_badgeDim dshi_badge" }, candidateKindLabel(candidate.kind)) : null,
3120
+ item.status ? h("span", { className: "dshi_badge" }, candidateStatusLabel(item.status)) : null,
3121
+ staleRow ? h("span", { className: "dshi_badge dshi_badgeStale", title: "该候选绑定的卡片版本与分析时不一致" }, "卡片已改") : null,
3122
+ // U5 改名:「稍后再说」(协议仍发 decision=reviewed)——只是收起来,
3123
+ // 不删除任何记忆;点击后该行立即离开「待处理」分组,可在「已阅」分组切回来。
3124
+ h("button", { className: "dshi_btn", disabled: rowDisabled, title: "只是收起来,不会删除任何记忆", onClick: function () { doReview(businessId, "reviewed"); } }, "稍后再说"),
3125
+ h("button", { className: "dshi_btn", disabled: rowDisabled, title: "把候选状态置为 dismissed", onClick: function () { doReview(businessId, "dismissed"); } }, "忽略")),
3126
+ candidateReason !== null ? h("div", { className: "dshi_hint" }, "理由:" + candidateReason) : null,
3127
+ staleRow ? h("div", { className: "dshi_hint" }, "这条候选绑定的卡片在你上次分析之后被改过") : null,
3128
+ // 原始 JSON 默认折叠:details 不写 open,铺满屏幕的长串移出主视线。
3129
+ // C4:item 是服务端快照(不可变),按引用记忆化——搜索/筛选逐键重渲不再重序列化。
3130
+ h("details", { className: "dshi_details" },
3131
+ h("summary", { className: "dshi_hint" }, "原始数据(JSON)"),
3132
+ h("pre", { className: "dshi_pre" }, stableStringifyCached(item))));
2395
3133
  };
2396
- var updateNewTopic = function (patch) {
2397
- setNewTopic(assign({}, newTopic, patch));
3134
+ var renderPlanRow = function (plan, index) {
3135
+ // 与候选行同一原则:下标只用作渲染 key,planId 缺失时禁用动作而非发下标。
3136
+ var businessPlanId = plan && plan.planId !== undefined && plan.planId !== null
3137
+ ? String(plan.planId)
3138
+ : (plan && plan.id !== undefined && plan.id !== null ? String(plan.id) : null);
3139
+ var planId = businessPlanId !== null ? businessPlanId : String(index);
3140
+ // Q-B:区分 open / executed / superseded(planStore list 投影的布尔;
3141
+ // superseded = 新预览作废旧 open 计划,P 侧 state.mjs 投影提供)。
3142
+ // operationId 仅在 DTO 提供时显示(当前投影只含 executed/superseded 布尔,向前兼容)。
3143
+ var executed = plan.executed === true;
3144
+ var superseded = plan.superseded === true;
3145
+ var executedWith = plan.executedWith ?? plan.operationId;
3146
+ var previewForThisPlan = previewTargetId !== null && businessPlanId !== null && previewTargetId === businessPlanId;
3147
+ var row = h("div", { key: planId, className: "dshi_item" },
3148
+ h("div", { className: "dshi_itemHead" },
3149
+ h("span", { className: "dshi_mono" }, businessPlanId !== null ? businessPlanId : "(缺少 planId)"),
3150
+ plan.kind ? h("span", { className: "dshi_badgeDim dshi_badge" }, planKindLabel(plan.kind)) : null,
3151
+ executed ? h("span", { className: "dshi_badge dshi_badgeWarn" }, planStateLabel("executed"))
3152
+ : superseded ? h("span", { className: "dshi_badge dshi_badgeWarn" }, planStateLabel("superseded"))
3153
+ : h("span", { className: "dshi_badgeDim dshi_badge" }, planStateLabel("open")),
3154
+ executedWith !== undefined && executedWith !== null ? h("span", { className: "dshi_hint dshi_mono" }, "op " + String(executedWith)) : null,
3155
+ executed ? null
3156
+ : h("button", { className: "dshi_btn", disabled: actionsDisabled || businessPlanId === null || superseded, onClick: function () { doPreviewForgetting(businessPlanId); } }, "预览遗忘计划")),
3157
+ executed ? h("div", { className: "dshi_hint" }, "该计划已执行:不可再次预览 / 执行;要再次遗忘请重新「分析遗忘候选」。")
3158
+ : superseded ? h("div", { className: "dshi_hint" }, "该计划已被新预览作废(superseded):不可再预览 / 执行(服务端会拒绝并报 REVISION_CONFLICT),请使用最新计划。")
3159
+ : null,
3160
+ h("details", { className: "dshi_details" },
3161
+ h("summary", { className: "dshi_hint" }, "原始数据(JSON)"),
3162
+ h("pre", { className: "dshi_pre" }, stableStringifyCached(plan)))); // C4:同候选行,按引用记忆化
3163
+ return previewForThisPlan ? [row, renderPreviewCard("preview-" + planId)] : row;
2398
3164
  };
2399
- // Q-A 合并卡渲染器:内容 / 三步状态机与原实现逐行一致,仅把卡片从「候选卡之后」
2400
- // 搬到被点击候选行的正下方(同一 dshi_items 容器内就地展开),避免按钮在列表中间、
2401
- // 控件在页面底部。候选 id 只显示前 8 位,完整 id 放 title。
2402
- var renderMergeCard = function (candidateId) {
2403
- var fullId = String(candidateId);
2404
- var shortId = fullId.slice(0, 8) + "…";
2405
- return h("div", { key: "merge-" + fullId, className: "dshi_itemMerge", style: { minWidth: 0 } },
2406
- h("div", { className: "dshi_card", style: { marginLeft: 12 } },
2407
- h("div", { className: "dshi_row" },
2408
- h("span", { className: "dshi_cardTitle", title: "候选完整 id:" + fullId }, "合并进主题(候选 " + shortId + ")"),
2409
- h("button", { className: "dshi_btn", disabled: topics !== null && topics.loading, onClick: loadTopics }, "刷新主题"),
2410
- h("button", { className: "dshi_btn", onClick: closeMerge }, "收起")),
2411
- // 步骤引导(纯展示):① 选目标主题 → ② 载入 before/token 出合并表单 → ③ after → 预览 diff → 确认执行。
2412
- // mergeForm 为空时 ① 标「进行中」(主色 badge),其余 dim;不改任何 RPC / 状态机逻辑。
2413
- h("div", { className: "dshi_hint" }, "合并流程(3 步,按当前进度高亮):"),
2414
- h("div", { className: "dshi_items" },
2415
- h("div", { className: "dshi_row" },
2416
- h("span", { className: mergeForm ? "dshi_badgeDim dshi_badge" : "dshi_badge" }, mergeForm ? "① 已完成" : "① 进行中"),
2417
- h("span", { className: "dshi_hint" }, "选择目标主题:点主题列表某行的「合并到这个主题」,或在下方新建主题后点「创建并选择」。")),
2418
- h("div", { className: "dshi_row" },
2419
- h("span", { className: "dshi_badgeDim dshi_badge" }, mergeForm ? "② 已完成" : "② 待完成"),
2420
- h("span", { className: "dshi_hint" }, "选定后自动载入 before 正文与 revision token,并出现「合并表单」。")),
2421
- h("div", { className: "dshi_row" },
2422
- h("span", { className: "dshi_badgeDim dshi_badge" }, mergeForm ? "③ 下一步" : "③ 待完成"),
2423
- h("span", { className: "dshi_hint" }, "在合并表单里编辑 after → 点「预览 diff(previewPlan)」→ 在下方确认卡里点「确认执行」。合并后源卡将 retired,不可撤销。"))),
2424
- topics === null || topics.loading ? h("div", { className: "dshi_loading" }, "主题列表加载中…") : null,
2425
- topics && topics.error ? ErrorBox(topics.error) : null,
2426
- topics && !topics.loading && !topics.error ? h("div", { className: "dshi_items" },
2427
- topics.topics.length === 0 ? h("div", { className: "dshi_hint" },
2428
- "当前 scope 没有可用的非 legacy 主题(legacy 主题只读,服务端拒绝作为合并目标)。请在下方新建主题。")
2429
- : topics.topics.map(function (row) {
2430
- var key = String(row.key ?? "");
2431
- return h("div", { key: key, className: "dshi_item" },
2432
- h("div", { className: "dshi_itemHead" },
2433
- h("span", { className: "dshi_mono" }, key),
2434
- row.title ? h("span", { className: "dshi_badgeDim dshi_badge" }, String(row.title)) : null,
2435
- row.updated ? h("span", { className: "dshi_hint" }, String(row.updated)) : null,
2436
- row.revision ? h("span", { className: "dshi_hint dshi_mono" }, "rev " + topicRevisionPrefix(row.revision)) : null,
2437
- // D:legacy 行只读(服务端拒 UNSUPPORTED)——加 title 说明但不禁用按钮;
2438
- // loadTopics 通常已过滤 legacy 行,这里保留防御性提示。
2439
- h("button", {
2440
- className: "dshi_btn",
2441
- disabled: busy || ro,
2442
- title: isLegacyTopicRow(row) ? "legacy 主题只读,不能作为合并目标" : undefined,
2443
- onClick: function () { openTopicForMerge(row); }
2444
- }, "合并到这个主题")));
2445
- })) : null,
2446
- // B/C:未选定目标主题时的中性提示(不是错误,不用 ErrorBox / 红色);选定后换成下一步提示。
2447
- mergeForm ? h("div", { className: "dshi_hint", style: { fontWeight: 600 } },
2448
- "已在合并表单中:编辑 after 后点「预览 diff(previewPlan)」,再在下方确认卡里确认执行。")
2449
- : h("div", { className: "dshi_hint", style: { fontWeight: 600 } },
2450
- "还没有选择目标主题:先点上方某行「合并到这个主题」,或在下方新建主题并点「创建并选择」。选定之后才会出现「合并表单」和「预览 diff」按钮。"),
2451
- h("div", { className: "dshi_cardTitle", style: { marginTop: 6 } }, "或新建主题"),
2452
- newTopic.error ? ErrorBox(newTopic.error) : null,
2453
- h("div", { className: "dshi_row" },
2454
- h("input", { className: "dshi_input", placeholder: "key(安全文件名,core 保留)", value: newTopic.topic, onChange: function (event) { updateNewTopic({ topic: event.target.value }); } }),
2455
- h("input", { className: "dshi_input", placeholder: "标题", value: newTopic.title, onChange: function (event) { updateNewTopic({ title: event.target.value }); } }),
2456
- h("input", { className: "dshi_input", placeholder: "单行摘要(≤60 字符)", value: newTopic.summary, onChange: function (event) { updateNewTopic({ summary: event.target.value }); } }),
2457
- h("button", { className: "dshi_btn dshi_btnPrimary", disabled: busy || newTopic.busy || ro, onClick: submitNewTopic }, newTopic.busy ? "创建中…" : "创建并选择")),
2458
- mergeForm ? h("div", null,
2459
- h("div", { className: "dshi_itemHead", style: { marginTop: 6 } },
2460
- h("span", { className: "dshi_cardTitle" }, "合并表单(目标 " + mergeForm.key + ")"),
2461
- h("span", { className: "dshi_hint dshi_mono" }, "token(" + mergeForm.tokenSource + ") " + topicRevisionPrefix(mergeForm.expectedRevision))),
2462
- h("div", { className: "dshi_hint" }, "before(" + mergeForm.before.length + " 字符,服务端按 append-only 校验 after 必须保留它)已载入;源保全块由服务端自动追加。"),
2463
- h("label", { className: "dshi_label" }, "标题",
2464
- h("input", { className: "dshi_input", value: mergeForm.title, onChange: function (event) { updateMergeForm({ title: event.target.value }); } })),
2465
- h("label", { className: "dshi_label" }, "单行摘要(≤60 字符)",
2466
- h("input", { className: "dshi_input", value: mergeForm.summary, onChange: function (event) { updateMergeForm({ summary: event.target.value }); } })),
2467
- h("label", { className: "dshi_label" }, "合并后正文(after,可编辑;必须保留 before 全文)",
2468
- h("textarea", { className: "dshi_textarea", value: mergeForm.after, onChange: function (event) { updateMergeForm({ after: event.target.value }); } })),
2469
- h("div", { className: "dshi_row" },
2470
- h("button", { className: "dshi_btn dshi_btnPrimary", disabled: busy || ro, onClick: doMergePreview }, "预览 diff(previewPlan)"))) : null
2471
- ));
3165
+ // 0.3:手动归档入口——原合并卡里的专题列表独立成卡,只保留「移出索引 /
3166
+ // 恢复到索引」(0.2.2 归档入口,previewPlan kind=archive-topic,协议不变)。
3167
+ var renderArchiveTopicRow = function (row) {
3168
+ var key = String(row.key ?? "");
3169
+ var archived = row.archived === true;
3170
+ return h("div", { key: key, className: "dshi_item" },
3171
+ h("div", { className: "dshi_itemHead" },
3172
+ h("span", { className: "dshi_mono" }, key),
3173
+ row.title ? h("span", { className: "dshi_badgeDim dshi_badge" }, String(row.title)) : null,
3174
+ archived ? h("span", { className: "dshi_badgeDim dshi_badge" }, "已归档") : null,
3175
+ row.updated ? h("span", { className: "dshi_hint" }, String(row.updated)) : null,
3176
+ row.revision ? h("span", { className: "dshi_hint dshi_mono" }, "rev " + topicRevisionPrefix(row.revision)) : null,
3177
+ archived ? h("button", {
3178
+ className: "dshi_btn",
3179
+ disabled: busy || ro,
3180
+ onClick: function () { doArchiveTopicPreview(row, false); }
3181
+ }, "恢复到索引")
3182
+ : h("button", {
3183
+ className: "dshi_btn",
3184
+ disabled: busy || ro,
3185
+ onClick: function () { doArchiveTopicPreview(row, true); }
3186
+ }, "移出索引")));
2472
3187
  };
3188
+ // U5:open 计划直接列出;executed / superseded 收进默认折叠的分组(数量在组头)。
3189
+ var activePlans = visiblePlans.filter(function (p) { return !(p && (p.executed === true || p.superseded === true)); });
3190
+ var archivedPlans = visiblePlans.filter(function (p) { return Boolean(p && (p.executed === true || p.superseded === true)); });
3191
+ // 筛选 / 搜索后的可见候选行(0.3 起 Flat 列表,不再按 kind 分组折叠)。
3192
+ var visibleRows = [];
3193
+ items.forEach(function (item, index) {
3194
+ var candidate = queueItemCandidate(item);
3195
+ if (!rowVisible(item, candidate)) return;
3196
+ visibleRows.push(renderCandidateRow(item, index, candidate));
3197
+ });
2473
3198
  return h("div", null,
2474
3199
  h("div", { className: "dshi_row", style: { marginBottom: 8 } },
2475
- h("span", { className: "dshi_cardTitle" }, "整理 / 遗忘:候选审阅与执行"),
2476
- h("button", { className: "dshi_btn", onClick: load, disabled: busy }, "刷新"),
2477
- h("button", { className: "dshi_btn", title: "找出该合并进主题、该建链接、该单独成卡的卡(只读分析,不改数据)", onClick: function () { doAnalyze("organize"); }, disabled: actionsDisabled }, "分析整理候选"),
2478
- h("button", { className: "dshi_btn", title: "按衰减分数找出该归档的旧卡(只读分析)", onClick: function () { doAnalyze("forgetting"); }, disabled: actionsDisabled }, "分析遗忘候选"),
3200
+ h("span", { className: "dshi_cardTitle" }, "遗忘:候选审阅与执行"),
3201
+ h("button", { className: "dshi_btn", title: "只重新读取队列快照与计划列表,不会重新分析;要重新分析请点「分析遗忘候选」", onClick: load, disabled: busy }, "刷新"),
3202
+ h("button", { className: "dshi_btn", title: "按衰减分数找出该归档的旧卡(只读分析,不改数据)", onClick: function () { doAnalyze("forgetting"); }, disabled: actionsDisabled }, "分析遗忘候选"),
2479
3203
  loaded ? h("span", { className: "dshi_badgeDim dshi_badge" }, "queueRevision " + queueRevision) : null),
2480
3204
  ErrorBox(error),
2481
3205
  ro ? h("div", { className: "dshi_roHint" }, READONLY_HINT_TEXT) : null,
2482
3206
  data ? h(fragment, null,
2483
3207
  h("div", { className: "dshi_card" },
2484
3208
  h("div", { className: "dshi_cardTitle" }, "候选(" + items.length + ")"),
2485
- h("div", { className: "dshi_hint" }, "候选由「分析整理候选 / 分析遗忘候选」生成:集群(≥8 张共享实体或触发词的卡)可直接「合并进主题」,孤立卡只能用内置预览,可建链接用「预览整理计划」。"),
2486
- items.length === 0 ? h("div", { className: "dshi_hint" }, "(空)") : h("div", { className: "dshi_items" }, items.map(function (item, index) {
2487
- // 真机 queueDto:id/kind 在 item.candidate 里(queueItemCandidate 兼容旧扁平形状)。
2488
- // 下标只用作渲染 key;没有业务 id 的行禁用全部动作,不把下标当 candidateId 发 RPC。
2489
- var candidate = queueItemCandidate(item);
2490
- var businessId = candidate && candidate.id !== undefined && candidate.id !== null
2491
- ? String(candidate.id) : null;
2492
- var key = businessId !== null ? businessId : String(index);
2493
- var isCluster = candidate ? String(candidate.kind ?? "") === "cluster" : false;
2494
- var rowDisabled = actionsDisabled || businessId === null;
2495
- // 就地展开:只有被点击的那一行才在自身正下方渲染合并卡(同一 dshi_items 容器内)。
2496
- var mergeForThisRow = Boolean(merge) && businessId !== null && String(merge.candidateId) === businessId;
2497
- // 有了 id→标题映射就把候选翻译成人话:集群说共享词 + 卡数,
2498
- // 链接说「A ↔ B」,孤立卡直接给源卡标题;都没有时退化成短 id。
2499
- var sourceIds = candidate && Array.isArray(candidate.sources)
2500
- ? candidate.sources.map(function (s) { return String(s && s.id); }).filter(Boolean) : [];
2501
- var sourceTitles = sourceIds.map(function (id) { return titles[id] || shortId(id); });
2502
- var evidence = candidate && candidate.evidence && typeof candidate.evidence === "object" ? candidate.evidence : {};
2503
- var candidateKind = candidate && candidate.kind ? String(candidate.kind) : "";
2504
- var candidateTitle = null;
2505
- if (candidateKind === "cluster") {
2506
- var sharedTerm = evidence.sharedTerm || evidence.field;
2507
- candidateTitle = sharedTerm
2508
- ? "合并「" + String(sharedTerm) + "」相关的 " + sourceIds.length + " 张卡"
2509
- : "合并 " + sourceIds.length + " 张卡";
2510
- } else if (candidateKind === "link" && sourceTitles.length >= 2) {
2511
- candidateTitle = "连接:" + sourceTitles.join(" ↔ ");
2512
- } else if (sourceTitles.length === 1) {
2513
- candidateTitle = sourceTitles[0];
2514
- } else if (sourceTitles.length > 1) {
2515
- candidateTitle = sourceTitles.join("、");
2516
- }
2517
- var row = h("div", { key: key, className: "dshi_item" },
2518
- h("div", { className: "dshi_itemHead" },
2519
- h("span", null, candidateTitle || "(未识别的卡片)"),
2520
- h("span", { className: "dshi_mono" }, businessId !== null ? shortId(businessId) : "(缺少 candidate.id)"),
2521
- candidate && candidate.kind ? h("span", { className: "dshi_badgeDim dshi_badge" }, candidateKindLabel(candidate.kind)) : null,
2522
- item.status ? h("span", { className: "dshi_badge" }, candidateStatusLabel(item.status)) : null,
2523
- h("button", { className: "dshi_btn", disabled: rowDisabled, title: "把候选状态置为 reviewed", onClick: function () { doReview(businessId, "reviewed"); } }, "标记已阅"),
2524
- h("button", { className: "dshi_btn", disabled: rowDisabled, title: "把候选状态置为 dismissed", onClick: function () { doReview(businessId, "dismissed"); } }, "忽略"),
2525
- h("button", { className: "dshi_btn", disabled: rowDisabled, onClick: function () { doPreviewOrganize(businessId); } }, "预览整理计划"),
2526
- // Q-A:cluster 候选一键进入「合并进主题」流程(选/建主题 → 自动 proposal
2527
- // → preview diff → 确认执行),不再要求手写 proposal JSON。
2528
- isCluster ? h("button", { className: "dshi_btn dshi_btnPrimary", disabled: rowDisabled, onClick: function () { openMerge(businessId); } }, "合并进主题") : null),
2529
- // 原始 JSON 默认折叠:details 不写 open,铺满屏幕的长串移出主视线。
2530
- h("details", { className: "dshi_details" },
2531
- h("summary", { className: "dshi_hint" }, "原始数据(JSON)"),
2532
- h("pre", { className: "dshi_pre" }, stableStringify(item))));
2533
- return mergeForThisRow ? [row, renderMergeCard(businessId)] : row;
2534
- })),
2535
- h("div", { className: "dshi_cardTitle", style: { marginTop: 6 } }, "计划(" + plans.length + ")"),
2536
- h("div", { className: "dshi_hint" }, "计划=预览(previewPlan)生成的待执行变更,含 diff 与 planDigest;确认执行后标为「已执行」,被新预览作废的标为「已作废」。整理类计划请从对应候选的「预览整理计划 / 合并进主题」发起,遗忘类计划可用行内「预览遗忘计划」。"),
2537
- plans.length === 0 ? h("div", { className: "dshi_hint" }, "(空)") : h("div", { className: "dshi_items" }, plans.map(function (plan, index) {
2538
- // 与候选行同一原则:下标只用作渲染 key,planId 缺失时禁用动作而非发下标。
2539
- var businessPlanId = plan && plan.planId !== undefined && plan.planId !== null
2540
- ? String(plan.planId)
2541
- : (plan && plan.id !== undefined && plan.id !== null ? String(plan.id) : null);
2542
- var planId = businessPlanId !== null ? businessPlanId : String(index);
2543
- // Q-B:区分 open / executed / superseded(planStore list 投影的布尔;
2544
- // superseded = 新预览作废旧 open 计划,P 侧 state.mjs 投影提供)。
2545
- // operationId 仅在 DTO 提供时显示(当前投影只含 executed/superseded 布尔,向前兼容)。
2546
- var executed = plan.executed === true;
2547
- var superseded = plan.superseded === true;
2548
- var executedWith = plan.executedWith ?? plan.operationId;
2549
- var isForgetting = plan.kind === undefined || String(plan.kind) === "forgetting";
2550
- return h("div", { key: planId, className: "dshi_item" },
2551
- h("div", { className: "dshi_itemHead" },
2552
- h("span", { className: "dshi_mono" }, businessPlanId !== null ? businessPlanId : "(缺少 planId)"),
2553
- plan.kind ? h("span", { className: "dshi_badgeDim dshi_badge" }, planKindLabel(plan.kind)) : null,
2554
- executed ? h("span", { className: "dshi_badge dshi_badgeWarn" }, planStateLabel("executed"))
2555
- : superseded ? h("span", { className: "dshi_badge dshi_badgeWarn" }, planStateLabel("superseded"))
2556
- : h("span", { className: "dshi_badgeDim dshi_badge" }, planStateLabel("open")),
2557
- executedWith !== undefined && executedWith !== null ? h("span", { className: "dshi_hint dshi_mono" }, "op " + String(executedWith)) : null,
2558
- executed || !isForgetting ? null
2559
- : h("button", { className: "dshi_btn", disabled: actionsDisabled || businessPlanId === null || superseded, onClick: function () { doPreviewForgetting(businessPlanId); } }, "预览遗忘计划")),
2560
- executed ? h("div", { className: "dshi_hint" }, "该计划已执行:不可再次预览 / 执行;如需再次整理请重新 analyze。")
2561
- : superseded ? h("div", { className: "dshi_hint" }, "该计划已被新预览作废(superseded):不可再预览 / 执行(服务端会拒绝并报 REVISION_CONFLICT),请使用最新计划。")
2562
- : (!isForgetting ? h("div", { className: "dshi_hint" }, "organize 计划请从对应候选的「预览 / 合并进主题」流程执行。") : null),
2563
- h("details", { className: "dshi_details" },
2564
- h("summary", { className: "dshi_hint" }, "原始数据(JSON)"),
2565
- h("pre", { className: "dshi_pre" }, stableStringify(plan))));
2566
- })),
2567
- h("label", { className: "dshi_label", style: { marginTop: 6 } }, "organize proposal(buildDraft 形状,服务端严格校验;默认留空——点候选行「preview organize」按候选预填骨架,cluster 候选推荐直接用「合并进主题」)",
2568
- h("textarea", { className: "dshi_textarea", value: proposal, placeholder: "留空=未填写(不发送)。点候选行「preview organize」自动预填;或按协议手写 link / merge-topic 形状。", onChange: function (event) { setProposal(event.target.value); } }))),
3209
+ h("div", { className: "dshi_hint" }, "候选是之前「整理分析」留下的待审条目(遗忘分析不产生候选,结果直接进下方计划)。每行可「稍后再说」(只是收起来,不删除任何记忆)或「忽略」。"),
3210
+ // U5:筛选条(状态 chips,含计数)+ 纯前端搜索框(按标题或短 id 过滤)。
3211
+ h("div", { className: "dshi_filterBar" },
3212
+ CANDIDATE_FILTERS.map(function (f) {
3213
+ return h("button", { key: f[0], className: "dshi_filterChip" + (filter === f[0] ? " dshi_filterChipOn" : ""), onClick: function () { setFilter(f[0]); } }, f[1] + "(" + statusCounts[f[0]] + ")");
3214
+ }),
3215
+ h("input", { className: "dshi_input dshi_searchInput", placeholder: "搜索:按标题或短 id 过滤", value: search, onChange: function (event) { setSearch(event.target.value); } })),
3216
+ items.length === 0 || visibleRows.length === 0 ? h("div", { className: "dshi_hint" }, "(空)") : h("div", { className: "dshi_items" }, visibleRows)),
3217
+ // 0.3:手动归档入口(原在「合并进主题」卡里,独立成卡;连线编辑不在这里,
3218
+ // 在闪回图谱点节点打开的卡片详情里)。
3219
+ h("div", { className: "dshi_card" },
3220
+ h("div", { className: "dshi_row" },
3221
+ h("span", { className: "dshi_cardTitle" }, "专题索引归档(手动)"),
3222
+ h("button", { className: "dshi_btn", disabled: busy || ro, onClick: loadTopics }, topics !== null && topics.loading ? "刷新中…" : "载入 / 刷新专题")),
3223
+ h("div", { className: "dshi_hint" }, "移出索引只影响每轮注入的 L1 索引条目,正文保留,memory_read(key) 随时可读,memory_search 仍能搜到;恢复到索引随时可逆。"),
3224
+ topics === null ? h("div", { className: "dshi_hint" }, "点「载入 / 刷新专题」列出当前 scope 的专题。") : null,
3225
+ topics !== null && topics.loading ? h("div", { className: "dshi_loading" }, "主题列表加载中…") : null,
3226
+ topics && topics.error ? ErrorBox(topics.error) : null,
3227
+ topics && !topics.loading && !topics.error ? (topics.topics.length === 0
3228
+ ? h("div", { className: "dshi_hint" }, "当前 scope 还没有专题。")
3229
+ : (function () {
3230
+ var unarchivedCount = sortTopicRows(topics.topics).filter(function (row) { return !(row && row.archived === true); }).length;
3231
+ return h("div", { className: "dshi_items" },
3232
+ h("div", { className: "dshi_hint" }, "未归档 " + unarchivedCount + " 篇。"),
3233
+ sortTopicRows(topics.topics).map(renderArchiveTopicRow));
3234
+ })()) : null),
3235
+ // 计划列表独立成卡(只含遗忘计划);已执行 / 已作废默认折叠。
3236
+ h("div", { className: "dshi_card" },
3237
+ h("div", { className: "dshi_cardTitle" }, "计划(" + visiblePlans.length + ")"),
3238
+ h("div", { className: "dshi_hint" }, "计划=预览(previewPlan)生成的待执行变更,含 diff 与 planDigest;确认执行后标为「已执行」,被新预览作废的标为「已作废」。遗忘计划由「分析遗忘候选」生成,行内「预览遗忘计划」后于确认卡执行。"),
3239
+ visiblePlans.length === 0 ? h("div", { className: "dshi_hint" }, "(空)") : null,
3240
+ activePlans.length > 0 ? h("div", { className: "dshi_items" }, activePlans.map(renderPlanRow)) : null,
3241
+ // 已执行 / 已作废默认折叠——原生 details(不写 open),行仍在 DOM 里,
3242
+ // 点开即可切回来查看;组头带数量。
3243
+ archivedPlans.length > 0 ? h("details", { className: "dshi_details" },
3244
+ h("summary", { className: "dshi_groupHead" },
3245
+ h("span", null, "已执行 / 已作废"),
3246
+ h("span", { className: "dshi_groupCount" }, "(" + archivedPlans.length + ")")),
3247
+ h("div", { className: "dshi_items" }, archivedPlans.map(renderPlanRow))) : null),
2569
3248
  ) : null,
2570
3249
  previewError ? ErrorBox(previewError) : null,
2571
- preview && preview.sessionId === props.sessionId ? h("div", { className: "dshi_confirm" },
2572
- h("div", { className: "dshi_cardTitle" }, "PlanView 预览(" + String(preview.plan.kind) + ")",
2573
- h("span", { className: "dshi_mono" }, String(preview.plan.planId)),
2574
- h("span", { className: "dshi_badgeDim dshi_badge" }, String(preview.plan.planDigest))),
2575
- preview.plan.summary ? h("div", { className: "dshi_hint" }, String(preview.plan.summary)) : null,
2576
- Array.isArray(preview.plan.diff) && preview.plan.diff.length > 0 ? preview.plan.diff.map(function (entry, index) {
2577
- return h("div", { key: index, className: "dshi_item" },
2578
- h("div", { className: "dshi_mono" }, String(entry.path ?? index)),
2579
- h("div", { className: "dshi_hint" }, "old"),
2580
- h("pre", { className: "dshi_pre" }, String(entry.oldText ?? "")),
2581
- h("div", { className: "dshi_hint" }, "new"),
2582
- h("pre", { className: "dshi_pre" }, String(entry.newText ?? "")));
2583
- }) : h("div", { className: "dshi_hint" }, "(无 diff 条目)"),
2584
- // Q-B:预览对应的计划若已在 plans 列表里标记 executed / superseded,执行按钮禁用
2585
- (function () {
2586
- var row = plans.find(function (p) { return String(p && p.planId) === String(preview.plan && preview.plan.planId); });
2587
- return row && (row.executed === true || row.superseded === true);
2588
- })() ? h("div", { className: "dshi_hint" }, "该计划已执行或已被新预览作废(plans 列表标记),执行按钮已禁用。") : null,
2589
- h("div", { className: "dshi_row" },
2590
- h("button", {
2591
- className: "dshi_btn dshi_btnDanger",
2592
- disabled: busy || ro || (function () {
2593
- var row = plans.find(function (p) { return String(p && p.planId) === String(preview.plan && preview.plan.planId); });
2594
- return Boolean(row && (row.executed === true || row.superseded === true));
2595
- })(),
2596
- onClick: doExecute
2597
- }, "确认执行(不可撤销)"),
2598
- h("button", { className: "dshi_btn", disabled: busy, onClick: function () { setPreview(null); } }, "取消")))
2599
- : null);
3250
+ showBottomPreview ? renderPreviewCard("preview-bottom") : null);
2600
3251
  }
2601
3252
 
2602
3253
  // ── L3:主题(topic)记忆管理 ────────────────────────────────────────────
2603
3254
  // memory_list_topics 只回元数据(key/title/summary/chars/revision),正文必须
2604
3255
  // memory_read(topic) 单独拿——几十个主题一次性全读会拖慢面板,所以列表默认只显示名字,
2605
- // 点「展开」才读正文。legacy 主题(updated === "legacy-unknown")服务端拒写,只读展示。
3256
+ // 点「展开」才读正文。
3257
+ // U6:updated 只取 YYYY-MM-DD 展示(缺失或非日期前缀显示 —);归档行(archived:true)
3258
+ // 加「已归档」徽章并把名称/摘要调灰弱化。
3259
+ // 0.2.2 归档入口:整理页专题列表排序——未归档在前、已归档整段排最后;组内按
3260
+ // updated 升序(最旧优先,空 / 缺失 updated 排该组末尾),updated 相同按 summary
3261
+ // 长度降序,再按 key(升序)。纯函数、不改入参,行对象形状异常按空值兜底。
3262
+ function compareTopicRows(a, b) {
3263
+ var aArchived = Boolean(a && a.archived === true);
3264
+ var bArchived = Boolean(b && b.archived === true);
3265
+ if (aArchived !== bArchived) return aArchived ? 1 : -1;
3266
+ var aUpdated = a && a.updated !== undefined && a.updated !== null ? String(a.updated) : "";
3267
+ var bUpdated = b && b.updated !== undefined && b.updated !== null ? String(b.updated) : "";
3268
+ if ((aUpdated === "") !== (bUpdated === "")) return aUpdated === "" ? 1 : -1;
3269
+ if (aUpdated !== bUpdated) return aUpdated < bUpdated ? -1 : 1;
3270
+ var aSummaryLen = a && a.summary !== undefined && a.summary !== null ? String(a.summary).length : 0;
3271
+ var bSummaryLen = b && b.summary !== undefined && b.summary !== null ? String(b.summary).length : 0;
3272
+ if (aSummaryLen !== bSummaryLen) return bSummaryLen - aSummaryLen;
3273
+ var aKey = String((a && a.key) ?? "");
3274
+ var bKey = String((b && b.key) ?? "");
3275
+ if (aKey !== bKey) return aKey < bKey ? -1 : 1;
3276
+ return 0;
3277
+ }
3278
+ function sortTopicRows(rows) {
3279
+ return (Array.isArray(rows) ? rows.slice() : []).sort(compareTopicRows);
3280
+ }
3281
+ function topicUpdatedDay(row) {
3282
+ var text = String((row && row.updated) ?? "");
3283
+ return /^\d{4}-\d{2}-\d{2}/.test(text) ? text.slice(0, 10) : "";
3284
+ }
2606
3285
  function TopicsTab(props) {
2607
3286
  var listState = useState(null);
2608
3287
  var topics = listState[0];
@@ -2640,22 +3319,46 @@ window.__ModuleLoader__.load({
2640
3319
  var saveOkState = useState(null);
2641
3320
  var saveOk = saveOkState[0];
2642
3321
  var setSaveOk = saveOkState[1];
3322
+ // U6 追加:搜索(key/title/summary 子串,忽略大小写)+ 排序(默认更新时间倒序),
3323
+ // 写法对齐整理页的 filterBar / searchInput(U5,见 CandidatesTab 同名 state)。
3324
+ var searchState = useState("");
3325
+ var search = searchState[0];
3326
+ var setSearch = searchState[1];
3327
+ var sortState = useState("updated-desc");
3328
+ var sort = sortState[0];
3329
+ var setSort = sortState[1];
3330
+ // P1-2:本 tab 的会话守卫 holder(新 state 一律追加在既有 state 之后)。
3331
+ var tabGuardState = useState({ sessionId: props.sessionId, gen: 0 });
3332
+ var tabGuard = makeTabSessionGuard(props, tabGuardState[0]);
3333
+ tabGuard.track(); // 每次渲染同步:会话一换,在途响应即刻过期
2643
3334
  // F7:只读态(另一实例在写)写按钮置灰。
2644
3335
  var ro = props.readOnly === true;
2645
3336
  // F4:时间线跳转目标(面板级 ref 传入;type 必须是 topic)。
2646
3337
  var focusTarget = props.focusTarget && props.focusTarget.type === "topic" ? props.focusTarget : null;
3338
+ // P1-3(详情串卡):opened 的镜像 ref + 读请求在途序号。ref 在渲染体同步、
3339
+ // openTopic 切换时立即同步(不等下一轮渲染),readTopic 的响应回来时用它
3340
+ // 判断「发起时的专题是否还是当前专题」。
3341
+ var openedRef = useRef(opened);
3342
+ openedRef.current = opened;
3343
+ var detailReqSeqRef = useRef(0);
2647
3344
 
2648
3345
  var load = async function () {
3346
+ var origin = tabGuard.mark();
2649
3347
  setBusy(true);
2650
3348
  setError(null);
2651
3349
  try {
2652
3350
  var result = await props.dsh.call("executeTool", props.sessionId, { name: "memory_list_topics", args: {} });
3351
+ if (tabGuard.isStale(origin)) return; // P1-2:会话已切换,丢弃旧响应
2653
3352
  setTopics(Array.isArray(result && result.topics) ? result.topics : []);
2654
3353
  } catch (e) {
3354
+ if (tabGuard.isStale(origin)) return;
2655
3355
  setTopics(null);
2656
- setError(e);
3356
+ // C6(审计 P2-6):与其他 tab 统一口径——会话级不可用交面板层缓存
3357
+ // (props.onSessionUnavailable),不重复吃同一条错误、不挂原始 ErrorBox。
3358
+ if (!reportSessionUnavailable(e, props, setError)) setError(e);
2657
3359
  } finally {
2658
- setBusy(false);
3360
+ // 过期请求不动 busy(新一轮 load 已接管 busy 的收尾)
3361
+ if (!tabGuard.isStale(origin)) setBusy(false);
2659
3362
  }
2660
3363
  };
2661
3364
  useEffect(function () { load(); }, [props.sessionId]);
@@ -2677,19 +3380,31 @@ window.__ModuleLoader__.load({
2677
3380
  && !topics.some(function (row) { return String(row && row.key) === focusTarget.id; }));
2678
3381
 
2679
3382
  var readTopic = async function (key) {
3383
+ // P1-3:发请求时记下在途序号;响应回来时若用户已切到别的专题(opened 变了)
3384
+ // 或已有更新的读请求在途,整包丢弃——不 setDetail、不 setDetailError,
3385
+ // 杜绝「点 A 立刻点 B,A 的响应晚到覆盖 B 的详情」。
3386
+ var mySeq = detailReqSeqRef.current + 1;
3387
+ detailReqSeqRef.current = mySeq;
3388
+ var isLatest = function () { return detailReqSeqRef.current === mySeq; };
2680
3389
  setDetailBusy(true);
2681
3390
  setDetailError(null);
2682
3391
  try {
2683
- setDetail(await props.dsh.call("executeTool", props.sessionId, { name: "memory_read", args: { topic: key } }));
3392
+ var result = await props.dsh.call("executeTool", props.sessionId, { name: "memory_read", args: { topic: key } });
3393
+ if (openedRef.current !== key || !isLatest()) return;
3394
+ setDetail(result);
2684
3395
  } catch (e) {
3396
+ if (openedRef.current !== key || !isLatest()) return;
2685
3397
  setDetail(null);
2686
- setDetailError(e);
3398
+ // C6:详情读失败同样先过会话不可用守卫(口径与 load 一致)。
3399
+ if (!reportSessionUnavailable(e, props, setDetailError)) setDetailError(e);
2687
3400
  } finally {
2688
- setDetailBusy(false);
3401
+ // 只有仍是最新一次读请求时才收 busy:过期请求不动 busy,交给在途的最新请求收尾。
3402
+ if (isLatest()) setDetailBusy(false);
2689
3403
  }
2690
3404
  };
2691
3405
  var openTopic = function (key) {
2692
3406
  if (opened === key) {
3407
+ openedRef.current = ""; // P1-3:镜像 ref 立即同步,不等下一轮渲染
2693
3408
  setOpened("");
2694
3409
  setDetail(null);
2695
3410
  setEditing(false);
@@ -2698,6 +3413,7 @@ window.__ModuleLoader__.load({
2698
3413
  setSaveError(null);
2699
3414
  return;
2700
3415
  }
3416
+ openedRef.current = key;
2701
3417
  setOpened(key);
2702
3418
  setDetail(null);
2703
3419
  setDetailError(null);
@@ -2717,7 +3433,15 @@ window.__ModuleLoader__.load({
2717
3433
  var cancelEdit = function () { setEditing(false); setDraft(""); setSaveError(null); };
2718
3434
  var save = async function () {
2719
3435
  if (!detail) return;
2720
- var key = detail.topic || opened;
3436
+ // P1-3:保存只认 opened 作为写目标。detail 是 memory_read 的响应快照,
3437
+ // 响应期间用户可能已切换专题——detail.topic 与 opened 不一致时直接不写,
3438
+ // 给中文提示,绝不把 A 专题的草稿写进 B 专题;expectedRevision 仍用 detail.revision。
3439
+ var key = opened;
3440
+ var detailTopic = detail.topic !== undefined && detail.topic !== null ? String(detail.topic) : "";
3441
+ if (detailTopic !== "" && detailTopic !== String(key)) {
3442
+ setSaveError("详情已切换,请重新打开该专题再保存");
3443
+ return;
3444
+ }
2721
3445
  setSaveBusy(true);
2722
3446
  setSaveError(null);
2723
3447
  setSaveOk(null);
@@ -2730,39 +3454,93 @@ window.__ModuleLoader__.load({
2730
3454
  await readTopic(key);
2731
3455
  await load();
2732
3456
  } catch (e) {
2733
- setSaveError(e);
3457
+ // C6:保存失败也统一会话口径——会话级不可用上报面板层缓存,不上挂原始 error。
3458
+ if (!reportSessionUnavailable(e, props, setSaveError)) setSaveError(e);
2734
3459
  } finally {
2735
3460
  setSaveBusy(false);
2736
3461
  }
2737
3462
  };
2738
3463
 
3464
+ // U6:纯前端搜索(key/title/summary 子串,忽略大小写;空串显示全部)+ 排序。
3465
+ // 与整理页 rowVisible / searchQuery 同一写法口径。
3466
+ var searchQuery = String(search ?? "").trim().toLowerCase();
3467
+ var visibleTopics = Array.isArray(topics) ? topics.filter(function (row) {
3468
+ if (!searchQuery) return true;
3469
+ var hay = [row && row.key, row && row.title, row && row.summary]
3470
+ .map(function (v) { return v === undefined || v === null ? "" : String(v); })
3471
+ .join(" ")
3472
+ .toLowerCase();
3473
+ return hay.indexOf(searchQuery) !== -1;
3474
+ }) : topics;
3475
+ if (Array.isArray(visibleTopics)) {
3476
+ // 缺失日期(空串)无论升序降序都排最后;升/降序各写显式比较器,
3477
+ // 不用换参取反——那会把「缺失最后」在降序下翻转成「缺失最先」。
3478
+ var updatedDayOf = topicUpdatedDay;
3479
+ visibleTopics = visibleTopics.slice();
3480
+ if (sort === "updated-asc") visibleTopics.sort(function (a, b) {
3481
+ var da = updatedDayOf(a);
3482
+ var db = updatedDayOf(b);
3483
+ if (!da && !db) return 0;
3484
+ if (!da) return 1;
3485
+ if (!db) return -1;
3486
+ return da < db ? -1 : da > db ? 1 : 0;
3487
+ });
3488
+ else if (sort === "chars-desc") visibleTopics.sort(function (a, b) { return ((b && b.chars) ?? 0) - ((a && a.chars) ?? 0); });
3489
+ else if (sort === "title-asc") visibleTopics.sort(function (a, b) {
3490
+ var ta = String((a && a.title) || (a && a.key) || "");
3491
+ var tb = String((b && b.title) || (b && b.key) || "");
3492
+ return ta.localeCompare(tb, "zh-Hans-CN");
3493
+ });
3494
+ // 默认 updated-desc:更新时间倒序。
3495
+ else visibleTopics.sort(function (a, b) {
3496
+ var da = updatedDayOf(a);
3497
+ var db = updatedDayOf(b);
3498
+ if (!da && !db) return 0;
3499
+ if (!da) return 1;
3500
+ if (!db) return -1;
3501
+ return da < db ? 1 : da > db ? -1 : 0;
3502
+ });
3503
+ }
3504
+ var archivedStyle = { color: "var(--dsw-alias-label-tertiary)" };
3505
+
2739
3506
  return h("div", null,
2740
3507
  h("div", { className: "dshi_row", style: { marginBottom: 8 } },
2741
3508
  h("span", { className: "dshi_cardTitle" }, "L3 主题记忆(topic)"),
2742
3509
  h("button", { className: "dshi_btn", disabled: busy, onClick: load }, busy ? "刷新中…" : "刷新"),
2743
3510
  h("span", { style: { flex: 1 } }),
2744
- h("span", { className: "dshi_hint" }, topics === null ? "" : "共 " + topics.length + " 个主题")),
3511
+ h("span", { className: "dshi_hint" },
3512
+ topics === null ? "" : (searchQuery ? "显示 " + visibleTopics.length + "/" + topics.length + " 个主题" : "共 " + topics.length + " 个主题"))),
2745
3513
  h("div", { className: "dshi_hint" }, "L3 是跨会话的长期主题记忆,每条按 key 存一个文件。这里列表只显示名字和字数,点「展开」才读正文;编辑是整篇覆盖,保存走版本校验。"),
3514
+ // U6:搜索框 + 排序下拉(默认更新时间倒序),样式复用整理页的 filterBar。
3515
+ h("div", { className: "dshi_filterBar" },
3516
+ h("input", { className: "dshi_input dshi_searchInput", placeholder: "搜索:按 key / 标题 / 摘要", value: search, onChange: function (event) { setSearch(event.target.value); } }),
3517
+ h("select", { className: "dshi_select", value: sort, title: "排序方式", onChange: function (event) { setSort(event.target.value); } },
3518
+ h("option", { value: "updated-desc" }, "更新时间(新→旧)"),
3519
+ h("option", { value: "updated-asc" }, "更新时间(旧→新)"),
3520
+ h("option", { value: "chars-desc" }, "字数(多→少)"),
3521
+ h("option", { value: "title-asc" }, "标题序"))),
2746
3522
  ErrorBox(error),
2747
3523
  focusMiss ? h("div", { className: "dshi_roHint" }, "时间线跳转:主题「" + focusTarget.id + "」不在当前列表(可能已删除或已归档)。") : null,
2748
3524
  ro ? h("div", { className: "dshi_roHint" }, READONLY_HINT_TEXT) : null,
2749
3525
  busy && topics === null ? h("div", { className: "dshi_loading" }, "正在读取主题列表…") : null,
2750
3526
  topics !== null && topics.length === 0 ? h("div", { className: "dshi_hint" }, "这个作用域下还没有主题。") : null,
2751
- topics !== null ? h("div", { className: "dshi_items" }, topics.map(function (row) {
3527
+ topics !== null && topics.length > 0 && visibleTopics.length === 0 ? h("div", { className: "dshi_hint" }, "没有匹配的主题,试试调整搜索词。") : null,
3528
+ topics !== null ? h("div", { className: "dshi_items" }, visibleTopics.map(function (row) {
2752
3529
  var key = String(row.key);
2753
- var legacy = isLegacyTopicRow(row);
3530
+ var archived = row.archived === true;
2754
3531
  var isOpen = opened === key;
2755
3532
  return h("div", { key: key, className: "dshi_item" },
2756
3533
  h("div", { className: "dshi_itemHead" },
2757
- h("span", { className: "dshi_cardTitle" }, key),
2758
- row.title ? h("span", { className: "dshi_hint" }, String(row.title)) : null,
2759
- legacy ? h("span", { className: "dshi_badge dshi_badgeWarn" }, "legacy 只读") : null,
3534
+ h("span", { className: "dshi_cardTitle", style: archived ? archivedStyle : undefined }, key),
3535
+ row.title ? h("span", { className: "dshi_hint", style: archived ? archivedStyle : undefined }, String(row.title)) : null,
3536
+ archived ? h("span", { className: "dshi_badge dshi_badgeWarn" }, "已归档") : null,
2760
3537
  h("span", { style: { flex: 1 } }),
3538
+ h("span", { className: "dshi_hint", title: "更新时间" }, topicUpdatedDay(row) || "—"),
2761
3539
  h("span", { className: "dshi_mono" }, (row.chars ?? 0) + " 字符"),
2762
3540
  h("button", { className: "dshi_btn", onClick: function () { openTopic(key); } }, isOpen ? "收起" : "展开")),
2763
3541
  isOpen
2764
3542
  ? h("div", null,
2765
- row.summary ? h("div", { className: "dshi_hint" }, String(row.summary)) : null,
3543
+ row.summary ? h("div", { className: "dshi_hint", style: archived ? archivedStyle : undefined }, String(row.summary)) : null,
2766
3544
  detailBusy ? h("div", { className: "dshi_loading" }, "正在读取正文…") : null,
2767
3545
  ErrorBox(detailError),
2768
3546
  detail ? h("div", null,
@@ -2771,13 +3549,11 @@ window.__ModuleLoader__.load({
2771
3549
  h("span", { className: "dshi_hint" }, (detail.bytes ?? 0) + " 字节"),
2772
3550
  detail.truncated ? h("span", { className: "dshi_badge dshi_badgeWarn" }, "正文过长,已截断") : null,
2773
3551
  h("span", { style: { flex: 1 } }),
2774
- legacy
2775
- ? h("span", { className: "dshi_hint" }, "legacy 主题由旧版写入,服务端拒绝改写")
2776
- : (editing
2777
- ? h(fragment, null,
2778
- h("button", { className: "dshi_btn dshi_btnPrimary", disabled: saveBusy || ro, onClick: save }, saveBusy ? "保存中…" : "保存"),
2779
- h("button", { className: "dshi_btn", disabled: saveBusy, onClick: cancelEdit }, "取消"))
2780
- : h("button", { className: "dshi_btn", disabled: ro, onClick: beginEdit }, "编辑"))),
3552
+ editing
3553
+ ? h(fragment, null,
3554
+ h("button", { className: "dshi_btn dshi_btnPrimary", disabled: saveBusy || ro, onClick: save }, saveBusy ? "保存中…" : "保存"),
3555
+ h("button", { className: "dshi_btn", disabled: saveBusy, onClick: cancelEdit }, "取消"))
3556
+ : h("button", { className: "dshi_btn", disabled: ro, onClick: beginEdit }, "编辑")),
2781
3557
  saveOk ? h("div", { className: "dshi_ok" }, saveOk) : null,
2782
3558
  ErrorBox(saveError),
2783
3559
  editing
@@ -3052,7 +3828,10 @@ window.__ModuleLoader__.load({
3052
3828
  try {
3053
3829
  setSnapshot(scope ? scope.getSnapshot() : null);
3054
3830
  } catch (e) {
3055
- setError({ code: "ui/scope", message: "读取设置命名空间失败:" + (e && e.message) });
3831
+ // C5(审计 P2-5):第三方 dsh 的 rejection 可能是字符串或无 message 的对象,
3832
+ // 直接拼 e.message 会把字面量 undefined 上屏;回落 String(e),与本仓既有的
3833
+ // (e && e.message) || String(e) 防御写法同口径。
3834
+ setError({ code: "ui/scope", message: "读取设置命名空间失败:" + ((e && e.message) || String(e)) });
3056
3835
  }
3057
3836
  }, []);
3058
3837
  useEffect(function () {
@@ -3321,15 +4100,29 @@ window.__ModuleLoader__.load({
3321
4100
  var errorState = useState(null);
3322
4101
  var error = errorState[0];
3323
4102
  var setError = errorState[1];
4103
+ // P1-2:本 tab 的会话守卫 holder(新 state 一律追加在既有 state 之后)。
4104
+ var tabGuardState = useState({ sessionId: props.sessionId, gen: 0 });
4105
+ var tabGuard = makeTabSessionGuard(props, tabGuardState[0]);
4106
+ tabGuard.track(); // 每次渲染同步:会话一换,在途响应即刻过期
3324
4107
  var load = async function () {
4108
+ var origin = tabGuard.mark();
3325
4109
  setError(null);
3326
4110
  try {
3327
4111
  var status = await props.dsh.call("getStatus", props.sessionId, {});
4112
+ if (tabGuard.isStale(origin)) return; // P1-2:会话已切换,丢弃旧响应
3328
4113
  setCaps(status && status.capabilities && typeof status.capabilities === "object" ? status.capabilities : null);
3329
- } catch (e) { setCaps(null); if (!reportSessionUnavailable(e, props, setError)) setError(e); }
4114
+ } catch (e) {
4115
+ if (tabGuard.isStale(origin)) return;
4116
+ setCaps(null); if (!reportSessionUnavailable(e, props, setError)) setError(e);
4117
+ }
3330
4118
  try {
3331
- setData(await props.dsh.call("getGraph", props.sessionId, {}));
3332
- } catch (e) { setData(null); if (!reportSessionUnavailable(e, props, setError)) setError(e); }
4119
+ var graph = await props.dsh.call("getGraph", props.sessionId, {});
4120
+ if (tabGuard.isStale(origin)) return;
4121
+ setData(graph);
4122
+ } catch (e) {
4123
+ if (tabGuard.isStale(origin)) return;
4124
+ setData(null); if (!reportSessionUnavailable(e, props, setError)) setError(e);
4125
+ }
3333
4126
  };
3334
4127
  useEffect(function () { load(); }, [props.sessionId]);
3335
4128
  var nodes = data && Array.isArray(data.nodes) ? data.nodes : [];
@@ -3408,12 +4201,12 @@ window.__ModuleLoader__.load({
3408
4201
  // ── F4:最近变更(getTimeline 时间线)────────────────────────────────
3409
4202
  // wire 不收 scope 入参:列表恒展示服务端按可信 scope 返回的条目(含 scope
3410
4203
  // 标签),前端不做跨 scope 过滤——要做得扩 wire,本期不做。
3411
- // 分页每页 100 条;hasMore=false 时禁用「下一页」。
4204
+ // 分页每页 20 条(0.3 起:100 条一页太长,翻页找近期变更更直接);hasMore=false 时禁用「下一页」。
3412
4205
  // scanLimited 提示里的 N 用下方 TIMELINE_SCAN_LIMIT:它是服务端
3413
4206
  // src/timeline/index.mjs TIMELINE_JOURNAL_SCAN_LIMIT(=4000)的手工同步副本
3414
4207
  //(审查 P3②;wire 不返回该值,前端拿不到真值只能落常数)。数据层一旦调整
3415
4208
  // 这个常量,必须同步改这里,否则「只扫描了最近 N 个文件」的数字会撒谎。
3416
- var TIMELINE_PAGE_SIZE = 100;
4209
+ var TIMELINE_PAGE_SIZE = 20;
3417
4210
  // 同步副本:与 src/timeline/index.mjs 的 TIMELINE_JOURNAL_SCAN_LIMIT(4000)一致。
3418
4211
  var TIMELINE_SCAN_LIMIT = 4000;
3419
4212
  var TIMELINE_ACTION_LABELS = {
@@ -3457,17 +4250,25 @@ window.__ModuleLoader__.load({
3457
4250
  var busyState = useState(false);
3458
4251
  var busy = busyState[0];
3459
4252
  var setBusy = busyState[1];
4253
+ // P1-2:本 tab 的会话守卫 holder(新 state 一律追加在既有 state 之后)。
4254
+ var tabGuardState = useState({ sessionId: props.sessionId, gen: 0 });
4255
+ var tabGuard = makeTabSessionGuard(props, tabGuardState[0]);
4256
+ tabGuard.track(); // 每次渲染同步:会话一换,在途响应即刻过期
3460
4257
  var load = async function (nextOffset) {
4258
+ var origin = tabGuard.mark();
3461
4259
  setBusy(true);
3462
4260
  setError(null);
3463
4261
  try {
3464
4262
  var result = await props.dsh.call("getTimeline", props.sessionId, { offset: nextOffset, limit: TIMELINE_PAGE_SIZE });
4263
+ if (tabGuard.isStale(origin)) return; // P1-2:会话已切换,丢弃旧响应
3465
4264
  setPage(result && typeof result === "object" ? result : null);
3466
4265
  } catch (e) {
4266
+ if (tabGuard.isStale(origin)) return;
3467
4267
  setPage(null);
3468
4268
  if (!reportSessionUnavailable(e, props, setError)) setError(e);
3469
4269
  } finally {
3470
- setBusy(false);
4270
+ // 过期请求不动 busy(新一轮 load 已接管 busy 的收尾)
4271
+ if (!tabGuard.isStale(origin)) setBusy(false);
3471
4272
  }
3472
4273
  };
3473
4274
  useEffect(function () { load(offset); }, [props.sessionId, offset]);
@@ -3497,7 +4298,7 @@ window.__ModuleLoader__.load({
3497
4298
  var detail = item && item.detail && typeof item.detail === "object" ? item.detail : null;
3498
4299
  var deduped = Boolean(detail && Array.isArray(detail.dedupedWith) && detail.dedupedWith.length > 0);
3499
4300
  // 跳转仅专题 → 专题 tab、卡片 → 图谱 tab(任务边界);核心写入没有
3500
- // 对应 tab,不提供定位,提示去「记忆 L0/L1」页看。
4301
+ // 对应 tab,不提供定位,提示去「记忆内容」页看。
3501
4302
  var jumpable = (type === "topic" || type === "spark") && id !== "" && typeof props.onJump === "function";
3502
4303
  return h("div", { key: String((item && item.at) ?? "") + "-" + index, className: "dshi_item" },
3503
4304
  h("div", { className: "dshi_itemHead" },
@@ -3510,7 +4311,7 @@ window.__ModuleLoader__.load({
3510
4311
  ? h("button", { className: "dshi_btn", onClick: function () { props.onJump(type, id); } }, "定位")
3511
4312
  : null),
3512
4313
  h("div", { className: "dshi_hint" },
3513
- "涉及对象:" + timelineTargetText(target) + (type === "core" ? "(核心记忆在「记忆 L0/L1」页查看)" : "")));
4314
+ "涉及对象:" + timelineTargetText(target) + (type === "core" ? "(核心记忆在「记忆内容」页查看)" : "")));
3514
4315
  })) : null,
3515
4316
  items.length > 0 ? h("div", { className: "dshi_row" },
3516
4317
  h("button", {
@@ -3529,12 +4330,15 @@ window.__ModuleLoader__.load({
3529
4330
  var TABS = [
3530
4331
  { id: "status", label: "状态" },
3531
4332
  { id: "timeline", label: "最近变更" },
3532
- { id: "memory", label: "记忆 L0/L1" },
3533
- { id: "graph", label: "图谱" },
3534
- { id: "candidates", label: "候选 / 计划" },
3535
- { id: "topics", label: "L3/topic 记忆管理" },
4333
+ // U6 改名(GLOSSARY U0 定稿落地):界面名主位,tab id 与协议不变。
4334
+ { id: "memory", label: "记忆内容" },
4335
+ { id: "graph", label: "闪回图谱" },
4336
+ // U5 改名:候选审阅 + 计划执行合称「整理与遗忘」(tab id 仍为 candidates,协议不变)。
4337
+ // 0.3 收敛:整理流程裁撤,本页只做遗忘,tab 名同步只讲遗忘。
4338
+ { id: "candidates", label: "遗忘" },
4339
+ { id: "topics", label: "专题" },
3536
4340
  { id: "flashbacks", label: "闪回命中" },
3537
- { id: "budgets", label: "预算配置" }
4341
+ { id: "budgets", label: "记忆预算" }
3538
4342
  ];
3539
4343
 
3540
4344
  // R6 追加:inert / shadow 时数据 tab 一律渲染「未配置」占位——不让用户点进去