dsh-lm-memory 0.19.1 → 0.19.8

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.
@@ -594,8 +594,10 @@ function commitMemoryTx({ kind, content, tags = "", source = "agent", createdAt,
594
594
  try {
595
595
  if (source === "auto-extract" && db.prepare("SELECT 1 FROM suppression WHERE hash=?").get(contentHash(c))) { db.exec("ROLLBACK"); return {ok:false, reason:"suppressed"}; }
596
596
  if (supersedesId && validityOf(supersedesId)) { db.exec('ROLLBACK'); return { ok: false, reason: 'dated_requires_explicit_update' }; }
597
- // Exact text first (indexed), then the same atomic claim in other punctuation or width.
598
- const dup = db.prepare("SELECT id FROM memories WHERE status='active' AND content = ?").get(c) ?? sameFact(kind, c);
597
+ // Exact text first (indexed), then the same atomic claim in other punctuation or
598
+ // width. Both lookups are kind-scoped: the same sentence stored as a fact and as
599
+ // a procedure are two different memories (v0.19.4 复审实锤:跨类型被误判 EXISTS).
600
+ const dup = db.prepare("SELECT id FROM memories WHERE status='active' AND kind=? AND content = ?").get(kind, c) ?? sameFact(kind, c);
599
601
  if (dup) {
600
602
  const corroborated = recordCorroboration(dup.id, evidence, sessionId, revision);
601
603
  db.exec("COMMIT");
@@ -1088,35 +1090,56 @@ server.registerTool("memory_correct", {
1088
1090
  server.registerTool("memory_forget", {
1089
1091
  title: "忘记",
1090
1092
  description: "删除一条记忆。默认逻辑删除(保留 tombstone 供审计,不再被召回);hard=true 物理擦除该行(隐私purge)。active 与 dormant 均可删。",
1091
- inputSchema: { id: z.number().int().positive(), reason: z.string().max(500).default(""), hard: z.boolean().default(false).describe("物理删除该行(含已休眠/已接棒的行),用于隐私擦除;默认 false 为可逆逻辑删除") },
1092
- }, async ({ id, reason, hard }) => {
1093
- const any = db.prepare("SELECT id, kind, content, status FROM memories WHERE id=?").get(id);
1094
- if (!any) return ok(`ERROR: id=${id} 不存在。`);
1093
+ inputSchema: { id: z.number().int().positive(), reason: z.string().max(500).default(""), hard: z.boolean().default(false).describe("物理删除该行(含已休眠/已接棒的行),用于隐私擦除;默认 false 为可逆逻辑删除"),
1094
+ expected_version: z.number().int().positive().optional().describe("乐观并发:提供时与当前 version 不符则拒绝(0.19.5)") },
1095
+ }, async ({ id, reason, hard, expected_version }) => {
1096
+ // v0.19.6 外审 P1 修正:乐观版本校验必须与实际删除在【同一个 BEGIN IMMEDIATE
1097
+ // 写锁事务】内完成。0.19.5 曾把校验单独开事务提前 COMMIT——写锁随即释放,
1098
+ // 其他连接仍可在「校验后、删除前」改写记录,竞态窗口并未消除。
1099
+ // 实现要点:BEGIN IMMEDIATE 拿写锁 → 事务内读最新行 → 比对 expected_version
1100
+ // → 同一事务内执行删除/软删 → COMMIT。校验失败整事务回滚,不产生部分写入。
1101
+ const wantVersion = Number.isSafeInteger(expected_version);
1102
+ let wasStatus = null; // 事务内 fresh 行的删除前状态,供事务外审计使用
1095
1103
  if (hard) {
1096
- // v0.15.1 擦除契约(复核实锤旧版 hard 被 active/dormant 过滤挡住):按 id 物理擦除任何生命周期状态的行。
1097
- // 范围诚实声明:只删此行(含 FTS 索引,触发器联动)——不清理版本链其它行、队列文件、历史热流摘要。
1098
- db.exec("BEGIN");
1104
+ // v0.15.1 擦除契约:按 id 物理擦除任何生命周期状态的行。只删此行(含 FTS 索引触发器联动),
1105
+ // 不清理版本链其它行、队列文件、历史热流摘要。
1106
+ db.exec("BEGIN IMMEDIATE");
1099
1107
  try {
1100
- db.prepare("INSERT OR IGNORE INTO suppression VALUES (?,?)").run(contentHash(any.content), now());
1108
+ const fresh = db.prepare("SELECT id, version, kind, content, status FROM memories WHERE id=?").get(id);
1109
+ if (!fresh) { db.exec("ROLLBACK"); return ok(`ERROR: id=${id} 不存在。`); }
1110
+ if (wantVersion && fresh.version !== expected_version) {
1111
+ db.exec("ROLLBACK");
1112
+ return ok(`VERSION_CONFLICT: id=${id} 当前 v${fresh.version} ≠ 期望 v${expected_version}。请刷新后重试。`);
1113
+ }
1114
+ wasStatus = fresh.status;
1115
+ db.prepare("INSERT OR IGNORE INTO suppression VALUES (?,?)").run(contentHash(fresh.content), now());
1101
1116
  db.prepare("DELETE FROM provenance WHERE memory_id=?").run(id);
1102
1117
  db.prepare('DELETE FROM corroboration WHERE memory_id=?').run(id);
1103
1118
  db.prepare('DELETE FROM validity WHERE memory_id=?').run(id);
1104
1119
  db.prepare("DELETE FROM memories WHERE id=?").run(id);
1105
- outboxInsert("forget", { id, kind: any.kind, reason: reason.slice(0, 80), hard: true, was: any.status }); // 删除事件不带原文(复核实锤)
1120
+ outboxInsert("forget", { id, kind: fresh.kind, reason: reason.slice(0, 80), hard: true, was: fresh.status }); // 删除事件不带原文
1106
1121
  db.exec("COMMIT");
1107
1122
  } catch (e) { db.exec("ROLLBACK"); throw e; }
1108
1123
  flushOutbox();
1109
- audit("forget", { id, reason: reason.slice(0, 80), hard: true, was: any.status }); // 审计不含全文
1124
+ audit("forget", { id, reason: reason.slice(0, 80), hard: true, was: wasStatus }); // 0.19.6 复审:审计需能还原删除前状态
1110
1125
  regenerateCurrentMd(); rebuildEdgesSafe();
1111
- return ok(`OK: id=${id} 已物理擦除(原状态 ${any.status})。范围:仅此行(版本链其它行/队列/历史热流摘要不在本次范围)。`);
1126
+ return ok(`OK: id=${id} 已物理擦除。范围:仅此行(版本链其它行/队列/历史热流摘要不在本次范围)。`);
1112
1127
  }
1113
- if (any.status !== "active" && any.status !== "dormant")
1114
- return ok(`ERROR: id=${id} 状态为 ${any.status}(保留供审计)。如需物理擦除请携带 hard=true 重试。`);
1115
- db.exec("BEGIN");
1128
+ db.exec("BEGIN IMMEDIATE");
1116
1129
  try {
1117
- db.prepare("INSERT OR IGNORE INTO suppression VALUES (?,?)").run(contentHash(any.content), now());
1130
+ const fresh = db.prepare("SELECT id, version, kind, content, status FROM memories WHERE id=?").get(id);
1131
+ if (!fresh) { db.exec("ROLLBACK"); return ok(`ERROR: id=${id} 不存在。`); }
1132
+ if (wantVersion && fresh.version !== expected_version) {
1133
+ db.exec("ROLLBACK");
1134
+ return ok(`VERSION_CONFLICT: id=${id} 当前 v${fresh.version} ≠ 期望 v${expected_version}。请刷新后重试。`);
1135
+ }
1136
+ if (fresh.status !== "active" && fresh.status !== "dormant") {
1137
+ db.exec("ROLLBACK");
1138
+ return ok(`ERROR: id=${id} 状态为 ${fresh.status}(保留供审计)。如需物理擦除请携带 hard=true 重试。`);
1139
+ }
1140
+ db.prepare("INSERT OR IGNORE INTO suppression VALUES (?,?)").run(contentHash(fresh.content), now());
1118
1141
  db.prepare("UPDATE memories SET status='deleted', updated_at=? WHERE id=?").run(now(), id);
1119
- outboxInsert("forget", { id, kind: any.kind, reason: reason.slice(0, 80), status: "deleted" }); // v0.15.2:删除事件一律不带原文(复核收窄声明)
1142
+ outboxInsert("forget", { id, kind: fresh.kind, reason: reason.slice(0, 80), status: "deleted" }); // 删除事件一律不带原文
1120
1143
  db.exec("COMMIT");
1121
1144
  } catch (e) { db.exec("ROLLBACK"); throw e; }
1122
1145
  flushOutbox();
package/server/viewer.mjs CHANGED
@@ -94,6 +94,9 @@ const saveConflictReview = (oldR, newR, verdict) => {
94
94
  } catch {}
95
95
  };
96
96
  // 带缓存的复核:返回 { total, needAction, pairs:[{...p, verdict}] };llm 不可用时 verdict 全为 null(未复核)
97
+ //裁决接口的重校验数据源:与列表页同一套规则(不触发模型复核,只取规则候选)
98
+ const conflictCandidatesCurrent = () => findConflictPairs(ro(), { maxPairs: 20 }).pairs;
99
+
97
100
  async function conflictCandidates() {
98
101
  const r = findConflictPairs(ro(), { maxPairs: 20 });
99
102
  const pairs = r.pairs.map((p) => ({ ...p, verdict: conflictReviewVerdict(p.old, p.new) }));
@@ -102,12 +105,14 @@ async function conflictCandidates() {
102
105
  const raw = await llm(buildReviewPrompt(pending));
103
106
  const verdicts = parseReview(raw, pending.length);
104
107
  if (verdicts) {
105
- verdicts.forEach((v, idx) => {
106
- const p = pending[idx];
107
- if (!p) return;
108
+ // v.i 是模型答的候选下标(buildReviewPrompt 按 pending 顺序编号),
109
+ // 必须用 v.i 定位;用遍历下标会在模型漏答时把判定错挂到别的对上。
110
+ for (const v of verdicts) {
111
+ const p = pending[v.i];
112
+ if (!p || p.verdict !== null) continue;
108
113
  p.verdict = v.verdict;
109
114
  saveConflictReview(p.old, p.new, v.verdict);
110
- });
115
+ }
111
116
  // 未拿到判定的残余(模型漏答)保持 null
112
117
  }
113
118
  }
@@ -604,6 +609,19 @@ let t; $("#q").addEventListener("input", (e) => { clearTimeout(t); t = setTimeou
604
609
  load();
605
610
  </script></body></html>`;
606
611
 
612
+ const CONSOLE_PAGE = (() => {
613
+ try { return fs.readFileSync(new URL("./console.html", import.meta.url), "utf8"); }
614
+ catch { return null; }
615
+ })();
616
+ const tailLines = (file, n) => {
617
+ try { return fs.readFileSync(file, "utf8").trim().split("\n").slice(-n); } catch { return []; }
618
+ };
619
+ const parseLines = (lines) => lines.flatMap((line) => { try { return [JSON.parse(line)]; } catch { return []; } });
620
+ // viewer 自己的审计条目(与 memory-server 的 log.jsonl 同一文件、同一形态)
621
+ const auditViewer = (op, data = {}) => {
622
+ try { fs.appendFileSync(path.join(MEM_DIR, "log.jsonl"), JSON.stringify({ ts: new Date().toISOString(), op, by: "viewer", ...data }) + "\n"); } catch {}
623
+ };
624
+
607
625
  http.createServer(async (req, res) => {
608
626
  const json = (d, code = 200) => { res.writeHead(code, { "Content-Type": "application/json; charset=utf-8" }); res.end(JSON.stringify(d)); };
609
627
  try {
@@ -638,9 +656,10 @@ http.createServer(async (req, res) => {
638
656
  }
639
657
  }
640
658
  if (!["127.0.0.1", "localhost", "[::1]", ""].includes(hostName)) { res.writeHead(403, { "Content-Type": "text/plain" }); return res.end("forbidden host"); }
641
- if (req.method === "GET" && u.pathname === "/") {
642
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
643
- return res.end(PAGE);
659
+ if (req.method === "GET" && (u.pathname === "/" || u.pathname === "/classic")) {
660
+ const body = u.pathname === "/classic" || !CONSOLE_PAGE ? PAGE : CONSOLE_PAGE;
661
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
662
+ return res.end(body);
644
663
  }
645
664
  // v0.10 版本端点:供插件探测旧版 viewer 并自动升级重启(detached 进程 app 重启杀不掉)
646
665
  if (req.method === "GET" && u.pathname === "/api/version") {
@@ -713,13 +732,92 @@ http.createServer(async (req, res) => {
713
732
  const r = await call("memory_pin", { id: body.id, action: body.action, reason: "viewer" });
714
733
  return json({ ok: String(r).includes("OK"), msg: String(r).slice(0, 80) });
715
734
  }
735
+ if (u.pathname === "/api/conflict/resolve") {
736
+ // v0.19.4 复审加固:判定白名单、候选对重校验、乐观并发、写后审计。
737
+ const VERDICTS = { adopt: "superseded", keep: "related", unrelated: "unrelated" };
738
+ const verdict = VERDICTS[body.verdict];
739
+ if (!verdict) return json({ ok: false, msg: "verdict 必须是 adopt / keep / unrelated" }, 400);
740
+ const oldId = Number(body.old), newId = Number(body.new);
741
+ if (!Number.isSafeInteger(oldId) || !Number.isSafeInteger(newId) || oldId === newId)
742
+ return json({ ok: false, msg: "old/new 必须是不同的记忆 id" }, 400);
743
+ const candidate = conflictCandidatesCurrent().find((p) =>
744
+ (p.old.id === oldId && p.new.id === newId) || (p.old.id === newId && p.new.id === oldId));
745
+ if (!candidate) return json({ ok: false, msg: "这对已不在待裁决列表(可能已裁决或库已变化),请刷新" }, 409);
746
+ const oldRow = ro().prepare("SELECT id, version, kind, content, updated_at FROM memories WHERE id = ? AND status = 'active'").get(candidate.old.id);
747
+ const newRow = ro().prepare("SELECT id, version, kind, content, updated_at FROM memories WHERE id = ? AND status = 'active'").get(candidate.new.id);
748
+ if (!oldRow || !newRow) return json({ ok: false, msg: "候选对已变化,请刷新后重试" }, 409);
749
+ const expectOld = Number(body.expected_old_version), expectNew = Number(body.expected_new_version);
750
+ if (!Number.isSafeInteger(expectOld) || !Number.isSafeInteger(expectNew))
751
+ return json({ ok: false, msg: '缺少 expected_old_version / expected_new_version' }, 400);
752
+ if (expectOld !== oldRow.version)
753
+ return json({ ok: false, msg: `旧条版本已变化(当前 v${oldRow.version}),请刷新后重试` }, 409);
754
+ if (expectNew !== newRow.version)
755
+ return json({ ok: false, msg: `新条版本已变化(当前 v${newRow.version}),请刷新后重试` }, 409);
756
+ if (verdict === "superseded") {
757
+ // 版本校验下沉:expected_version 由 memory_forget 在写锁事务内原子比对;
758
+ // 版本冲突对客户端是 409(0.19.6 外审:失败不能伪装成 200)
759
+ const r = await call("memory_forget", { id: oldRow.id, reason: "conflict-adopt", expected_version: oldRow.version });
760
+ const msg = String(r).slice(0, 140);
761
+ if (!r.includes("OK")) return json({ ok: false, msg }, msg.startsWith("VERSION_CONFLICT") ? 409 : 502);
762
+ saveConflictReview(oldRow, newRow, verdict);
763
+ auditViewer("conflict_resolve", { old: oldRow.id, new: newRow.id, verdict: "superseded" });
764
+ return json({ ok: true, msg: "已采纳新说法,旧条转为历史(审计可查;默认召回不再返回)" });
765
+ }
766
+ saveConflictReview(oldRow, newRow, verdict);
767
+ auditViewer("conflict_resolve", { old: oldRow.id, new: newRow.id, verdict });
768
+ return json({ ok: true, msg: verdict === "related" ? "已记录:两条都保留" : "已记录:判为无关,不再提示" });
769
+ }
716
770
  if (u.pathname === "/api/sleep") {
717
771
  const r = await call("memory_sleep", {});
718
772
  return json({ ok: true, msg: String(r).slice(0, 200) });
719
773
  }
720
774
  }
775
+ if (req.method === "GET" && u.pathname === "/api/events") {
776
+ const changes = parseLines(tailLines(path.join(MEM_DIR, "changes.jsonl"), 400));
777
+ const log = parseLines(tailLines(path.join(MEM_DIR, "log.jsonl"), 400));
778
+ const nowMs = Date.now();
779
+ const hours = [];
780
+ for (let i = 23; i >= 0; i--) {
781
+ const start = new Date(nowMs - i * 3600e3);
782
+ hours.push({
783
+ hour: start.toLocaleTimeString("zh-CN", { hour: "2-digit", hour12: false }),
784
+ n: changes.filter((c) => { const t = new Date(c.ts); return t >= start && t < new Date(start.getTime() + 3600e3); }).length,
785
+ });
786
+ }
787
+ const dayAgo = new Date(nowMs - 864e5);
788
+ const last24 = changes.filter((c) => new Date(c.ts) >= dayAgo);
789
+ const failures = log.filter((l) => /failed|error/i.test(String(l.op ?? "")));
790
+ return json({
791
+ version: PKG_VERSION, pid: process.pid, db: path.join(MEM_DIR, "memory.db"),
792
+ hours,
793
+ events: changes.slice(-40).reverse().map((c) => ({
794
+ ts: c.ts, op: c.op, id: c.new_id ?? c.id ?? null, kind: c.kind ?? null,
795
+ clip: String(c.content ?? c.reason ?? (c.total ? c.total + " 组冲突" : "") ?? "").slice(0, 90),
796
+ })),
797
+ failures: failures.slice(-6).reverse().map((l) => ({ ts: l.ts, op: l.op, session: String(l.sessionId ?? "").slice(8, 16), attempts: l.attempts ?? null })),
798
+ last24: last24.length,
799
+ writes24: last24.filter((c) => ["remember", "episode", "ingest"].includes(c.op)).length,
800
+ corrections24: last24.filter((c) => c.op === "correct").length,
801
+ failures24: failures.filter((l) => new Date(l.ts) >= dayAgo).length,
802
+ });
803
+ }
804
+ if (req.method === "GET" && u.pathname === "/api/audit") {
805
+ const log = parseLines(tailLines(path.join(MEM_DIR, "log.jsonl"), 400));
806
+ const rows = log.slice(-300).reverse().map((l) => ({
807
+ ts: l.ts, op: String(l.op ?? ""),
808
+ by: String(l.by ?? "").replace("mcp:lm-memory", "mcp").replace("extract-helper", "helper"),
809
+ detail: String(l.reason ?? l.error ?? l.sessionId ?? l.id ?? l.patch ?? "").slice(0, 70),
810
+ hard: l.hard === true || undefined, // 0.19.6 复审:审计需能还原删除方式与删除前状态
811
+ was: typeof l.was === "string" ? l.was : undefined,
812
+ }));
813
+ const opCount = {};
814
+ for (const row of rows) opCount[row.op] = (opCount[row.op] ?? 0) + 1;
815
+ return json({ rows, ops: Object.entries(opCount).sort((a, b) => b[1] - a[1]) });
816
+ }
721
817
  json({ error: "not found" }, 404);
722
818
  } catch (e) { json({ error: String(e.message) }, 500); }
723
- }).listen(PORT, "127.0.0.1", () => {
724
- console.log(`lm-memory viewer → http://127.0.0.1:${PORT} (dir: ${MEM_DIR})`);
819
+ }).listen(PORT, "127.0.0.1", function () {
820
+ // PORT=0 时由 OS 分配实际端口(外审 P2-2:测试用动态端口,不再先占再放)
821
+ const actual = this.address().port;
822
+ console.log(`lm-memory viewer → http://127.0.0.1:${actual} (dir: ${MEM_DIR})`);
725
823
  });