@modusensus/dsh-mneme 0.7.22 → 0.7.23

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/README.en.md CHANGED
@@ -7,7 +7,7 @@ English | [简体中文](README.md)
7
7
  [![npm version](https://img.shields.io/npm/v/@modusensus/dsh-mneme?color=blue&label=npm)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
8
8
  [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
9
9
  [![Awesome](https://awesome-dsh-plugin.com/badge.svg)](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin)
10
- [![tests](https://img.shields.io/badge/tests-685%20passed-success)](https://github.com/modusensus/dsh-mneme)
10
+ [![tests](https://img.shields.io/badge/tests-712%20passed-success)](https://github.com/modusensus/dsh-mneme)
11
11
 
12
12
  > A cross-session memory plugin for DeepSeek Harness: it lets the Agent remember you, remember your projects, and organize memories automatically. **Mneme** (Μνήμη) — named after Mnemosyne, the Greek goddess of memory who presides over memory and dreams, just as autoDream consolidates memories in the background.
13
13
 
@@ -58,15 +58,15 @@ English | [简体中文](README.md)
58
58
 
59
59
  #### dreamMaxTokens Tuning Guide
60
60
 
61
- The default `8192` covers ordinary memory stores. When the **memory volume is large** (tens of thousands of characters or more), the decision list and summary may exceed the default budget; scale it up by size:
61
+ The default `32768` reserves headroom for reasoning models, where reasoning alone may consume 8k+ tokens before any body output. For **larger memory stores** scale it up by size:
62
62
 
63
63
  | Memory store size | Recommended `dreamMaxTokens` |
64
64
  |-----------|----------------------|
65
- | Ordinary (<10k chars) | `8192` (default) |
65
+ | Ordinary (<10k chars) | `32768` (default) |
66
66
  | Medium (10k–50k chars) | `65536` |
67
67
  | Large (>50k chars) | `131072` (cap) |
68
68
 
69
- > With **reasoning models** (e.g. DeepSeek-R1-like), the model may spend the entire budget on reasoning and return an empty body (the log shows `no json array in llm output`). In that case, setting `dreamReasoningEffort` to `low` suppresses reasoning overhead and leaves the budget for the body output; the sleep side has the corresponding `sleepReasoningEffort`. The default `none` omits the field entirely, fully honoring the model's own default behavior identical to earlier versions.
69
+ > With **reasoning models** (e.g. DeepSeek-R1-like), the model may spend the entire budget on reasoning and return an empty body (the log shows `no json array in llm output`). Resolution order: set `dreamReasoningEffort` to `low` to suppress reasoning overhead (when the provider rejects the parameter it is stripped automatically and retried once — the rejection reason lands in `llm_audit`; some models, e.g. v4-flash-ga, reject every effort tier); ② if the retry still returns an empty body under the model's default reasoning behavior, raise `dreamMaxTokens` (reasoning and body share this budget) or route `dreamProvider`/`dreamModel` to a non-reasoning model. The sleep side has the corresponding `sleepReasoningEffort`.
70
70
 
71
71
  ### Sleep Mode: System-Level Sleep 💤 (v0.4.0, opt-in)
72
72
 
@@ -166,6 +166,7 @@ Every **background LLM call** (autoDream consolidation + summary, autoSummarize
166
166
 
167
167
  | Version | Highlights |
168
168
  |------|------|
169
+ | **v0.7.23** | Root-caused "memory consolidation keeps failing": a legal empty decision array `[]` from consolidation is no longer treated as a failure (CONSOLIDATION_PROMPT explicitly allows "no output when nothing needs changing", so a model with a healthy, non-redundant memory legitimately returns `[]` — yet `validateDecisions` hard-rejected it as `decision list must be a non-empty array`, failing the whole run and flooding the audit with failures; **model-agnostic** — ChatGPT/Claude hit the same trap; fix: empty array short-circuits to `ok:true` no-op instead of tripping the implicit-keep coverage check). Plus: empty-body fix part 2 (`dreamMaxTokens` default 8192→32768 so thinking models don't burn the whole budget on reasoning) + skipInvalid splice residue bug (length equality ≠ content equality, skipped decisions leaked into apply/audit); 712 tests green |
169
170
  | **v0.7.22** | Restored the v0.6.9 skipInvalid tolerant-validation path (issue #89 regression, lost in the v0.7.11 rewrite): `dreamSkipInvalid` (default true) skips individual invalid decisions, applies the valid subset, and marks the run degraded; `allowCrossTypeMerge` (default false) explicitly relaxes cross-type merging — weak models (e.g. qwen3.8-flash) with jittery schema compliance no longer fail the whole batch and burn LLM calls. Strict mode and the sleep path behave unchanged; global caps/coverage floors still reject the whole run (running over cap = broken model, not minor schema drift). New `dreamMinIntervalMinutes` (0–10080, default 0 = unlimited) minimum autoDream trigger interval — failed/degraded runs also consume the interval (throttling exists to stop back-to-back failing calls); feature_flags whitelist now 34 keys; 696 tests green |
170
171
  | **v0.7.21** | Fixed autoDream/sleep effort fallback being dead code on the stream path (the catch-based retry from v0.7.16 never fired): dsh-llm rc.1 turns adapter-stage failures (incl. `UNSUPPORTED_REASONING_EFFORT`) into a terminal error finish chunk instead of a throw; `streamText` now captures the finish-chunk failure cause (`describeStreamFailure` normalizes `{code,message}`) + `withEffortFallback` gains a `getStreamError` accessor (retries without effort when rejected) + `runAuditedLlm` supports `spec.streamError` (audit `error_message` carries the real cause; `run.error` stays a stable `"llm failed"`); 688 tests green |
171
172
  | **v0.7.20** | Heat model restored (issue #87): v0.7.0 self-evolving memory back (`src/heat.js` power-law decay `H=1/(1+λΔt)^α` + per-type half-lives), sleep demotion dual protection (cold time-window + heat<0.05 + importance<5), touchRecalled gating back on `heatEnabled`, entity heat projection (ego node heat → size/opacity), recall_runs recording on by default; **default OFF** (matches v0.7.12 behavior out of the box) + feature_flags whitelist rollback switch + lightMode linkage + sleep demotion audit counts exposed (workbench can show "N demoted") + phase-two frontend (/list heat projection, HeatBadge three-tier badge, self-gated status heat-distribution card, order=heat page-local sort, all self-gated); better-sidebar fix (issue #88: soft integration moved to an inner dynamic sub-plugin, no more startup failure without bs); 685 tests green |
@@ -291,7 +292,7 @@ It works out of the box with the defaults. To adjust, override in `~/.dsh/profil
291
292
  | `dreamThresholdChars` | `5000` | Total character threshold that triggers consolidation |
292
293
  | `dreamDelayMs` | `2000` | Asynchronous consolidation delay (debounce) |
293
294
  | `dreamProvider` / `dreamModel` | empty | Explicit dream LLM route — config wins over the agent's default model (config-first, v0.7.16); left empty, the agent's default model is used |
294
- | `dreamMaxTokens` | `8192` | Maximum tokens per dream LLM call (cap 131072; increase for large memory stores — see the tuning guide below) |
295
+ | `dreamMaxTokens` | `32768` | Maximum tokens per dream LLM call (cap 131072; reasoning and body share this budget on reasoning models raise it when the body comes back empty, see the tuning guide below) |
295
296
  | `dreamReasoningEffort` | `none` | Reasoning-effort passthrough for the dream LLM: `low` / `medium` / `high` / `none` (`none` = omit the field and use the model default; set `low` when a reasoning model exhausts its budget on reasoning and produces an empty body) |
296
297
  | `apiToken` | empty | Optional API auth token; once set, write operations and key endpoints require `Authorization: Bearer <apiToken>` |
297
298
  | `embedProvider` | `openai` | Semantic backend: `openai` (default, v0.1-compatible) / `local` (ONNX offline) / `ollama` |
@@ -440,7 +441,7 @@ src/
440
441
  lib/
441
442
  ├── client.js # Web 面板(手写 ModuleLoader bundle)
442
443
  └── *.js # src 的同步分发产物
443
- test/ # 662 node:test tests (audit + three-axis stress invariants)
444
+ test/ # 712 node:test tests (audit + three-axis stress invariants)
444
445
  scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压测 · sync-lib.js 同步
445
446
  ```
446
447
 
@@ -449,7 +450,7 @@ scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压
449
450
  ```bash
450
451
  cd dsh-mneme
451
452
  npm install # 安装 peer 依赖(以 devDependencies 形式,用于本地测试)
452
- npm test # 运行 662 个测试
453
+ npm test # 运行 712 个测试
453
454
  npm run stress # 三轴线压测:长会话检索 / 冲突仲裁 / 多 Agent 并发(离线 mock LLM)
454
455
  npm run sync # 把 src/ 同步到 lib/(发布时由 prepack 钩子自动执行)
455
456
  ```
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![npm version](https://img.shields.io/npm/v/@modusensus/dsh-mneme?color=blue&label=npm)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
6
6
  [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
7
7
  [![Awesome](https://awesome-dsh-plugin.com/badge.svg)](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin)
8
- [![tests](https://img.shields.io/badge/tests-685%20passed-success)](https://github.com/modusensus/dsh-mneme)
8
+ [![tests](https://img.shields.io/badge/tests-712%20passed-success)](https://github.com/modusensus/dsh-mneme)
9
9
  [![CI](https://img.shields.io/github/actions/workflow/status/modusensus/dsh-mneme/ci.yml)](https://github.com/modusensus/dsh-mneme/actions)
10
10
  [![node](https://img.shields.io/badge/node-24%2B-blue)](https://nodejs.org)
11
11
  [![npm downloads](https://img.shields.io/npm/dm/@modusensus/dsh-mneme?color=blue&label=downloads)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
@@ -81,15 +81,15 @@ dsh web
81
81
 
82
82
  #### dreamMaxTokens 调优指南
83
83
 
84
- 默认 `8192` 已覆盖常规记忆库。当**记忆量大**(数万字符以上)时,决策清单与摘要可能超过默认预算,建议按规模调大:
84
+ 默认 `32768` 已为思考型模型预留推理+正文的双重预算(部分思考型模型仅推理就可能消耗 8k+ token)。当**记忆量大**(数万字符以上)时按规模继续调大:
85
85
 
86
86
  | 记忆库规模 | 建议 `dreamMaxTokens` |
87
87
  |-----------|----------------------|
88
- | 常规(<1 万字) | `8192`(默认) |
88
+ | 常规(<1 万字) | `32768`(默认) |
89
89
  | 中等(1 万-5 万字) | `65536` |
90
90
  | 大型(5 万字以上) | `131072`(上限) |
91
91
 
92
- > 若使用**思考型模型**(如 deepseek-v4-flash / DeepSeek-R1 类),模型可能把全部预算花在 reasoning 上导致正文为空(日志出现 `no json array in llm output`,v0.7.16 已修复)。此时把 `dreamReasoningEffort` 设为 `low` 显式压低思考(`none` 默认不传该字段,完全沿用模型自身默认,行为与旧版本一致);即使被方舟拒绝该参数,v0.7.16 起也会自动去掉重试一次。sleep 侧对应 `sleepReasoningEffort`。
92
+ > 若使用**思考型模型**(如 deepseek-v4-flash / DeepSeek-R1 类),模型可能把全部预算花在 reasoning 上导致正文为空(日志出现 `no json array in llm output`)。处理顺序:① `dreamReasoningEffort` 设为 `low` 显式压低思考(被方舟拒绝该参数时自动去掉重试一次,拒绝原因会记入 llm_audit——部分模型如 v4-flash-ga 不支持任何 effort 档位);② 重试走模型默认思考行为后正文仍为空的,调大 `dreamMaxTokens`(reasoning 与正文共享该预算)或配置 `dreamProvider`/`dreamModel` 指向非思考模型。sleep 侧对应 `sleepReasoningEffort`。
93
93
 
94
94
  ### Sleep Mode 系统级睡眠 💤(v0.4.0,opt-in)
95
95
 
@@ -207,6 +207,7 @@ v0.3.0 起新增**记忆基因**层:从记忆里抽取**命名实体**、**带
207
207
 
208
208
  | 版本 | 亮点 |
209
209
  |------|------|
210
+ | **v0.7.23** | 记忆沉淀「反复失败」根治:consolidation 合法空数组 `[]` 不再误判 failed(CONSOLIDATION_PROMPT 允许「无问题无需输出」,模型无冗余时合法返回 `[]`——此前 `validateDecisions` 硬判 non-empty → 整单 failed、审计反复失败,且与模型无关,ChatGPT/Claude 同样踩中;修复:空数组显式短路 `ok:true` no-op)+ 空体修复第二段(`dreamMaxTokens` 默认 8192→32768,思考模型推理烧光预算的根治余量,设置面板可调)+ skipInvalid splice 残留 bug(长度相等≠内容一致,被跳决策残留);712 测试全绿 |
210
211
  | **v0.7.22** | 恢复 v0.6.9 的 skipInvalid 宽容校验路径(issue #89 回归,v0.7.11 重写丢失):`dreamSkipInvalid`(默认 true)单条非法决策跳过 + 合法子集应用 + run 记 degraded,`allowCrossTypeMerge`(默认 false)显式放宽跨类型合并——弱模型(如 qwen3.8-flash)决策合规抖动不再整单拒绝白烧 LLM 调用;严格模式/sleep 路径行为不变,全局上限/覆盖率下限仍整单拒绝(刷爆上限=模型坏了,非轻微 schema 漂移);新增 `dreamMinIntervalMinutes`(0-10080,默认 0=不限)autoDream 最小触发间隔,失败/degraded run 也占用间隔(节流防失败调用连发);feature_flags 白名单 34 键;696 测试全绿 |
211
212
  | **v0.7.21** | 修复 autoDream/sleep 的 effort 回退在流式路径失效(v0.7.16 的 catch 式回退是死代码):dsh-llm rc.1 把 adapter 阶段异常(含 `UNSUPPORTED_REASONING_EFFORT`)转成终态 error finish chunk 不再抛出;`streamText` 现捕获 finish-chunk 失败原因(新增 `describeStreamFailure` 归一化 `{code,message}`)+ `withEffortFallback` 增加 `getStreamError` 访问器(effort 被拒时去掉重试一次)+ `runAuditedLlm` 支持 `spec.streamError`(audit 行 `error_message` 携带真实原因,`run.error` 稳定 `"llm failed"` 不变);688 测试全绿 |
212
213
  | **v0.7.20** | heat 热度模型回归(issue #87):找回 v0.7.0 自进化记忆(`src/heat.js` 幂律衰减 `H=1/(1+λΔt)^α` + per-type 差异化半衰期)、sleep 降级热联合双保护(时间窗冷 + heat<0.05 + importance<5)、touchRecalled 门控改回 `heatEnabled`、实体热投影(ego 节点 heat → 前端大小/明暗)、recall_runs 默认记录;**默认关**(默认=与 v0.7.12 行为一致)+ feature_flags 白名单回滚开关 + lightMode 联动 + sleep 降级审计计数暴露(工作动态可展示"降级 N 条")+ 阶段二前端(/list heat 投影、HeatBadge 三档徽章、状态页热度分布卡、order=heat 页内排序,全部自门控);better-sidebar 修复(issue #88:软集成改内层动态子插件,无 bs 环境不再启动失败);685 测试全绿 |
@@ -292,6 +293,7 @@ v0.3.0 起新增**记忆基因**层:从记忆里抽取**命名实体**、**带
292
293
  | **v0.7.18** | ✅ 完成 | 生态第一步 + 查询收敛 | better-sidebar 软集成(inject 声明 + optional peer `dsh-better-sidebar` + registerTab 复用四视图,未装安全跳过;窄容器 `@container` 适配)+ `/list?deposited=only` 沉淀视图(receipt_chain ∪ source=dream)+ 记忆库沉淀/已归档筛选 chip + 状态页仪表盘化(统计 + 查看全部跳转预置筛选)+ 抽屉归档记忆「恢复」;667 测试全绿 |
293
294
  | **v0.7.20** | ✅ 完成 | heat 回归 + 阶段二前端 + better-sidebar 修复 | heat 热度模型完整找回(issue #87,v0.7.10 移植:幂律衰减 + TYPE_DECAY + sleep 热联合双保护 + 实体热投影)+ 验收清单落地(heatEnabled 默认关 / feature_flags 31 键 / lightMode 联动 / sleep 降级审计暴露 / updated_at⊥last_accessed_at 契约)+ 阶段二前端(/list heat 投影、HeatBadge 三档、order=heat 页内排序)+ better-sidebar 修复(issue #88:内层动态子插件);685 测试全绿 |
294
295
  | **v0.7.21** | ✅ 完成 | effort 回退流式修复 | autoDream/sleep 的 catch 式 effort 回退在流式路径是死代码(dsh-llm rc.1 把 adapter 异常转成终态 error finish chunk 不再抛出)→ `streamText` 捕获 finish-chunk 失败原因(`describeStreamFailure` 归一化)+ `withEffortFallback` 增加 `getStreamError` 访问器(effort 被拒去重试)+ `runAuditedLlm` 支持 `spec.streamError`(audit 记真实原因);688 测试全绿 |
296
+ | **v0.7.23** | ✅ 完成 | 记忆沉淀「反复失败」根治 + 空体第二段 + skipInvalid splice 修复 | consolidation 合法空数组 `[]` no-op(CONSOLIDATION_PROMPT 允许无问题无需输出;此前 validateDecisions 硬判 non-empty → 整单 failed,模型无关、ChatGPT/Claude 同样踩中;修复:空数组显式短路 ok,不再触发隐式 keep 覆盖率误判);`dreamMaxTokens` 默认 8192→32768(思考模型推理烧光预算根治余量);skipInvalid splice 残留 bug(长度相等≠内容一致,被跳决策残留进 apply);712 测试全绿 |
295
297
  | **v0.7.22** | ✅ 完成 | skipInvalid 宽容校验回归(issue #89)+ autoDream 节流 | 恢复 v0.6.9 的 skipInvalid 双轨结构(v0.7.11 重写丢失):`dreamSkipInvalid` 单条非法决策跳过 + 合法子集应用 + run 记 degraded,`allowCrossTypeMerge` 显式放宽跨类型合并;弱模型(qwen3.8-flash)决策合规抖动不再整单拒绝;新增 `dreamMinIntervalMinutes`(0-10080,默认 0=不限)最小触发间隔,失败/degraded run 也占用间隔;严格模式/sleep 路径行为不变;feature_flags 白名单 34 键;696 测试全绿 |
296
298
  | **v0.8.0** | 🚧 计划中(9 月末) | 图谱增强 | 兴趣漂移可视化 + scope 隔离(issue #17)+ 跨 workspace 记忆共享 |
297
299
 
@@ -363,7 +365,7 @@ dsh web
363
365
  | `dreamThresholdChars` | `5000` | 触发整理的总字符阈值 |
364
366
  | `dreamDelayMs` | `2000` | 整理异步延迟(去抖) |
365
367
  | `dreamProvider` / `dreamModel` | 空 | dream 的 LLM 路由覆盖(显式配置优先于 agent 默认模型;留空则回退到 agent 默认模型) |
366
- | `dreamMaxTokens` | `8192` | dream LLM 调用最大 token 数(上限 131072;大记忆量建议调大,见下方调优指南) |
368
+ | `dreamMaxTokens` | `32768` | dream LLM 调用最大 token 数(上限 131072;思考型模型的 reasoning 与正文共享该预算,正文为空时优先调大,见下方调优指南) |
367
369
  | `dreamReasoningEffort` | `none` | dream LLM 推理强度透传:`low` / `medium` / `high` / `none`(`none`=不传该字段,沿用模型默认;思考型模型(如 deepseek-v4-flash)想压低思考可设 `low`;被方舟拒绝该参数时 v0.7.16 起自动去掉重试一次) |
368
370
  | `apiToken` | 空 | 可选 API 鉴权 token;设置后写操作与密钥接口要求 `Authorization: Bearer <apiToken>` |
369
371
  | `embedProvider` | `openai` | 语义后端:`openai`(默认,兼容 v0.1)/ `local`(ONNX 离线)/ `ollama` |
@@ -527,7 +529,7 @@ src/
527
529
  ├── api.js # HTTP 路由(Web 面板数据通道)
528
530
  └── index.js # 插件接线
529
531
  lib/ # src 的同步分发产物(npm run sync;发布前由 root prepack 的 check-sync.js 校验一致性;唯一手写例外 lib/client.js——Web 面板 bundle,sync 不覆盖)
530
- test/ # 662 个 node:test 测试(审计与三轴线压测不变量;src↔lib 一致性由 scripts/check-sync.js 发布闸门校验)
532
+ test/ # 712 个 node:test 测试(审计与三轴线压测不变量;src↔lib 一致性由 scripts/check-sync.js 发布闸门校验)
531
533
  scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压测 · sync-lib.js 同步 · check-sync.js 发布闸门 · benchmark-recall.js 召回基准
532
534
  ```
533
535
 
@@ -536,7 +538,7 @@ scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压
536
538
  ```bash
537
539
  cd dsh-mneme
538
540
  npm install # 安装 peer 依赖(以 devDependencies 形式,用于本地测试)
539
- npm test # 运行 662 个测试
541
+ npm test # 运行 712 个测试
540
542
  npm run stress # 三轴线压测:长会话检索 / 冲突仲裁 / 多 Agent 并发(离线 mock LLM)
541
543
  npm run sync # 把 src/ 同步到 lib/(发布时由 prepack 钩子自动执行)
542
544
  ```
package/bin/cli.mjs CHANGED
File without changes
package/lib/config.js CHANGED
@@ -54,7 +54,7 @@ export const Config = z.object({
54
54
  dreamMinIntervalMinutes: z.natural().min(0).max(10080).default(0),
55
55
  dreamProvider: z.string(),
56
56
  dreamModel: z.string(),
57
- dreamMaxTokens: z.natural().min(256).max(131072).default(8192),
57
+ dreamMaxTokens: z.natural().min(256).max(131072).default(32768),
58
58
  // Pass-through reasoning effort for dream's LLM calls. 'none' (default)
59
59
  // omits the field so the provider's own default applies; low/medium/high
60
60
  // are forwarded verbatim. Useful to cap reasoning spend on thinking-type
@@ -25,8 +25,15 @@ export function validateDecisions(decisions, snapshot, options = {}) {
25
25
  const skipInvalid = options.skipInvalid === true;
26
26
  const maxUpdatePerRun = options.maxUpdatePerRun ?? 2;
27
27
  const minAgeHours = options.minAgeHours ?? 24;
28
- if (!Array.isArray(decisions) || decisions.length === 0) {
29
- return { ok: false, errors: ["decision list must be a non-empty array"] };
28
+ if (!Array.isArray(decisions)) {
29
+ return { ok: false, errors: ["decision list must be an array"] };
30
+ }
31
+ // 空决策 = 模型完整评估后确认无需操作(CONSOLIDATION_PROMPT 明确允许"无问题的
32
+ // 条目无需输出")。合法 JSON [] 不是空体(那是无输出/截断),也不是"残缺输出"
33
+ // ——显式短路直接 ok,避免隐式 keep 的覆盖率检查把 0% 误判为模型坏了。与
34
+ // sleep 的空模式(skipped no-op)语义对齐:下游 applied=0、audit 记 ok。
35
+ if (decisions.length === 0) {
36
+ return { ok: true, errors: [], skipped: [] };
30
37
  }
31
38
  const claimed = new Set();
32
39
  for (const [index, d] of decisions.entries()) {
@@ -183,10 +190,10 @@ export function validateDecisions(decisions, snapshot, options = {}) {
183
190
  }
184
191
  // 调用方下游(apply/audit)复用同一 decisions 引用:就地同步为 survivors——
185
192
  // 在 skipInvalid 模式下去掉被跳过的非法决策;在隐式 keep 下追加补齐的 keep。
186
- // 内容一致时(无跳过、无补齐)为 no-op。
187
- if (survivors.length !== decisions.length) {
188
- decisions.splice(0, decisions.length, ...survivors);
189
- }
193
+ // 不能以 survivors.length !== decisions.length 作为是否 splice 的判据:
194
+ // 当"被跳过的非法决策数 == 隐式补齐的 keep 数"时长度回到相等但内容已变,
195
+ // 被跳过的决策会残留进 apply/audit。一律无条件 splice 最安全。
196
+ decisions.splice(0, decisions.length, ...survivors);
190
197
  return { ok: true, errors, skipped };
191
198
  }
192
199
 
package/lib/index.js CHANGED
@@ -21,7 +21,10 @@ import { join } from "node:path";
21
21
  import { homedir } from "node:os";
22
22
 
23
23
  export const name = "dsh-mneme";
24
- export const inject = ["tools", "systemPrompt", "webServer", "llm", "agentDefaultModel", "commands"];
24
+ // webServer 为可选依赖(headless/无 UI 宿主兼容):从 inject 声明中去掉,cordis
25
+ // 不再等待它激活;运行时 ctx.webServer 为空则跳过 API 注册(下方 if 守卫),
26
+ // 记忆工具/注入/dream 全部照常工作。
27
+ export const inject = ["tools", "systemPrompt", "llm", "agentDefaultModel", "commands"];
25
28
  export { Config };
26
29
 
27
30
  // Arrow (not function declaration): cordis 4 treats any apply with a
package/lib/settings.js CHANGED
@@ -74,7 +74,8 @@ const FEATURE_FLAG_INT_RANGES = {
74
74
  distillRateLimitBaseDelayMs: [100, 60000],
75
75
  distillMaxChars: [1000, 200000],
76
76
  codingBoostFactor: [1, 5],
77
- dreamMinIntervalMinutes: [0, 10080]
77
+ dreamMinIntervalMinutes: [0, 10080],
78
+ dreamMaxTokens: [256, 131072]
78
79
  };
79
80
  // 自由字符串开关(与 config.js 的 z.string() 同名同型):trim 后 ≤200 字符,
80
81
  // 空串合法(= 跟随主对话模型/默认路径,面板显示 placeholder)。
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.22",
4
+ "version": "0.7.23",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
package/src/config.js CHANGED
@@ -54,7 +54,7 @@ export const Config = z.object({
54
54
  dreamMinIntervalMinutes: z.natural().min(0).max(10080).default(0),
55
55
  dreamProvider: z.string(),
56
56
  dreamModel: z.string(),
57
- dreamMaxTokens: z.natural().min(256).max(131072).default(8192),
57
+ dreamMaxTokens: z.natural().min(256).max(131072).default(32768),
58
58
  // Pass-through reasoning effort for dream's LLM calls. 'none' (default)
59
59
  // omits the field so the provider's own default applies; low/medium/high
60
60
  // are forwarded verbatim. Useful to cap reasoning spend on thinking-type
@@ -25,8 +25,15 @@ export function validateDecisions(decisions, snapshot, options = {}) {
25
25
  const skipInvalid = options.skipInvalid === true;
26
26
  const maxUpdatePerRun = options.maxUpdatePerRun ?? 2;
27
27
  const minAgeHours = options.minAgeHours ?? 24;
28
- if (!Array.isArray(decisions) || decisions.length === 0) {
29
- return { ok: false, errors: ["decision list must be a non-empty array"] };
28
+ if (!Array.isArray(decisions)) {
29
+ return { ok: false, errors: ["decision list must be an array"] };
30
+ }
31
+ // 空决策 = 模型完整评估后确认无需操作(CONSOLIDATION_PROMPT 明确允许"无问题的
32
+ // 条目无需输出")。合法 JSON [] 不是空体(那是无输出/截断),也不是"残缺输出"
33
+ // ——显式短路直接 ok,避免隐式 keep 的覆盖率检查把 0% 误判为模型坏了。与
34
+ // sleep 的空模式(skipped no-op)语义对齐:下游 applied=0、audit 记 ok。
35
+ if (decisions.length === 0) {
36
+ return { ok: true, errors: [], skipped: [] };
30
37
  }
31
38
  const claimed = new Set();
32
39
  for (const [index, d] of decisions.entries()) {
@@ -183,10 +190,10 @@ export function validateDecisions(decisions, snapshot, options = {}) {
183
190
  }
184
191
  // 调用方下游(apply/audit)复用同一 decisions 引用:就地同步为 survivors——
185
192
  // 在 skipInvalid 模式下去掉被跳过的非法决策;在隐式 keep 下追加补齐的 keep。
186
- // 内容一致时(无跳过、无补齐)为 no-op。
187
- if (survivors.length !== decisions.length) {
188
- decisions.splice(0, decisions.length, ...survivors);
189
- }
193
+ // 不能以 survivors.length !== decisions.length 作为是否 splice 的判据:
194
+ // 当"被跳过的非法决策数 == 隐式补齐的 keep 数"时长度回到相等但内容已变,
195
+ // 被跳过的决策会残留进 apply/audit。一律无条件 splice 最安全。
196
+ decisions.splice(0, decisions.length, ...survivors);
190
197
  return { ok: true, errors, skipped };
191
198
  }
192
199
 
package/src/index.js CHANGED
@@ -21,7 +21,10 @@ import { join } from "node:path";
21
21
  import { homedir } from "node:os";
22
22
 
23
23
  export const name = "dsh-mneme";
24
- export const inject = ["tools", "systemPrompt", "webServer", "llm", "agentDefaultModel", "commands"];
24
+ // webServer 为可选依赖(headless/无 UI 宿主兼容):从 inject 声明中去掉,cordis
25
+ // 不再等待它激活;运行时 ctx.webServer 为空则跳过 API 注册(下方 if 守卫),
26
+ // 记忆工具/注入/dream 全部照常工作。
27
+ export const inject = ["tools", "systemPrompt", "llm", "agentDefaultModel", "commands"];
25
28
  export { Config };
26
29
 
27
30
  // Arrow (not function declaration): cordis 4 treats any apply with a
package/src/settings.js CHANGED
@@ -74,7 +74,8 @@ const FEATURE_FLAG_INT_RANGES = {
74
74
  distillRateLimitBaseDelayMs: [100, 60000],
75
75
  distillMaxChars: [1000, 200000],
76
76
  codingBoostFactor: [1, 5],
77
- dreamMinIntervalMinutes: [0, 10080]
77
+ dreamMinIntervalMinutes: [0, 10080],
78
+ dreamMaxTokens: [256, 131072]
78
79
  };
79
80
  // 自由字符串开关(与 config.js 的 z.string() 同名同型):trim 后 ≤200 字符,
80
81
  // 空串合法(= 跟随主对话模型/默认路径,面板显示 placeholder)。
package/test/api.test.js CHANGED
@@ -527,14 +527,16 @@ test("GET /api/dsh-mneme/features returns empty overrides and effective config d
527
527
  assert.equal(res.statusCode, 200);
528
528
  const data = JSON.parse(res.body);
529
529
  assert.deepEqual(data.overrides, {});
530
- // effective 覆盖全部 34 个白名单键(含 v0.7.20 heatEnabledIssue #89 回归
531
- // 修复新增的 dreamSkipInvalid/allowCrossTypeMerge/dreamMinIntervalMinutes),
532
- // 未覆盖时取 bundle 配置的解析默认值;dreamProvider/dreamModel 无 schema
533
- // 默认值(Config({}) 解析为 undefined),不编造给前端 → 34 - 2 = 32
534
- assert.equal(Object.keys(data.effective).length, 32);
530
+ // effective 覆盖全部 35 个白名单键(含 v0.7.20 heatEnabledIssue #89 新增
531
+ // dreamSkipInvalid/allowCrossTypeMerge/dreamMinIntervalMinutes 与本轮补入面板
532
+ // dreamMaxTokens),未覆盖时取 bundle 配置的解析默认值;
533
+ // dreamProvider/dreamModel 无 schema 默认值(Config({}) 解析为 undefined),
534
+ // 不编造给前端 → 35 - 2 = 33
535
+ assert.equal(Object.keys(data.effective).length, 33);
535
536
  assert.equal(data.effective.dreamSkipInvalid, true);
536
537
  assert.equal(data.effective.allowCrossTypeMerge, false);
537
538
  assert.equal(data.effective.dreamMinIntervalMinutes, 0);
539
+ assert.equal(data.effective.dreamMaxTokens, 32768);
538
540
  assert.equal(data.effective.autoInject, true);
539
541
  assert.equal(data.effective.codingRetrospect, false);
540
542
  assert.equal(data.effective.distillMaxChars, 24000);
@@ -62,10 +62,13 @@ test("archived or summary entries cannot be decision targets", () => {
62
62
  assert.equal(ok, false);
63
63
  });
64
64
 
65
- test("empty decision list rejects", () => {
66
- const { ok, errors } = validateDecisions([], snapshot(["a"]));
67
- assert.equal(ok, false);
68
- assert.ok(errors.some((e) => e.includes("non-empty array")));
65
+ test("empty decision list is a no-op success (model: nothing to consolidate)", () => {
66
+ // 合法 JSON [] 是模型完整评估后确认无需操作(CONSOLIDATION_PROMPT 允许空输出),
67
+ // 不是空体/截断——显式短路 ok,避免隐式 keep 的覆盖率检查误判 0% 为失败。
68
+ const { ok, errors, skipped } = validateDecisions([], snapshot(["a"]));
69
+ assert.equal(ok, true);
70
+ assert.deepEqual(errors, []);
71
+ assert.deepEqual(skipped, []);
69
72
  });
70
73
 
71
74
  test("empty ids rejects", () => {
@@ -825,7 +828,9 @@ test("consolidation prompt pins the decision schema (action field, single-string
825
828
  logger: { warn: () => {} },
826
829
  llm: {
827
830
  async *stream(options) {
828
- systemText = options.messages.find((m) => m.role === "system")?.content?.[0]?.text ?? "";
831
+ // 只捕获第一次调用(consolidation)的 system 文本:空数组现在走 no-op 成功、
832
+ // summary 会照常跑并覆盖 systemText,所以最后一次调用捕获到的是 SUMMARY_PROMPT。
833
+ if (!systemText) systemText = options.messages.find((m) => m.role === "system")?.content?.[0]?.text ?? "";
829
834
  yield { type: "text-delta", text: "[]" };
830
835
  yield { type: "finish", reason: { kind: "ok" } };
831
836
  }
@@ -8,7 +8,7 @@
8
8
  import test from "node:test";
9
9
  import assert from "node:assert/strict";
10
10
  import { Config } from "../src/config.js";
11
- import { createDreamScheduler } from "../src/dream.js";
11
+ import { createDreamScheduler, parseReceipt } from "../src/dream.js";
12
12
  import { runSleep } from "../src/dream/sleep.js";
13
13
  import { createStore } from "../src/store.js";
14
14
  import { createService } from "../src/service.js";
@@ -24,12 +24,20 @@ const embedder = {
24
24
 
25
25
  // ---------------------------------------------------------------- config schema
26
26
 
27
- test("issue#9: dreamMaxTokens accepts the widened 131072 cap and defaults to 4096", () => {
28
- assert.equal(Config({}).dreamMaxTokens, 8192, "default unchanged");
27
+ test("issue#9: dreamMaxTokens defaults to 32768 and accepts values up to 131072", () => {
28
+ assert.equal(Config({}).dreamMaxTokens, 32768, "default raised for thinking-model headroom");
29
29
  assert.equal(Config({ dreamMaxTokens: 131072 }).dreamMaxTokens, 131072, "new upper bound accepted");
30
30
  assert.equal(Config({ dreamMaxTokens: 65536 }).dreamMaxTokens, 65536, "intermediate value accepted");
31
31
  });
32
32
 
33
+ test("issue#9: dreamMaxTokens clamps to [256, 131072], out-of-range values are rejected", () => {
34
+ assert.equal(Config({ dreamMaxTokens: 256 }).dreamMaxTokens, 256, "lower bound accepted");
35
+ assert.equal(Config({ dreamMaxTokens: 100000 }).dreamMaxTokens, 100000, "raised default tier accepted");
36
+ assert.throws(() => Config({ dreamMaxTokens: 255 }), "below min rejected");
37
+ assert.throws(() => Config({ dreamMaxTokens: 131073 }), "above max rejected");
38
+ assert.throws(() => Config({ dreamMaxTokens: 0 }), "zero rejected");
39
+ });
40
+
33
41
  test("issue#9: reasoningEffort config defaults to none and rejects unknown values", () => {
34
42
  const cfg = Config({});
35
43
  assert.equal(cfg.dreamReasoningEffort, "none");
@@ -107,6 +115,63 @@ test("issue#9: dream forwards dreamReasoningEffort on both LLM calls", async ()
107
115
  store.close();
108
116
  });
109
117
 
118
+ test("issue#9: dreamMaxTokens is forwarded as maxTokens on consolidation and summary calls", async () => {
119
+ const store = createStore(":memory:");
120
+ const service = createService({ store, mirror: null, config: {} });
121
+ const dream = createDreamScheduler({ onRun: () => Promise.resolve({ ok: true, skipped: true }) });
122
+ const { memory: a } = service.saveWithDedupe({ type: "project", title: "插件", content: "旧", importance: 3 });
123
+ const { memory: b } = service.saveWithDedupe({ type: "project", title: "插件2", content: "新细节", importance: 4 });
124
+ const captured = [];
125
+ const ctx = dreamCtx({
126
+ captured,
127
+ onConsolidation: () => JSON.stringify([
128
+ { action: "merge", ids: [a.id, b.id], keepSource: b.id, title: "插件总览", content: "合并内容", importance: 4 }
129
+ ])
130
+ });
131
+ const result = await dream.runDream(ctx, service, { dreamMaxTokens: 100000 });
132
+ assert.equal(result.ok, true);
133
+ assert.equal(captured.length, 2, "consolidation + summary both hit the LLM");
134
+ for (const options of captured) {
135
+ assert.equal(options.maxTokens, 100000, `raised budget forwarded on ${options.purpose}`);
136
+ }
137
+ store.close();
138
+ });
139
+
140
+ test("issue#9: thinking-model empty body (no text emitted, budget burnt on reasoning) fails as no json array", async () => {
141
+ const store = createStore(":memory:");
142
+ const service = createService({ store, mirror: null, config: {} });
143
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "中文" });
144
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
145
+ const ctx = dreamCtx({ onConsolidation: () => "" }); // 思考型模型把预算烧光 → 无正文
146
+ const result = await dream.runDream(ctx, service, { dreamMaxTokens: 32768 });
147
+ assert.equal(result.ok, false, "empty body is a hard failure, never faked ok");
148
+ assert.match(result.error, /no json array/);
149
+ const run = store.listDreamRuns()[0];
150
+ assert.equal(run.status, "failed", "audit row records failed");
151
+ assert.match(run.error, /no json array/, "audit error_message carries the empty-body cause");
152
+ assert.equal(parseReceipt(run.receipt).status, "failed", "receipt records failed");
153
+ store.close();
154
+ });
155
+
156
+ test("legal empty decision list [] is a no-op success, not a failure", async () => {
157
+ // 真实模型在记忆无冗余时合法输出 [](CONSOLIDATION_PROMPT 允许"无问题无需输出"),
158
+ // 此前被 validateDecisions 判 failed → 审计表反复失败。现在应 ok:true、applied 0、
159
+ // 审计记 ok,且 summary 照常产出。
160
+ const store = createStore(":memory:");
161
+ const service = createService({ store, mirror: null, config: {} });
162
+ service.saveWithDedupe({ type: "project", title: "插件", content: "内容", importance: 3 });
163
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
164
+ const ctx = dreamCtx({ onConsolidation: () => "[]" }); // 模型:无需合并
165
+ const result = await dream.runDream(ctx, service, { dreamMaxTokens: 32768 });
166
+ assert.equal(result.ok, true, "empty [] is a valid no-op, never failed");
167
+ assert.equal(result.applied, 0, "no decisions to apply");
168
+ assert.equal(result.summary, true, "summary still produced");
169
+ const run = store.listDreamRuns()[0];
170
+ assert.equal(run.status, "ok", "audit row records ok, not failed");
171
+ assert.equal(parseReceipt(run.receipt).status, "ok", "receipt records ok");
172
+ store.close();
173
+ });
174
+
110
175
  test("issue#25: dreamProvider/dreamModel config wins over the agentDefaultModel route", async () => {
111
176
  const store = createStore(":memory:");
112
177
  const service = createService({ store, mirror: null, config: {} });
@@ -0,0 +1,260 @@
1
+ // --- Issue #89 恢复功能的全量单测(v0.7.22)----------------------------------
2
+ // v0.7.22 把 v0.6.9(Issue #26)的 skipInvalid 宽容校验路径原样搬回。核心行为
3
+ // 契约:单条非法决策只跳过该条(记入 skipped、不 claim 任何 id),合法子集照常
4
+ // 应用、run 记 degraded;但全局信号(update/create 上限、显式覆盖率下限)不受
5
+ // 该开关影响、始终整单拒绝。以下测试逐条锁死恢复后的分支:非法动作按原因分类
6
+ // 跳过(create/unknown/archived/summary/重复 claim/merge 参数/update 参数/
7
+ // conflict 参数)、skipInvalid 与覆盖率下限/上限/allowCrossTypeMerge 的交互,
8
+ // 以及 runDream 层"全非法仍 failed / 部分非法 degraded 如实进审计"。
9
+ import test from "node:test";
10
+ import assert from "node:assert/strict";
11
+ import { validateDecisions, createDreamScheduler, parseReceipt } from "../src/dream.js";
12
+ import { createStore } from "../src/store.js";
13
+ import { createService } from "../src/service.js";
14
+ import { mockCtx } from "./helpers/dream-mock.js";
15
+
16
+ function dreamSetup() {
17
+ const store = createStore(":memory:");
18
+ const service = createService({ store, mirror: null, config: {} });
19
+ return { store, service };
20
+ }
21
+
22
+ // 合法记忆快照工厂:id 首字母作 type 前缀(p=preference / 其余 project),
23
+ // created_at 默认 2020 年(保证 update 保护期检查放行)。
24
+ function makeSnap(ids) {
25
+ return new Map(ids.map((id) => [
26
+ id,
27
+ {
28
+ id,
29
+ type: id.startsWith("p") ? "preference" : "project",
30
+ title: `标题${id}`,
31
+ content: `内容${id}`,
32
+ importance: 3,
33
+ archived: false,
34
+ forgotten: false,
35
+ created_at: "2020-01-01T00:00:00.000Z"
36
+ }
37
+ ]));
38
+ }
39
+
40
+ // ------------------------------------------------------------- 按原因逐条跳过
41
+
42
+ test("validateDecisions skipInvalid: create with empty title is skipped; strict mode rejects it", () => {
43
+ const emptySnap = new Map(); // create 不 claim id:空快照下覆盖率恒 1
44
+ const decisions = [
45
+ { action: "create", title: "", content: "body", type: "pattern" },
46
+ { action: "create", title: "ok", content: "c", type: "pattern" }
47
+ ];
48
+ const { ok, errors, skipped } = validateDecisions(decisions, emptySnap, { skipInvalid: true });
49
+ assert.equal(ok, true, `valid create should survive, got: ${errors.join("; ")}`);
50
+ assert.equal(skipped.length, 1);
51
+ assert.match(skipped[0].error, /create needs non-empty title/);
52
+ assert.deepEqual(decisions.map((d) => d.action), ["create"], "empty-title create spliced out");
53
+ assert.deepEqual(decisions[0].title, "ok");
54
+
55
+ const strict = validateDecisions([{ action: "create", title: "", content: "b", type: "pattern" }], emptySnap);
56
+ assert.equal(strict.ok, false, "strict mode hard-rejects a bad create");
57
+ assert.ok(strict.errors.some((e) => e.includes("create needs non-empty title")));
58
+ });
59
+
60
+ test("validateDecisions skipInvalid: unknown id, archived, and summary targets are skipped, valid siblings survive", () => {
61
+ const snap = new Map([
62
+ ...makeSnap(["b", "c"]),
63
+ ["arch", { id: "arch", type: "project", title: "旧arch", content: "x", importance: 3, archived: true, forgotten: false, created_at: "2020-01-01T00:00:00.000Z" }],
64
+ ["s", { id: "s", type: "summary", title: "总览", content: "y", importance: 3, archived: false, forgotten: false, created_at: "2020-01-01T00:00:00.000Z" }]
65
+ ]);
66
+ const decisions = [
67
+ { action: "archive", ids: ["zzz"], reason: "gone" },
68
+ { action: "archive", ids: ["arch"], reason: "stale" },
69
+ { action: "archive", ids: ["s"], reason: "stale" },
70
+ { action: "archive", ids: ["b"], reason: "stale" },
71
+ { action: "archive", ids: ["c"], reason: "stale" }
72
+ ];
73
+ const { ok, errors, skipped } = validateDecisions(decisions, snap, { skipInvalid: true });
74
+ assert.equal(ok, true, `valid archives should survive, got: ${errors.join("; ")}`);
75
+ assert.equal(skipped.length, 3);
76
+ assert.match(skipped[0].error, /unknown id/);
77
+ assert.match(skipped[1].error, /archived or summary/);
78
+ assert.match(skipped[2].error, /archived or summary/);
79
+ // claimed = {b,c} = 2/4 = 50% 恰好过下限;arch/s 未 claim → 隐式 keep
80
+ assert.deepEqual(decisions.map((d) => d.action), ["archive", "archive", "keep", "keep"]);
81
+ assert.deepEqual(decisions[0].ids, ["b"]);
82
+ });
83
+
84
+ test("validateDecisions skipInvalid: a later decision re-claiming an already-claimed id is skipped, first survives", () => {
85
+ const snap = makeSnap(["a", "b", "c"]);
86
+ const decisions = [
87
+ { action: "merge", ids: ["a", "b"], keepSource: "a", title: "合并", content: "m", importance: 4 },
88
+ { action: "merge", ids: ["b", "c"], keepSource: "b", title: "合并2", content: "m2", importance: 4 }
89
+ ];
90
+ const { ok, errors, skipped } = validateDecisions(decisions, snap, { skipInvalid: true });
91
+ assert.equal(ok, true, `first merge should survive, got: ${errors.join("; ")}`);
92
+ assert.equal(skipped.length, 1);
93
+ assert.equal(skipped[0].index, 1);
94
+ assert.match(skipped[0].error, /claimed by multiple/);
95
+ // claimed = {a,b} = 2/3 = 67% 过下限;c 隐式 keep,绝不因重复 claim 双 keep
96
+ assert.deepEqual(decisions.map((d) => d.action), ["merge", "keep"]);
97
+ assert.deepEqual(decisions[0].ids, ["a", "b"]);
98
+ });
99
+
100
+ test("validateDecisions skipInvalid: merge with keepSource outside ids is skipped", () => {
101
+ const snap = makeSnap(["a", "b"]);
102
+ const decisions = [
103
+ { action: "merge", ids: ["a", "b"], keepSource: "zzz", title: "t", content: "c", importance: 4 },
104
+ { action: "archive", ids: ["a"], reason: "stale" }
105
+ ];
106
+ const { ok, errors, skipped } = validateDecisions(decisions, snap, { skipInvalid: true });
107
+ assert.equal(ok, true, `valid archive should survive, got: ${errors.join("; ")}`);
108
+ assert.equal(skipped.length, 1);
109
+ assert.match(skipped[0].error, /keepSource must be one of ids/);
110
+ assert.deepEqual(decisions.map((d) => d.action), ["archive", "keep"]);
111
+ });
112
+
113
+ test("validateDecisions skipInvalid: update targeting multiple ids / no change / summary / too-young memory is skipped", () => {
114
+ const now = Date.now();
115
+ const snap = new Map([
116
+ ...makeSnap(["a", "b"]),
117
+ ["s", { id: "s", type: "summary", title: "总览", content: "y", importance: 3, archived: false, forgotten: false, created_at: "2020-01-01T00:00:00.000Z" }],
118
+ ["y", { id: "y", type: "project", title: "Y", content: "新Y", importance: 3, archived: false, forgotten: false, created_at: new Date(now).toISOString() }]
119
+ ]);
120
+ const decisions = [
121
+ { action: "update", ids: ["a", "b"], content: "x" },
122
+ { action: "update", ids: ["a"], content: "内容a" },
123
+ { action: "update", ids: ["s"], content: "x" },
124
+ { action: "update", ids: ["y"], content: "x" },
125
+ { action: "update", ids: ["a"], content: "新A" },
126
+ { action: "update", ids: ["b"], content: "新B" }
127
+ ];
128
+ const { ok, errors, skipped } = validateDecisions(decisions, snap, { skipInvalid: true });
129
+ assert.equal(ok, true, `valid updates should survive, got: ${errors.join("; ")}`);
130
+ assert.equal(skipped.length, 4);
131
+ assert.match(skipped[0].error, /exactly one id/);
132
+ assert.match(skipped[1].error, /change at least one field/);
133
+ assert.match(skipped[2].error, /cannot update summary/);
134
+ assert.match(skipped[3].error, /too young/);
135
+ // claimed = {a,b} = 2/4 = 50% 过下限;s/y 隐式 keep
136
+ assert.deepEqual(decisions.map((d) => d.action), ["update", "update", "keep", "keep"]);
137
+ });
138
+
139
+ test("validateDecisions skipInvalid: conflict without a distinct winner/loser is skipped", () => {
140
+ const snap = makeSnap(["w", "l", "c"]);
141
+ const decisions = [
142
+ { action: "conflict", winner: "w", loser: "l" },
143
+ { action: "conflict", loser: "c" }
144
+ ];
145
+ const { ok, errors, skipped } = validateDecisions(decisions, snap, { skipInvalid: true });
146
+ assert.equal(ok, true, `valid conflict should survive, got: ${errors.join("; ")}`);
147
+ assert.equal(skipped.length, 1);
148
+ assert.match(skipped[0].error, /conflict needs distinct winner and loser/);
149
+ assert.deepEqual(decisions.map((d) => d.action), ["conflict", "keep"]);
150
+ });
151
+
152
+ // ------------------------------------------------------- skipInvalid 与全局闸门
153
+
154
+ test("validateDecisions skipInvalid: valid subset below the coverage floor still rejects the whole batch", () => {
155
+ const snap = makeSnap(["p", "j", "x"]);
156
+ const decisions = [
157
+ { action: "archive", ids: ["p"], reason: "stale" },
158
+ { action: "merge", ids: ["p", "j"], keepSource: "p", title: "跨类型", content: "m", importance: 4 }
159
+ ];
160
+ const { ok, errors, skipped } = validateDecisions(decisions, snap, { skipInvalid: true });
161
+ assert.equal(ok, false, "skip does not bypass the coverage floor");
162
+ assert.equal(skipped.length, 1);
163
+ assert.ok(errors.some((e) => e.includes("coverage")), "coverage error present");
164
+ assert.equal(decisions.length, 2, "rejected batch left untouched (splice only on the success path)");
165
+ });
166
+
167
+ test("validateDecisions skipInvalid: updates skipped for other reasons do not count toward the update cap", () => {
168
+ const snap = makeSnap(["a", "b", "c", "d"]);
169
+ const decisions = [
170
+ { action: "update", ids: ["a"], content: "内容a" },
171
+ { action: "update", ids: ["b"], content: "内容b" },
172
+ { action: "update", ids: ["c"], content: "新C" },
173
+ { action: "archive", ids: ["d"], reason: "stale" }
174
+ ];
175
+ const { ok, errors, skipped } = validateDecisions(decisions, snap, { skipInvalid: true, maxUpdatePerRun: 2 });
176
+ assert.equal(ok, true, `cap counts survivors only, got: ${errors.join("; ")}`);
177
+ assert.equal(skipped.length, 2);
178
+ // 3 条 update 输入 → 2 条跳过 → 幸存 1 条 ≤ cap 2;claimed {c,d} = 2/4 = 50%
179
+ assert.deepEqual(decisions.map((d) => d.action), ["update", "archive", "keep", "keep"]);
180
+ });
181
+
182
+ test("validateDecisions skipInvalid: creates skipped for other reasons do not count toward the create cap", () => {
183
+ const emptySnap = new Map();
184
+ const decisions = [];
185
+ for (let i = 0; i < 5; i++) decisions.push({ action: "create", title: `t${i}`, content: "c", type: "pattern" });
186
+ decisions.push({ action: "create", title: "", content: "x", type: "pattern" });
187
+ const { ok, errors, skipped } = validateDecisions(decisions, emptySnap, { skipInvalid: true, maxCreatePerRun: 5 });
188
+ assert.equal(ok, true, `cap counts survivors only, got: ${errors.join("; ")}`);
189
+ assert.equal(skipped.length, 1);
190
+ assert.equal(decisions.length, 5, "only the 5 valid creates survive the cap");
191
+ });
192
+
193
+ test("validateDecisions skipInvalid + allowCrossTypeMerge compose: cross-type merge allowed, unrelated invalid entry still skipped", () => {
194
+ const snap = makeSnap(["p", "j", "b", "c"]);
195
+ const decisions = [
196
+ { action: "merge", ids: ["p", "j"], keepSource: "p", title: "合并", content: "m", importance: 4 },
197
+ { action: "archive", ids: ["zzz"], reason: "gone" }
198
+ ];
199
+ const { ok, errors, skipped } = validateDecisions(decisions, snap, { skipInvalid: true, allowCrossTypeMerge: true });
200
+ assert.equal(ok, true, `flag-enabled merge survives, got: ${errors.join("; ")}`);
201
+ assert.equal(skipped.length, 1);
202
+ assert.match(skipped[0].error, /unknown id/);
203
+ assert.deepEqual(decisions.map((d) => d.action), ["merge", "keep", "keep"]);
204
+ });
205
+
206
+ // ----------------------------------------------------------- runDream 层 e2e
207
+
208
+ test("issue#89: with default skipInvalid on, an all-invalid batch still fails the run (nothing valid survives)", async () => {
209
+ const { store, service } = dreamSetup();
210
+ const a = service.saveWithDedupe({ type: "project", title: "旧A", content: "过时A" }).memory;
211
+ const b = service.saveWithDedupe({ type: "project", title: "旧B", content: "过时B" }).memory;
212
+ const pref = service.saveWithDedupe({ type: "preference", title: "语言", content: "中文" }).memory;
213
+ const pref2 = service.saveWithDedupe({ type: "preference", title: "语气", content: "轻松" }).memory;
214
+ const ctx = mockCtx({
215
+ onConsolidation: () => JSON.stringify([
216
+ { action: "merge", ids: [pref.id, a.id], keepSource: pref.id, title: "跨类型", content: "x", importance: 4 },
217
+ { action: "merge", ids: [pref2.id, b.id], keepSource: pref2.id, title: "跨类型2", content: "y", importance: 4 }
218
+ ])
219
+ });
220
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
221
+ const result = await dream.runDream(ctx, service, { dreamProvider: "mock", dreamModel: "mock-model" });
222
+ assert.equal(result.ok, false, "all invalid → whole batch rejected, not silently kept");
223
+ assert.match(result.error, /invalid decisions/);
224
+ const run = store.listDreamRuns()[0];
225
+ assert.equal(run.status, "failed", "audit row marks failed, not degraded (nothing valid landed)");
226
+ assert.equal(parseReceipt(run.receipt).status, "failed", "receipt marks failed");
227
+ assert.equal(store.getById(a.id).archived, false, "nothing applied");
228
+ assert.equal(store.getById(b.id).archived, false, "nothing applied");
229
+ store.close();
230
+ });
231
+
232
+ test("issue#89: a partial-invalid run is marked degraded in the audit row and receipt", async () => {
233
+ const { store, service } = dreamSetup();
234
+ const a = service.saveWithDedupe({ type: "project", title: "旧A", content: "过时A" }).memory;
235
+ const b = service.saveWithDedupe({ type: "project", title: "旧B", content: "过时B" }).memory;
236
+ const pref = service.saveWithDedupe({ type: "preference", title: "语言", content: "中文" }).memory;
237
+ const c = service.saveWithDedupe({ type: "project", title: "旧C", content: "过时C" }).memory;
238
+ const warnings = [];
239
+ const ctx = {
240
+ ...mockCtx({
241
+ onConsolidation: () => JSON.stringify([
242
+ { action: "merge", ids: [pref.id, a.id], keepSource: pref.id, title: "跨类型", content: "x", importance: 4 },
243
+ { action: "archive", ids: [b.id], reason: "stale" },
244
+ { action: "archive", ids: [c.id], reason: "stale" }
245
+ ])
246
+ }),
247
+ logger: { warn: (m) => warnings.push(String(m)) }
248
+ };
249
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
250
+ const result = await dream.runDream(ctx, service, { dreamProvider: "mock", dreamModel: "mock-model" });
251
+ assert.equal(result.ok, true, "valid subset absorbed (ok for the baseline)");
252
+ assert.equal(result.status, "degraded", "run marked degraded, not faked ok");
253
+ const run = store.listDreamRuns()[0];
254
+ assert.equal(run.status, "degraded", "audit row records degraded, never ok");
255
+ assert.equal(parseReceipt(run.receipt).status, "degraded", "receipt records degraded");
256
+ assert.equal(store.getById(b.id).archived, true, "valid archive landed");
257
+ assert.equal(store.getById(pref.id).archived, false, "invalid merge did not touch its targets");
258
+ assert.ok(warnings.some((w) => w.includes("skipped") && w.includes("multiple types")), "skip reason logged");
259
+ store.close();
260
+ });