dsh-memsearch-community 0.3.5 → 0.4.0

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,17 @@ computed locally with ONNX.
12
15
 
13
16
  ## Changes from upstream
14
17
 
18
+ **0.4.0 — one folder per session, numbered volumes**
19
+
20
+ The archive is now `root/<YYYY.MM.DD>/<session title>/<session title>.txt`. When a
21
+ file reaches `maxFileSizeKB` (default 512) the next turn continues in
22
+ `<session title>(2).txt`, then `(3)`, and so on; readers walk the day folder,
23
+ the title folder, and every `.txt` in it. Renaming a session in DSH renames the
24
+ folder and all of its volumes. Archives written by earlier versions
25
+ (`<day>/<title>.txt`) are migrated into the new layout on first start.
26
+
27
+ A version badge was added to the top of this README.
28
+
15
29
  **0.3.5 — one file per session, and renames never overwrite**
16
30
 
17
31
  Two sessions can share a title on the same day. They used to append into a
@@ -123,10 +137,13 @@ profile patch. Also: Windows `PATH` handling, and graceful degradation when the
123
137
  | Behaviour | Detail |
124
138
  | --- | --- |
125
139
  | Journal capture | After each turn, appends the user prompt and the final assistant reply to `~/.memsearch/memory/YYYY-MM-DD.md` |
140
+ | Session archive | Also writes `<root>/<YYYY.MM.DD>/<session title>/<session title>.txt`, continuing in `(2)`, `(3)` volumes when a file reaches `maxFileSizeKB` |
126
141
  | Auto indexing | Runs `memsearch index` in the background so the next turn can search the previous one |
127
142
  | Session status | Injects one short status line at the start of a session (version, embedding provider, journal path, number of past journal files) |
128
143
  | Graceful degradation | Without the `memsearch` CLI it still writes the journal, and skips indexing instead of failing |
129
144
 
145
+ Reading the archive walks `root → day folder → title folder → every .txt volume`.
146
+
130
147
  It does **not** push memories into the model's context automatically. It gives
131
148
  the agent a searchable store; the agent (or you) decides when to query it.
132
149
 
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,12 +1,14 @@
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 title inside it, and one or more
7
+ * text 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.
8
10
  */
9
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync, appendFileSync } from "node:fs";
11
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
10
12
  import { join } from "node:path";
11
13
 
12
14
  const pad = (n) => String(n).padStart(2, "0");
@@ -20,7 +22,7 @@ export function dayStamp(date = new Date()) {
20
22
  return `${dayName(date)} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
21
23
  }
22
24
 
23
- /** Windows-safe file name from a session title. */
25
+ /** Windows-safe name from a session title. */
24
26
  export function safeFileBase(title, fallback) {
25
27
  const cleaned = String(title || "")
26
28
  .replace(/[\\/:*?"<>|\u0000-\u001f]/g, " ")
@@ -31,21 +33,37 @@ export function safeFileBase(title, fallback) {
31
33
  return base.length > 80 ? base.slice(0, 80).trim() : base;
32
34
  }
33
35
 
36
+ /** `base.txt`, `base(2).txt`, `base(3).txt` … */
37
+ export function volumeName(base, index) {
38
+ return index <= 1 ? `${base}.txt` : `${base}(${index}).txt`;
39
+ }
40
+
41
+ /** Matches `base.txt` or `base(n).txt`, returning n (1 when unnumbered). */
42
+ export function volumeIndexOf(fileName, base) {
43
+ if (fileName === `${base}.txt`) return 1;
44
+ const m = fileName.match(new RegExp(`^${escapeRegExp(base)}((\\d+))\\.txt$`));
45
+ return m ? Number(m[1]) : 0;
46
+ }
47
+
48
+ function escapeRegExp(text) {
49
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
50
+ }
51
+
34
52
  /**
35
53
  * Escape timestamp-looking lines inside captured text.
36
54
  *
37
55
  * `appendTurn` separates turns with a line that starts with `[YYYY.MM.DD HH:MM]`.
38
56
  * 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.
57
+ * read as a turn boundary and split one exchange into several.
41
58
  */
42
59
  export function defuseStamps(text) {
43
60
  return String(text).replace(/^(\[\d{4}\.\d{2}\.\d{2} \d{2}:\d{2}\])/gm, "\\$1");
44
61
  }
45
62
 
46
63
  export class Archive {
47
- constructor(root) {
64
+ constructor(root, { maxBytes = 512 * 1024 } = {}) {
48
65
  this.root = root;
66
+ this.maxBytes = maxBytes;
49
67
  this.statePath = join(root, ".dsh-memsearch-state.json");
50
68
  this.state = this.#load();
51
69
  }
@@ -54,8 +72,6 @@ export class Archive {
54
72
  try {
55
73
  const parsed = JSON.parse(readFileSync(this.statePath, "utf8"));
56
74
  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
75
  if (!state.sessions || typeof state.sessions !== "object") state.sessions = {};
60
76
  if (!state.flags || typeof state.flags !== "object") state.flags = {};
61
77
  return state;
@@ -107,6 +123,13 @@ export class Archive {
107
123
  return dir;
108
124
  }
109
125
 
126
+ /** `<root>/<day>/<base>` — the folder holding one session's volumes. */
127
+ sessionDir(day, base) {
128
+ const dir = join(this.dayDir(day), base);
129
+ mkdirSync(dir, { recursive: true });
130
+ return dir;
131
+ }
132
+
110
133
  /** Day folders currently on disk, oldest first. */
111
134
  listDays() {
112
135
  try {
@@ -118,108 +141,158 @@ export class Archive {
118
141
  }
119
142
  }
120
143
 
144
+ /** Every text file of a session folder, in volume order. */
145
+ volumes(day, base) {
146
+ const dir = join(this.root, day, base);
147
+ try {
148
+ return readdirSync(dir)
149
+ .filter((f) => volumeIndexOf(f, base) > 0)
150
+ .sort((a, b) => volumeIndexOf(a, base) - volumeIndexOf(b, base))
151
+ .map((f) => join(dir, f));
152
+ } catch {
153
+ return [];
154
+ }
155
+ }
156
+
157
+ #sizeOf(file) {
158
+ try {
159
+ return statSync(file).size;
160
+ } catch {
161
+ return 0;
162
+ }
163
+ }
164
+
121
165
  /**
122
- * Pick the file a session owns inside `dir` for `base`.
123
- *
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.
166
+ * Pick the volume a new block belongs in: keep filling the session's current
167
+ * file while it stays under the limit, otherwise open the next volume.
128
168
  */
129
- #claimName(dir, base, sessionId, selfPath) {
130
- const owner = new Map();
131
- for (const [id, record] of Object.entries(this.state.sessions)) {
132
- if (record && record.path) owner.set(record.path, id);
133
- }
134
- 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;
137
- if (!existsSync(candidate)) return candidate;
138
- const holder = owner.get(candidate);
139
- if (holder === undefined || holder === sessionId) return candidate;
169
+ #targetVolume(day, base, record, blockBytes) {
170
+ const dir = this.sessionDir(day, base);
171
+ const existing = this.volumes(day, base);
172
+
173
+ if (record && record.day === day && record.path && existsSync(record.path)) {
174
+ if (this.#sizeOf(record.path) + blockBytes <= this.maxBytes) return record.path;
140
175
  }
141
- return join(dir, `${base} (${Date.now()}).txt`);
176
+
177
+ if (existing.length === 0) return join(dir, volumeName(base, 1));
178
+ const last = existing[existing.length - 1];
179
+ if (this.#sizeOf(last) + blockBytes <= this.maxBytes) return last;
180
+ const nextIndex = volumeIndexOf(last.split(/[\\/]/).pop(), base) + 1;
181
+ return join(dir, volumeName(base, nextIndex));
142
182
  }
143
183
 
144
184
  /**
145
- * Append one exchange. Returns the file path, renaming an existing file when
146
- * the session title changed since the last write.
185
+ * Append one exchange and return the file it went into.
186
+ * Renames the session folder and its volumes when the title changed.
147
187
  */
148
188
  appendTurn({ sessionId, title, date = new Date(), userText, assistantText }) {
149
189
  this.ensureRoot();
150
190
  const day = dayName(date);
151
- const dir = this.dayDir(day);
152
191
  const base = safeFileBase(title, `会话-${String(sessionId).slice(-6)}`);
153
192
 
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
193
  const block = [
178
194
  `[${dayStamp(date)}]`,
179
195
  `[User]: ${defuseStamps(userText)}`,
180
196
  `[DSH]: ${defuseStamps(assistantText || "(无回答)")}`,
181
197
  "",
182
198
  ].join("\n");
199
+
200
+ const record = this.state.sessions[sessionId];
201
+ // A title change moves the whole session into its new folder first.
202
+ if (record && record.title && record.title !== base && record.path && existsSync(record.path)) {
203
+ this.renameForTitle(sessionId, base);
204
+ }
205
+
206
+ const target = this.#targetVolume(day, base, this.state.sessions[sessionId], Buffer.byteLength(block, "utf8"));
183
207
  appendFileSync(target, block, "utf8");
184
208
  this.state.sessions[sessionId] = { path: target, day, title: base };
185
209
  this.save();
186
210
  return target;
187
211
  }
188
212
 
189
- /** Rename a session's file after a title change. */
213
+ /** Move a session's folder and volumes after a title change. */
190
214
  renameForTitle(sessionId, title) {
191
215
  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;
201
- }
202
- // Never let a rename replace another session's file: Windows overwrites.
203
- if (existsSync(target)) return previous;
216
+ if (!record || !record.path || !existsSync(record.path)) return null;
217
+
218
+ const currentBase = record.title || record.path.split(/[\\/]/).slice(-2)[0];
219
+ const nextBase = safeFileBase(title, currentBase);
220
+ if (nextBase === currentBase) return record.path;
221
+
222
+ const day = record.day;
223
+ const fromDir = join(this.root, day, currentBase);
224
+ let toDir = join(this.root, day, nextBase);
225
+
204
226
  try {
205
- renameSync(previous, target);
227
+ if (existsSync(fromDir)) {
228
+ if (existsSync(toDir)) {
229
+ // Another session already uses this title today: keep folders apart.
230
+ let n = 2;
231
+ while (existsSync(`${toDir}(${n})`)) n++;
232
+ toDir = `${toDir}(${n})`;
233
+ }
234
+ renameSync(fromDir, toDir);
235
+ } else {
236
+ mkdirSync(toDir, { recursive: true });
237
+ }
238
+
239
+ // Rename the volumes to the new base name, keeping their numbers.
240
+ for (const file of readdirSync(toDir)) {
241
+ const index = volumeIndexOf(file, currentBase);
242
+ if (index === 0) continue;
243
+ const next = volumeName(nextBase, index);
244
+ if (next === file) continue;
245
+ const target = join(toDir, next);
246
+ if (existsSync(target)) continue;
247
+ renameSync(join(toDir, file), target);
248
+ }
249
+
250
+ const volumes = readdirSync(toDir).filter((f) => volumeIndexOf(f, nextBase) > 0);
251
+ const first = volumes.sort((a, b) => volumeIndexOf(a, nextBase) - volumeIndexOf(b, nextBase))[0];
252
+ record.path = first ? join(toDir, first) : join(toDir, volumeName(nextBase, 1));
253
+ record.title = nextBase;
254
+ this.save();
255
+ return record.path;
206
256
  } catch {
207
- return previous;
257
+ return record.path;
208
258
  }
209
- record.path = target;
210
- record.title = base;
211
- this.save();
212
- return target;
213
259
  }
214
260
 
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 */
261
+ /**
262
+ * Move files written by the flat layout (`<day>/<title>.txt`) into the folder
263
+ * layout. Runs once; safe to call on every start.
264
+ */
265
+ migrateLayout() {
266
+ if (this.countsAsFlag("layoutMigrated")) return 0;
267
+ let moved = 0;
268
+ for (const day of this.listDays()) {
269
+ const dir = join(this.root, day);
270
+ let entries;
271
+ try {
272
+ entries = readdirSync(dir);
273
+ } catch {
274
+ continue;
275
+ }
276
+ for (const name of entries) {
277
+ const full = join(dir, name);
278
+ try {
279
+ if (!statSync(full).isFile() || !name.endsWith(".txt")) continue;
280
+ } catch {
281
+ continue;
282
+ }
283
+ const base = name.slice(0, -4);
284
+ const targetDir = join(dir, base);
285
+ mkdirSync(targetDir, { recursive: true });
286
+ const target = join(targetDir, name);
287
+ try {
288
+ if (!existsSync(target)) renameSync(full, target);
289
+ moved++;
290
+ } catch {
291
+ /* leave it in place */
292
+ }
220
293
  }
221
- } catch {
222
- /* ignore */
223
294
  }
295
+ this.setFlag("layoutMigrated", true);
296
+ return moved;
224
297
  }
225
298
  }
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.0",
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": {