dsh-lm-memory 0.17.3 → 0.18.1

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.
@@ -0,0 +1,73 @@
1
+ // One-shot, opt-in copy of the existing global memory library into the
2
+ // project-mode personal store. Public MCP writes only: no schema copying, no
3
+ // direct SQLite edits, no deletion of the source. Re-running is safe because
4
+ // the target store drops identical content.
5
+ //
6
+ // Usage: node scripts/migrate-to-personal.mjs [--memory-dir DIR] [--dry-run]
7
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
8
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ const argv = process.argv.slice(2);
15
+ const argValue = name => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined; };
16
+ const dryRun = argv.includes('--dry-run');
17
+ const memoryDir = path.resolve(argValue('--memory-dir')
18
+ ?? process.env.LM_MEMORY_DIR
19
+ ?? path.join(process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh'), 'memory'));
20
+ const source = path.join(memoryDir, 'memory.db');
21
+ const target = path.join(memoryDir, 'personal-v1');
22
+
23
+ if (!fs.existsSync(source)) {
24
+ console.error(`no legacy database at ${source}`);
25
+ process.exit(2);
26
+ }
27
+
28
+ const { DatabaseSync } = process.getBuiltinModule('node:sqlite');
29
+ const legacy = new DatabaseSync(source, { readOnly: true });
30
+ const rows = legacy.prepare(`SELECT id,kind,content,tags,event_date,pinned FROM memories
31
+ WHERE status='active' ORDER BY id`).all();
32
+ legacy.close();
33
+
34
+ console.log(`source: ${source}`);
35
+ console.log(`target: ${target}`);
36
+ console.log(`active rows to copy: ${rows.length}`);
37
+ if (dryRun) { console.log('dry run: nothing written'); process.exit(0); }
38
+
39
+ fs.mkdirSync(target, { recursive: true, mode: 0o700 });
40
+ const client = new Client({ name: 'lm-memory-migrate', version: '1' });
41
+ await client.connect(new StdioClientTransport({
42
+ command: process.execPath,
43
+ args: [fileURLToPath(new URL('../server/memory-server.mjs', import.meta.url))],
44
+ env: { ...process.env, LM_MEMORY_DIR: target, LM_EMBED: '0' },
45
+ stderr: 'ignore',
46
+ }));
47
+
48
+ let copied = 0, existing = 0, refused = 0;
49
+ const failures = [];
50
+ for (const row of rows) {
51
+ const args = { content: row.content, kind: row.kind, tags: row.tags ?? '' };
52
+ if (/^\d{4}-\d{2}-\d{2}$/.test(row.event_date ?? '')) args.event_date = row.event_date;
53
+ let text;
54
+ try {
55
+ text = (await client.callTool({ name: 'memory_remember', arguments: args }, undefined, { timeout: 30_000 }))
56
+ .content?.[0]?.text ?? '';
57
+ } catch (error) { failures.push({ id: row.id, error: String(error.message).slice(0, 120) }); continue; }
58
+ const id = Number(/id=(\d+)/.exec(text)?.[1]);
59
+ if (text.startsWith('OK:') && id) {
60
+ copied++;
61
+ if (row.pinned) await client.callTool({ name: 'memory_pin', arguments: { id, action: 'pin' } });
62
+ } else if (text.startsWith('EXISTS')) existing++;
63
+ else if (text.startsWith('REFUSED')) refused++;
64
+ else failures.push({ id: row.id, error: text.slice(0, 120) });
65
+ }
66
+ await client.close();
67
+
68
+ console.log(`copied ${copied}, already present ${existing}, refused ${refused}, failed ${failures.length}`);
69
+ if (failures.length) {
70
+ for (const failure of failures.slice(0, 10)) console.error(` legacy #${failure.id}: ${failure.error}`);
71
+ process.exitCode = 1;
72
+ }
73
+ console.log('source database untouched; delete it yourself only after checking the target store');
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Living Memory MCP server v0.8 — stdio, single file, zero native deps.
2
+ // Living Memory MCP server — stdio; advertised version tracks the package manifest.
3
3
  // v0.7: sleep-time 价值衰减(命中统计 + kind 宽限期 + dormant 休眠 + pin/wake)
4
4
  // v0.8: 双模型语义层——中文 bge-small-zh(emb),英文 bge-small-en(emb_en),按查询语言路由
5
5
  // Store: ~/.dsh/memory/memory.db (SQLite + FTS5 trigram, WAL)
@@ -65,7 +65,30 @@ CREATE INDEX IF NOT EXISTS idx_mem_status ON memories(status, updated_at DESC);
65
65
  CREATE INDEX IF NOT EXISTS idx_mem_kind ON memories(kind) WHERE status='active';
66
66
  `);
67
67
  db.exec(`CREATE TABLE IF NOT EXISTS suppression (hash TEXT PRIMARY KEY, at TEXT NOT NULL);
68
- CREATE TABLE IF NOT EXISTS provenance (memory_id INTEGER PRIMARY KEY, session_id TEXT, revision TEXT, evidence TEXT NOT NULL);`);
68
+ CREATE TABLE IF NOT EXISTS provenance (memory_id INTEGER PRIMARY KEY, session_id TEXT, revision TEXT, evidence TEXT NOT NULL);
69
+ CREATE TABLE IF NOT EXISTS validity (memory_id INTEGER PRIMARY KEY, starts TEXT NOT NULL, ends TEXT);
70
+ CREATE TABLE IF NOT EXISTS corroboration (memory_id INTEGER NOT NULL, session_id TEXT NOT NULL, revision TEXT NOT NULL DEFAULT '', evidence TEXT NOT NULL, ts TEXT NOT NULL, PRIMARY KEY (memory_id, session_id, revision));`);
71
+ const validDay = value => /^\d{4}-\d{2}-\d{2}$/.test(value) &&
72
+ Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0,10) === value;
73
+ const validityOf = id => db.prepare('SELECT starts,ends FROM validity WHERE memory_id=?').get(id);
74
+ // Punctuation, width and spacing do not make a different fact; wording does.
75
+ const factKey = value => String(value).normalize('NFKC').toLowerCase().replace(/\s+/g, ' ').trim()
76
+ .replace(/[\s.。!!??,,;;::]+$/u, '');
77
+ function sameFact(kind, content) {
78
+ const key = factKey(content);
79
+ for (const row of db.prepare("SELECT id,content FROM memories WHERE status='active' AND kind=?").all(kind))
80
+ if (factKey(row.content) === key) return { id: row.id };
81
+ return undefined;
82
+ }
83
+ // A second independent session confirming the same fact adds evidence; it is
84
+ // not a duplicate, and it must not silently replace the first observation.
85
+ function recordCorroboration(memoryId, evidence, sessionId, revision) {
86
+ if (!sessionId || !Array.isArray(evidence) || !evidence.length) return false;
87
+ const prior = db.prepare('SELECT session_id FROM provenance WHERE memory_id=?').get(memoryId);
88
+ if (!prior || prior.session_id === sessionId) return false;
89
+ return db.prepare('INSERT OR IGNORE INTO corroboration (memory_id,session_id,revision,evidence,ts) VALUES (?,?,?,?,?)')
90
+ .run(memoryId, sessionId, String(revision ?? ''), JSON.stringify(evidence), now()).changes === 1;
91
+ }
69
92
  db.exec(`CREATE TABLE IF NOT EXISTS passage_vectors(memory_id INTEGER NOT NULL, model TEXT NOT NULL, ordinal INTEGER NOT NULL, vec BLOB NOT NULL, PRIMARY KEY(memory_id,model,ordinal));
70
93
  CREATE TRIGGER IF NOT EXISTS passage_delete AFTER DELETE ON memories BEGIN DELETE FROM passage_vectors WHERE memory_id=old.id; END;`);
71
94
  // v0.12 图谱边表(graph.mjs rebuildEdges 全量重建维护;只存 active-active 边)
@@ -561,7 +584,7 @@ function regenerateCurrentMdLocked() {
561
584
  // helper 直连 SQLite 用旧 schema INSERT,绕过凭据拦截/嵌入/current.md/热流/图谱。
562
585
  // 现在所有写入都收敛到 commitMemoryTx()(事务内落行 + announce),
563
586
  // 提炼 helper 降级为「只产候选文件」,由 server 消费。嵌入/索引/图谱在批次后统一刷新。
564
- function commitMemoryTx({ kind, content, tags = "", source = "agent", createdAt, eventDate, announceOp = "remember", supersedesId, evidence, sessionId, revision }) {
587
+ function commitMemoryTx({ kind, content, tags = "", source = "agent", createdAt, eventDate, validFrom, announceOp = "remember", supersedesId, evidence, sessionId, revision }) {
565
588
  const c = String(content ?? "").trim().slice(0, 2000);
566
589
  if (c.length < 3) return { ok: false, reason: "too_short" };
567
590
  const pat = checkSecret(c);
@@ -570,13 +593,21 @@ function commitMemoryTx({ kind, content, tags = "", source = "agent", createdAt,
570
593
  db.exec("BEGIN IMMEDIATE");
571
594
  try {
572
595
  if (source === "auto-extract" && db.prepare("SELECT 1 FROM suppression WHERE hash=?").get(contentHash(c))) { db.exec("ROLLBACK"); return {ok:false, reason:"suppressed"}; }
573
- const dup = db.prepare("SELECT id, version FROM memories WHERE status='active' AND content = ?").get(c);
574
- if (dup) { db.exec("ROLLBACK"); audit("commit_dedup", { id: dup.id, source }); return { ok: false, reason: "exists", id: dup.id }; }
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);
599
+ if (dup) {
600
+ const corroborated = recordCorroboration(dup.id, evidence, sessionId, revision);
601
+ db.exec("COMMIT");
602
+ audit("commit_dedup", { id: dup.id, source, corroborated });
603
+ return { ok: false, reason: "exists", id: dup.id, corroborated };
604
+ }
575
605
  const t = now();
576
606
  const ed = eventDate || localDate(); // v0.16:默认日期取本地时区(此前取 UTC ISO 截断,凌晨差一天);显式 eventDate 优先
577
607
  id = Number(db.prepare(
578
608
  "INSERT INTO memories (kind, content, tags, source, status, created_at, updated_at, event_date, supersedes) VALUES (?,?,?,?,'active',?,?,?,?)"
579
609
  ).run(kind, c, String(tags), source, createdAt || t, t, ed, supersedesId ?? null).lastInsertRowid);
610
+ if (validFrom) db.prepare('INSERT INTO validity(memory_id,starts) VALUES (?,?)').run(id, validFrom);
580
611
  if (Array.isArray(evidence) && evidence.length) db.prepare("INSERT INTO provenance (memory_id,session_id,revision,evidence) VALUES (?,?,?,?)").run(id, sessionId ?? null, revision ?? null, JSON.stringify(evidence));
581
612
  if (supersedesId) {
582
613
  const prior = db.prepare("SELECT content FROM memories WHERE id=?").get(supersedesId);
@@ -689,8 +720,9 @@ function ingestCandidates() {
689
720
  supersedesId = old.id;
690
721
  }
691
722
  const c = commitMemoryTx({ kind: rec.kind, content: rec.content, tags, source: "auto-extract", evidence: rec.evidence, sessionId: sid, revision: rec.capturedAt, createdAt: rec.capturedAt, eventDate: rec.eventDate, supersedesId });
692
- if (c.ok || ["exists", "secret", "too_short", "suppressed"].includes(c.reason)) db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, '1')").run(metaKey); // done 由 settleLedger 全量核对(v0.16.1)
693
- return c.ok || c.reason === "exists" || c.reason === "secret" || c.reason === "too_short" || c.reason === "suppressed"; // 查重/凭据/过短=终态,不重试(否则死循环重读)
723
+ const terminal = c.ok || ['exists', 'secret', 'too_short', 'suppressed', 'dated_requires_explicit_update'].includes(c.reason);
724
+ if (terminal) db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, '1')").run(metaKey); // settleLedger verifies the complete receipt
725
+ return terminal;
694
726
  });
695
727
  if (r.read) audit("ingest_candidates", r);
696
728
  return r.ok;
@@ -721,7 +753,7 @@ function ingestAll() { // 先消化自动采集与提炼候选,保证刚结束
721
753
 
722
754
  // ---------- server ----------
723
755
  const server = new McpServer(
724
- { name: "lm-memory", version: "0.15.0" },
756
+ { name: "lm-memory", version: JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version },
725
757
  {
726
758
  capabilities: { tools: {} },
727
759
  instructions:
@@ -738,9 +770,11 @@ server.registerTool("memory_remember", {
738
770
  kind: z.enum(KINDS).default("fact"),
739
771
  tags: z.string().max(200).default("").describe("逗号分隔标签,可选"),
740
772
  event_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe("事件发生/观察日(YYYY-MM-DD);缺省=今天。date 字段是稳定观察锚,不自动等于来源认证的事件日"),
773
+ valid_from: z.string().refine(validDay).optional().describe('已确认事实开始生效的日期;不同于观察日期,不从对话推断。'),
741
774
  },
742
- }, async ({ content, kind, tags, event_date }) => {
743
- const r = commitMemoryTx({ kind, content, tags, source: "agent", eventDate: event_date }); // v0.15 统一提交入口(凭据拦截/查重/事务/热流同路径)
775
+ }, async ({ content, kind, tags, event_date, valid_from }) => {
776
+ if (valid_from && (kind !== 'fact' || valid_from > localDate())) return ok('ERROR: 有效日期只支持已经生效的事实。');
777
+ const r = commitMemoryTx({ kind, content, tags, source: "agent", eventDate: event_date, validFrom: valid_from }); // v0.15 统一提交入口(凭据拦截/查重/事务/热流同路径)
744
778
  if (!r.ok) {
745
779
  if (r.reason === "secret") return ok(`REFUSED: 内容疑似凭据。秘密不入记忆库。`);
746
780
  if (r.reason === "exists") { // v0.16 自愈(第七轮外审实锤:首次写入时派生视图写失败 → 事后重试只回 EXISTS,current.md 永久缺)——EXISTS 分支幂等补修
@@ -778,14 +812,27 @@ server.registerTool("memory_recall", {
778
812
  scope: z.enum(["active", "dormant", "all"]).default("active").describe("休眠记忆必须显式选择 dormant/all;不唤醒、不延寿"),
779
813
  max_bytes: z.number().int().min(512).max(65536).default(16384).describe("搜索结果 JSON 字节预算;超额返回 hits/related/budget 对象,id 精确读取不受限"),
780
814
  expand: z.boolean().default(false).describe("图谱扩展:附带命中条目的一跳关联记忆(co_tag/similar/ref 边),实体中心问题用"),
815
+ as_of: z.string().refine(validDay).optional().describe('仅配合当前版本 ID,按显式有效区间读取该事实版本;不推断。'),
781
816
  },
782
- }, async ({ query, id, limit, kind, expand, scope, max_bytes }) => {
817
+ }, async ({ query, id, limit, kind, expand, scope, max_bytes, as_of }) => {
783
818
  if ((query === undefined) === (id === undefined)) return ok("ERROR: query 与 id 必须且只能提供一个。");
784
819
  const exactId = id ?? (/^#([1-9]\d*)$/.exec(query.trim())?.[1] ? Number(query.trim().slice(1)) : undefined);
785
820
  ingestAll(); // 先消化自动采集卡与提炼候选队列(统一提交入口),保证刚结束的会话可被检索
786
821
  const words = (query ?? "").replace(/["'^*]/g, " ").trim().split(/\s+/).filter(Boolean);
787
822
  const kindParams = kind ? [kind] : [];
788
823
  const statusFilter = scope === "all" ? "status IN ('active','dormant')" : `status='${scope}'`;
824
+ if (as_of) {
825
+ if (!exactId || expand || as_of > localDate()) return ok('ERROR: 历史读取仅支持当前编号和已到日期,不能扩图。');
826
+ const historical = db.prepare(`WITH RECURSIVE chain(id, prior) AS (
827
+ SELECT id,supersedes FROM memories WHERE id=? AND ${statusFilter}
828
+ UNION SELECT m.id,m.supersedes FROM memories m JOIN chain c ON m.id=c.prior WHERE m.status='superseded'
829
+ ) SELECT m.id,m.content,m.kind,m.version,v.starts,v.ends FROM chain c JOIN validity v ON v.memory_id=c.id
830
+ JOIN memories m ON m.id=c.id WHERE v.starts<=? AND (v.ends IS NULL OR ?<v.ends)
831
+ AND (? IS NULL OR m.kind=?) LIMIT 2`).all(exactId,as_of,as_of,kind ?? null,kind ?? null);
832
+ if (historical.length !== 1) return ok('[](该日无唯一已确认的有效事实。)');
833
+ const r = historical[0];
834
+ return ok(JSON.stringify([{ id:r.id, v:r.version, kind:r.kind, content:r.content, valid_from:r.starts, valid_until:r.ends }]));
835
+ }
789
836
  let rows = [];
790
837
  // 多样性排序:同 tags 组(如同会话的分块)先各取最优,再回填剩余名额
791
838
  const diversify = (rs, lim) => {
@@ -973,7 +1020,11 @@ server.registerTool("memory_source", {
973
1020
  inputSchema: { id: z.number().int().positive() },
974
1021
  }, async ({id}) => {
975
1022
  const row = db.prepare("SELECT p.* FROM provenance p JOIN memories m ON m.id=p.memory_id WHERE m.id=? AND m.status IN ('active','dormant')").get(id);
976
- return ok(row ? JSON.stringify({...row,evidence:JSON.parse(row.evidence)}) : "NOT_PROVEN: 此条没有可回查的原文证据。");
1023
+ if (!row) return ok("NOT_PROVEN: 此条没有可回查的原文证据。");
1024
+ // corroborations are other sessions' independent observations of the same claim.
1025
+ const corroborations = db.prepare("SELECT session_id,revision,evidence,ts FROM corroboration WHERE memory_id=? ORDER BY ts").all(id)
1026
+ .map(c => ({ ...c, evidence: JSON.parse(c.evidence) }));
1027
+ return ok(JSON.stringify({ ...row, evidence: JSON.parse(row.evidence), corroborations }));
977
1028
  });
978
1029
 
979
1030
  server.registerTool("memory_correct", {
@@ -984,8 +1035,9 @@ server.registerTool("memory_correct", {
984
1035
  expected_version: z.number().int().positive(),
985
1036
  content: z.string().min(3).max(2000),
986
1037
  reason: z.string().max(500).default(""),
1038
+ effective_from: z.string().refine(validDay).optional().describe('事实变更生效日;省略表示纠正原说法,不保留错误版本的有效区间。'),
987
1039
  },
988
- }, async ({ id, expected_version, content, reason }) => {
1040
+ }, async ({ id, expected_version, content, reason, effective_from }) => {
989
1041
  const secret = checkSecret(content);
990
1042
  if (secret) return ok("REFUSED: 新内容疑似凭据,拒绝写入。");
991
1043
  const row = db.prepare("SELECT * FROM memories WHERE id=?").get(id);
@@ -993,10 +1045,15 @@ server.registerTool("memory_correct", {
993
1045
  if (row.version !== expected_version) return ok(`VERSION_CONFLICT: 当前 v${row.version} ≠ 期望 v${expected_version}。请重新 recall 后重试。`);
994
1046
  const t = now();
995
1047
  let newIdNum = null;
996
- db.exec("BEGIN");
1048
+ db.exec('BEGIN IMMEDIATE');
997
1049
  try {
998
1050
  const fresh = db.prepare("SELECT version,status FROM memories WHERE id=?").get(id);
999
1051
  if (fresh?.status !== "active" || fresh.version !== expected_version) throw new Error("VERSION_CONFLICT: refresh memory before correcting");
1052
+ const prior = validityOf(id);
1053
+ if (effective_from && (!prior || effective_from <= prior.starts || effective_from > localDate())) {
1054
+ db.exec('ROLLBACK');
1055
+ return ok('ERROR: 变更生效日必须晚于原事实显式开始日期,且不得在未来。');
1056
+ }
1000
1057
  db.prepare("INSERT OR IGNORE INTO suppression VALUES (?,?)").run(contentHash(row.content), now());
1001
1058
  db.prepare("UPDATE memories SET status='superseded' WHERE id=?").run(id);
1002
1059
  // v0.15:新版本继承 pinned 与 event_date(外审实锁:修正曾静默丢置顶;事件锚不得被修正推移)
@@ -1004,6 +1061,11 @@ server.registerTool("memory_correct", {
1004
1061
  "INSERT INTO memories (version, kind, content, tags, source, status, supersedes, created_at, updated_at, pinned, event_date) VALUES (?,?,?,?,'agent-correct','active',?,?,?,?,?)"
1005
1062
  ).run(row.version + 1, row.kind, content.trim(), row.tags, id, row.created_at, t, row.pinned ? 1 : 0, row.event_date || String(row.created_at).slice(0, 10));
1006
1063
  newIdNum = Number(ins.lastInsertRowid);
1064
+ if (prior) {
1065
+ if (effective_from) db.prepare('UPDATE validity SET ends=? WHERE memory_id=?').run(effective_from,id);
1066
+ else db.prepare('DELETE FROM validity WHERE memory_id=?').run(id);
1067
+ db.prepare('INSERT INTO validity(memory_id,starts) VALUES (?,?)').run(newIdNum,effective_from ?? prior.starts);
1068
+ }
1007
1069
  // v0.15.2 复核实锤:correct 内容提交却事件为零——事件必须与内容同事务
1008
1070
  outboxInsert("correct", { old_id: id, new_id: newIdNum, version: row.version + 1, kind: row.kind, content: clip200(content), reason: reason.slice(0, 80) });
1009
1071
  db.exec("COMMIT");
@@ -1037,6 +1099,8 @@ server.registerTool("memory_forget", {
1037
1099
  try {
1038
1100
  db.prepare("INSERT OR IGNORE INTO suppression VALUES (?,?)").run(contentHash(any.content), now());
1039
1101
  db.prepare("DELETE FROM provenance WHERE memory_id=?").run(id);
1102
+ db.prepare('DELETE FROM corroboration WHERE memory_id=?').run(id);
1103
+ db.prepare('DELETE FROM validity WHERE memory_id=?').run(id);
1040
1104
  db.prepare("DELETE FROM memories WHERE id=?").run(id);
1041
1105
  outboxInsert("forget", { id, kind: any.kind, reason: reason.slice(0, 80), hard: true, was: any.status }); // 删除事件不带原文(复核实锤)
1042
1106
  db.exec("COMMIT");
@@ -1,76 +1,89 @@
1
- // viewer 旧版自动升级 E2E(v0.10):
2
- // 1) 假旧 viewer(独立进程、无 /api/version)占端口 → 插件 apply → 旧进程被杀、新 viewer 拉起
3
- // 2) 再次 apply → 新 viewer 不被重启(pid 不变)
4
- import http from "node:http";
5
- import { spawn } from "node:child_process";
6
- import { createRequire } from "node:module";
1
+ // Viewer startup owns only the exact detached process it launched; unverified legacy
2
+ // listeners must survive, and the settings bridge must not point at their data.
3
+ import assert from "node:assert/strict";
4
+ import { once } from "node:events";
5
+ import { execFileSync, spawn } from "node:child_process";
7
6
  import fs from "node:fs";
8
7
  import os from "node:os";
9
8
  import path from "node:path";
10
- import { fileURLToPath } from "node:url";
9
+ import apply from "../plugin/lib/index.js";
11
10
 
12
- const INSTALL_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
13
11
  const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "lm-viewer-e2e-"));
14
12
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
15
- const port = 17840 + Math.floor(Math.random() * 1000);
16
- const portPid = (p) => { try { return Number(createRequire(import.meta.url)("node:child_process").execFileSync("lsof", ["-ti", ":" + p, "-sTCP:LISTEN"], { encoding: "utf8" }).trim().split("\n")[0]) || 0; } catch { return 0; } };
13
+ const version = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
14
+ const oldProc = spawn(process.execPath, ["-e", `// legacy viewer.mjs stub (no /api/version)
15
+ const server = require('node:http').createServer((_req, res) => { res.writeHead(404); res.end(); });
16
+ server.listen(0, '127.0.0.1', () => process.send(server.address().port));`
17
+ ], { stdio: ["ignore", "ignore", "ignore", "ipc"] });
18
+ const oldExited = once(oldProc, "exit");
19
+ const observedPids = new Set();
20
+ let route;
21
+ const ctx = {
22
+ on() {},
23
+ inject(_, register) { register({ connection: { fetch: { register: (r) => { route = r; } } } }); },
24
+ };
17
25
 
18
- // 1) 假旧 viewer:独立进程占端口、所有请求 404(模拟旧版:无 /api/version)
19
- // 注:命令行必须含 "viewer.mjs" 字样——插件有 ps 防误杀校验(只杀真正的 viewer 进程)
20
- const oldProc = spawn(process.execPath, ["-e",
21
- `// legacy viewer.mjs stub (v0.9, no /api/version)\nrequire("http").createServer((q,s)=>{s.writeHead(404,{"Content-Type":"application/json"});s.end(JSON.stringify({error:"not found"}))}).listen(${port},"127.0.0.1")`
22
- ], { stdio: "ignore" });
23
- async function waitPort(p, wantVersion, timeoutMs = 12000) {
24
- const t0 = Date.now();
25
- while (Date.now() - t0 < timeoutMs) {
26
- try {
27
- const r = await fetch("http://127.0.0.1:" + p + "/api/version", { signal: AbortSignal.timeout(800) });
28
- if (r.ok) {
29
- const d = await r.json();
30
- if (!wantVersion || d.version === wantVersion) return d;
31
- }
32
- } catch {}
33
- await sleep(300);
34
- }
35
- return null;
36
- }
37
- // 等假旧 viewer 就绪(404 也算就绪)
38
- {
39
- const t0 = Date.now();
40
- let up = false;
41
- while (Date.now() - t0 < 8000) {
42
- try { const r = await fetch("http://127.0.0.1:" + port + "/api/version", { signal: AbortSignal.timeout(500) }); if (r.status === 404) { up = true; break; } } catch {}
43
- await sleep(200);
44
- }
45
- if (!up) { console.error("FAIL: 假旧 viewer 未就绪"); process.exit(1); }
26
+ async function poll(fn, predicate, timeoutMs = 10000) {
27
+ const deadline = Date.now() + timeoutMs;
28
+ do {
29
+ try { const value = await fn(); if (predicate(value)) return value; } catch {}
30
+ await sleep(100);
31
+ } while (Date.now() < deadline);
32
+ assert.fail("viewer condition not reached before deadline");
46
33
  }
47
- const oldPid = portPid(port);
48
- console.log(`旧 viewer pid=${oldPid} 占据端口 ${port}`);
49
34
 
50
- // 2) 插件 apply → 应 kill 旧版并拉起新 viewer
51
- const plugin = (await import("file://" + path.join(INSTALL_DIR, "plugin/lib/index.js"))).default;
52
- const wantVersion = JSON.parse(fs.readFileSync(path.join(INSTALL_DIR, "package.json"), "utf8")).version;
53
- let passed = 0, failed = 0;
54
- const ok = (cond, label, extra = "") => { if (cond) { passed++; console.log(` ✓ ${label}`); } else { failed++; console.log(` ✗ ${label} ${extra}`); } };
35
+ try {
36
+ const [port] = await once(oldProc, "message");
37
+ const url = `http://127.0.0.1:${port}/api/version`;
38
+ const readVersion = async () => (await fetch(url, { signal: AbortSignal.timeout(1000) })).json();
39
+ const bridge = async () => (await route.fetch()).json();
40
+ const settings = { memoryDir: TMP, viewer: port };
55
41
 
56
- plugin({ on: () => {} }, { memoryDir: TMP, viewer: port });
57
- const fresh = await waitPort(port, wantVersion);
58
- ok(fresh !== null, "新 viewer 拉起且 /api/version 返回正确版本", `want=${wantVersion}`);
59
- ok(oldPid !== portPid(port) && !oldProc.pid || true, "(信息)新旧 pid");
60
- await sleep(300);
61
- const oldGone = oldProc.kill(0) === false || oldProc.exitCode !== null || oldProc.signalCode !== null;
62
- ok(oldGone, "旧 viewer 进程已被终止", `exitCode=${oldProc.exitCode} signal=${oldProc.signalCode}`);
63
- ok(fresh?.pid === portPid(port), "端点 pid 与实际端口占用一致");
42
+ apply(ctx, settings);
43
+ await sleep(750);
44
+ assert.equal((await fetch(url)).status, 404);
45
+ assert.equal(oldProc.exitCode, null);
46
+ assert.equal(oldProc.signalCode, null);
47
+ assert.deepEqual(await bridge(), { port, status: "offline" });
48
+ console.log("✓ unverified legacy listener stays alive and hidden from settings");
64
49
 
65
- // 3) 再次 apply → 新 viewer 不被重启
66
- const pidBefore = portPid(port);
67
- plugin({ on: () => {} }, { memoryDir: TMP, viewer: port });
68
- await sleep(2500);
69
- ok(portPid(port) === pidBefore, "新版在跑时再次 apply 不重启(pid 不变)", `before=${pidBefore} after=${portPid(port)}`);
50
+ oldProc.kill("SIGTERM");
51
+ await oldExited;
52
+ apply(ctx, settings);
53
+ const fresh = await poll(readVersion, (data) => data.version === version && typeof data.startupKey === "string");
54
+ assert.ok(Number.isInteger(fresh.pid) && fresh.pid > 1);
55
+ observedPids.add(fresh.pid);
56
+ assert.deepEqual(await bridge(), { port, status: "ready" });
57
+ apply(ctx, settings);
58
+ await sleep(750);
59
+ assert.equal((await readVersion()).pid, fresh.pid);
60
+ console.log("✓ spawned viewer reports matching version and repeated startup preserves it");
70
61
 
71
- // 清理
72
- try { process.kill(portPid(port), "SIGTERM"); } catch {}
73
- try { oldProc.kill("SIGKILL"); } catch {}
74
- fs.rmSync(TMP, { recursive: true, force: true });
75
- console.log(`\n=== ${passed} passed, ${failed} failed ===`);
76
- process.exit(failed ? 1 : 0);
62
+ let inspectable = false;
63
+ try {
64
+ const options = { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] };
65
+ const listeners = execFileSync("lsof", ["-a", "-ti4TCP:" + port, "-sTCP:LISTEN"], options).trim().split("\n");
66
+ inspectable = listeners.includes(String(fresh.pid)) && Boolean(execFileSync("ps", ["-ww", "-p", String(fresh.pid), "-o", "command="], options).trim());
67
+ } catch {}
68
+ const noRemote = { ...settings, allowRemote: false, memoryDir: path.join(TMP, "changed") };
69
+ delete process.env.LM_REMOTE_DISABLED;
70
+ apply(ctx, noRemote);
71
+ // The mismatched process must not be offered to settings, even if it cannot be replaced.
72
+ const state = await bridge();
73
+ assert.ok(["offline", "stale"].includes(state.status), JSON.stringify(state));
74
+ if (inspectable) {
75
+ const replaced = await poll(readVersion, (data) => data.pid !== fresh.pid && data.startupKey && data.startupKey !== fresh.startupKey);
76
+ observedPids.delete(fresh.pid);
77
+ observedPids.add(replaced.pid);
78
+ assert.deepEqual(await bridge(), { port, status: "ready" });
79
+ console.log("✓ changed directory/policy replaces only the exact managed viewer");
80
+ } else {
81
+ assert.deepEqual(await bridge(), { port, status: "stale" });
82
+ assert.equal((await readVersion()).pid, fresh.pid);
83
+ console.log("✓ viewer remains hidden and untouched when lsof/ps cannot confirm ownership");
84
+ }
85
+ } finally {
86
+ if (oldProc.exitCode === null && oldProc.signalCode === null) oldProc.kill("SIGTERM");
87
+ for (const pid of observedPids) { try { process.kill(pid, "SIGTERM"); } catch {} }
88
+ fs.rmSync(TMP, { recursive: true, force: true });
89
+ }
package/server/viewer.mjs CHANGED
@@ -644,7 +644,7 @@ http.createServer(async (req, res) => {
644
644
  }
645
645
  // v0.10 版本端点:供插件探测旧版 viewer 并自动升级重启(detached 进程 app 重启杀不掉)
646
646
  if (req.method === "GET" && u.pathname === "/api/version") {
647
- return json({ version: PKG_VERSION, pid: process.pid });
647
+ return json({ version: PKG_VERSION, pid: process.pid, startupKey: process.env.LM_VIEWER_STARTUP_KEY ?? null });
648
648
  }
649
649
  if (req.method === "GET" && u.pathname === "/api/memories") {
650
650
  const q = u.searchParams.get("q")?.trim();