dsh-memsearch-community 0.3.5 → 0.4.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.
package/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # dsh-memsearch-community
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/dsh-memsearch-community.svg)](https://www.npmjs.com/package/dsh-memsearch-community)
4
+ [![license](https://img.shields.io/npm/l/dsh-memsearch-community.svg)](LICENSE)
5
+
3
6
  Automatic, local, cross-session memory for **DeepSeek Harness**.
4
7
 
5
8
  Every finished turn is appended to a daily markdown journal, the journal is
@@ -12,6 +15,27 @@ computed locally with ONNX.
12
15
 
13
16
  ## Changes from upstream
14
17
 
18
+ **0.4.1 — sessions never share a folder**
19
+
20
+ Two sessions with the same title used to share one folder, so renaming one moved
21
+ the other session's transcript into its own directory. A folder is now claimed per
22
+ session (`周报`, `周报(2)`), and the ownership map also understands state files
23
+ written by 0.4.0 that only recorded a file path.
24
+
25
+ Also fixes the volume helper reading the wrong directory when a session folder was
26
+ disambiguated.
27
+
28
+ **0.4.0 — one folder per session, numbered volumes**
29
+
30
+ The archive is now `root/<YYYY.MM.DD>/<session title>/<session title>.txt`. When a
31
+ file reaches `maxFileSizeKB` (default 512) the next turn continues in
32
+ `<session title>(2).txt`, then `(3)`, and so on; readers walk the day folder,
33
+ the title folder, and every `.txt` in it. Renaming a session in DSH renames the
34
+ folder and all of its volumes. Archives written by earlier versions
35
+ (`<day>/<title>.txt`) are migrated into the new layout on first start.
36
+
37
+ A version badge was added to the top of this README.
38
+
15
39
  **0.3.5 — one file per session, and renames never overwrite**
16
40
 
17
41
  Two sessions can share a title on the same day. They used to append into a
@@ -123,10 +147,13 @@ profile patch. Also: Windows `PATH` handling, and graceful degradation when the
123
147
  | Behaviour | Detail |
124
148
  | --- | --- |
125
149
  | Journal capture | After each turn, appends the user prompt and the final assistant reply to `~/.memsearch/memory/YYYY-MM-DD.md` |
150
+ | Session archive | Also writes `<root>/<YYYY.MM.DD>/<session title>/<session title>.txt`, continuing in `(2)`, `(3)` volumes when a file reaches `maxFileSizeKB` |
126
151
  | Auto indexing | Runs `memsearch index` in the background so the next turn can search the previous one |
127
152
  | Session status | Injects one short status line at the start of a session (version, embedding provider, journal path, number of past journal files) |
128
153
  | Graceful degradation | Without the `memsearch` CLI it still writes the journal, and skips indexing instead of failing |
129
154
 
155
+ Reading the archive walks `root → day folder → title folder → every .txt volume`.
156
+
130
157
  It does **not** push memories into the model's context automatically. It gives
131
158
  the agent a searchable store; the agent (or you) decides when to query it.
132
159
 
package/cordis.patch.yml CHANGED
@@ -1,4 +1,4 @@
1
- - insert:
1
+ - insert:
2
2
  - id: memsearch-community
3
3
  name: dsh-memsearch-community
4
4
  config:
@@ -11,3 +11,4 @@
11
11
  autoInstallCli: false
12
12
  importHistory: ask
13
13
  retentionDays: 60
14
+ maxFileSizeKB: 512
package/lib/index.js CHANGED
@@ -48,6 +48,8 @@ const Config = z.object({
48
48
  importHistory: z.union([z.const("ask"), z.const("yes"), z.const("no")]).default("ask"),
49
49
  /** Day folders kept before the cleanup prompt appears. */
50
50
  retentionDays: z.number().default(60),
51
+ /** Size cap of one archive text file; a new volume starts when it is reached. */
52
+ maxFileSizeKB: z.number().default(512),
51
53
  });
52
54
 
53
55
  const MS_TIMEOUT = 300000;
@@ -435,12 +437,14 @@ async function checkRetention(config, archive, log) {
435
437
 
436
438
  function archiveFor(config) {
437
439
  const root = config.dataRoot ? expandPath(config.dataRoot) : defaultDataRoot();
438
- const archive = new Archive(root);
440
+ const maxBytes = Math.max(64, Number(config.maxFileSizeKB) || 512) * 1024;
441
+ const archive = new Archive(root, { maxBytes });
439
442
  // A folder picked in a previous run wins over the computed default, which can
440
443
  // be wrong when the launcher hands the process a mojibake home directory.
441
444
  const saved = archive.state && archive.state.flags && archive.state.flags.dataRoot;
442
445
  if (!config.dataRoot && saved && saved !== root) {
443
446
  archive.relocate(saved);
447
+ archive.maxBytes = maxBytes;
444
448
  }
445
449
  if (config.dataRoot && !archive.state.flags.dataRootAsked) {
446
450
  archive.setFlag("dataRootAsked");
@@ -460,6 +464,15 @@ function apply(ctx, config) {
460
464
  };
461
465
  const log = (message) => console.error(message);
462
466
 
467
+ // Upgrading from the flat layout (`<day>/<title>.txt`) moves those files into
468
+ // their session folder once; later starts are no-ops.
469
+ try {
470
+ const moved = archive.migrateLayout();
471
+ if (moved) log(`[memsearch] 归档结构迁移: ${moved} 个文件移入会话文件夹`);
472
+ } catch (err) {
473
+ log(`[memsearch] 归档迁移失败: ${err && err.message ? err.message : String(err)}`);
474
+ }
475
+
463
476
  ctx.on("agent/pre-step", async ({ agent, messages, step, signal }, next) => {
464
477
  try {
465
478
  const decision = await next();
package/lib/tree.js CHANGED
@@ -1,13 +1,18 @@
1
1
  /**
2
- * The human-facing conversation archive: `<root>/<YYYY.MM.DD>/<session title>.txt`.
2
+ * The human-facing conversation archive.
3
3
  *
4
- * One folder per day, one text file per session, named after the session title
5
- * so a title change in DSH renames the file too. Turns are appended with a
6
- * timestamp header; the vector-search journal in `~/.memsearch/memory` stays the
7
- * machine-readable copy.
4
+ * Layout: `<root>/<YYYY.MM.DD>/<session title>/<session title>.txt`
5
+ *
6
+ * One folder per day, one folder per session inside it, and one or more text
7
+ * files inside that. When a file reaches `maxBytes` the next turn opens a
8
+ * numbered continuation, `<title>(2).txt`, then `(3)`, and so on. Readers walk
9
+ * the day folder, then the title folder, then every `.txt` in it.
10
+ *
11
+ * Two sessions may share a title on the same day; the second one gets
12
+ * `<title>(2)` as its folder so renaming one never moves the other's transcript.
8
13
  */
9
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync, appendFileSync } from "node:fs";
10
- import { join } from "node:path";
14
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
15
+ import { basename, join } from "node:path";
11
16
 
12
17
  const pad = (n) => String(n).padStart(2, "0");
13
18
 
@@ -20,7 +25,7 @@ export function dayStamp(date = new Date()) {
20
25
  return `${dayName(date)} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
21
26
  }
22
27
 
23
- /** Windows-safe file name from a session title. */
28
+ /** Windows-safe name from a session title. */
24
29
  export function safeFileBase(title, fallback) {
25
30
  const cleaned = String(title || "")
26
31
  .replace(/[\\/:*?"<>|\u0000-\u001f]/g, " ")
@@ -31,21 +36,37 @@ export function safeFileBase(title, fallback) {
31
36
  return base.length > 80 ? base.slice(0, 80).trim() : base;
32
37
  }
33
38
 
39
+ /** `base.txt`, `base(2).txt`, `base(3).txt` … */
40
+ export function volumeName(base, index) {
41
+ return index <= 1 ? `${base}.txt` : `${base}(${index}).txt`;
42
+ }
43
+
44
+ /** Matches `base.txt` or `base(n).txt`, returning n (1 when unnumbered). */
45
+ export function volumeIndexOf(fileName, base) {
46
+ if (fileName === `${base}.txt`) return 1;
47
+ const m = fileName.match(new RegExp(`^${escapeRegExp(base)}((\\d+))\\.txt$`));
48
+ return m ? Number(m[1]) : 0;
49
+ }
50
+
51
+ function escapeRegExp(text) {
52
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
53
+ }
54
+
34
55
  /**
35
56
  * Escape timestamp-looking lines inside captured text.
36
57
  *
37
58
  * `appendTurn` separates turns with a line that starts with `[YYYY.MM.DD HH:MM]`.
38
59
  * A reply that quotes such a line — an example, another archive, a log — would
39
- * read as a turn boundary and split one exchange into several. Prefixing the
40
- * line with a backslash keeps it visible but no longer a separator.
60
+ * read as a turn boundary and split one exchange into several.
41
61
  */
42
62
  export function defuseStamps(text) {
43
63
  return String(text).replace(/^(\[\d{4}\.\d{2}\.\d{2} \d{2}:\d{2}\])/gm, "\\$1");
44
64
  }
45
65
 
46
66
  export class Archive {
47
- constructor(root) {
67
+ constructor(root, { maxBytes = 512 * 1024 } = {}) {
48
68
  this.root = root;
69
+ this.maxBytes = maxBytes;
49
70
  this.statePath = join(root, ".dsh-memsearch-state.json");
50
71
  this.state = this.#load();
51
72
  }
@@ -54,8 +75,6 @@ export class Archive {
54
75
  try {
55
76
  const parsed = JSON.parse(readFileSync(this.statePath, "utf8"));
56
77
  const state = parsed && typeof parsed === "object" ? parsed : {};
57
- // A hand-edited or older state file may lack either container; normalise
58
- // so callers can index into `sessions` and `flags` without guarding.
59
78
  if (!state.sessions || typeof state.sessions !== "object") state.sessions = {};
60
79
  if (!state.flags || typeof state.flags !== "object") state.flags = {};
61
80
  return state;
@@ -118,108 +137,200 @@ export class Archive {
118
137
  }
119
138
  }
120
139
 
140
+ /** Every text file of a session folder, in volume order. */
141
+ volumes(day, base) {
142
+ const dir = join(this.root, day, base);
143
+ try {
144
+ return readdirSync(dir)
145
+ .filter((f) => volumeIndexOf(f, base) > 0)
146
+ .sort((a, b) => volumeIndexOf(a, base) - volumeIndexOf(b, base))
147
+ .map((f) => join(dir, f));
148
+ } catch {
149
+ return [];
150
+ }
151
+ }
152
+
153
+ #sizeOf(file) {
154
+ try {
155
+ return statSync(file).size;
156
+ } catch {
157
+ return 0;
158
+ }
159
+ }
160
+
121
161
  /**
122
- * Pick the file a session owns inside `dir` for `base`.
162
+ * Pick the folder a session owns inside a day.
123
163
  *
124
- * One file per session per day: when another session already claimed the name,
125
- * fall back to `base (2).txt`, `base (3).txt`, and so on instead of appending
126
- * two conversations into one file. `selfPath` is the caller's current file: it
127
- * counts as free because the caller is about to move away from it.
164
+ * Folders are named after the session title, but two sessions can share a
165
+ * title: the second one gets `标题(2)`. `selfFolder` is the caller's current
166
+ * folder and counts as free because the caller is moving away from it.
128
167
  */
129
- #claimName(dir, base, sessionId, selfPath) {
168
+ #claimFolder(day, base, sessionId, selfFolder) {
130
169
  const owner = new Map();
131
170
  for (const [id, record] of Object.entries(this.state.sessions)) {
132
- if (record && record.path) owner.set(record.path, id);
171
+ if (!record) continue;
172
+ // Older state records only carry `path`; their folder is its parent.
173
+ const folder = record.folder || (record.path ? record.path.slice(0, Math.max(record.path.lastIndexOf("\\"), record.path.lastIndexOf("/"))) : null);
174
+ if (folder) owner.set(folder, id);
133
175
  }
176
+ const dayDir = this.dayDir(day);
134
177
  for (let n = 1; n < 1000; n++) {
135
- const candidate = join(dir, n === 1 ? `${base}.txt` : `${base} (${n}).txt`);
136
- if (candidate === selfPath) return candidate;
178
+ const candidate = join(dayDir, n === 1 ? base : `${base}(${n})`);
179
+ if (candidate === selfFolder) return candidate;
137
180
  if (!existsSync(candidate)) return candidate;
138
181
  const holder = owner.get(candidate);
139
182
  if (holder === undefined || holder === sessionId) return candidate;
140
183
  }
141
- return join(dir, `${base} (${Date.now()}).txt`);
184
+ return join(dayDir, `${base}(${Date.now()})`);
142
185
  }
143
186
 
144
187
  /**
145
- * Append one exchange. Returns the file path, renaming an existing file when
146
- * the session title changed since the last write.
188
+ * Pick the volume a new block belongs in: keep filling the session's current
189
+ * file while it stays under the limit, otherwise open the next volume.
190
+ */
191
+ #targetVolume(folder, base, currentPath, blockBytes) {
192
+ const files = readdirSync(folder)
193
+ .filter((f) => volumeIndexOf(f, base) > 0)
194
+ .sort((a, b) => volumeIndexOf(a, base) - volumeIndexOf(b, base))
195
+ .map((f) => join(folder, f));
196
+
197
+ if (currentPath && existsSync(currentPath) && this.#sizeOf(currentPath) + blockBytes <= this.maxBytes) {
198
+ return currentPath;
199
+ }
200
+ if (files.length === 0) return join(folder, volumeName(base, 1));
201
+ const last = files[files.length - 1];
202
+ if (this.#sizeOf(last) + blockBytes <= this.maxBytes) return last;
203
+ const nextIndex = volumeIndexOf(basename(last), base) + 1;
204
+ return join(folder, volumeName(base, nextIndex));
205
+ }
206
+
207
+ /**
208
+ * Append one exchange and return the file it went into.
209
+ * Renames the session folder and its volumes when the title changed.
147
210
  */
148
211
  appendTurn({ sessionId, title, date = new Date(), userText, assistantText }) {
149
212
  this.ensureRoot();
150
213
  const day = dayName(date);
151
- const dir = this.dayDir(day);
152
214
  const base = safeFileBase(title, `会话-${String(sessionId).slice(-6)}`);
153
215
 
154
- const record = this.state.sessions[sessionId];
155
- let target = this.#claimName(dir, base, sessionId);
156
-
157
- // The session already owns a file from earlier today; keep appending to it,
158
- // renaming only when the title changed.
159
- if (record && record.day === day && existsSync(record.path)) {
160
- const desired = target;
161
- if (record.path !== desired) {
162
- try {
163
- if (!existsSync(desired)) {
164
- renameSync(record.path, desired);
165
- target = desired;
166
- } else {
167
- target = record.path;
168
- }
169
- } catch {
170
- target = record.path;
171
- }
172
- } else {
173
- target = record.path;
174
- }
175
- }
176
-
177
216
  const block = [
178
217
  `[${dayStamp(date)}]`,
179
218
  `[User]: ${defuseStamps(userText)}`,
180
219
  `[DSH]: ${defuseStamps(assistantText || "(无回答)")}`,
181
220
  "",
182
221
  ].join("\n");
222
+
223
+ const record = this.state.sessions[sessionId];
224
+ let folder;
225
+ let currentPath;
226
+
227
+ if (record && record.day === day && record.folder && existsSync(record.folder)) {
228
+ folder = record.folder;
229
+ currentPath = record.path;
230
+ if (record.title !== base) {
231
+ folder = this.#renameFolder(sessionId, record, day, base);
232
+ currentPath = this.state.sessions[sessionId].path;
233
+ }
234
+ } else {
235
+ folder = this.#claimFolder(day, base, sessionId);
236
+ mkdirSync(folder, { recursive: true });
237
+ currentPath = null;
238
+ }
239
+
240
+ const fileBase = basename(folder);
241
+ const target = this.#targetVolume(folder, fileBase, currentPath, Buffer.byteLength(block, "utf8"));
183
242
  appendFileSync(target, block, "utf8");
184
- this.state.sessions[sessionId] = { path: target, day, title: base };
243
+ this.state.sessions[sessionId] = { path: target, day, title: fileBase, folder };
185
244
  this.save();
186
245
  return target;
187
246
  }
188
247
 
189
- /** Rename a session's file after a title change. */
248
+ /** Move a session's folder and volumes after a title change. */
190
249
  renameForTitle(sessionId, title) {
191
250
  const record = this.state.sessions[sessionId];
192
- if (!record || !existsSync(record.path)) return null;
193
- const dir = join(this.root, record.day);
194
- const base = safeFileBase(title, `会话-${String(sessionId).slice(-6)}`);
195
- const previous = record.path;
196
- const target = this.#claimName(dir, base, sessionId, previous);
197
- if (target === previous) {
198
- record.title = base;
199
- this.save();
200
- return previous;
251
+ if (!record || !record.folder || !existsSync(record.folder)) return null;
252
+ const nextBase = safeFileBase(title, record.title || basename(record.folder));
253
+ if (nextBase === record.title) return record.path;
254
+ return this.#renameFolder(sessionId, record, record.day, nextBase);
255
+ }
256
+
257
+ #renameFolder(sessionId, record, day, nextBase) {
258
+ const previousFolder = record.folder;
259
+ const previousBase = basename(previousFolder);
260
+ const targetFolder = this.#claimFolder(day, nextBase, sessionId, previousFolder);
261
+ const targetBase = basename(targetFolder);
262
+
263
+ if (targetFolder !== previousFolder) {
264
+ try {
265
+ if (existsSync(targetFolder)) {
266
+ mkdirSync(targetFolder, { recursive: true });
267
+ }
268
+ renameSync(previousFolder, targetFolder);
269
+ } catch {
270
+ return previousFolder; // keep the old folder rather than lose the data
271
+ }
201
272
  }
202
- // Never let a rename replace another session's file: Windows overwrites.
203
- if (existsSync(target)) return previous;
273
+
274
+ // Rename the volumes to the new base name, keeping their numbers.
204
275
  try {
205
- renameSync(previous, target);
276
+ for (const file of readdirSync(targetFolder)) {
277
+ const index = volumeIndexOf(file, previousBase);
278
+ if (index === 0) continue;
279
+ const next = volumeName(targetBase, index);
280
+ if (next === file) continue;
281
+ const target = join(targetFolder, next);
282
+ if (existsSync(target)) continue;
283
+ renameSync(join(targetFolder, file), target);
284
+ }
206
285
  } catch {
207
- return previous;
286
+ /* leave whatever was renamed renamed */
208
287
  }
209
- record.path = target;
210
- record.title = base;
288
+
289
+ const files = readdirSync(targetFolder)
290
+ .filter((f) => volumeIndexOf(f, targetBase) > 0)
291
+ .sort((a, b) => volumeIndexOf(a, targetBase) - volumeIndexOf(b, targetBase));
292
+
293
+ const path = files.length ? join(targetFolder, files[0]) : join(targetFolder, volumeName(targetBase, 1));
294
+ this.state.sessions[sessionId] = { ...record, path, title: targetBase, folder: targetFolder, day };
211
295
  this.save();
212
- return target;
296
+ return path;
213
297
  }
214
298
 
215
- #pruneEmpty(oldPath) {
216
- try {
217
- const dir = oldPath.slice(0, oldPath.lastIndexOf("\\") >= 0 ? oldPath.lastIndexOf("\\") : oldPath.lastIndexOf("/"));
218
- if (dir && readdirSync(dir).length === 0) {
219
- /* leave the empty day folder; it is harmless and keeps the count visible */
299
+ /**
300
+ * Move files written by the flat layout (`<day>/<title>.txt`) into the folder
301
+ * layout. Runs once; safe to call on every start.
302
+ */
303
+ migrateLayout() {
304
+ if (this.countsAsFlag("layoutMigrated")) return 0;
305
+ let moved = 0;
306
+ for (const day of this.listDays()) {
307
+ const dir = join(this.root, day);
308
+ let entries;
309
+ try {
310
+ entries = readdirSync(dir);
311
+ } catch {
312
+ continue;
313
+ }
314
+ for (const name of entries) {
315
+ const full = join(dir, name);
316
+ try {
317
+ if (!statSync(full).isFile() || !name.endsWith(".txt")) continue;
318
+ } catch {
319
+ continue;
320
+ }
321
+ const base = name.slice(0, -4);
322
+ const targetDir = join(dir, base);
323
+ mkdirSync(targetDir, { recursive: true });
324
+ const target = join(targetDir, name);
325
+ try {
326
+ if (!existsSync(target)) renameSync(full, target);
327
+ moved++;
328
+ } catch {
329
+ /* leave it in place */
330
+ }
220
331
  }
221
- } catch {
222
- /* ignore */
223
332
  }
333
+ this.setFlag("layoutMigrated", true);
334
+ return moved;
224
335
  }
225
336
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memsearch-community",
3
- "version": "0.3.5",
4
- "description": "Automatic local memory for DeepSeek Harness: per-day conversation archive by session title, semantic search index, first-run setup prompts, optional history import.",
3
+ "version": "0.4.1",
4
+ "description": "Automatic local memory for DeepSeek Harness: per-day, per-session conversation archive with numbered volumes, semantic search index, first-run setup prompts, optional history import.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {