@modusensus/dsh-mneme 0.7.20 → 0.7.22
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 +9 -1
- package/README.md +7 -0
- package/lib/config.js +12 -0
- package/lib/dream/decisions.js +105 -73
- package/lib/dream/sleep.js +29 -10
- package/lib/dream.js +78 -21
- package/lib/index.js +1 -0
- package/lib/settings.js +5 -1
- package/package.json +1 -1
- package/src/config.js +12 -0
- package/src/dream/decisions.js +105 -73
- package/src/dream/sleep.js +29 -10
- package/src/dream.js +78 -21
- package/src/index.js +1 -0
- package/src/settings.js +5 -1
- package/test/api.test.js +8 -4
- package/test/dream.test.js +172 -0
- package/test/reasoning-effort.test.js +114 -0
package/README.en.md
CHANGED
|
@@ -166,6 +166,8 @@ Every **background LLM call** (autoDream consolidation + summary, autoSummarize
|
|
|
166
166
|
|
|
167
167
|
| Version | Highlights |
|
|
168
168
|
|------|------|
|
|
169
|
+
| **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
|
+
| **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 |
|
|
169
171
|
| **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 |
|
|
170
172
|
| **v0.7.18** | Ecosystem step one + query convergence: better-sidebar soft integration (inject declaration + optional peer `dsh-better-sidebar` + registerTab reusing the four views, safe skip when absent; narrow-container `@container` adaptation) + `/list?deposited=only` view (receipt_chain ∪ source=dream) + deposited/archived filter chips in the library + status-page dashboard (server totals + view-all jumps) + drawer restore for archived memories; 667 tests green |
|
|
171
173
|
| **v0.7.17** | Panel polish: sidebar entry continuously aligned with the host (MutationObserver syncs the New-Session class + `width:100%` + native centering restored, resilient to async skin rewrites) + importance rendered as Lucide star glyphs (`ImportanceStars` filled/hollow component replacing text ★) + toolbar dropdown stacking fix (z-index moved to the container; export/import menu no longer painted under the sticky month header); 664 tests green |
|
|
@@ -212,7 +214,13 @@ Every **background LLM call** (autoDream consolidation + summary, autoSummarize
|
|
|
212
214
|
| v0.7.1–0.7.8 | ✅ Done | Issue fixes + graph backfill | tags↔entity_attrs bridge, inline-confirm delete, sidebar trigger toggle, brace escaping, user/fact layered types + stats endpoint (later removed), prefix-id resolution (later removed), sleep batch entity extraction, snapshotEvents() DSH compat; 764→812 tests green |
|
|
213
215
|
| v0.7.9 | ✅ Done | lib-sync gate | Issue #65: src-only shim silently killed the shipped lib — synced lib + pre-publish src↔lib consistency check + lib smoke tests; 815 tests green |
|
|
214
216
|
| v0.7.10–0.7.12 | ✅ Done | Panel redesign + near-rewrite | UX upgrades (color dots, pan/zoom, pagination, global search), then near-rewrite: inlined panel → pure HTTP API + standalone CLI + lightMode; TYPES narrowed 8→6 |
|
|
215
|
-
| v0.7.13–0.7.
|
|
217
|
+
| v0.7.13–0.7.15 | ✅ Done | Distillation, security, desktop | codingRetrospect + 429 governor; private reasoning blocks dropped (CWE-200); desktop panel redesign + feature flags + status dashboard + import/export |
|
|
218
|
+
| v0.7.16 | ✅ Done | autoDream thinking-model fix | config-first routing restored (Issue #25) + reasoningEffort auto-retry + honest audit on parse failure; backfilled API-route & lib smoke tests; 662 tests green |
|
|
219
|
+
| v0.7.17 | ✅ Done | Panel polish | Sidebar entry continuously aligned with the host (MutationObserver syncs the New-Session class + `width:100%` + native centering, resilient to async skin rewrites) + Lucide star glyphs (`ImportanceStars`) + toolbar dropdown stacking fix; 664 tests green |
|
|
220
|
+
| v0.7.18 | ✅ Done | Ecosystem step one + query convergence | better-sidebar soft integration (inject declaration + optional peer + registerTab reusing the four views, safe skip when absent; narrow-container `@container`) + `/list?deposited=only` view + deposited/archived filter chips + status-page dashboard + drawer restore; 667 tests green |
|
|
221
|
+
| v0.7.20 | ✅ Done | Heat restore + phase-two frontend + better-sidebar fix | Heat model fully restored (issue #87, backported from v0.7.10: power-law decay + TYPE_DECAY + sleep heat-combined dual protection + entity heat projection) + acceptance checklist landed (heatEnabled default OFF / feature_flags 31 keys / lightMode linkage / sleep demotion audit / updated_at⊥last_accessed_at contract) + phase-two frontend (/list heat projection, HeatBadge three-tier, order=heat page-local sort) + better-sidebar fix (issue #88: inner dynamic sub-plugin); 685 tests green |
|
|
222
|
+
| v0.7.21 | ✅ Done | effort-fallback stream fix | Catch-based effort fallback was dead code on the stream path (dsh-llm rc.1 turns adapter failures into a terminal error finish chunk instead of a throw) → `streamText` captures the finish-chunk cause (`describeStreamFailure`) + `withEffortFallback` gains a `getStreamError` accessor (retries without effort when rejected) + `runAuditedLlm` supports `spec.streamError` (real cause in audit); 688 tests green |
|
|
223
|
+
| v0.7.22 | ✅ Done | skipInvalid tolerant-validation restore (issue #89) + autoDream throttle | Restored v0.6.9 skipInvalid dual-track structure (lost in the v0.7.11 rewrite): `dreamSkipInvalid` skips individual invalid decisions + applies the valid subset + marks the run degraded; `allowCrossTypeMerge` explicitly relaxes cross-type merging; weak models (qwen3.8-flash) with jittery schema compliance no longer fail the whole batch. New `dreamMinIntervalMinutes` (0–10080, default 0) minimum trigger interval — failed/degraded runs also consume it. Strict mode / sleep path unchanged; feature_flags whitelist 34 keys; 696 tests green |
|
|
216
224
|
| **v0.8.0** | 🚧 Planned (late Sep) | Graph enhancement | Interest-drift visualization + scope isolation (issue #17) + cross-workspace sharing |
|
|
217
225
|
|
|
218
226
|
> All new capabilities ship as **toggleable features** (enabled/disabled via configuration), conservatively on by default and never breaking existing behavior. The `failure_memories` table and the autoDream decision engine have already paved the way for future reflective growth.
|
package/README.md
CHANGED
|
@@ -207,6 +207,8 @@ v0.3.0 起新增**记忆基因**层:从记忆里抽取**命名实体**、**带
|
|
|
207
207
|
|
|
208
208
|
| 版本 | 亮点 |
|
|
209
209
|
|------|------|
|
|
210
|
+
| **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
|
+
| **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 测试全绿 |
|
|
210
212
|
| **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 测试全绿 |
|
|
211
213
|
| **v0.7.18** | 生态第一步 + 查询收敛:better-sidebar 软集成(inject 声明 + optional peer `dsh-better-sidebar` + registerTab 复用四视图,未装安全跳过;窄容器 `@container` 适配)+ `/list?deposited=only` 沉淀视图(receipt_chain ∪ source=dream)+ 记忆库沉淀/已归档筛选 chip + 状态页仪表盘化(统计 + 查看全部跳转预置筛选)+ 抽屉归档记忆「恢复」;667 测试全绿 |
|
|
212
214
|
| **v0.7.17** | 面板体验细化:侧边栏入口持续对齐宿主(MutationObserver 同步「新会话」类名 + `width:100%` + 交还原生居中,皮肤异步改写不再失配)+ 重要性星级换 Lucide 星形(`ImportanceStars` 实心/空心组件,替换文本 ★)+ 工具栏下拉层级修复(z-index 提到容器,导出/导入菜单不再被吸顶月份头遮挡);664 测试全绿 |
|
|
@@ -286,6 +288,11 @@ v0.3.0 起新增**记忆基因**层:从记忆里抽取**命名实体**、**带
|
|
|
286
288
|
| **v0.7.14** | ✅ 完成 | 安全修复(CWE-200) | 蒸馏不再采集私有推理块:`collectMessages` 只采公开 text,防止记忆库沉淀模型私有思考链;617 测试全绿 |
|
|
287
289
|
| **v0.7.15** | ✅ 完成 | 桌面端适配 | 记忆库面板重设计 + 功能开关 30 键 UI(features API)+ 状态页工作台 + 导入导出(镜像同构 md 黄金闭环)+ Token 面板默认遮蔽;645 测试全绿 |
|
|
288
290
|
| **v0.7.16** | ✅ 完成 | autoDream thinking 模型空体修复 + 补测 | 恢复 config-first 路由(设置面板「巩固模型」生效,Issue #25)+ reasoningEffort 被拒自动去掉重试 + 解析失败如实记 llm_audit error;补测 API 路由空白(/delete、/entities、/external-api)+ lib 运行时冒烟;662 测试全绿 |
|
|
291
|
+
| **v0.7.17** | ✅ 完成 | 面板体验细化 | 侧边栏入口持续对齐宿主(MutationObserver 同步「新会话」类名 + `width:100%` + 交还原生居中,皮肤异步改写不再失配)+ 重要性星级换 Lucide 星形(`ImportanceStars` 实心/空心组件,替换文本 ★)+ 工具栏下拉层级修复(z-index 提到容器,导出/导入菜单不再被吸顶月份头遮挡);664 测试全绿 |
|
|
292
|
+
| **v0.7.18** | ✅ 完成 | 生态第一步 + 查询收敛 | better-sidebar 软集成(inject 声明 + optional peer `dsh-better-sidebar` + registerTab 复用四视图,未装安全跳过;窄容器 `@container` 适配)+ `/list?deposited=only` 沉淀视图(receipt_chain ∪ source=dream)+ 记忆库沉淀/已归档筛选 chip + 状态页仪表盘化(统计 + 查看全部跳转预置筛选)+ 抽屉归档记忆「恢复」;667 测试全绿 |
|
|
293
|
+
| **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
|
+
| **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 测试全绿 |
|
|
295
|
+
| **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 测试全绿 |
|
|
289
296
|
| **v0.8.0** | 🚧 计划中(9 月末) | 图谱增强 | 兴趣漂移可视化 + scope 隔离(issue #17)+ 跨 workspace 记忆共享 |
|
|
290
297
|
|
|
291
298
|
> 新能力一律做成**可开关的功能**(配置启用/关闭),默认保守开启、不破坏现有行为。`failure_memories` 表与 autoDream 决策引擎已为后续反思性成长铺好路。
|
package/lib/config.js
CHANGED
|
@@ -47,6 +47,11 @@ export const Config = z.object({
|
|
|
47
47
|
dreamThresholdCount: z.natural().min(1).max(1000).default(10),
|
|
48
48
|
dreamThresholdChars: z.natural().min(100).max(100000).default(5000),
|
|
49
49
|
dreamDelayMs: z.natural().min(0).max(60000).default(2000),
|
|
50
|
+
// autoDream 触发最小间隔(分钟,0 = 不限制,Issue #89 请求 2):高频写入
|
|
51
|
+
// 场景下防止巩固调用(含失败重试)连发刷爆配额。间隔从每次实际开跑时刻
|
|
52
|
+
// 起算,失败/degraded 的 run 也占用间隔;间隔内的触发请求静默跳过,下一次
|
|
53
|
+
// 写入事件会重新评估。
|
|
54
|
+
dreamMinIntervalMinutes: z.natural().min(0).max(10080).default(0),
|
|
50
55
|
dreamProvider: z.string(),
|
|
51
56
|
dreamModel: z.string(),
|
|
52
57
|
dreamMaxTokens: z.natural().min(256).max(131072).default(8192),
|
|
@@ -74,6 +79,13 @@ export const Config = z.object({
|
|
|
74
79
|
// → 整单拒绝,防止残缺输出被隐式 keep 洗白成 ok 后再被真实 apply。0-1,
|
|
75
80
|
// 默认 0.5(至少显式覆盖一半 snapshot)。
|
|
76
81
|
dreamMinExplicitCoverage: z.number().min(0).max(1).default(0.5),
|
|
82
|
+
// Issue #89:v0.6.9(Issue #26)的宽容路径回归。默认跳过单条非法决策
|
|
83
|
+
// (未知 id / 跨类型合并等)、应用合法子集、run 记 degraded;设 false 恢复
|
|
84
|
+
// 整单拒绝的严格模式。全局上限与覆盖率下限不受此开关影响、始终整单拒绝。
|
|
85
|
+
dreamSkipInvalid: z.boolean().default(true),
|
|
86
|
+
// 显式开启后放宽跨类型合并检查(类型边界由用户自行承担);配合
|
|
87
|
+
// dreamSkipInvalid 理解:关闭 skipInvalid 时跨类型 merge 直接整单拒绝。
|
|
88
|
+
allowCrossTypeMerge: z.boolean().default(false),
|
|
77
89
|
// Rule version for dream adjudication: when this bumps, older dream_runs
|
|
78
90
|
// degrade to historical evidence (their receipts no longer drive live
|
|
79
91
|
// decisions). Default 0 = no versioning in use yet.
|
package/lib/dream/decisions.js
CHANGED
|
@@ -7,12 +7,22 @@ const EPISTEMIC_PRIORITY = { observation: 3, inferred: 2, subjective: 1 };
|
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* Validate a dream decision list against a snapshot of eligible memories.
|
|
10
|
-
* @param decisions - LLM-produced decision list.
|
|
10
|
+
* @param decisions - LLM-produced decision list. In skipInvalid mode, invalid
|
|
11
|
+
* entries are spliced out of this array in place (the caller reuses the same
|
|
12
|
+
* reference downstream for apply/audit); implicit keeps are appended here too.
|
|
11
13
|
* @param snapshot - Map<id, memory> of eligible (non-archived, non-summary) entries.
|
|
12
|
-
* @returns {{ok: boolean, errors: string[]}}
|
|
14
|
+
* @returns {{ok: boolean, errors: string[], skipped?: Array<{index, action, ids, error}>}}
|
|
13
15
|
*/
|
|
14
16
|
export function validateDecisions(decisions, snapshot, options = {}) {
|
|
15
17
|
const errors = [];
|
|
18
|
+
// Issue #89 回归修复(v0.6.9 / Issue #26 的 skipInvalid 路径原样移植,该路径
|
|
19
|
+
// 在 v0.7.11 重写中丢失):skipInvalid 开启时,单条非法决策只跳过该条(记录
|
|
20
|
+
// 到 skipped、不 claim 任何 id),合法子集照常应用,调用方据此把 run 记为
|
|
21
|
+
// degraded。全局信号(update/create 上限、显式覆盖率下限)依旧整单拒绝——
|
|
22
|
+
// 刷爆上限或覆盖率不达标的输出是模型坏了,不是轻微 schema 漂移。
|
|
23
|
+
const skipped = [];
|
|
24
|
+
const survivors = [];
|
|
25
|
+
const skipInvalid = options.skipInvalid === true;
|
|
16
26
|
const maxUpdatePerRun = options.maxUpdatePerRun ?? 2;
|
|
17
27
|
const minAgeHours = options.minAgeHours ?? 24;
|
|
18
28
|
if (!Array.isArray(decisions) || decisions.length === 0) {
|
|
@@ -21,106 +31,122 @@ export function validateDecisions(decisions, snapshot, options = {}) {
|
|
|
21
31
|
const claimed = new Set();
|
|
22
32
|
for (const [index, d] of decisions.entries()) {
|
|
23
33
|
const at = `decision[${index}]`;
|
|
34
|
+
// 单条校验错误先进 local:skipInvalid 模式下整条跳过,严格模式下才并入
|
|
35
|
+
// 全局 errors(沿用 v0.6.9 的双轨结构)。
|
|
36
|
+
const local = [];
|
|
37
|
+
const ids = d && d.action === "conflict" ? [d.winner, d.loser] : (d?.ids ?? []);
|
|
24
38
|
if (!d || typeof d !== "object" || !ACTIONS.has(d.action)) {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
}
|
|
28
|
-
const ids = d.action === "conflict" ? [d.winner, d.loser] : (d.ids ?? []);
|
|
29
|
-
if (d.action === "conflict") {
|
|
39
|
+
local.push(`${at}: invalid action ${JSON.stringify(d?.action)}`);
|
|
40
|
+
} else if (d.action === "conflict") {
|
|
30
41
|
if (!d.winner || !d.loser || d.winner === d.loser) {
|
|
31
|
-
|
|
32
|
-
continue;
|
|
42
|
+
local.push(`${at}: conflict needs distinct winner and loser`);
|
|
33
43
|
}
|
|
34
44
|
} else if (d.action === "create") {
|
|
35
45
|
// Mint a fresh memory (sleep pattern discovery). Claims no existing id,
|
|
36
46
|
// so it skips the claiming loop below; evidence is optional provenance
|
|
37
47
|
// (already filtered to real ids by the caller) and is stored in content.
|
|
38
48
|
if (typeof d.title !== "string" || !d.title.trim()) {
|
|
39
|
-
|
|
40
|
-
continue;
|
|
49
|
+
local.push(`${at}: create needs non-empty title`);
|
|
41
50
|
}
|
|
42
51
|
if (typeof d.content !== "string" || !d.content.trim()) {
|
|
43
|
-
|
|
44
|
-
continue;
|
|
52
|
+
local.push(`${at}: create needs non-empty content`);
|
|
45
53
|
}
|
|
46
54
|
if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
|
|
47
|
-
|
|
55
|
+
local.push(`${at}: create importance must be an integer 1-5 when provided`);
|
|
48
56
|
}
|
|
49
57
|
if (typeof d.type !== "string" || !d.type.trim()) {
|
|
50
|
-
|
|
58
|
+
local.push(`${at}: create needs non-empty type`);
|
|
51
59
|
}
|
|
52
|
-
continue;
|
|
53
60
|
} else if (!Array.isArray(d.ids) || d.ids.length === 0) {
|
|
54
|
-
|
|
55
|
-
continue;
|
|
61
|
+
local.push(`${at}: ${d.action} needs non-empty ids`);
|
|
56
62
|
}
|
|
57
63
|
// update-specific field validation runs BEFORE claiming ids, so a failing
|
|
58
64
|
// update never pollutes the claimed set (which drives the "every id must
|
|
59
65
|
// appear in a decision" check below).
|
|
60
|
-
if (d
|
|
66
|
+
if (local.length === 0 && d?.action === "update") {
|
|
61
67
|
// 只能更新单条
|
|
62
68
|
if (!Array.isArray(d.ids) || d.ids.length !== 1) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
if (ageHours < minAgeHours) {
|
|
83
|
-
errors.push(`${at}: memory too young (< ${minAgeHours}h)`);
|
|
84
|
-
continue;
|
|
69
|
+
local.push(`${at}: update must target exactly one id`);
|
|
70
|
+
} else {
|
|
71
|
+
// 必须产生实际变化
|
|
72
|
+
const mem = snapshot.get(d.ids[0]);
|
|
73
|
+
const hasChange = (d.title !== undefined && d.title !== mem?.title)
|
|
74
|
+
|| (d.content !== undefined && d.content !== mem?.content)
|
|
75
|
+
|| (d.importance !== undefined && d.importance !== mem?.importance);
|
|
76
|
+
if (!hasChange) {
|
|
77
|
+
local.push(`${at}: update must change at least one field`);
|
|
78
|
+
} else if (mem?.type === "summary") {
|
|
79
|
+
// 不能更新 summary
|
|
80
|
+
local.push(`${at}: cannot update summary via update action`);
|
|
81
|
+
} else {
|
|
82
|
+
// 保护期:新建记忆不可立即被 update(可配置)
|
|
83
|
+
const ageHours = (Date.now() - new Date(mem?.created_at).getTime()) / 3600000;
|
|
84
|
+
if (ageHours < minAgeHours) {
|
|
85
|
+
local.push(`${at}: memory too young (< ${minAgeHours}h)`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
85
88
|
}
|
|
86
89
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
90
|
+
if (local.length === 0 && d && d.action !== "create") {
|
|
91
|
+
// seen 捕获同一条决策内的重复 id;claimed 只含先前存活决策的 id
|
|
92
|
+
// (被跳过的决策不 claim,其目标留给其它合法决策/隐式 keep)。
|
|
93
|
+
const seen = new Set();
|
|
94
|
+
for (const id of ids) {
|
|
95
|
+
const mem = snapshot.get(id);
|
|
96
|
+
if (!mem) {
|
|
97
|
+
local.push(`${at}: unknown id ${JSON.stringify(id)}`);
|
|
98
|
+
} else if (mem.archived || mem.type === "summary") {
|
|
99
|
+
local.push(`${at}: id ${JSON.stringify(id)} is archived or summary (not eligible)`);
|
|
100
|
+
}
|
|
101
|
+
if (claimed.has(id) || seen.has(id)) {
|
|
102
|
+
local.push(`${at}: id ${JSON.stringify(id)} claimed by multiple decisions`);
|
|
103
|
+
}
|
|
104
|
+
seen.add(id);
|
|
93
105
|
}
|
|
94
|
-
if (
|
|
95
|
-
|
|
106
|
+
if (local.length === 0 && d.action === "merge") {
|
|
107
|
+
if (!d.keepSource || !d.ids.includes(d.keepSource)) {
|
|
108
|
+
local.push(`${at}: merge keepSource must be one of ids`);
|
|
109
|
+
}
|
|
110
|
+
if (typeof d.title !== "string" || !d.title.trim() || typeof d.content !== "string" || !d.content.trim()) {
|
|
111
|
+
local.push(`${at}: merge needs non-empty title and content`);
|
|
112
|
+
}
|
|
113
|
+
if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
|
|
114
|
+
local.push(`${at}: merge importance must be an integer 1-5 when provided`);
|
|
115
|
+
}
|
|
116
|
+
// Merging across types would blur preference/project/decision boundaries
|
|
117
|
+
// in the injected context; the snapshot carries each entry's type.
|
|
118
|
+
// Issue #26 (P1):默认禁止跨类型合并。用户显式开启 allowCrossTypeMerge
|
|
119
|
+
// 后放宽该检查,类型边界由用户自行承担。
|
|
120
|
+
const mergeTypes = new Set(d.ids.map((id) => snapshot.get(id)?.type));
|
|
121
|
+
if (mergeTypes.size > 1 && options.allowCrossTypeMerge !== true) {
|
|
122
|
+
local.push(`${at}: merge ids span multiple types (${[...mergeTypes].join(", ")})`);
|
|
123
|
+
}
|
|
96
124
|
}
|
|
97
|
-
claimed.add(id);
|
|
98
125
|
}
|
|
99
|
-
if (
|
|
100
|
-
if (
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
errors.push(`${at}: merge importance must be an integer 1-5 when provided`);
|
|
108
|
-
}
|
|
109
|
-
// Merging across types would blur preference/project/decision boundaries
|
|
110
|
-
// in the injected context; the snapshot carries each entry's type.
|
|
111
|
-
const mergeTypes = new Set(d.ids.map((id) => snapshot.get(id)?.type));
|
|
112
|
-
if (mergeTypes.size > 1) {
|
|
113
|
-
errors.push(`${at}: merge ids span multiple types (${[...mergeTypes].join(", ")})`);
|
|
126
|
+
if (local.length > 0) {
|
|
127
|
+
if (skipInvalid) {
|
|
128
|
+
// 单条非法 → 跳过该决策,不 claim id(其目标记忆留给其它合法决策/隐式
|
|
129
|
+
// keep),并记录到 skipped 供调用方日志/审计。信息性跳过绝不写入全局
|
|
130
|
+
// errors,否则会误触发下方的整单拒绝。
|
|
131
|
+
skipped.push({ index, action: d?.action, ids, error: local.join("; ") });
|
|
132
|
+
} else {
|
|
133
|
+
errors.push(...local);
|
|
114
134
|
}
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (d.action !== "create") {
|
|
138
|
+
for (const id of ids) claimed.add(id);
|
|
115
139
|
}
|
|
140
|
+
survivors.push(d);
|
|
116
141
|
}
|
|
117
|
-
// Cap update churn: too many edits in one cycle signals a runaway model
|
|
118
|
-
|
|
142
|
+
// Cap update churn: too many edits in one cycle signals a runaway model.
|
|
143
|
+
// 全局信号——skipInvalid 模式下依旧整单拒绝(见函数头注释)。
|
|
144
|
+
const updateCount = survivors.filter((d) => d.action === "update").length;
|
|
119
145
|
if (updateCount > maxUpdatePerRun) {
|
|
120
146
|
errors.push(`too many update decisions: ${updateCount} > ${maxUpdatePerRun}`);
|
|
121
147
|
}
|
|
122
148
|
// Cap pattern minting per run (sleepMaxPatternPerRun passes through here).
|
|
123
|
-
const createCount =
|
|
149
|
+
const createCount = survivors.filter((d) => d.action === "create").length;
|
|
124
150
|
const maxCreatePerRun = options.maxCreatePerRun ?? 5;
|
|
125
151
|
if (createCount > maxCreatePerRun) {
|
|
126
152
|
errors.push(`too many create decisions: ${createCount} > ${maxCreatePerRun}`);
|
|
@@ -137,25 +163,31 @@ export function validateDecisions(decisions, snapshot, options = {}) {
|
|
|
137
163
|
// snapshot(claimed.size / snapshot.size < dreamMinExplicitCoverage)时整单拒绝,
|
|
138
164
|
// 而不是用 keep 把绝大部分 snapshot 全部"通过"。
|
|
139
165
|
if (errors.length > 0) {
|
|
140
|
-
return { ok: false, errors };
|
|
166
|
+
return { ok: false, errors, skipped };
|
|
141
167
|
}
|
|
142
168
|
const minCoverage = options.dreamMinExplicitCoverage ?? 0.5;
|
|
143
169
|
if (options.dreamImplicitKeep !== false) {
|
|
144
170
|
const coverage = snapshot.size > 0 ? claimed.size / snapshot.size : 1;
|
|
145
171
|
if (coverage < minCoverage) {
|
|
146
172
|
errors.push(`explicit decision coverage ${Math.round(coverage * 100)}% < minimum ${Math.round(minCoverage * 100)}%`);
|
|
147
|
-
return { ok: false, errors };
|
|
173
|
+
return { ok: false, errors, skipped };
|
|
148
174
|
}
|
|
149
175
|
for (const id of snapshot.keys()) {
|
|
150
|
-
if (!claimed.has(id))
|
|
176
|
+
if (!claimed.has(id)) survivors.push({ action: "keep", ids: [id] });
|
|
151
177
|
}
|
|
152
178
|
} else {
|
|
153
179
|
for (const id of snapshot.keys()) {
|
|
154
180
|
if (!claimed.has(id)) errors.push(`memory ${JSON.stringify(id)} missing from decisions`);
|
|
155
181
|
}
|
|
156
|
-
if (errors.length > 0) return { ok: false, errors };
|
|
182
|
+
if (errors.length > 0) return { ok: false, errors, skipped };
|
|
183
|
+
}
|
|
184
|
+
// 调用方下游(apply/audit)复用同一 decisions 引用:就地同步为 survivors——
|
|
185
|
+
// 在 skipInvalid 模式下去掉被跳过的非法决策;在隐式 keep 下追加补齐的 keep。
|
|
186
|
+
// 内容一致时(无跳过、无补齐)为 no-op。
|
|
187
|
+
if (survivors.length !== decisions.length) {
|
|
188
|
+
decisions.splice(0, decisions.length, ...survivors);
|
|
157
189
|
}
|
|
158
|
-
return { ok: true, errors };
|
|
190
|
+
return { ok: true, errors, skipped };
|
|
159
191
|
}
|
|
160
192
|
|
|
161
193
|
/** Marker thrown when a decision target changed since the run snapshot. */
|
package/lib/dream/sleep.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
import { randomUUID, createHash } from "node:crypto";
|
|
18
18
|
import { validateDecisions, applyDecisions } from "./decisions.js";
|
|
19
19
|
import { findPotentialConflicts } from "./clustering.js";
|
|
20
|
-
import { buildReceipt, withEffortFallback } from "../dream.js";
|
|
20
|
+
import { buildReceipt, describeStreamFailure, withEffortFallback } from "../dream.js";
|
|
21
21
|
import { computeHeat } from "../heat.js";
|
|
22
22
|
|
|
23
23
|
const SUMMARY_MAX = 120;
|
|
@@ -61,12 +61,17 @@ function parseJsonArray(text) {
|
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
/** Same stream consumption contract as dream.js. */
|
|
64
|
-
async function streamText(ctx, options) {
|
|
64
|
+
async function streamText(ctx, options, onStreamError) {
|
|
65
65
|
if (!ctx?.llm?.stream) return undefined;
|
|
66
66
|
let text = "";
|
|
67
67
|
for await (const chunk of ctx.llm.stream(options)) {
|
|
68
68
|
if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
|
|
69
69
|
if (chunk.type === "finish" && (chunk.reason?.kind === "error" || chunk.reason?.kind === "aborted")) {
|
|
70
|
+
// Same rc.1 error-as-finish-chunk behavior as dream.js — surface the
|
|
71
|
+
// cause instead of discarding it.
|
|
72
|
+
if (typeof onStreamError === "function") {
|
|
73
|
+
try { onStreamError(chunk.reason); } catch { /* diagnostics only */ }
|
|
74
|
+
}
|
|
70
75
|
return undefined;
|
|
71
76
|
}
|
|
72
77
|
}
|
|
@@ -186,7 +191,10 @@ async function phaseConflicts(ctx, service, config, logger, runId, semantic = nu
|
|
|
186
191
|
`候选冲突:\nid=${p.a.id} | type=${p.a.type} | title=${p.a.title}\n${p.a.content}\n---\nid=${p.b.id} | type=${p.b.type} | title=${p.b.title}\n${p.b.content}\n(相似度 ${p.similarity.toFixed(2)})`
|
|
187
192
|
).join("\n\n");
|
|
188
193
|
const sleepEffort = config.sleepReasoningEffort && config.sleepReasoningEffort !== "none" ? config.sleepReasoningEffort : null;
|
|
189
|
-
|
|
194
|
+
let conflictStreamFailure = "";
|
|
195
|
+
const runConflict = (withEffort) => {
|
|
196
|
+
conflictStreamFailure = "";
|
|
197
|
+
return streamText(ctx, {
|
|
190
198
|
provider: route.provider,
|
|
191
199
|
model: route.model,
|
|
192
200
|
purpose: "sleep-conflict",
|
|
@@ -196,9 +204,13 @@ async function phaseConflicts(ctx, service, config, logger, runId, semantic = nu
|
|
|
196
204
|
{ role: "system", content: [{ type: "text", text: CONFLICT_PROMPT }] },
|
|
197
205
|
{ role: "user", content: [{ type: "text", text: listText }] }
|
|
198
206
|
]
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
|
|
207
|
+
}, (reason) => { conflictStreamFailure = describeStreamFailure(reason); });
|
|
208
|
+
};
|
|
209
|
+
const text = await withEffortFallback(ctx, sleepEffort, () => runConflict(true), () => runConflict(false), () => conflictStreamFailure);
|
|
210
|
+
if (text === undefined) {
|
|
211
|
+
if (conflictStreamFailure) ctx.logger?.warn?.(`dsh-mneme sleep: conflict stream aborted or errored (${conflictStreamFailure})`);
|
|
212
|
+
return { status: "failed", error: "llm failed" };
|
|
213
|
+
}
|
|
202
214
|
const decisions = parseJsonArray(text);
|
|
203
215
|
if (!decisions) return { status: "failed", error: "invalid decisions json" };
|
|
204
216
|
// validateDecisions 要求每个 snapshot id 恰好被 claim 一次。v0.4.4 起它本身
|
|
@@ -298,7 +310,10 @@ async function phasePatterns(ctx, service, config, logger, runId, signal = null)
|
|
|
298
310
|
.join("\n");
|
|
299
311
|
const maxPatterns = config.sleepMaxPatternPerRun ?? 3;
|
|
300
312
|
const sleepEffort = config.sleepReasoningEffort && config.sleepReasoningEffort !== "none" ? config.sleepReasoningEffort : null;
|
|
301
|
-
|
|
313
|
+
let patternStreamFailure = "";
|
|
314
|
+
const runPattern = (withEffort) => {
|
|
315
|
+
patternStreamFailure = "";
|
|
316
|
+
return streamText(ctx, {
|
|
302
317
|
provider: route.provider,
|
|
303
318
|
model: route.model,
|
|
304
319
|
purpose: "sleep-pattern",
|
|
@@ -308,9 +323,13 @@ async function phasePatterns(ctx, service, config, logger, runId, signal = null)
|
|
|
308
323
|
{ role: "system", content: [{ type: "text", text: PATTERN_PROMPT.replace("N", String(maxPatterns)) }] },
|
|
309
324
|
{ role: "user", content: [{ type: "text", text: listText }] }
|
|
310
325
|
]
|
|
311
|
-
});
|
|
312
|
-
|
|
313
|
-
|
|
326
|
+
}, (reason) => { patternStreamFailure = describeStreamFailure(reason); });
|
|
327
|
+
};
|
|
328
|
+
const text = await withEffortFallback(ctx, sleepEffort, () => runPattern(true), () => runPattern(false), () => patternStreamFailure);
|
|
329
|
+
if (text === undefined) {
|
|
330
|
+
if (patternStreamFailure) ctx.logger?.warn?.(`dsh-mneme sleep: pattern stream aborted or errored (${patternStreamFailure})`);
|
|
331
|
+
return { status: "failed", error: "llm failed" };
|
|
332
|
+
}
|
|
314
333
|
const decisions = parseJsonArray(text);
|
|
315
334
|
if (!decisions || decisions.length === 0) return { status: "skipped", reason: "no patterns found" };
|
|
316
335
|
// Evidence ids are provenance refs; an LLM-fabricated id would mint a dead
|