Skip to content

Commit 37e77f1

Browse files
committed
Merge branch 'main' into feat/275-storage-reclaim
2 parents 230c35a + 8418916 commit 37e77f1

20 files changed

Lines changed: 942 additions & 42 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ dsh-mneme 是 DSH 宿主的记忆插件(蒸馏 / 注入 / 检索 / 巩固 / sc
3434
| 存储 | `src/store.js` | SQLite schema(memories / 实体三表 / dream_runs / recall_runs / 审计表)、幂等迁移 |
3535
| 存储生命周期 | `src/maintenance.js` | 无损回收维护入口(#275 第一批;`dsh-mneme reclaim`,默认 dry-run,VACUUM 单独指定) |
3636
| 服务层 | `src/service.js` | saveWithDedupe(去重键 type+title+scope 三元组)、fuseRecall 检索融合(keyword/vector/bm25/entity)、注入候选、镜像同步、冲突队列 |
37+
| 写入准入 | `src/write-admission.js` | 写入前的会话写入预算与同话题冷却(#254;第一阶段只计量不拦截,测量点落 `llm_audit_logs`) |
3738
| 注入 | `src/inject.js` | 注入位构造、内容截断、跨轮轮换 |
3839
| 蒸馏 | `src/summarize.js` + `src/quality-filter.js` | 会话 → 记忆;质量打分与处置(归档/降权) |
3940
| 巩固与睡眠 | `src/dream.js` + `src/dream/{decisions,clustering,sleep}.js` | LLM 巩固决策、dream_runs 审计回执 |

‎README.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-3E63DD?style=flat-square" alt="license"></a>
1111
<a href="https://github.com/slow-stack/mneme/actions"><img src="https://img.shields.io/github/actions/workflow/status/slow-stack/mneme/ci.yml?style=flat-square&label=CI" alt="CI"></a>
1212
<a href="https://nodejs.org"><img src="https://img.shields.io/badge/node-22%2B-3E63DD?style=flat-square&logo=nodedotjs&logoColor=white" alt="node"></a>
13-
<a href="https://github.com/slow-stack/mneme"><img src="https://img.shields.io/badge/tests-1329%20passed-3E63DD?style=flat-square" alt="tests"></a>
13+
<a href="https://github.com/slow-stack/mneme"><img src="https://img.shields.io/badge/tests-1342%20passed-3E63DD?style=flat-square" alt="tests"></a>
14+
<a href="https://github.com/slow-stack/mneme"><img src="https://img.shields.io/badge/tests-1342%20passed-3E63DD?style=flat-square" alt="tests"></a>
1415
<a href="https://codecov.io/gh/slow-stack/mneme"><img src="https://img.shields.io/codecov/c/github/slow-stack/mneme/main?style=flat-square" alt="coverage"></a>
1516
<a href="https://github.com/awesome-dsh-plugin/awesome-dsh-plugin"><img src="https://awesome-dsh-plugin.com/badge.svg" alt="Awesome"></a>
1617
</p>
@@ -182,7 +183,8 @@ dsh web
182183

183184
```bash
184185
cd dsh-mneme && npm install
185-
npm test # 1329 个测试
186+
npm test # 1342 个测试
187+
npm test # 1342 个测试
186188
npm run stress # 三轴线压测
187189
npm run sync # src → lib 同步
188190
```
@@ -364,7 +366,8 @@ The plugin ships a zero-dependency stdio MCP server (standalone npm package **`m
364366

365367
```bash
366368
cd dsh-mneme && npm install
367-
npm test # 1329 tests
369+
npm test # 1342 tests
370+
npm test # 1342 tests
368371
npm run stress # three-axis stress test
369372
npm run sync # src → lib sync
370373
```

‎dsh-mneme/CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,19 @@
2727
时服务端重新排队嵌入,回收不是单程票。实测(活库副本上跑:177 个 run 的输入快照 + 295 行
2828
归档向量,磁盘足迹 69.5 MiB 到 50.8 MiB,VACUUM 含 checkpoint 1.2 s)与代价见
2929
[`docs/STORAGE.md`](docs/STORAGE.md)。
30+
- **写入准入第一阶段:只计量、不拦截(issue #254)**:新增 `src/write-admission.js`。会话写入
31+
预算(g1)与同话题冷却(g2)两个闸门这一阶段只产遥测——不装阈值、不加拦截分支,写入行为
32+
逐字节不变(维护者 2026-09-23 拍板口径「先记录不拦,由遥测定」,N 与 X 等真实分布再定)。
33+
测量点落进既有 `llm_audit_logs`(`trigger_source='writeAdmission'`、`operation_type='write_admission'`、
34+
`status='skipped'`、`metadata.gate='g1'`),并新增可空列 `session_key` 与索引:一行一个新建行,
35+
「会话内新建条数」按会话直接计数即得;同话题新建行重复时在该行附 `metadata.g2`(`topic` 与
36+
`gap_ms`),即得「同话题重写间隔」分布。口径收口在三处:只在新行上取测量点(并入已有行不算,
37+
纯合并是去重机制在正常工作,也因此不刷新同话题基准);pinned 类型(constraint / preference)
38+
不进预算也不进基准,但仍照记一行(`metadata.exempt='pinned'`,穿透频率可观测);无会话身份的
39+
写入(dream / summarize / import / organize)不进预算。`llmAudit.enabled=false` 时一行都不写:
40+
那个开关同时关掉了审计行的启动期清理,否则就是在无保留期的表里按写入频次增长。计量全程旁路,
41+
任一步失败只 warn、绝不反噬写入;审计列表端点不外泄 `session_key`(内部计数键)。第二阶段的
42+
拦截与 `memory_save({confirm:true})` 不在本批。
3043
- **MCP server 拆出独立包 `mneme-memory`(讨论 #300 双包方案第一批)**:根目录新增
3144
`mcp/` 包目录(bin 名 `mneme-mcp`),零依赖单文件从 `dsh-mneme/bin/` 迁出——工具面、
3245
渲染与 standalone API 数据面完全不变,插件包内旧 bin `dsh-mneme-mcp` 原样保留

‎dsh-mneme/README.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
[![npm version](https://img.shields.io/npm/v/@modusensus/dsh-mneme?color=blue&label=npm)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
66
[![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
77
[![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-1329%20passed-success)](https://github.com/slow-stack/mneme)
8+
[![tests](https://img.shields.io/badge/tests-1342%20passed-success)](https://github.com/slow-stack/mneme)
9+
[![tests](https://img.shields.io/badge/tests-1342%20passed-success)](https://github.com/slow-stack/mneme)
910
[![CI](https://img.shields.io/github/actions/workflow/status/slow-stack/mneme/ci.yml)](https://github.com/slow-stack/mneme/actions)
1011
[![node](https://img.shields.io/badge/node-22%2B-blue)](https://nodejs.org)
1112
[![npm downloads](https://img.shields.io/npm/d18m/@modusensus/dsh-mneme.svg?color=blue&label=downloads)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
@@ -581,7 +582,8 @@ src/
581582
├── api.js # HTTP 路由(Web 面板数据通道,含 /conflicts 冲突队列)
582583
└── index.js # 插件接线
583584
lib/ # src 的同步分发产物(npm run sync;发布前由 root prepack 的 check-sync.js 校验一致性;唯一手写例外 lib/client.js——Web 面板 bundle,sync 不覆盖)
584-
test/ # 1329 个 node:test 测试(审计与三轴线压测不变量;src↔lib 一致性由 scripts/check-sync.js 发布闸门校验)
585+
test/ # 1342 个 node:test 测试(审计与三轴线压测不变量;src↔lib 一致性由 scripts/check-sync.js 发布闸门校验)
586+
test/ # 1342 个 node:test 测试(审计与三轴线压测不变量;src↔lib 一致性由 scripts/check-sync.js 发布闸门校验)
585587
scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压测 · sync-lib.js 同步 · check-sync.js 发布闸门 · benchmark-recall.js / benchmark-embed.js / benchmark-rerank.js 基准 · sync-test-badge.mjs 测试徽章 · build-runtime-manifest.mjs 运行时清单
586588
```
587589
@@ -590,7 +592,8 @@ scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压
590592
```bash
591593
cd dsh-mneme
592594
npm install # 安装 peer 依赖(以 devDependencies 形式,用于本地测试)
593-
npm test # 运行 1329 个测试
595+
npm test # 运行 1342 个测试
596+
npm test # 运行 1342 个测试
594597
npm run stress # 三轴线压测:长会话检索 / 冲突仲裁 / 多 Agent 并发(离线 mock LLM)
595598
npm run sync # 把 src/ 同步到 lib/(发布时由 prepack 钩子自动执行)
596599
```

‎dsh-mneme/lib/api.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,11 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
788788
const page = Math.max(1, Number(url.searchParams.get("page") ?? 1) || 1);
789789
const pageSize = Math.min(200, Math.max(1, Number(url.searchParams.get("pageSize") ?? 50) || 50));
790790
const source = url.searchParams.get("source") ?? undefined;
791-
const items = service.listLlmAudits?.({ limit: pageSize, offset: (page - 1) * pageSize, source }) ?? [];
791+
// 写入准入(#254)的 session_key 是内部计数键——session_id 不是对外的归属
792+
// 标识(见 scope.js 文件头),而本端点按注释在 apiToken 之下也保持开放,所以
793+
// 不回传它。按会话离线聚合直接读库。
794+
const items = (service.listLlmAudits?.({ limit: pageSize, offset: (page - 1) * pageSize, source }) ?? [])
795+
.map((row) => (row.session_key === undefined ? row : { ...row, session_key: undefined }));
792796
const total = service.countLlmAudits?.({ source }) ?? items.length;
793797
sendJson(res, 200, { items, total, page, pageSize });
794798
} catch {

‎dsh-mneme/lib/index.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { createMirror, TYPE_FILE } from "./mirror.js";
33
import { createDocumentIndex } from "./document-index.js";
44
import { resolveDocumentDir } from "./document.js";
55
import { createService } from "./service.js";
6+
// #254 写入准入(第一阶段只计量,不拦截):见 src/write-admission.js 的文件头。
7+
import { createWriteAdmission } from "./write-admission.js";
68
import { createTools } from "./tools.js";
79
import { createInjector } from "./inject.js";
810
import { createSummarizer } from "./summarize.js";
@@ -269,7 +271,12 @@ export const apply = (ctx, config) => {
269271
documentIndex.remove();
270272
}
271273

272-
const service = createService({ store, mirror, config: cfg, logger: ctx.logger, documentIndex });
274+
// 写入准入实例:本批次只做计量(决策恒放行、写审计行),所以不需要新开关——它
275+
// 不改变任何写入行为,也不新增拦截分支;既有的 llmAudit.enabled 关掉时它同样
276+
// 不写(那个开关连审计行的启动期清理一起关掉)。第二阶段把拦截打开时才按仓库
277+
// 惯例引入 opt-in 默认关的配置键,届时只改这一个实例的构造与 service 的调用点。
278+
const writeAdmission = createWriteAdmission({ store, config: cfg, logger: ctx.logger });
279+
const service = createService({ store, mirror, config: cfg, logger: ctx.logger, documentIndex, writeAdmission });
273280

274281
// F-NEW-03: if the mirror sync failed last run (persisted dirty state), retry
275282
// a safe re-render at boot so a stale mirror converges without needing a

‎dsh-mneme/lib/scope.js‎

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,7 @@ export function createScopeResolver({ ctx, config, logger } = {}) {
3434
};
3535

3636
return function resolveWriteScope(exec) {
37-
let session = null;
38-
try {
39-
session = exec?.agent?.session ?? null;
40-
} catch {
41-
session = null;
42-
}
37+
const session = sessionOf(exec);
4338

4439
// 持久化 header(issue #17 的身份契约):session.header 是创建时冻结的
4540
// SessionHeader(含 agentPreset/cwd)。⚠️ 不能先读 requestHeader()——那返回
@@ -83,6 +78,39 @@ export function createScopeResolver({ ctx, config, logger } = {}) {
8378
};
8479
}
8580

81+
/**
82+
* 工具 exec 上的会话对象。宿主 ctx 是 Proxy(cordis 4),裸读未 inject 的属性会
83+
* 抛错——所以取值恒包在 try 里,取不到返回 null。scope 解析与写入准入的会话键
84+
* 共用这一处取值口径。
85+
* @param {object} exec
86+
* @returns {object|null}
87+
*/
88+
export function sessionOf(exec) {
89+
try {
90+
return exec?.agent?.session ?? null;
91+
} catch {
92+
return null;
93+
}
94+
}
95+
96+
/**
97+
* 写入准入的会话键(#254 G1 会话写入预算的计数单位)。session_id 在这里只作
98+
* 「同一段对话」的标识,不作为作用域键(见文件头:记忆挂在持久化身份标签上);
99+
* 取不到会话身份(系统写入)返回 null = 不进预算。
100+
* @param {object} exec
101+
* @returns {string|null}
102+
*/
103+
export function sessionKeyOf(exec) {
104+
// 整个取值(含 .id)都在 try 里:宿主 session 可能是会抛错的 accessor,而这个
105+
// 函数在 memory_save 的保存之前被调用——抛出去就是一次工具调用直接失败。
106+
try {
107+
const id = sessionOf(exec)?.id;
108+
return id == null ? null : String(id);
109+
} catch {
110+
return null;
111+
}
112+
}
113+
86114
/**
87115
* v0.8.1 底座(issue #170):显式 scope 参数(memory_save / memory_update /
88116
* 面板编辑)的归一化。约定:

‎dsh-mneme/lib/service.js‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ const CODING_MEMORY_TYPES = new Set(["rejected_solution", "pitfall", "constraint
2929
// 注意 constraint 同时属于 CODING_MEMORY_TYPES,非编码任务里已被 codingGate
3030
// 滤掉,pin 池同样拿不到它;是否豁免该门控是待维护者拍板的口径问题,本批次
3131
// 不动既有门控(不放大行为面)。
32-
const PINNED_MEMORY_TYPES = new Set(["constraint", "preference"]);
32+
// 导出给写入准入(#254 的穿透口)与注入侧共用一份定义:两处各写一份 list 迟早
33+
// 漂移成「pin 池豁免了、预算没豁免」这类两套口径。
34+
export const PINNED_MEMORY_TYPES = new Set(["constraint", "preference"]);
3335

3436
/**
3537
* 判断一段文本是否编码类任务(关键词匹配,codingRetrospect 读取侧门控)。
@@ -167,7 +169,7 @@ export function computeRetrievalMetrics(actualIds, expectedIds) {
167169
};
168170
}
169171

170-
export function createService({ store, mirror, config, onWrite, logger, documentIndex }) {
172+
export function createService({ store, mirror, config, onWrite, logger, documentIndex, writeAdmission }) {
171173
const language = langOf(config);
172174
// Optional dream scheduler hook, installed via setDreamHook after creation
173175
// (the scheduler holds a reference back to the service, so it cannot be
@@ -1248,6 +1250,17 @@ export function createService({ store, mirror, config, onWrite, logger, document
12481250
scheduleEmbed(result);
12491251
return { action: "merged", memory: result };
12501252
}
1253+
// #254 写入准入(第一阶段只计量):决策恒 allow、不拦写入,只把两个闸门的
1254+
// 测量点算出来。放在 store.save 之前——第二阶段要在这里拦下写入,接缝先摆好。
1255+
// 计量是旁路:任何一环失败只 warn,绝不反噬写入(与质量打分同款容错)。
1256+
let admission = null;
1257+
if (writeAdmission) {
1258+
try {
1259+
admission = writeAdmission.evaluate({ memory, sessionKey: memory._sessionKey });
1260+
} catch (e) {
1261+
try { logger?.warn?.(`[dsh-mneme] write admission evaluate failed: ${String(e)}`); } catch { /* 不反噬 */ }
1262+
}
1263+
}
12511264
const created = store.save({
12521265
type: memory.type,
12531266
title: memory.title,
@@ -1268,6 +1281,17 @@ export function createService({ store, mirror, config, onWrite, logger, document
12681281
...(quality ? { quality_score: quality.score } : {})
12691282
});
12701283
const result = applyQualityDisposition(created, quality, qf);
1284+
if (admission) {
1285+
try {
1286+
writeAdmission.record({
1287+
sessionKey: memory._sessionKey,
1288+
verdict: admission,
1289+
memoryId: created.id
1290+
});
1291+
} catch (e) {
1292+
try { logger?.warn?.(`[dsh-mneme] write admission record failed: ${String(e)}`); } catch { /* 不反噬 */ }
1293+
}
1294+
}
12711295
afterSync("write");
12721296
notifyWrite();
12731297
scheduleEmbed(result);

‎dsh-mneme/lib/store.js‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,8 @@ CREATE TABLE IF NOT EXISTS llm_audit_logs (
193193
status TEXT NOT NULL, -- success | error | skipped
194194
error_message TEXT,
195195
related_memory_ids TEXT, -- JSON: ids the call operated on
196-
metadata TEXT -- JSON: free-form extras
196+
metadata TEXT, -- JSON: free-form extras
197+
session_key TEXT -- #254 写入准入的会话键(LLM 调用行恒 NULL)
197198
);
198199
CREATE INDEX IF NOT EXISTS idx_llm_audit_timestamp ON llm_audit_logs(timestamp);
199200
CREATE INDEX IF NOT EXISTS idx_llm_audit_source ON llm_audit_logs(trigger_source);
@@ -608,7 +609,9 @@ function toLlmAudit(row) {
608609
status: row.status,
609610
error_message: row.error_message ?? undefined,
610611
related_memory_ids: parseJsonArray(row.related_memory_ids),
611-
metadata
612+
metadata,
613+
// #254 写入准入的会话键;LLM 调用行恒 NULL。
614+
session_key: row.session_key ?? undefined
612615
};
613616
}
614617

@@ -725,6 +728,13 @@ export function createStore(path) {
725728
addColumn("mirror_state", "applied_generation", "ALTER TABLE mirror_state ADD COLUMN applied_generation INTEGER NOT NULL DEFAULT 0");
726729
addColumn("mirror_state", "type_status", "ALTER TABLE mirror_state ADD COLUMN type_status TEXT");
727730

731+
// #254 写入准入(第一阶段只计量):准入决策行按会话聚合——「会话内新建了几行」
732+
// 与「同话题重复间隔」都靠它算出来,所以会话键必须是可等值查询的列,而不是塞在
733+
// metadata 里做 JSON 匹配。列可空且不带 DEFAULT(存量行零重写)。索引建在加列
734+
// 之后:老库打开时列还不存在(SCHEMA 的 CREATE TABLE 只对新建库生效)。
735+
addColumn("llm_audit_logs", "session_key", "ALTER TABLE llm_audit_logs ADD COLUMN session_key TEXT");
736+
db.exec("CREATE INDEX IF NOT EXISTS idx_llm_audit_session ON llm_audit_logs(session_key);");
737+
728738
// Audit peer F: a legacy DB may hold a non-integer generation/applied_generation
729739
// (pre-v0.3.9 the JS gate truncated with Math.trunc and SQLite's CHECK only
730740
// enforced >= 0). Such a value is ambiguous — it cannot map to a real applied
@@ -1767,8 +1777,8 @@ export function createStore(path) {
17671777
db.prepare(
17681778
`INSERT INTO llm_audit_logs (timestamp, trigger_source, operation_type, model_id,
17691779
input_tokens, output_tokens, total_tokens, cost_usd, duration_ms, status,
1770-
error_message, related_memory_ids, metadata)
1771-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
1780+
error_message, related_memory_ids, metadata, session_key)
1781+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
17721782
).run(
17731783
entry.timestamp ?? now,
17741784
entry.trigger_source,
@@ -1784,33 +1794,43 @@ export function createStore(path) {
17841794
JSON.stringify(entry.related_memory_ids ?? []),
17851795
entry.metadata !== undefined
17861796
? (typeof entry.metadata === "string" ? entry.metadata : JSON.stringify(entry.metadata))
1787-
: null
1797+
: null,
1798+
entry.session_key ?? null
17881799
);
17891800
return toLlmAudit(db.prepare("SELECT * FROM llm_audit_logs ORDER BY id DESC LIMIT 1").get());
17901801
}
17911802

1792-
function listLlmAudits({ limit = 50, offset = 0, source } = {}) {
1803+
function listLlmAudits({ limit = 50, offset = 0, source, sessionKey } = {}) {
17931804
const { limit: lim, offset: off } = sanitizePage(limit, offset, 50);
17941805
const clauses = [];
17951806
const params = [];
17961807
if (source) {
17971808
clauses.push("trigger_source = ?");
17981809
params.push(source);
17991810
}
1811+
// #254 写入准入:会话内的话题回填只需要该会话的行(走 idx_llm_audit_session)。
1812+
if (sessionKey) {
1813+
clauses.push("session_key = ?");
1814+
params.push(sessionKey);
1815+
}
18001816
const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
18011817
const rows = db.prepare(
18021818
`SELECT * FROM llm_audit_logs ${where} ORDER BY timestamp DESC, id DESC LIMIT ? OFFSET ?`
18031819
).all(...params, lim, off);
18041820
return rows.map(toLlmAudit);
18051821
}
18061822

1807-
function countLlmAudits({ source } = {}) {
1823+
function countLlmAudits({ source, sessionKey } = {}) {
18081824
const clauses = [];
18091825
const params = [];
18101826
if (source) {
18111827
clauses.push("trigger_source = ?");
18121828
params.push(source);
18131829
}
1830+
if (sessionKey) {
1831+
clauses.push("session_key = ?");
1832+
params.push(sessionKey);
1833+
}
18141834
const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
18151835
return db.prepare(`SELECT count(*) AS c FROM llm_audit_logs ${where}`).get(...params).c;
18161836
}

0 commit comments

Comments
 (0)