dsh-cross-memory 0.2.8 → 0.2.10

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.md CHANGED
@@ -59,7 +59,7 @@ dsh plugin --profile <profile> add /path/to/packages/dsh-cross-memory
59
59
  | 后台抽取 | 会话空闲或按周期被扫描,用一次辅助模型调用抽取可复用的事实;落盘前做密钥擦除。 |
60
60
  | 合并重整 | 受限子代理对一批记忆去重、改写、退役;有风险的决定进入「待裁决」由你决定。 |
61
61
  | 分层注入 | 每个会话注入一次有界摘要;另有按需补注(当前这轮明显相关时)、标题轮转与增量块。 |
62
- | 按需召回 | 关键词 + 时间衰减 + 一跳扩展;命中原因可在日志里核对。 |
62
+ | 按需召回 | BM25 排序 + 词法证据门控 + 时间衰减 + 一跳扩展;命中原因可在日志里核对。 |
63
63
  | 原始片段(可选) | 补注块可附带来源会话的原文片段,默认关闭,因为它会把别的会话的原文带进当前上下文。 |
64
64
  | persona | 维护「这个人是谁」的画像(`persona/human.md`),注入在记忆摘要之前,默认预算 12000 字节;设置 → 记忆 → 画像 可查看/编辑,并可锁定不让后台改写。 |
65
65
  | 开放承诺 | 把会话里答应过、但还没到期/没做的事记成台账,到期未闭环会提醒。 |
@@ -72,6 +72,16 @@ dsh plugin --profile <profile> add /path/to/packages/dsh-cross-memory
72
72
  - **怎么编辑**:**设置 → 记忆 → 画像**,改完点「保存画像」即写回,不经过后台合并,不用重启宿主。
73
73
  - **锁定**:同一页勾选「锁定画像」会在画像旁边写 `persona/human.lock`;锁定后后台 consolidation 即使提出画像改写也会跳过(日志会记 `persona is locked; the automatic profile update was skipped`),只有你手动保存才会改变它。取消勾选即解除。
74
74
 
75
+ ### 确认合并提案
76
+
77
+ 后台合并把「可能丢信息」的改动留在待确认里。除了 **设置 → 记忆 → 待裁决** 和 `/memories plan|apply|reject`,现在还可以直接在回答里确认:
78
+
79
+ 1. 问助手「记忆变更 / 待确认 / 待裁决」。
80
+ 2. 助手加载 `memory-proposal` 技能,在最终回答末尾给出一张卡片,显示范围、待确认条数和生成时间。
81
+ 3. 点「确认应用」整批应用,「拒绝」整批丢弃,「稍后」保留待确认。
82
+
83
+ 卡片只在确实存在待确认提案时出现。出卡依赖模型按技能格式在回答末尾写出 `action-card` 块;模型没写就没有卡片,旧入口照常可用。三个入口操作的是同一份 `pending/consolidation.json`,进度一致。
84
+
75
85
  更细的设计说明见 [`docs/DETAIL.zh.md`](docs/DETAIL.zh.md)(英文版 [`docs/DETAIL.md`](docs/DETAIL.md))。
76
86
 
77
87
  ## 配置
@@ -200,7 +210,7 @@ $DSH_HOME/memories/
200
210
  - **后台模型调用**会经过你配置的模型路由(默认沿用会话自己的路由)。抽取输入是会话尾部,只取用户与助手正文,丢弃工具结果和插件注入的内容,避免记忆自噬;落盘前做密钥擦除(`sk-…`、`ghp_…`、`AKIA…`、JWT、私钥块、`api_key=…`、`Bearer …` 等)。
201
211
  - **注入的内容是背景数据,不是指令**:注入块会明确告诉模型,记忆记录的是写入时的事实,不一定现在仍成立。
202
212
  - **原始片段是 opt-in**:`rawRecall` 默认关闭;打开后补注块会附带来源会话的原文(只读本机会话日志)。
203
- - **通知可选**:默认通过操作系统通知提醒(每日摘要、积压警告、到期承诺),`noticeQuietHours` 可设置静默时段,`noticesEnabled: false` 完全关闭。通知投递目前只在 macOS 生效(走 `osascript`);其他平台投递失败,通知仍留在队列里,可用 `/memories notices` 查看。
213
+ - **通知可选**:默认通过操作系统通知提醒(每日摘要、到期承诺),`noticeQuietHours` 可设置静默时段,`noticesEnabled: false` 完全关闭。通知投递目前只在 macOS 生效(走 `osascript`);其他平台投递失败,通知仍留在队列里,可用 `/memories notices` 查看。
204
214
  - **彻底关掉后台行为**:`autoExtract: false`、`consolidate: false`、`reflectionEnabled: false`;再设 `maxSummaryBytes: 0` 或 `recallMode: off` 就只剩 `memory` 工具与 `/memories` 命令。
205
215
  - 归档与合并只动 `$DSH_HOME` 下的文件;归档条目可 `restore`,合并失败的改动会回滚。
206
216
 
package/docs/DETAIL.md CHANGED
@@ -44,6 +44,7 @@ Consolidation is the second pass. It resolves contradictions and fragments acros
44
44
  - Only reversible changes are applied unattended: merging duplicates, sharpening wording, retiring entries nothing ever read. Rewrites and retirements that could lose information wait for you: an entry a person wrote, a pinned or permanent entry, a retire of a memory that was actually read, and a rewrite that drops cited file paths or shrinks the body below half its previous length are never applied silently.
45
45
  - An existing entry never changes scope; only new memories are placed as `global` or `project` by this pass.
46
46
  - A pending proposal expires after `consolidateProposalMaxAgeHours` (default 72). `autoDecide` (on by default) lets an AI adjudicate first, but a verdict below `autoDecideMinConfidence` (default 0.7) still waits for you.
47
+ - There are three confirmation entries over the same `pending/consolidation.json`: an in-answer `resolve_memory_proposal` action card (Apply / Reject / Not now), the per-row 待裁决 panel in Settings, and `/memories plan|apply|reject`. The model offers the card from the `memory-proposal` skill as an `action-card` block at the end of its answer; `details` carries only the current proposal's `label`, `count` and `stagedAt`. Every action reconciles first, so a proposal already decided by the command, the panel or a newer pass settles as `settled-elsewhere`/`superseded` instead of being applied twice. The notice pump no longer sends pending-decision backlog (this deployment has no usable `osascript` channel); confirmation goes through the three entries above.
47
48
  - When two memories contradict each other, the sub-agent reports the pair as a conflict instead of picking one silently.
48
49
  - Consolidation maintains the persona profile unless `persona/human.lock` exists, and turns repeatable procedures into skill drafts (at most 2 per pass). A draft lands in `memories/skills/<name>/SKILL.md`; `/memories promote` copies it to `$DSH_HOME/skills/<name>/SKILL.md`, and re-promotion is refused when the promoted copy is newer than the draft.
49
50
 
package/docs/DETAIL.zh.md CHANGED
@@ -44,6 +44,7 @@ dsh-cross-memory 把会话里值得长期保留的内容(偏好、决定、踩
44
44
  - 可以自动执行的是可逆改动:合并重复、收紧措辞、退役从没被读过的条目。可能丢信息的改写与退役进入**待裁决**:人手写、置顶或永久保留的条目,被读到过的退役,丢失正文里文件路径引用或正文不到原来一半的改写,都不会被静默处理。
45
45
  - 已在库里的条目不会换作用域,新记忆才由这一遍决定放在 `global` 还是 `project`。
46
46
  - 待裁决方案在 `consolidateProposalMaxAgeHours`(默认 72)小时后自动作废;`autoDecide`(默认开)允许 AI 先判断是否丢信息,置信度低于 `autoDecideMinConfidence`(默认 0.7)时仍然留给你。
47
+ - 确认入口有三个,操作同一份 `pending/consolidation.json`:回答内的 `resolve_memory_proposal` 卡片(确认应用 / 拒绝 / 稍后)、设置页「待裁决」逐条处理、`/memories plan|apply|reject`。卡片由模型按 `memory-proposal` 技能在最终回答末尾用 `action-card` 块给出,`details` 只带当前提案的 `label`/`count`/`stagedAt`;点按钮前 Host 会先 reconcile,提案已被 `/memories`、设置页或新的一轮合并处理掉时卡片落 `settled-elsewhere`/`superseded`,不会重复应用。通知泵不再推送待确认积压(本机没有可用的 `osascript` 投递通道),待确认只走上面三个入口。
47
48
  - 两条记忆互相矛盾时,子代理把这一对列进冲突报告(保留哪条、丢弃哪条),而不是悄悄挑一个。
48
49
  - 合并会维护画像,`persona/human.lock` 存在时跳过;也会把重复流程提成技能草稿(每轮最多 2 个),草稿落在 `memories/skills/<name>/SKILL.md`,`/memories promote` 才复制到 `$DSH_HOME/skills/<name>/SKILL.md`;已晋升的文件比草稿新时,重复晋升会被拒绝。
49
50
 
package/lib/bm25.js ADDED
@@ -0,0 +1,100 @@
1
+ import { tokenize } from './tokenize.js';
2
+ /** Term frequency saturation, from the sensitivity audit's best cell. */
3
+ export const BM25_K1 = 1.2;
4
+ /** Length normalisation, from the same cell. */
5
+ export const BM25_B = 0.75;
6
+ /** Field multiplicity: a title word counts twice, a key twice, the rest once. */
7
+ export const BM25_FIELDS = {
8
+ title: 2,
9
+ keys: 2,
10
+ tags: 1,
11
+ appliesTo: 1,
12
+ body: 1,
13
+ };
14
+ /** Cache of built indexes, keyed by the exact array they were built from. */
15
+ const indexCache = new WeakMap();
16
+ /** The searchable text of one entry, with the field multiplicity applied. */
17
+ function documentText(entry) {
18
+ const parts = [];
19
+ for (let index = 0; index < BM25_FIELDS.title; index += 1)
20
+ parts.push(entry.title);
21
+ for (const key of entry.keys ?? [])
22
+ for (let index = 0; index < BM25_FIELDS.keys; index += 1)
23
+ parts.push(key);
24
+ for (const tag of entry.tags ?? [])
25
+ for (let index = 0; index < BM25_FIELDS.tags; index += 1)
26
+ parts.push(tag);
27
+ for (let index = 0; index < BM25_FIELDS.appliesTo; index += 1)
28
+ parts.push(entry.appliesTo ?? '');
29
+ for (let index = 0; index < BM25_FIELDS.body; index += 1)
30
+ parts.push(entry.body ?? '');
31
+ return parts.filter((part) => part.length > 0).join('\n');
32
+ }
33
+ /** Build (or reuse) the index for one entry array.
34
+ *
35
+ * @param entries - the entries to rank, in any order.
36
+ * @returns the index; repeated calls with the same array are free.
37
+ */
38
+ export function createBm25Index(entries) {
39
+ const cached = indexCache.get(entries);
40
+ if (cached !== undefined)
41
+ return cached;
42
+ const docs = entries.map((entry) => {
43
+ const terms = tokenize(documentText(entry));
44
+ const tf = new Map();
45
+ for (const term of terms)
46
+ tf.set(term, (tf.get(term) ?? 0) + 1);
47
+ return { id: entry.id, tf, length: terms.length };
48
+ });
49
+ const df = new Map();
50
+ for (const doc of docs)
51
+ for (const term of doc.tf.keys())
52
+ df.set(term, (df.get(term) ?? 0) + 1);
53
+ const averageLength = docs.reduce((sum, doc) => sum + doc.length, 0) / Math.max(1, docs.length);
54
+ const total = docs.length;
55
+ const index = {
56
+ entries,
57
+ score(query) {
58
+ const terms = [...new Set(tokenize(query))];
59
+ const scores = new Map();
60
+ if (terms.length === 0 || total === 0)
61
+ return scores;
62
+ for (const doc of docs) {
63
+ let score = 0;
64
+ for (const term of terms) {
65
+ const frequency = doc.tf.get(term);
66
+ if (frequency === undefined)
67
+ continue;
68
+ const documentFrequency = df.get(term) ?? 0;
69
+ const idf = Math.log(1 + (total - documentFrequency + 0.5) / (documentFrequency + 0.5));
70
+ score += idf * ((frequency * (BM25_K1 + 1)) / (frequency + BM25_K1 * (1 - BM25_B + (BM25_B * doc.length) / averageLength)));
71
+ }
72
+ if (score > 0)
73
+ scores.set(doc.id, score);
74
+ }
75
+ return scores;
76
+ },
77
+ };
78
+ indexCache.set(entries, index);
79
+ return index;
80
+ }
81
+ /**
82
+ * Rank entries against a query by BM25, strongest first.
83
+ *
84
+ * Only entries with a positive score are returned: an entry that shares no term
85
+ * with the query is not a candidate, exactly as the gatekeeper sees it.
86
+ *
87
+ * @param entries - the entries to rank.
88
+ * @param query - raw query text.
89
+ * @returns entries in descending score order.
90
+ */
91
+ export function bm25Rank(entries, query) {
92
+ if (entries.length === 0 || query.trim().length === 0)
93
+ return [];
94
+ const scores = createBm25Index(entries).score(query);
95
+ if (scores.size === 0)
96
+ return [];
97
+ return entries
98
+ .filter((entry) => (scores.get(entry.id) ?? 0) > 0)
99
+ .sort((left, right) => (scores.get(right.id) ?? 0) - (scores.get(left.id) ?? 0));
100
+ }
package/lib/cards.js ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * The `resolve_memory_proposal` action card: a staged consolidation proposal
3
+ * offered in the answer, decided by a click.
4
+ *
5
+ * Before 0.2.9 a staged proposal could only wait for `/memories plan` +
6
+ * `/memories apply|reject` or the settings page, and the notification pump that
7
+ * pointed at it is unusable on macOS in this deployment (no osascript channel).
8
+ * A card is the same question where the user already is: the model loads a
9
+ * skill, ends its answer with an `action-card` block, and the buttons apply or
10
+ * discard the whole waiting batch.
11
+ *
12
+ * The kind owns no state of its own: every action reads the real pending file
13
+ * through {@link ProposalCardRuntime}, so a card can never apply a proposal the
14
+ * store no longer has, and the same pending batch stays actionable from the
15
+ * command and the settings panel.
16
+ *
17
+ * The Host services are described by the small structural interfaces below
18
+ * instead of importing `@deepseek-ai/dsh-action-cards` / `dsh-skill` types. Two
19
+ * reasons: the card mechanism is an optional capability (an older Host has no
20
+ * `skillProvider` and this plugin must still compose), and both packages ship
21
+ * their own `schemastery` copy, whose duplicate type identity made this
22
+ * package's `Config` declaration non-portable.
23
+ *
24
+ * @module dsh-cross-memory/cards
25
+ */
26
+ import { z } from 'zod';
27
+ /** Value of the card's `action` field; also what the skill's block names. */
28
+ export const PROPOSAL_ACTION = 'resolve_memory_proposal';
29
+ /** Skill name that tells the model when to offer the card. */
30
+ export const PROPOSAL_SKILL = 'memory-proposal';
31
+ /** Host validation for one card's `details`. */
32
+ export const PROPOSAL_DETAILS = z.object({
33
+ label: z.string().min(1),
34
+ count: z.number().int().positive(),
35
+ stagedAt: z.number().int(),
36
+ });
37
+ /**
38
+ * Recorded phases after which the card shows its outcome and offers no action.
39
+ * `dismissed` is recorded by the Host frame, and `failed` is this kind's
40
+ * retryable phase.
41
+ */
42
+ const TERMINAL_PHASES = new Set(['applied', 'rejected', 'dismissed', 'superseded', 'settled-elsewhere']);
43
+ /** Guidance the status notice adds after a decision, for the model to read. */
44
+ const STATUS_GUIDANCE = 'Memory proposals: applied means the whole staged batch is now in the store with the reported written and retired counts; '
45
+ + 'rejected means the batch was discarded and the store is unchanged; dismissed means the user set it aside, so do not offer that same proposal again; '
46
+ + 'superseded or settled-elsewhere means another entry (/memories apply, /memories reject, the settings 待裁决 panel, or a newer pass) already decided it — '
47
+ + 'report that state instead of offering the card again. Only the proposal that is still pending may be offered, and only once per answer.';
48
+ /**
49
+ * A skill has to route on text alone, so the description names the trigger in
50
+ * both languages the user works in and explicitly excludes ordinary memory work.
51
+ */
52
+ const SKILL_CANDIDATE = {
53
+ name: PROPOSAL_SKILL,
54
+ description: 'Offer the staged memory-consolidation proposal as a confirmable action card when the user asks about memory changes, a pending merge, or what still needs confirmation (记忆变更 / 待确认 / 待裁决). 只有存在待确认提案时才用;不用于普通的记忆搜索、写入或问答。',
55
+ invocation: { modelInvocable: true, userInvocable: false },
56
+ provider: 'dsh-cross-memory',
57
+ source: 'runtime',
58
+ // Same value as @deepseek-ai/dsh-skill's BUNDLED_SKILL_RANK, kept as a literal
59
+ // so this package needs no runtime dependency on the host's skill package.
60
+ rank: 600,
61
+ locator: null,
62
+ };
63
+ /** What the model is told when it loads the skill. */
64
+ export const PROPOSAL_SKILL_CONTENT = [
65
+ '# 记忆变更确认卡',
66
+ '',
67
+ '本插件的后台合并会先把「可能丢信息」的改动放进一份待确认提案(`pending/consolidation.json`)。',
68
+ '用户问起「记忆变更 / 待确认 / 待裁决 / 合并提案」时,用一张 `action-card` 让本人当场确认,不要只说去哪个页面。',
69
+ '',
70
+ '## 什么时候出卡',
71
+ '',
72
+ '- 只有存在待确认提案时。提案的 label、count、stagedAt 见本轮注入里的 "Pending consolidation proposal" 那一行;没有这一行就不要出卡。',
73
+ '- 卡片只代表「当前 pending 文件里那一批」,不要自己编造或合并别的批次,也不要给出一个不同的数字。',
74
+ '- 如果状态通知已经说这批是 applied / rejected / dismissed / superseded / settled-elsewhere,就不要再出卡;直接说明结果。',
75
+ '',
76
+ '## 块格式',
77
+ '',
78
+ '在最终回答的最后放一个 fenced code block,语言必须是字面的 `action-card`,内容是一个 JSON 对象:',
79
+ '',
80
+ '````',
81
+ '```action-card',
82
+ '{"action":"resolve_memory_proposal","title":"确认这批记忆变更","brief":"这批提案会写回若干条记忆并退役若干条,确认后才会动存储。","details":{"label":"<scope label>","count":3,"stagedAt":1750000000000}}',
83
+ '```',
84
+ '````',
85
+ '',
86
+ '- `action` 固定为 `resolve_memory_proposal`。',
87
+ '- `title`、`brief` 用用户的语言写;brief 说清「确认后才会改动存储」。',
88
+ '- `details.label` 照抄注入行里的提案 label。',
89
+ '- `details.count` 是待拍板的条数,必须是正整数,照抄注入行;不要用计划里的写回/退役条数代替。',
90
+ '- `details.stagedAt` 是提案生成时间(epoch 毫秒),照抄注入行里的 stagedAt。',
91
+ '',
92
+ '## 出卡之后',
93
+ '',
94
+ '- 块前留一句邀请:点下面的按钮确认应用或拒绝;`/memories plan|apply|reject` 和「设置 → 记忆 → 待裁决」仍然可用。',
95
+ '- 每轮只能有一个 `action-card` 块,放在回答末尾;不要放进引用、四级缩进或另一个代码块里。',
96
+ '- 卡片按钮会整批应用或整批丢弃,不是逐条处理。',
97
+ '- 点了按钮之后,下一轮会收到一条 action-card 状态通知;按通知里的阶段回答,不要重复提议同一批。',
98
+ ].join('\n');
99
+ /** Own entries only: browser-supplied ids such as `toString` never reach inherited object members. */
100
+ function ownDecision(cards, agent, cardId) {
101
+ const decisions = cards.view(agent.session).decisions;
102
+ return Object.hasOwn(decisions, cardId) ? decisions[cardId] : undefined;
103
+ }
104
+ /** Whether a pending proposal is the exact one this card describes. */
105
+ function matches(proposal, pending) {
106
+ return pending.label === proposal.label && pending.count === proposal.count && pending.stagedAt === proposal.stagedAt;
107
+ }
108
+ /** Record one decision and return it as the settled result. */
109
+ function settle(cards, agent, cardId, phase, data) {
110
+ const decision = { cardId, action: PROPOSAL_ACTION, phase, ...data === undefined ? {} : { data } };
111
+ cards.record(agent, decision);
112
+ return { status: 'settled', decision };
113
+ }
114
+ /**
115
+ * Register the card kind and the skill that offers it for the caller's lifetime.
116
+ *
117
+ * The caller must run this inside `ctx.inject(['actionCards', 'skills'], …)` and
118
+ * hold the returned disposer in `ctx.effect`; disposing removes both, so an
119
+ * unloaded plugin leaves no half-registered card behind.
120
+ *
121
+ * @param cards - the Host action-card service.
122
+ * @param skills - the Host skill registry.
123
+ * @param runtime - the store seam described by {@link ProposalCardRuntime}.
124
+ * @returns disposer removing the kind and the skill provider.
125
+ */
126
+ export function registerProposalCard(cards, skills, runtime) {
127
+ const disposeKind = cards.register({
128
+ action: PROPOSAL_ACTION,
129
+ details: PROPOSAL_DETAILS,
130
+ // Both buttons change memory files; a read-only Session may not.
131
+ verbs: { accept: { writes: true }, reject: { writes: true } },
132
+ // A failed apply already rolled the store back; the card stays actionable
133
+ // so the same click can be retried.
134
+ openPhases: ['failed'],
135
+ statusGuidance: STATUS_GUIDANCE,
136
+ statusFields: ['written', 'retired'],
137
+ // Every action, including Not now, first learns whether another entry already
138
+ // decided this proposal or a newer pass replaced it.
139
+ reconcile: async (agent, proposal) => {
140
+ const previous = ownDecision(cards, agent, proposal.cardId);
141
+ if (previous !== undefined && TERMINAL_PHASES.has(previous.phase))
142
+ return;
143
+ const pending = await runtime.pending();
144
+ if (pending === undefined) {
145
+ settle(cards, agent, proposal.cardId, 'settled-elsewhere');
146
+ return;
147
+ }
148
+ if (!matches(proposal.details, pending))
149
+ settle(cards, agent, proposal.cardId, 'superseded');
150
+ },
151
+ act: async (agent, proposal, verb) => {
152
+ if (verb === 'reject') {
153
+ const dropped = await runtime.reject();
154
+ // Another entry discarded it between reconciliation and this click.
155
+ if (dropped === undefined)
156
+ return settle(cards, agent, proposal.cardId, 'settled-elsewhere');
157
+ return settle(cards, agent, proposal.cardId, 'rejected');
158
+ }
159
+ if (verb !== 'accept')
160
+ return { status: 'refused', reason: 'unknown-verb' };
161
+ const applied = await runtime.apply(agent);
162
+ if (applied === undefined)
163
+ return settle(cards, agent, proposal.cardId, 'settled-elsewhere');
164
+ // `applyPendingPlan` clears the proposal only after every write succeeded;
165
+ // a still-readable proposal therefore means the store was rolled back.
166
+ const pending = await runtime.pending();
167
+ if (pending !== undefined) {
168
+ return settle(cards, agent, proposal.cardId, matches(proposal.details, pending) ? 'failed' : 'superseded');
169
+ }
170
+ return settle(cards, agent, proposal.cardId, 'applied', { written: applied.written, retired: applied.retired });
171
+ },
172
+ });
173
+ const disposeSkill = skills.registerProvider(cards.skillProvider(SKILL_CANDIDATE, async (_candidate, options) => {
174
+ options.signal?.throwIfAborted();
175
+ return {
176
+ name: SKILL_CANDIDATE.name,
177
+ description: SKILL_CANDIDATE.description,
178
+ invocation: SKILL_CANDIDATE.invocation,
179
+ source: SKILL_CANDIDATE.source,
180
+ provider: SKILL_CANDIDATE.provider,
181
+ content: PROPOSAL_SKILL_CONTENT,
182
+ };
183
+ }));
184
+ return () => {
185
+ disposeSkill();
186
+ disposeKind();
187
+ };
188
+ }
package/lib/client.js CHANGED
@@ -6,6 +6,181 @@ window.__ModuleLoader__.load({
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
7
  const PACKAGE = "dsh-cross-memory";
8
8
  const REMOTE_INVOCATION_DATA = [{"method":"overview","parameters":[],"result":"overview"},{"method":"list","parameters":[{"name":"project","wire":"project","shape":"text","optional":true},{"name":"scope","wire":"scope","shape":"text","optional":true},{"name":"query","wire":"query","shape":"text","optional":true},{"name":"kind","wire":"kind","shape":"text","optional":true},{"name":"limit","wire":"limit","shape":"number","optional":true}],"result":"entries"},{"method":"add","parameters":[{"name":"project","wire":"project","shape":"text","optional":true},{"name":"scope","wire":"scope","shape":"text"},{"name":"kind","wire":"kind","shape":"text","optional":true},{"name":"title","wire":"title","shape":"text"},{"name":"body","wire":"body","shape":"text"},{"name":"tags","wire":"tags","shape":"text","optional":true}],"result":"entry"},{"method":"forget","parameters":[{"name":"project","wire":"project","shape":"text","optional":true},{"name":"scope","wire":"scope","shape":"text"},{"name":"id","wire":"id","shape":"text"}],"result":"removed"},{"method":"promoteSkill","parameters":[{"name":"name","wire":"name","shape":"text"}],"result":"skill"},{"method":"discardSkill","parameters":[{"name":"name","wire":"name","shape":"text"}],"result":"discard"},{"method":"persona","parameters":[],"result":"persona"},{"method":"savePersona","parameters":[{"name":"text","wire":"text","shape":"text"},{"name":"locked","wire":"locked","shape":"flag"}],"result":"persona"},{"method":"disputes","parameters":[],"result":"disputes"},{"method":"resolveDispute","parameters":[{"name":"id","wire":"id","shape":"text"},{"name":"decision","wire":"decision","shape":"text"}],"result":"text"}];
9
+ // ---- .client-build/parts/action-card.js ----
10
+ "use strict";
11
+ /**
12
+ * The `resolve_memory_proposal` card body.
13
+ *
14
+ * The shared action-card frame renders the title, the folded brief and the
15
+ * buttons of a registered body. This body reads the card's `details` with its
16
+ * own schema — the browser validates what the Host already validated, exactly
17
+ * like every shipped kind — and shows the waiting batch: its scope label,
18
+ * decision count and staging time, then 确认应用 / 拒绝 / 稍后.
19
+ *
20
+ * The body is plain `createElement` code with no imports, like the rest of the
21
+ * browser half, so the bundle needs no bundler; `client/index.ts` registers it
22
+ * and the copy table with the shell.
23
+ */
24
+ /** Value of the card's `action`; must match the Host kind. */
25
+ const PROPOSAL_CARD_ACTION = 'resolve_memory_proposal';
26
+ /** Locale namespace the copy below is registered under. */
27
+ const PROPOSAL_CARD_LOCALE = 'memoriesProposal';
28
+ /** Recorded phases that still offer the actions; `dismissed` is recorded by the frame. */
29
+ const PROPOSAL_OPEN_PHASES = ['failed'];
30
+ /** Every string this body renders, per locale. */
31
+ const PROPOSAL_COPY = {
32
+ zh: {
33
+ scope: '范围:{label}',
34
+ count: '{count} 条变更待确认',
35
+ staged: '提案生成于 {when}',
36
+ accept: '确认应用',
37
+ reject: '拒绝',
38
+ later: '稍后',
39
+ working: '处理中…',
40
+ applied: '已应用:{written} 条写回,{retired} 条退役。',
41
+ rejected: '已拒绝,记忆保持原样。',
42
+ dismissed: '已稍后处理,这批提案还等着你。',
43
+ superseded: '这批提案已被新的提案取代。',
44
+ 'settled-elsewhere': '这批提案已在别处处理(/memories 或设置页)。',
45
+ failed: '应用失败,存储已回滚,可以重试。',
46
+ unknown: '找不到这批提案,请重新打开会话。',
47
+ unavailable: '这个操作现在不可用。',
48
+ 'read-only': '当前会话是只读的,不能改动记忆。',
49
+ 'access-denied': '没有改动记忆的权限。',
50
+ 'not-live-root': '请在原会话里操作这张卡片。',
51
+ closing: '插件正在重载,请稍后再试。',
52
+ transport: '没有收到结果,请刷新后重试。',
53
+ },
54
+ en: {
55
+ scope: 'Scope: {label}',
56
+ count: '{count} change(s) waiting',
57
+ staged: 'Staged {when}',
58
+ accept: 'Apply',
59
+ reject: 'Reject',
60
+ later: 'Not now',
61
+ working: 'Working…',
62
+ applied: '{written} written, {retired} retired.',
63
+ rejected: 'Rejected; the memories are unchanged.',
64
+ dismissed: 'Set aside; the proposal is still waiting.',
65
+ superseded: 'A newer proposal replaced this one.',
66
+ 'settled-elsewhere': 'This proposal was already decided elsewhere (/memories or the settings page).',
67
+ failed: 'Applying failed and the store was rolled back; you can retry.',
68
+ unknown: 'This proposal is unavailable. Reopen the conversation.',
69
+ unavailable: 'That action is unavailable now.',
70
+ 'read-only': 'This Session is read-only, so memories cannot change.',
71
+ 'access-denied': 'You do not have permission to change memories.',
72
+ 'not-live-root': 'Use this card in its original conversation.',
73
+ closing: 'The plugin is reloading. Try again shortly.',
74
+ transport: 'No result arrived. Refresh and try again.',
75
+ },
76
+ };
77
+ /** One validated card's details. */
78
+ function parseProposalDetails(value) {
79
+ if (value === null || typeof value !== 'object')
80
+ return undefined;
81
+ const label = value.label;
82
+ const count = value.count;
83
+ const stagedAt = value.stagedAt;
84
+ if (typeof label !== 'string' || label.length === 0)
85
+ return undefined;
86
+ if (typeof count !== 'number' || !Number.isInteger(count) || count <= 0)
87
+ return undefined;
88
+ if (typeof stagedAt !== 'number' || !Number.isInteger(stagedAt))
89
+ return undefined;
90
+ return { label, count, stagedAt };
91
+ }
92
+ /** Render an epoch-millisecond instant in the reader's locale. */
93
+ function proposalWhen(ms) {
94
+ return ms > 0 ? new Date(ms).toLocaleString() : '—';
95
+ }
96
+ /** One refusal reason, mapped to copy this body owns; unknown reasons read as unavailable. */
97
+ function proposalReasonKey(reason) {
98
+ return typeof reason === 'string' && Object.hasOwn(PROPOSAL_COPY.en, reason) ? reason : 'unavailable';
99
+ }
100
+ /** The copy of one recorded phase; `undefined` while the card is unstarted or open. */
101
+ function proposalStatus(t, phase, data) {
102
+ switch (phase) {
103
+ case 'applied': {
104
+ const written = typeof data?.written === 'number' ? data.written : 0;
105
+ const retired = typeof data?.retired === 'number' ? data.retired : 0;
106
+ return t('applied', { written: String(written), retired: String(retired) });
107
+ }
108
+ case 'rejected':
109
+ case 'dismissed':
110
+ case 'superseded':
111
+ case 'settled-elsewhere':
112
+ case 'failed':
113
+ return t(phase);
114
+ default:
115
+ return undefined;
116
+ }
117
+ }
118
+ /** The class of one status line: a failure is an error, a decision is a success. */
119
+ function proposalStatusClass(phase) {
120
+ if (phase === 'failed')
121
+ return 'dshm-status dshm-error';
122
+ if (phase === 'applied' || phase === 'rejected' || phase === 'dismissed')
123
+ return 'dshm-status dshm-ok';
124
+ return 'dshm-status';
125
+ }
126
+ /**
127
+ * Build the card body component.
128
+ *
129
+ * @param React - the shell's React instance.
130
+ * @returns the body component registered under {@link PROPOSAL_CARD_ACTION}.
131
+ */
132
+ function createProposalCardBody(React) {
133
+ return function MemoryProposalCard(props) {
134
+ const details = parseProposalDetails(props.proposal?.details);
135
+ if (details === undefined)
136
+ return props.fallback;
137
+ const [pending, setPending] = React.useState(undefined);
138
+ const [error, setError] = React.useState(undefined);
139
+ const phase = props.decision?.phase;
140
+ const settled = phase !== undefined && !PROPOSAL_OPEN_PHASES.includes(phase);
141
+ const status = phase === undefined ? undefined : proposalStatus(props.t, phase, props.decision?.data);
142
+ const run = (verb) => {
143
+ setPending(verb);
144
+ setError(undefined);
145
+ Promise.resolve().then(() => props.act(verb)).then((result) => {
146
+ if (result === undefined)
147
+ setError('transport');
148
+ else if (result.status === 'refused' || result.status === 'unconfirmed')
149
+ setError(proposalReasonKey(result.reason));
150
+ }, () => setError('transport')).then(() => setPending(undefined));
151
+ };
152
+ const button = (key, label, variant, verb) => React.createElement('button', {
153
+ key,
154
+ type: 'button',
155
+ className: variant === 'primary' ? 'dshm-btn dshm-btn-primary' : 'dshm-btn',
156
+ disabled: pending !== undefined,
157
+ onClick: () => { run(verb); },
158
+ }, pending === verb ? props.t('working') : label);
159
+ const children = [
160
+ props.summary,
161
+ React.createElement('p', { key: 'meta', className: 'dshm-meta' }, [
162
+ React.createElement('span', { key: 'scope' }, props.t('scope', { label: details.label })),
163
+ React.createElement('span', { key: 'count' }, props.t('count', { count: String(details.count) })),
164
+ React.createElement('span', { key: 'staged' }, props.t('staged', { when: proposalWhen(details.stagedAt) })),
165
+ ]),
166
+ ];
167
+ if (status !== undefined) {
168
+ children.push(React.createElement('p', { key: 'status', role: 'status', className: proposalStatusClass(phase) }, status));
169
+ }
170
+ if (error !== undefined) {
171
+ children.push(React.createElement('p', { key: 'error', role: 'alert', className: 'dshm-status dshm-error' }, props.t(error)));
172
+ }
173
+ if (!settled) {
174
+ children.push(React.createElement('footer', { key: 'footer', className: 'dshm-actions' }, [
175
+ button('later', props.t('later'), 'ghost', 'dismiss'),
176
+ button('reject', props.t('reject'), 'ghost', 'reject'),
177
+ button('accept', props.t('accept'), 'primary', 'accept'),
178
+ ]));
179
+ }
180
+ return React.createElement('div', { className: 'dshm-panel' }, children);
181
+ };
182
+ }
183
+
9
184
  // ---- .client-build/parts/card.js ----
10
185
  "use strict";
11
186
  /**
@@ -128,6 +303,11 @@ window.__ModuleLoader__.load({
128
303
  label: { zh: '全量检索会话数上限', en: 'Session logs opened per recall' },
129
304
  hint: { zh: '全量检索最多打开几份 session 日志(按最近修改排序);0 等于关闭。', en: 'How many session logs full-history retrieval may open, newest first. 0 disables it.' },
130
305
  },
306
+ {
307
+ field: 'denseEnabled', kind: 'boolean',
308
+ label: { zh: '语义召回通道', en: 'Dense recall channel' },
309
+ hint: { zh: '在词法排序之上加一路本地嵌入(RRF 融合),补「和提问没有共同词但语义相关」的记忆。需要本机运行 ollama(qwen3-embedding:0.6b);服务不可用时自动退回词法,不影响补注。默认关闭。', en: 'Adds a local embedding channel (RRF-fused with BM25) for memories that share no word with the turn but are about it. Needs ollama running locally (qwen3-embedding:0.6b); when the service is unreachable the recall silently stays lexical. Off by default.' },
310
+ },
131
311
  {
132
312
  field: 'recallMinQueryChars', kind: 'number', min: 0, step: 1,
133
313
  label: { zh: '触发补注的最短发问长度', en: 'Shortest turn worth recalling' },
@@ -1602,7 +1782,7 @@ window.__ModuleLoader__.load({
1602
1782
  * `factory(require)`, and mounts the exported plugin (`apply` + `inject`) into
1603
1783
  * the browser Cordis tree.
1604
1784
  *
1605
- * It contributes two surfaces, both fed by the same pieces:
1785
+ * It contributes three surfaces, fed by the same pieces:
1606
1786
  *
1607
1787
  * - the **Memories page** (`settings.section`): it lists, searches, adds, and
1608
1788
  * deletes memories through the Remote namespace the host registers, and it
@@ -1612,6 +1792,9 @@ window.__ModuleLoader__.load({
1612
1792
  * on the Plugins page, between the description and the rows — where the
1613
1793
  * official plugins put their configuration. The card is reused verbatim;
1614
1794
  * only its registration is new.
1795
+ * - the **confirmation card body** (`ctx.actionCards.register`, since 0.2.9):
1796
+ * the buttons of the `resolve_memory_proposal` card the Host kind offers in
1797
+ * an answer. Without this body the shell's frame would offer only Not now.
1615
1798
  *
1616
1799
  * Both edit the entry's own live form, so the two editors can never disagree.
1617
1800
  * The page keeps its menu: it is a feature surface, not a configuration menu.
@@ -1641,8 +1824,24 @@ window.__ModuleLoader__.load({
1641
1824
  const React = require('react');
1642
1825
  const Card = createMemoriesCard(React);
1643
1826
  const Section = createMemoriesSection(React, Card);
1827
+ const ProposalCard = createProposalCardBody(React);
1644
1828
  const apply = async (ctx) => {
1645
1829
  ensureStyles();
1830
+ // The consolidation confirmation card: the shell's action-card frame finds
1831
+ // this body by the action the Host kind registered. Both services are
1832
+ // optional — an older shell keeps the memories page and simply offers no
1833
+ // card body (its frame would show Not now alone), which is the same
1834
+ // degradation the page already documents.
1835
+ if (typeof ctx.inject === 'function') {
1836
+ ctx.inject(['actionCards', 'locale'], (child) => {
1837
+ child.effect(() => child.locale.register(PROPOSAL_CARD_LOCALE, PROPOSAL_COPY), 'dsh-cross-memory.proposalLocale');
1838
+ child.effect(() => child.actionCards.register({
1839
+ action: PROPOSAL_CARD_ACTION,
1840
+ locale: PROPOSAL_CARD_LOCALE,
1841
+ Body: ProposalCard,
1842
+ }), 'dsh-cross-memory.proposalCard');
1843
+ });
1844
+ }
1646
1845
  // The form is shared with every other editor of this entry and owned by the
1647
1846
  // settings provider, so this half only subscribes to it (inside
1648
1847
  // `useSnapshot`) and never disposes it.
package/lib/config.js CHANGED
@@ -218,6 +218,12 @@ export const DEFAULT_RAG_RECALL_BYTES = 12_000;
218
218
  export const DEFAULT_RAG_RECALL_EXCERPTS = 6;
219
219
  export const DEFAULT_RAG_RECALL_SESSIONS = 0;
220
220
  export const DEFAULT_RAG_RECALL_CHARS = 2_000;
221
+ /** Dense ranking is opt-in: it needs a local embedding service on every machine that recalls. */
222
+ export const DEFAULT_DENSE_ENABLED = false;
223
+ /** Ollama's default endpoint; the plugin never calls outside the machine unless this is changed. */
224
+ export const DEFAULT_DENSE_URL = 'http://127.0.0.1:11434';
225
+ /** The model the bench measured (1024 dimensions). */
226
+ export const DEFAULT_DENSE_MODEL = 'qwen3-embedding:0.6b';
221
227
  /**
222
228
  * Default number of distinct strong-field terms a recall needs.
223
229
  *
@@ -287,13 +293,16 @@ export const DEFAULT_EXTRACT_TIMEOUT_MS = 120_000;
287
293
  /**
288
294
  * Default max drafts one extraction may produce.
289
295
  *
290
- * 8 rather than 5: on a real production session, an audit of 50 Mubea
296
+ * 12 rather than 5, then 8: on a real production session, an audit of 50 Mubea
291
297
  * Invoice-Insight conversations found 247 durable facts, and the cap of 5 was
292
298
  * the single biggest cause of missed material on long sessions (one audit
293
- * session held 16 facts and kept 5). Eight keeps a long session's findings
294
- * without letting a short one pad itself.
299
+ * session held 16 facts and kept 5). The real-session bench then measured a
300
+ * clean dose-response on one fixed corpus: 5 → 19/33, 10 → 22/33, 20 → 24/33,
301
+ * so the curve is still rising at 20 but flattening. Twelve is where the next
302
+ * step buys about one more answered question per extra pass, before the entry
303
+ * count (and the consolidation load it creates) starts to dominate.
295
304
  */
296
- export const DEFAULT_EXTRACT_MAX_MEMORIES = 8;
305
+ export const DEFAULT_EXTRACT_MAX_MEMORIES = 12;
297
306
  /**
298
307
  * What the extractor is allowed to keep, by default.
299
308
  *
@@ -425,6 +434,7 @@ export const Config = z.object({
425
434
  ragRecallExcerpts: z.number().default(DEFAULT_RAG_RECALL_EXCERPTS).description('Most full-history excerpts one recall block may carry.').volatile(),
426
435
  ragRecallSessions: z.number().default(DEFAULT_RAG_RECALL_SESSIONS).description('How many session logs the full-history retrieval may open per recall, newest first. 0 opens all of them.').volatile(),
427
436
  ragRecallChars: z.number().default(DEFAULT_RAG_RECALL_CHARS).description('Longest one full-history excerpt may be, in characters.').volatile(),
437
+ denseEnabled: z.boolean().default(DEFAULT_DENSE_ENABLED).description('Add an embedding channel to recall ranking (RRF fusion with BM25). Off by default: it needs a local embedding service on every machine that recalls, and the bench gain is mostly in entries the lexical path misses entirely. When the service is unreachable the recall silently stays lexical.').volatile(),
428
438
  /** Shortest user turn worth a recall decision. */
429
439
  recallMinQueryChars: z.number().default(DEFAULT_RECALL_MIN_QUERY_CHARS).description('Shortest user turn, in characters, that may trigger a recall delta. Short acknowledgements are skipped instead of scanning the store.').volatile(),
430
440
  /** Distinct strong-field terms a recall needs before it is credited. */
@@ -568,6 +578,7 @@ export const MEMORIES_SETTINGS_DEFAULTS = {
568
578
  ragRecallExcerpts: DEFAULT_RAG_RECALL_EXCERPTS,
569
579
  ragRecallSessions: DEFAULT_RAG_RECALL_SESSIONS,
570
580
  ragRecallChars: DEFAULT_RAG_RECALL_CHARS,
581
+ denseEnabled: DEFAULT_DENSE_ENABLED,
571
582
  recallMinQueryChars: DEFAULT_RECALL_MIN_QUERY_CHARS,
572
583
  recallMinTerms: DEFAULT_RECALL_MIN_TERMS,
573
584
  injectDelta: DEFAULT_INJECT_DELTA,
@@ -687,6 +698,7 @@ export function normalizeSettings(input) {
687
698
  ragRecallExcerpts: positive(value.ragRecallExcerpts, DEFAULT_RAG_RECALL_EXCERPTS, 0),
688
699
  ragRecallSessions: nonNegative(value.ragRecallSessions, DEFAULT_RAG_RECALL_SESSIONS),
689
700
  ragRecallChars: positive(value.ragRecallChars, DEFAULT_RAG_RECALL_CHARS, 0),
701
+ denseEnabled: value.denseEnabled ?? DEFAULT_DENSE_ENABLED,
690
702
  recallMinQueryChars: positive(value.recallMinQueryChars, DEFAULT_RECALL_MIN_QUERY_CHARS, 0),
691
703
  recallMinTerms: positive(value.recallMinTerms, DEFAULT_RECALL_MIN_TERMS, 0),
692
704
  injectDelta: value.injectDelta ?? DEFAULT_INJECT_DELTA,