@modusensus/dsh-mneme 0.7.32 → 0.8.1

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.
@@ -0,0 +1,122 @@
1
+ // 版本自检(issue #174 后续,2026-09-15 拍板):独立插件不把「用户在用哪个
2
+ // 版本」托付给插件市场——市场收录有 ~26h 年龄闸门 + 30min 缓存,且安装时
3
+ // 精确指定过版本的 profile 会被 pnpm 钉子挡住(update 尊重既有 semver 范围,
4
+ // 永不跨 minor/major,#174 的报障者正是这样用着 0.7.32 的行为模型来报 bug)。
5
+ //
6
+ // 本模块只做三件事:
7
+ // 1. 向 npm registry 查 @modusensus/dsh-mneme 的 latest dist-tag(带 TTL
8
+ // 缓存 + 超时 + 全失败静默——离线/被墙/registry 异常都返回 null,调用方
9
+ // 据 null 渲染「未知」,前端不打扰);
10
+ // 2. 与运行版本做纯函数比对(classify);
11
+ // 3. 对外暴露 registry URL 白名单校验(validateRegistryUrl)——发请求前
12
+ // 强制 https + 精确 host,构造上排除本机与内网地址。
13
+ import { readFileSync } from "node:fs";
14
+
15
+ // 运行版本:src/ 与 lib/ 都在插件根下一层,相对 import.meta.url 解析一致;
16
+ // 读取失败(打包/受限环境)降级 "unknown",横幅随之静默。
17
+ const PACKAGE_VERSION = (() => {
18
+ try {
19
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version ?? "unknown";
20
+ } catch {
21
+ return "unknown";
22
+ }
23
+ })();
24
+
25
+ // registry 查询地址是模块常量而非用户输入;validateRegistryUrl 仍作为发请求
26
+ // 前的强制闸(构造上即排除非 https 与非白名单 host,双保险且可单测)。
27
+ const REGISTRY_URL = "https://registry.npmjs.org/@modusensus%2Fdsh-mneme/latest";
28
+ const REGISTRY_HOST = "registry.npmjs.org";
29
+ // 市场收录本身有 ~1 天年龄闸门,1h 的 registry 缓存远低于该粒度,足够新鲜。
30
+ const CACHE_TTL_MS = 60 * 60 * 1000;
31
+ const FETCH_TIMEOUT_MS = 5000;
32
+
33
+ // 精确 host 白名单:协议必须 https,且 host 逐字等于 registry.npmjs.org。
34
+ // 这一条即构造性排除本机回环、私有网段与保留地址——不做任何
35
+ // 「看起来像公网」的宽松判断,将来换源必须显式改这里的常量。
36
+ export function validateRegistryUrl(candidate) {
37
+ let url;
38
+ try {
39
+ url = new URL(candidate);
40
+ } catch {
41
+ return false;
42
+ }
43
+ return url.protocol === "https:" && url.hostname === REGISTRY_HOST;
44
+ }
45
+
46
+ /** 解析 `x.y.z` / `x.y.z-后缀` 为可比较结构;解析失败返回 null。 */
47
+ function parseVersion(text) {
48
+ if (typeof text !== "string") return null;
49
+ const match = text.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);
50
+ if (!match) return null;
51
+ return {
52
+ major: Number(match[1]),
53
+ minor: Number(match[2]),
54
+ patch: Number(match[3]),
55
+ // 有 prerelease 后缀的同号版本视为更旧(0.9.0-rc.1 < 0.9.0)。
56
+ prerelease: match[4] !== undefined
57
+ };
58
+ }
59
+
60
+ /**
61
+ * 三元组语义化比较:a<b → -1,a>b → 1,无法比较 → null(调用方归入 unknown)。
62
+ * 仅比较数字部分;数字相等时,带 prerelease 的一方更旧(0.9.0-rc.1 < 0.9.0),
63
+ * 两侧都带则视为同版——横幅只关心「是否落后于 latest」,不追求完整 semver 序。
64
+ */
65
+ export function compareVersions(a, b) {
66
+ const va = parseVersion(a);
67
+ const vb = parseVersion(b);
68
+ if (!va || !vb) return null;
69
+ for (const key of ["major", "minor", "patch"]) {
70
+ if (va[key] !== vb[key]) return va[key] < vb[key] ? -1 : 1;
71
+ }
72
+ if (va.prerelease !== vb.prerelease) return va.prerelease ? -1 : 1;
73
+ return 0;
74
+ }
75
+
76
+ /**
77
+ * 运行版本 vs registry latest 的展示归类。latest 为 null(查询失败/离线)
78
+ * 或任一侧解析失败时归 unknown——前端对 unknown 完全静默。
79
+ */
80
+ export function classify(version, latest) {
81
+ const cmp = compareVersions(version, latest);
82
+ if (cmp === null) return "unknown";
83
+ if (cmp < 0) return "outdated";
84
+ if (cmp > 0) return "ahead";
85
+ return "up-to-date";
86
+ }
87
+
88
+ // 模块级缓存:面板可能多处/多次拉取,TTL 内一律复用,不重复打 registry。
89
+ // at 用 -Infinity 作「从未拉取」哨兵:任何时钟下 now-at 都是正无穷,首轮
90
+ // 必然真实请求(测试的假时钟从 0 起也不会被误判成新鲜缓存)。
91
+ let cache = { at: -Infinity, latest: null };
92
+
93
+ /**
94
+ * 查询 registry latest。TTL 内直接命中缓存;任何失败(网络/超时/非 2xx/
95
+ * 响应形状不对/URL 校验不过)都静默返回 null——版本提示是锦上添花,绝不
96
+ * 让它成为新的故障面。失败不写缓存:TTL 起点保持旧值,下次调用立刻重试。
97
+ */
98
+ export async function fetchLatestVersion({ fetchImpl = typeof fetch === "function" ? fetch : () => Promise.reject(new Error("no fetch")), now = Date.now } = {}) {
99
+ if (now() - cache.at < CACHE_TTL_MS) return cache.latest;
100
+ if (!validateRegistryUrl(REGISTRY_URL)) return null;
101
+ let manifest;
102
+ try {
103
+ const response = await fetchImpl(REGISTRY_URL, {
104
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
105
+ headers: { accept: "application/json" }
106
+ });
107
+ if (!response.ok) return null;
108
+ manifest = await response.json();
109
+ } catch {
110
+ return null;
111
+ }
112
+ const latest = typeof manifest?.version === "string" && manifest.version ? manifest.version : null;
113
+ cache = { at: now(), latest };
114
+ return latest;
115
+ }
116
+
117
+ /** 仅供测试:清空模块级缓存与时间戳。 */
118
+ export function resetCacheForTest() {
119
+ cache = { at: -Infinity, latest: null };
120
+ }
121
+
122
+ export { PACKAGE_VERSION, REGISTRY_URL, CACHE_TTL_MS };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@modusensus/dsh-mneme",
3
3
  "description": "Cross-session memory plugin for DeepSeek Harness with autoDream consolidation: SQLite store, Markdown mirrors, 7 model tools, automatic injection, session summarization, user profile/rules, custom slash commands, vector (semantic) search, and a Web GUI panel",
4
- "version": "0.7.32",
4
+ "version": "0.8.1",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
package/src/api.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { URL } from "node:url";
2
- import { readFileSync } from "node:fs";
3
2
  import { timingSafeEqual, randomBytes } from "node:crypto";
4
3
  import { FEATURE_FLAG_SPEC } from "./settings.js";
5
4
  import { TYPE_FILE, renderMirrorText, parseHumanEdits } from "./mirror.js";
@@ -8,6 +7,7 @@ import { computeHeat } from "./heat.js";
8
7
  import { describeStreamFailure, resolveRoute } from "./dream.js";
9
8
  import { describeLocalRuntime, publicRuntimeStatus } from "./runtime/loader.js";
10
9
  import { hostModulesDir, provisionRuntime } from "./runtime/provision.js";
10
+ import { classify, fetchLatestVersion, PACKAGE_VERSION } from "./version-check.js";
11
11
 
12
12
  // headers:少数端点(/export 附件下载)需要追加 Content-Disposition 等响应头。
13
13
  function sendJson(res, status, payload, headers = {}) {
@@ -24,16 +24,8 @@ function sendAttachment(res, status, contentType, filename, body) {
24
24
  res.end(body);
25
25
  }
26
26
 
27
- // 导出 JSON 的 version 字段:读插件根的 package.json(src/ 与 lib/ 都在根下
28
- // 一层,相对 import.meta.url 解析一致)。读取失败(打包/受限环境)降级为
29
- // "unknown",导出本身仍然可用。
30
- const PACKAGE_VERSION = (() => {
31
- try {
32
- return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version ?? "unknown";
33
- } catch {
34
- return "unknown";
35
- }
36
- })();
27
+ // 版本号统一从 version-check.js 取(同一份读 package.json 逻辑,读取失败
28
+ // 同样降级 "unknown")——/info 与 /version-check 两个路由共用,不再各写一份。
37
29
 
38
30
  // Defaults for the standalone external API — keep in step with the schema
39
31
  // defaults in config.js (externalApiPort / externalApiHost).
@@ -175,6 +167,29 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
175
167
  }
176
168
  });
177
169
 
170
+ // 版本自检(#174 后续):运行版本 vs npm registry latest。只读,宿主围栏
171
+ // 统一鉴权(与 dream-status 同款,面板 apiFetch 直接可用)。registry 查询
172
+ // 全失败时 latest=null、status=unknown——前端对 unknown 完全静默,版本提示
173
+ // 是锦上添花,绝不因它新增故障面。
174
+ register({
175
+ kind: "exact",
176
+ path: "/api/dsh-mneme/version-check",
177
+ handler(req, res) {
178
+ if (req.method !== "GET") {
179
+ sendJson(res, 404, { error: "not-found" });
180
+ return;
181
+ }
182
+ fetchLatestVersion()
183
+ .then((latest) => sendJson(res, 200, {
184
+ version: PACKAGE_VERSION,
185
+ latest,
186
+ status: classify(PACKAGE_VERSION, latest),
187
+ checkedAt: new Date().toISOString()
188
+ }))
189
+ .catch(() => sendJson(res, 200, { version: PACKAGE_VERSION, latest: null, status: "unknown" }));
190
+ }
191
+ });
192
+
178
193
  register({
179
194
  kind: "exact",
180
195
  path: "/api/dsh-mneme/list",
@@ -480,6 +495,19 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
480
495
  }
481
496
  patch.tags = body.tags;
482
497
  }
498
+ // v0.8.1 底座(issue #170):显式 scope 修正。null=放宽到全局,
499
+ // 字符串=收窄/改标;归一化("global"/"*"/空白→NULL + explicit 章 +
500
+ // 审计行)在 service.updateMemory 内做,路由只做形状校验。
501
+ if (body.agent_scope !== undefined && body.agent_scope !== null && typeof body.agent_scope !== "string") {
502
+ sendJson(res, 400, { error: "invalid-agent-scope" });
503
+ return;
504
+ }
505
+ if (body.workspace_scope !== undefined && body.workspace_scope !== null && typeof body.workspace_scope !== "string") {
506
+ sendJson(res, 400, { error: "invalid-workspace-scope" });
507
+ return;
508
+ }
509
+ if (body.agent_scope !== undefined) patch.agent_scope = body.agent_scope;
510
+ if (body.workspace_scope !== undefined) patch.workspace_scope = body.workspace_scope;
483
511
  if (body.archived !== undefined && typeof body.archived !== "boolean") {
484
512
  sendJson(res, 400, { error: "invalid-archived" });
485
513
  return;
@@ -501,7 +529,7 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
501
529
  ...history
502
530
  ].slice(0, 20);
503
531
  }
504
- if (Object.keys(patch).length) service.update(id, patch);
532
+ if (Object.keys(patch).length) service.update(id, patch, { actor: "panel" });
505
533
  if (body.archived !== undefined) service.setArchived(id, body.archived);
506
534
  sendJson(res, 200, { memory: service.getById(id) });
507
535
  });
@@ -1014,6 +1042,66 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
1014
1042
  }
1015
1043
  });
1016
1044
 
1045
+ // --- 冲突集中处理(v0.8.0):队列 + 人工确认 --------------------------------
1046
+ // GET /conflicts:未解决冲突 + 双方当前内容(此前面板只有计数与徽章,
1047
+ // resolveConflictPending 在存储层躺着没有任何调用方)。POST /conflicts/resolve:
1048
+ // {id, winner: "a"|"b"|null, apply}——盖章审计,apply 时按 dream 非冻结
1049
+ // conflict 路径同款处置(service.resolveConflictPending 内部复用
1050
+ // applyDecisions:CAS + 事务 + 注记 + 幂等)。认证与其他写路由一致。
1051
+ register({
1052
+ kind: "exact",
1053
+ path: "/api/dsh-mneme/conflicts",
1054
+ handler(req, res) {
1055
+ try {
1056
+ if (req.method !== "GET") {
1057
+ sendJson(res, 404, { error: "not-found" });
1058
+ return;
1059
+ }
1060
+ if (!requireAuth(req, res, apiToken)) return;
1061
+ const url = new URL(req.url, "http://localhost");
1062
+ const limit = Math.min(200, Math.max(1, Number(url.searchParams.get("limit") ?? 50) || 50));
1063
+ const offset = Math.max(0, Number(url.searchParams.get("offset") ?? 0) || 0);
1064
+ const items = service.listConflictQueue({ limit, offset });
1065
+ sendJson(res, 200, { items, total: service.countConflictPending?.() ?? items.length });
1066
+ } catch {
1067
+ sendJson(res, 500, { error: "internal" });
1068
+ }
1069
+ }
1070
+ });
1071
+
1072
+ register({
1073
+ kind: "exact",
1074
+ path: "/api/dsh-mneme/conflicts/resolve",
1075
+ handler(req, res) {
1076
+ try {
1077
+ if (req.method !== "POST") {
1078
+ sendJson(res, 404, { error: "not-found" });
1079
+ return;
1080
+ }
1081
+ if (!requireAuth(req, res, apiToken)) return;
1082
+ return readBody(req).then((text) => {
1083
+ let body = {};
1084
+ try { body = JSON.parse(text || "{}"); } catch { /* 坏 JSON → 走缺参分支 */ }
1085
+ const id = typeof body.id === "string" ? body.id.trim() : "";
1086
+ if (!id) {
1087
+ sendJson(res, 400, { error: "missing-id" });
1088
+ return;
1089
+ }
1090
+ const winner = body.winner === "a" || body.winner === "b" ? body.winner : null;
1091
+ const apply = body.apply !== false;
1092
+ const result = service.resolveConflictPending(id, { winner, apply });
1093
+ if (!result) {
1094
+ sendJson(res, 404, { error: "not-found" });
1095
+ return;
1096
+ }
1097
+ sendJson(res, 200, { ok: true, conflict: result });
1098
+ }).catch(() => sendJson(res, 500, { error: "internal" }));
1099
+ } catch {
1100
+ sendJson(res, 500, { error: "internal" });
1101
+ }
1102
+ }
1103
+ });
1104
+
1017
1105
  // --- health: mirror sync state (F-NEW-03 / v0.3.6) ---
1018
1106
  // Auth-gated; only returns a sanitized error code (never raw last_error which
1019
1107
  // may leak paths/token-like strings/internal hosts). On state read failure it
package/src/commands.js CHANGED
@@ -1,11 +1,16 @@
1
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
1
2
  import { STR } from "./lang.js";
2
3
 
3
4
  // Custom slash-command manager: keeps the DSH command registry in sync with
4
5
  // user-defined commands persisted in SQLite. Commands are registered on boot
5
6
  // and (re)registered on add/remove through the API.
6
7
  //
7
- // Each custom command's handler returns the user-authored instruction as a
8
- // success result; the DSH UI surfaces it as a model-directed instruction.
8
+ // Per the DSH command contract, a handler's CommandResult text is only a UI
9
+ // settlement notice and never reaches the model. To actually drive the agent,
10
+ // the handler submits the user-authored instruction itself as a user followup
11
+ // message on the receiving agent (same pattern as the official /goal command).
12
+ // The notice just acknowledges the submission; an optional rawInput suffix
13
+ // typed after the command is appended for the model.
9
14
 
10
15
  export function createCommandManager({ ctx, settings, logger, language = "zh" }) {
11
16
  const registered = new Map(); // name -> disposer
@@ -18,7 +23,8 @@ export function createCommandManager({ ctx, settings, logger, language = "zh" })
18
23
  name: command.name,
19
24
  // 缺省描述随实例语言(命令描述进命令注册表,对 LLM 可见)。
20
25
  description: command.description || STR.commandFallbackDesc[language](command.name),
21
- handler: () => ({ kind: "success", text: command.instruction })
26
+ input: { hint: STR.commandInputHint[language] },
27
+ handler: (invocation) => submit(command, invocation)
22
28
  });
23
29
  } catch (error) {
24
30
  logger?.warn?.(`dsh-mneme: failed to register command /${command.name}: ${String(error)}`);
@@ -27,6 +33,27 @@ export function createCommandManager({ ctx, settings, logger, language = "zh" })
27
33
  registered.set(command.name, dispose);
28
34
  }
29
35
 
36
+ /** Submit the instruction (plus optional rawInput suffix) to the receiving agent. */
37
+ function submit(command, invocation) {
38
+ const suffix = typeof invocation?.rawInput === "string" ? invocation.rawInput.trim() : "";
39
+ const text = suffix ? `${command.instruction}\n\n${suffix}` : command.instruction;
40
+ const agent = invocation?.agent;
41
+ if (typeof agent?.followup !== "function") {
42
+ // 兜底:宿主未提供接收 agent 时退回旧行为,至少把指令展示在 notice 里。
43
+ return { kind: "success", text };
44
+ }
45
+ try {
46
+ agent.followup(createUserMessage({
47
+ content: [{ type: "text", text }],
48
+ source: { kind: "user" }
49
+ }));
50
+ } catch (error) {
51
+ logger?.warn?.(`dsh-mneme: failed to submit /${command.name} to agent: ${String(error)}`);
52
+ return { kind: "error", text: STR.commandSubmitFailed[language](command.name) };
53
+ }
54
+ return { kind: "success", text: STR.commandSubmitted[language](command.name) };
55
+ }
56
+
30
57
  function unregisterOne(name) {
31
58
  const dispose = registered.get(name);
32
59
  if (dispose) {
package/src/config.js CHANGED
@@ -58,6 +58,11 @@ export const Config = z.object({
58
58
  // 编码记忆注入加权系数:编码任务时对 rejected_solution/pitfall/constraint
59
59
  // 记忆的 importance 乘以该系数排序,让编码记忆在编码场景更靠前。
60
60
  codingBoostFactor: z.number().min(1).max(5).default(2),
61
+ // 注入边界花括号转义(issue #162,v0.7.4 曾修后被 v0.7.11 重构误删):默认开启,
62
+ // 在 memory / 短期上下文 / 用户设置三处注入出口对连续 2+ 个花括号插 `\`
63
+ // (`{{a}}`→`{\{a\}\}`),让 DSH 的 interpolate() 不再扫到非法变量名而 throw。
64
+ // 关闭时按原样透传。
65
+ escapePromptVariables: z.boolean().default(true),
61
66
  autoDream: z.boolean().default(true),
62
67
  dreamThresholdCount: z.natural().min(1).max(1000).default(10),
63
68
  dreamThresholdChars: z.natural().min(100).max(100000).default(5000),
@@ -438,6 +443,22 @@ export const Config = z.object({
438
443
  recallRecordDefault: z.boolean().default(true),
439
444
  // recall_runs 滚动清理保留天数。
440
445
  recallRetentionDays: z.natural().min(1).max(3650).default(90),
446
+
447
+ // --- scope: v0.8.0 A1 存储层(issue #17)--------------------------------
448
+ // 总开关默认关:关闭时写入不标注 scope、去重维持 (type, title) 现状,行为
449
+ // 逐字节不变。开启后 memory_save 写入 agent_scope(session header 的
450
+ // agentPreset)与 workspace_scope(registry 反查 canonical path,header.cwd
451
+ // 兜底,取不到 NULL——解析绝不阻塞写入),去重键扩展为 (type, title,
452
+ // agent_scope, workspace_scope, sensitivity)。检索侧加权/过滤在 A2/A3 落地。
453
+ // 也走 feature_flags(FEATURE_FLAG_BOOLEANS 白名单),面板可启停=线上回滚开关。
454
+ scopeEnabled: z.boolean().default(false),
455
+ // strictScope(A3):硬过滤模式。关闭=A2 软隔离(他 scope 降权保留可见);
456
+ // 开启后检索/注入/list/get 按 issue #17 四象限可见性公式硬过滤——带他 scope
457
+ // 的记忆完全不可见,未标注(NULL)恒可见;当前会话某维度解析不到时该维度
458
+ // 带标注的记忆一律不可见(fail-closed:身份不明只见全局)。依赖 scopeEnabled
459
+ // 打开才有意义(没有写入标注就无可过滤维度),但独立成键:可先开标注积累
460
+ // 数据、观察 A2 加权质量后再切硬过滤。
461
+ strictScope: z.boolean().default(false),
441
462
  });
442
463
 
443
464
  // Fields forced to false by the light-mode preset. Everything not listed here
@@ -4,6 +4,8 @@ import { STR, langOf } from "../lang.js";
4
4
  // 1. conflict resolution — high-similarity same-type pairs are either parked
5
5
  // for review (freeze mode) or adjudicated by the LLM (winner kept / loser
6
6
  // archived), reusing the dream conflict machinery. Strictness-graded.
7
+ // v0.8.1 (issue #170): cross-scope pairs are ALWAYS parked for human
8
+ // ownership review with a dedicated reason — never auto-adjudicated.
7
9
  // 2. archival demotion — memories unreferenced past sleepArchiveDays shrink
8
10
  // to a one-line summary with the full body moved to _full_content; past
9
11
  // sleepCompressDays they are archived outright.
@@ -18,6 +20,7 @@ import { STR, langOf } from "../lang.js";
18
20
  import { randomUUID, createHash } from "node:crypto";
19
21
  import { validateDecisions, applyDecisions, ACTIONS } from "./decisions.js";
20
22
  import { findPotentialConflicts, cosineSimilarity } from "./clustering.js";
23
+ import { scopeKeyOf } from "../scope.js";
21
24
  import { buildReceipt, describeStreamFailure, resolveDreamEffort, withEffortFallback, maintainIndexAfterDream } from "../dream.js";
22
25
  import { computeHeat } from "../heat.js";
23
26
 
@@ -169,29 +172,57 @@ async function phaseConflicts(ctx, service, config, logger, runId, semantic = nu
169
172
  selected.push(p);
170
173
  }
171
174
 
172
- // Freeze mode: park pairs for manual review, no LLM required.
175
+ // v0.8.1(issue #170 第 2 步):跨 scope 相似对分流。同一内容落在两个归属下
176
+ // (任一维标注键不等即算,NULL=未标注=全局也参与比较——「全局副本 + 专属副本
177
+ // 并存」正是收窄/提升裁决的典型候选)不能自动裁决:归档败者可能销毁该内容在
178
+ // 某个归属下的唯一副本,LLM 也无从替用户决定归属。一律停车到冲突待确认队列
179
+ // (专属 reason),同 scope 对维持既有路径(freeze 停车 / LLM 裁决)。
180
+ const isCrossScopePair = (p) =>
181
+ scopeKeyOf(p.a.agent_scope) !== scopeKeyOf(p.b.agent_scope)
182
+ || scopeKeyOf(p.a.workspace_scope) !== scopeKeyOf(p.b.workspace_scope);
183
+ const crossPairs = selected.filter(isCrossScopePair);
184
+ const samePairs = selected.filter((p) => !isCrossScopePair(p));
185
+ const parkPair = (p, reason) => {
186
+ try {
187
+ // 返回 undefined = 该对已被人工裁决且两侧内容未变(复核项 4)——不算停车。
188
+ return service.saveConflictPending({ run_id: runId, memory_a: p.a.id, memory_b: p.b.id, reason }) != null;
189
+ } catch (error) {
190
+ logger?.warn?.(`dsh-mneme sleep: failed to park conflict ${p.a.id}/${p.b.id}: ${String(error)}`);
191
+ return false;
192
+ }
193
+ };
194
+ const scopeReason = (p) => STR.scopeCandidateReason[language](p.similarity.toFixed(2));
195
+ const simReason = (p) => STR.similarityReason[language](p.similarity.toFixed(2));
196
+
197
+ // Freeze mode: park pairs for manual review, no LLM required. Cross-scope
198
+ // pairs carry the dedicated scope-candidate reason so the queue reads them
199
+ // as ownership decisions rather than plain duplicates.
173
200
  if (config.conflictFreezeEnabled === true) {
174
201
  let frozen = 0;
175
202
  for (const p of selected) {
176
- try {
177
- service.saveConflictPending({ run_id: runId, memory_a: p.a.id, memory_b: p.b.id, reason: STR.similarityReason[language](p.similarity.toFixed(2)) });
178
- frozen++;
179
- } catch (error) {
180
- logger?.warn?.(`dsh-mneme sleep: failed to freeze conflict ${p.a.id}/${p.b.id}: ${String(error)}`);
181
- }
203
+ if (parkPair(p, isCrossScopePair(p) ? scopeReason(p) : simReason(p))) frozen++;
182
204
  }
183
- return { status: frozen > 0 ? "ok" : "noop", frozen, pairs: selected.length };
205
+ return { status: frozen > 0 ? "ok" : "noop", frozen, scopeCandidates: crossPairs.length, pairs: selected.length };
184
206
  }
185
207
 
186
- // LLM adjudication.
208
+ // 非 freeze:跨 scope 对先停车(绝不进 LLM 裁决),同 scope 对照常走 LLM。
209
+ let scopeParked = 0;
210
+ for (const p of crossPairs) {
211
+ if (parkPair(p, scopeReason(p))) scopeParked++;
212
+ }
213
+ if (samePairs.length === 0) {
214
+ return { status: scopeParked > 0 ? "ok" : "noop", frozen: 0, scopeCandidates: scopeParked, pairs: selected.length };
215
+ }
216
+
217
+ // LLM adjudication(仅同 scope 对)。
187
218
  const route = resolveSleepRoute(ctx, config, logger);
188
- if (!route) return { status: "skipped", reason: "no llm route" };
219
+ if (!route) return { status: "skipped", reason: "no llm route", scopeCandidates: scopeParked, pairs: selected.length };
189
220
  const snapshot = new Map();
190
- for (const p of selected) {
221
+ for (const p of samePairs) {
191
222
  snapshot.set(p.a.id, p.a);
192
223
  snapshot.set(p.b.id, p.b);
193
224
  }
194
- const listText = selected.map((p) =>
225
+ const listText = samePairs.map((p) =>
195
226
  STR.candidateConflicts[language](p)
196
227
  ).join("\n\n");
197
228
  const sleepEffort = await resolveDreamEffort(ctx, route, config.sleepReasoningEffort, logger);
package/src/dream.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { validateDecisions, applyDecisions } from "./dream/decisions.js";
2
2
  import { clusterMemories, findPotentialConflicts, cosineSimilarity } from "./dream/clustering.js";
3
+ import { scopeKeyOf } from "./scope.js";
3
4
  import { createHash, randomUUID } from "node:crypto";
4
5
  import { STR, langOf } from "./lang.js";
5
6
  export { validateDecisions, applyDecisions, withEffortFallback, describeStreamFailure, resolveDreamEffort, resolveRoute };
@@ -989,7 +990,21 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
989
990
  // bounds the review queue; overflow is skipped with a warning.
990
991
  let frozenCount = 0;
991
992
  const frozenIds = [];
992
- const applyList = freezeEnabled ? decisions.filter((d) => d.action !== "conflict") : decisions;
993
+ // v0.8.1(issue #170 复核项 3):跨 scope 的 conflict 决策两种模式都一律
994
+ // 停车人工裁决、绝不自动归档——否则普通 dream 的 LLM 能归档别的 scope 的
995
+ // 唯一副本,sleep 路径(scope-candidate-queue)的保护在这里缺位。同 scope
996
+ // 的 conflict 决策照旧:freeze 停车 / 非 freeze 自动裁决。
997
+ const isCrossScopeDecision = (d) => {
998
+ const a = snapshot.get(d.winner);
999
+ const b = snapshot.get(d.loser);
1000
+ return !!a && !!b && (
1001
+ scopeKeyOf(a.agent_scope) !== scopeKeyOf(b.agent_scope)
1002
+ || scopeKeyOf(a.workspace_scope) !== scopeKeyOf(b.workspace_scope)
1003
+ );
1004
+ };
1005
+ const applyList = freezeEnabled
1006
+ ? decisions.filter((d) => d.action !== "conflict")
1007
+ : decisions.filter((d) => d.action !== "conflict" || !isCrossScopeDecision(d));
993
1008
  if (freezeEnabled) {
994
1009
  const conflictsToFreeze = decisions.filter((d) => d.action === "conflict");
995
1010
  if (conflictsToFreeze.length > 0) {
@@ -1003,7 +1018,10 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
1003
1018
  }
1004
1019
  for (const d of toFreeze) {
1005
1020
  try {
1006
- service.saveConflictPending({ run_id: runId, memory_a: d.winner, memory_b: d.loser, reason: d.reason });
1021
+ // 返回 undefined = 该对已被人工裁决且两侧内容未变(issue #170 复核
1022
+ // 项 4:内容变了才重新入队)——不算停车、不进 frozenIds。
1023
+ const parked = service.saveConflictPending({ run_id: runId, memory_a: d.winner, memory_b: d.loser, reason: d.reason });
1024
+ if (parked == null) continue;
1007
1025
  frozenCount++;
1008
1026
  frozenIds.push(d.winner, d.loser);
1009
1027
  } catch (error) {
@@ -1014,6 +1032,29 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
1014
1032
  logger?.warn?.(`dsh-mneme dream: conflict freeze lookup failed: ${String(error)}`);
1015
1033
  }
1016
1034
  }
1035
+ } else {
1036
+ // 非 freeze:跨 scope conflict 停车(绝不进 applyDecisions)。带专属
1037
+ // reason + 模型给出的裁决理由,队列里读起来是「归属裁决」而非重复项。
1038
+ const crossScope = decisions.filter((d) => d.action === "conflict" && isCrossScopeDecision(d));
1039
+ for (const d of crossScope) {
1040
+ try {
1041
+ const parked = service.saveConflictPending({
1042
+ run_id: runId,
1043
+ memory_a: d.winner,
1044
+ memory_b: d.loser,
1045
+ reason: STR.scopeConflictParkReason[language](d.reason)
1046
+ });
1047
+ if (parked != null) {
1048
+ frozenCount++;
1049
+ frozenIds.push(d.winner, d.loser);
1050
+ }
1051
+ } catch (error) {
1052
+ logger?.warn?.(`dsh-mneme dream: failed to park cross-scope conflict ${d.winner}/${d.loser}: ${String(error)}`);
1053
+ }
1054
+ }
1055
+ if (crossScope.length > 0) {
1056
+ logger?.info?.(`[dsh-mneme] dream: parked ${crossScope.length} cross-scope conflict(s) for human ownership review`);
1057
+ }
1017
1058
  }
1018
1059
 
1019
1060
  // CAS-guarded, per-decision-transactional apply against the run snapshot:
package/src/inject.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createScopeResolver } from "./scope.js";
1
2
  import { createHotMemory } from "./hot-memory.js";
2
3
  import { STR, langOf } from "./lang.js";
3
4
 
@@ -51,8 +52,16 @@ function extractRounds(ctx, maxRounds) {
51
52
  // 这里用 ?? 兜底而不是直接改成 data.message.content:user 消息与旧的扁平形状都照旧可用。
52
53
  const parts = event?.data?.content ?? event?.data?.message?.content;
53
54
  if (!Array.isArray(parts)) return "";
55
+ // 只取正文 part(type === "text" 或字符串),跳过 reasoning(issue #162):
56
+ // reasoning 里出现 Go template / Vue / Handlebars / 正则 / 日志原文的概率远高于
57
+ // 正文,把它带进 hot memory 会让 `{{...}}` 模板片段注入 prompt。旧的扁平形状
58
+ // (字符串 part)照旧取用,无 type 字段的兜底视为正文。
54
59
  return parts
55
- .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
60
+ .map((p) => {
61
+ if (typeof p === "string") return p;
62
+ if (p?.type && p.type !== "text") return "";
63
+ return p?.text ?? "";
64
+ })
56
65
  .filter(Boolean)
57
66
  .join("\n")
58
67
  .trim();
@@ -85,6 +94,10 @@ export function createInjector(ctx, service, settings, config) {
85
94
  const language = langOf(config);
86
95
  const maxItems = config.maxInjectedItems ?? 5;
87
96
  const threshold = config.importanceThreshold ?? 3;
97
+ // v0.8.0 A3(issue #17):注入路径的会话 scope 解析——strictScope 硬过滤
98
+ // 需要。渲染 ctx 与工具 exec 同形(agent.session),解析器直接复用。
99
+ // logger 透传:registry 反查失败时 warnOnce 才有出口。
100
+ const resolveSessionScope = createScopeResolver({ ctx, config, logger: ctx.logger });
88
101
 
89
102
  // Bug6: bound the injected memory block. Each entry's content is truncated to
90
103
  // MAX_CONTENT chars (trailing `…`); the whole block gets a MAX_BLOCK budget
@@ -103,6 +116,24 @@ export function createInjector(ctx, service, settings, config) {
103
116
  return text.length <= maxLength ? text : `${text.slice(0, maxLength)}…`;
104
117
  }
105
118
 
119
+ // Prompt-variable brace escaping (issue #162, restored from v0.7.4 #40):
120
+ // DSH's interpolate() scans every injected section for `{{...}}` and throws
121
+ // unless the variable name matches /^[a-z][a-z0-9_]*$/ — memory/profile
122
+ // content carrying legal template syntax (docker `--format "{{.Server.Version}}"`,
123
+ // Obsidian-style `{{hl|}}`, `{{挖空}}`, `{{关键词}}`) would hit an illegal
124
+ // variable name and throw, crashing the whole turn. At the injection boundary
125
+ // we escape every run of 2+ consecutive braces, inserting a `\` between each
126
+ // pair, so no `{{`/`}}` substring survives into the prompt: `{{a}}` → `{\{a\}\}`,
127
+ // and odd runs like `{{{a}}}` (which pair-wise escaping would leave with a
128
+ // literal `{{`) are handled too. The text keeps its readable template form,
129
+ // the transform is idempotent (escaped braces are single + `\`, never two
130
+ // adjacent), and single braces pass through untouched — interpolate only
131
+ // scans `{{`. Off via config.escapePromptVariables=false (default true).
132
+ function escapePromptVars(text) {
133
+ if (config.escapePromptVariables === false) return String(text);
134
+ return String(text).replace(/[{}]{2,}/g, (run) => run.split("").join("\\"));
135
+ }
136
+
106
137
  // Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
107
138
  // the materialized event log on every render — stateless, so it survives
108
139
  // session switches and never persists anywhere.
@@ -119,7 +150,7 @@ export function createInjector(ctx, service, settings, config) {
119
150
  for (const r of rounds) hot.add(r);
120
151
  const body = hot.getContext();
121
152
  if (!body) return "";
122
- return STR.hotHeader[language](rounds.length, body);
153
+ return escapePromptVars(STR.hotHeader[language](rounds.length, body));
123
154
  }
124
155
 
125
156
  function render(candidates) {
@@ -143,7 +174,7 @@ export function createInjector(ctx, service, settings, config) {
143
174
  lines.push(`- [${m.type}] ${verified}${title}`);
144
175
  }
145
176
  }
146
- return lines.join("\n");
177
+ return escapePromptVars(lines.join("\n"));
147
178
  }
148
179
 
149
180
  // Bug4: the system-prompt render is synchronous, so the semantic query vector
@@ -177,7 +208,7 @@ export function createInjector(ctx, service, settings, config) {
177
208
  const lines = [STR.userSettingsHeader[language]];
178
209
  if (profile) lines.push(STR.profileLine[language](profile));
179
210
  for (const rule of rules) lines.push(STR.ruleLine[language](rule));
180
- return lines.join("\n");
211
+ return escapePromptVars(lines.join("\n"));
181
212
  }
182
213
 
183
214
  const disposers = [
@@ -192,7 +223,10 @@ export function createInjector(ctx, service, settings, config) {
192
223
  const query = lastUserQuery(ctx);
193
224
  if (query) prefetchQueryVector(query);
194
225
  const queryVector = queryVectorCache.get(query);
195
- const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold });
226
+ // v0.8.0 A3:scope 随请求解析(strict 开启时 injectCandidates 内硬过滤;
227
+ // flag 关闭时解析器返回 null,注入行为不变)。
228
+ const scope = resolveSessionScope(ctx);
229
+ const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold, scope });
196
230
  // Hot memory (v0.5.0 1.3) leads the single memory block: the agent
197
231
  // sees the short-term rounds first, then the cross-session recall —
198
232
  // the documented injection order 1→2. Folding it here (instead of a