dsh-memsearch-community 0.4.0 → 0.5.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.
Files changed (3) hide show
  1. package/README.md +28 -0
  2. package/lib/tree.js +206 -99
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -15,6 +15,34 @@ computed locally with ONNX.
15
15
 
16
16
  ## Changes from upstream
17
17
 
18
+ **0.5.0 — day numbering, overflow volumes and retrieval hints**
19
+
20
+ A session that spans several days keeps counting instead of restarting:
21
+
22
+ | File | Meaning |
23
+ | --- | --- |
24
+ | `标题.txt` | day 1 |
25
+ | `标题(2).txt` | day 2 |
26
+ | `标题(3).txt` | day 3 |
27
+
28
+ Inside one day, a file that reaches `maxFileSizeKB` opens an overflow volume
29
+ numbered from 1 within that day: `标题(1.1).txt`, `标题(1.2).txt` for day 1 and
30
+ `标题(2.1).txt` for day 2.
31
+
32
+ Every continuation file now starts with a retrieval hint: read the session's
33
+ first file, then follow the date/volume order. Renaming a session renames its
34
+ folder on **every** day it spans, and a rename never lands on an occupied folder.
35
+
36
+ **0.4.1 — sessions never share a folder**
37
+
38
+ Two sessions with the same title used to share one folder, so renaming one moved
39
+ the other session's transcript into its own directory. A folder is now claimed per
40
+ session (`周报`, `周报(2)`), and the ownership map also understands state files
41
+ written by 0.4.0 that only recorded a file path.
42
+
43
+ Also fixes the volume helper reading the wrong directory when a session folder was
44
+ disambiguated.
45
+
18
46
  **0.4.0 — one folder per session, numbered volumes**
19
47
 
20
48
  The archive is now `root/<YYYY.MM.DD>/<session title>/<session title>.txt`. When a
package/lib/tree.js CHANGED
@@ -1,15 +1,26 @@
1
1
  /**
2
2
  * The human-facing conversation archive.
3
3
  *
4
- * Layout: `<root>/<YYYY.MM.DD>/<session title>/<session title>.txt`
4
+ * Layout: `<root>/<YYYY.MM.DD>/<session title>/<file>.txt`
5
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.
6
+ * A session that keeps going on later days continues numbering instead of
7
+ * restarting:
8
+ *
9
+ * day 1: 标题.txt
10
+ * day 2: 标题(2).txt
11
+ * day 3: 标题(3).txt
12
+ *
13
+ * Inside one day, a file that reaches `maxBytes` opens an overflow volume, which
14
+ * is numbered from 1 within that day:
15
+ *
16
+ * 标题(1.1).txt, 标题(1.2).txt … (day 1 overflow)
17
+ * 标题(2.1).txt, 标题(2.2).txt … (day 2 overflow)
18
+ *
19
+ * Every continuation file starts with a retrieval hint telling a reader to begin
20
+ * at the session's first file and follow the date/volume order.
10
21
  */
11
22
  import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
12
- import { join } from "node:path";
23
+ import { basename, join } from "node:path";
13
24
 
14
25
  const pad = (n) => String(n).padStart(2, "0");
15
26
 
@@ -33,16 +44,24 @@ export function safeFileBase(title, fallback) {
33
44
  return base.length > 80 ? base.slice(0, 80).trim() : base;
34
45
  }
35
46
 
36
- /** `base.txt`, `base(2).txt`, `base(3).txt` … */
37
- export function volumeName(base, index) {
38
- return index <= 1 ? `${base}.txt` : `${base}(${index}).txt`;
47
+ /**
48
+ * File name for one day/volume slot of a session.
49
+ *
50
+ * Volume 0 is the day's first file: the bare title on day 1, `标题(2)` on day 2.
51
+ * Overflow files of that day are numbered from 1: `标题(2.1)`, `标题(2.2)` …
52
+ */
53
+ export function volumeName(base, dayIndex, volume = 0) {
54
+ if (volume <= 0) return dayIndex <= 1 ? `${base}.txt` : `${base}(${dayIndex}).txt`;
55
+ return `${base}(${dayIndex}.${volume}).txt`;
39
56
  }
40
57
 
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;
58
+ /** Parse `base.txt`, `base(n).txt` or `base(n.m).txt`. Returns null otherwise. */
59
+ export function parseVolume(fileName, base) {
60
+ if (!fileName.endsWith(".txt")) return null;
61
+ if (fileName === `${base}.txt`) return { day: 1, volume: 0 };
62
+ const m = fileName.match(new RegExp(`^${escapeRegExp(base)}((\\d+)(?:\\.(\\d+))?)\\.txt$`));
63
+ if (!m) return null;
64
+ return { day: Number(m[1]), volume: m[2] === undefined ? 0 : Number(m[2]) };
46
65
  }
47
66
 
48
67
  function escapeRegExp(text) {
@@ -50,16 +69,25 @@ function escapeRegExp(text) {
50
69
  }
51
70
 
52
71
  /**
53
- * Escape timestamp-looking lines inside captured text.
54
- *
55
- * `appendTurn` separates turns with a line that starts with `[YYYY.MM.DD HH:MM]`.
56
- * A reply that quotes such a line — an example, another archive, a log — would
57
- * read as a turn boundary and split one exchange into several.
72
+ * Escape timestamp-looking lines inside captured text, so a quoted example such
73
+ * as `[2026.12.04 09:00]` is not mistaken for a turn boundary.
58
74
  */
59
75
  export function defuseStamps(text) {
60
76
  return String(text).replace(/^(\[\d{4}\.\d{2}\.\d{2} \d{2}:\d{2}\])/gm, "\\$1");
61
77
  }
62
78
 
79
+ /** Header written at the top of every continuation file. */
80
+ export function continuationHint(dayIndex, volume) {
81
+ const slot = volume > 0 ? `第 ${dayIndex} 天第 ${volume} 卷` : `第 ${dayIndex} 天`;
82
+ return [
83
+ "【检索指引】",
84
+ `本文件是该会话的延续内容(${slot}),不是开头。`,
85
+ "检索、总结或补充本会话时,请先读同目录下的初始文件,再按日期与卷号顺序依次读取:",
86
+ "初始文件 → (2) → (2.1) → (2.2) → (3) → …",
87
+ "",
88
+ ].join("\n");
89
+ }
90
+
63
91
  export class Archive {
64
92
  constructor(root, { maxBytes = 512 * 1024 } = {}) {
65
93
  this.root = root;
@@ -89,15 +117,12 @@ export class Archive {
89
117
  }
90
118
  }
91
119
 
92
- /** Point the archive at another root, keeping the flags already recorded. */
93
120
  relocate(root) {
94
121
  const previous = this.state;
95
122
  this.root = root;
96
123
  this.statePath = join(root, ".dsh-memsearch-state.json");
97
124
  this.state = this.#load();
98
- if (previous && previous.flags) {
99
- this.state.flags = { ...previous.flags, ...(this.state.flags || {}) };
100
- }
125
+ if (previous && previous.flags) this.state.flags = { ...previous.flags, ...(this.state.flags || {}) };
101
126
  this.ensureRoot();
102
127
  this.save();
103
128
  return this.root;
@@ -123,14 +148,6 @@ export class Archive {
123
148
  return dir;
124
149
  }
125
150
 
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
-
133
- /** Day folders currently on disk, oldest first. */
134
151
  listDays() {
135
152
  try {
136
153
  return readdirSync(this.root)
@@ -141,14 +158,26 @@ export class Archive {
141
158
  }
142
159
  }
143
160
 
144
- /** Every text file of a session folder, in volume order. */
161
+ /** Session folders of one day. */
162
+ sessionsOfDay(day) {
163
+ try {
164
+ return readdirSync(join(this.root, day))
165
+ .filter((name) => statSync(join(this.root, day, name)).isDirectory())
166
+ .sort();
167
+ } catch {
168
+ return [];
169
+ }
170
+ }
171
+
172
+ /** Every text file of a session folder, ordered by day then volume. */
145
173
  volumes(day, base) {
146
174
  const dir = join(this.root, day, base);
147
175
  try {
148
176
  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));
177
+ .map((name) => ({ name, slot: parseVolume(name, base) }))
178
+ .filter((entry) => entry.slot)
179
+ .sort((a, b) => a.slot.day - b.slot.day || a.slot.volume - b.slot.volume)
180
+ .map((entry) => join(dir, entry.name));
152
181
  } catch {
153
182
  return [];
154
183
  }
@@ -162,33 +191,59 @@ export class Archive {
162
191
  }
163
192
  }
164
193
 
165
- /**
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.
168
- */
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;
194
+ /** Folders are claimed per session so a rename never moves another transcript. */
195
+ #claimFolder(day, base, sessionId, selfFolder) {
196
+ const owner = new Map();
197
+ for (const [id, record] of Object.entries(this.state.sessions)) {
198
+ if (!record) continue;
199
+ if (record.folder) owner.set(record.folder, id);
200
+ for (const folder of Object.values(record.folders || {})) {
201
+ if (folder) owner.set(folder, id);
202
+ }
203
+ if (!record.folder && record.path) {
204
+ const parent = record.path.slice(0, Math.max(record.path.lastIndexOf("\\"), record.path.lastIndexOf("/")));
205
+ if (parent) owner.set(parent, id);
206
+ }
175
207
  }
208
+ const dayDir = this.dayDir(day);
209
+ for (let n = 1; n < 1000; n++) {
210
+ const candidate = join(dayDir, n === 1 ? base : `${base}(${n})`);
211
+ if (candidate === selfFolder) return candidate;
212
+ if (!existsSync(candidate)) return candidate;
213
+ const holder = owner.get(candidate);
214
+ if (holder === undefined || holder === sessionId) return candidate;
215
+ }
216
+ return join(dayDir, `${base}(${Date.now()})`);
217
+ }
176
218
 
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));
219
+ /** Which day of this session `day` is (1-based), registering new days in order. */
220
+ #dayIndexOf(record, day) {
221
+ const days = Array.isArray(record && record.days) ? [...record.days] : [];
222
+ if (!days.includes(day)) days.push(day);
223
+ return { days, index: days.indexOf(day) + 1 };
224
+ }
225
+
226
+ /** Highest volume already used for `dayIndex` in this folder (-1 when none). */
227
+ #maxVolume(folder, base, dayIndex) {
228
+ let max = -1;
229
+ try {
230
+ for (const name of readdirSync(folder)) {
231
+ const slot = parseVolume(name, base);
232
+ if (slot && slot.day === dayIndex) max = Math.max(max, slot.volume);
233
+ }
234
+ } catch {
235
+ /* empty folder */
236
+ }
237
+ return max;
182
238
  }
183
239
 
184
240
  /**
185
241
  * Append one exchange and return the file it went into.
186
- * Renames the session folder and its volumes when the title changed.
187
242
  */
188
243
  appendTurn({ sessionId, title, date = new Date(), userText, assistantText }) {
189
244
  this.ensureRoot();
190
245
  const day = dayName(date);
191
- const base = safeFileBase(title, `会话-${String(sessionId).slice(-6)}`);
246
+ const wanted = safeFileBase(title, `会话-${String(sessionId).slice(-6)}`);
192
247
 
193
248
  const block = [
194
249
  `[${dayStamp(date)}]`,
@@ -197,71 +252,122 @@ export class Archive {
197
252
  "",
198
253
  ].join("\n");
199
254
 
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);
255
+ let record = this.state.sessions[sessionId];
256
+ let folder;
257
+ let currentPath = null;
258
+
259
+ const sameDayFolder = record && record.day === day && record.folder && existsSync(record.folder);
260
+
261
+ if (sameDayFolder && record.title === wanted) {
262
+ folder = record.folder;
263
+ currentPath = record.path;
264
+ } else if (sameDayFolder) {
265
+ folder = this.#renameAllDays(sessionId, record, wanted);
266
+ record = this.state.sessions[sessionId];
267
+ folder = record.folder;
268
+ currentPath = record.path;
269
+ } else {
270
+ // New session, or the same session on another day: one folder per day.
271
+ folder = this.#claimFolder(day, wanted, sessionId);
272
+ mkdirSync(folder, { recursive: true });
204
273
  }
205
274
 
206
- const target = this.#targetVolume(day, base, this.state.sessions[sessionId], Buffer.byteLength(block, "utf8"));
275
+ const base = basename(folder);
276
+ const { days, index: dayIndex } = this.#dayIndexOf(record, day);
277
+ const folders = { ...(record && record.folders ? record.folders : {}), [day]: folder };
278
+
279
+ // Continue the current file while it has room.
280
+ if (currentPath && existsSync(currentPath)) {
281
+ const slot = parseVolume(basename(currentPath), base);
282
+ const room = this.#sizeOf(currentPath) + Buffer.byteLength(block, "utf8") <= this.maxBytes;
283
+ if (slot && slot.day === dayIndex && room) {
284
+ appendFileSync(currentPath, block, "utf8");
285
+ this.state.sessions[sessionId] = { ...record, path: currentPath, day, title: base, folder, days, folders };
286
+ this.save();
287
+ return currentPath;
288
+ }
289
+ }
290
+
291
+ // Otherwise open the next volume of this day.
292
+ const nextVolume = this.#maxVolume(folder, base, dayIndex) + 1;
293
+ const target = join(folder, volumeName(base, dayIndex, nextVolume));
294
+ if (!(dayIndex === 1 && nextVolume === 0)) {
295
+ appendFileSync(target, continuationHint(dayIndex, nextVolume), "utf8");
296
+ }
207
297
  appendFileSync(target, block, "utf8");
208
- this.state.sessions[sessionId] = { path: target, day, title: base };
298
+ this.state.sessions[sessionId] = { ...record, path: target, day, title: base, folder, days, folders };
209
299
  this.save();
210
300
  return target;
211
301
  }
212
302
 
213
- /** Move a session's folder and volumes after a title change. */
303
+ /** Public rename entry used by the session/title event. */
214
304
  renameForTitle(sessionId, title) {
215
305
  const record = this.state.sessions[sessionId];
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);
306
+ if (!record || !record.folder || !existsSync(record.folder)) return null;
307
+ const next = safeFileBase(title, record.title || basename(record.folder));
308
+ if (next === record.title) return record.path;
309
+ this.#renameAllDays(sessionId, record, next);
310
+ return this.state.sessions[sessionId].path;
311
+ }
225
312
 
226
- try {
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})`;
313
+ /**
314
+ * Rename every day folder a session owns, keeping each file's day/volume slot.
315
+ *
316
+ * A session may already have per-day folder names that differ (one day the
317
+ * folder was disambiguated as `周报(2)`), so the recorded folder map is the
318
+ * source of truth rather than a single derived name.
319
+ */
320
+ #renameAllDays(sessionId, record, nextBase) {
321
+ const days = Array.isArray(record.days) && record.days.length ? record.days : [record.day];
322
+ const folders = { ...(record.folders || {}) };
323
+ let currentFolder = record.folder;
324
+ let currentPath = record.path;
325
+
326
+ for (const day of days) {
327
+ const fromDir = folders[day] || join(this.root, day, record.title || nextBase);
328
+ if (!existsSync(fromDir)) continue;
329
+ const previousBase = basename(fromDir);
330
+ const toDir = this.#claimFolder(day, nextBase, sessionId, fromDir);
331
+ const nextFolderBase = basename(toDir);
332
+
333
+ if (toDir !== fromDir) {
334
+ // Never rename onto an existing folder: Windows would replace it.
335
+ if (existsSync(toDir)) continue;
336
+ try {
337
+ renameSync(fromDir, toDir);
338
+ } catch {
339
+ continue;
233
340
  }
234
- renameSync(fromDir, toDir);
235
- } else {
236
- mkdirSync(toDir, { recursive: true });
237
341
  }
238
342
 
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);
343
+ try {
344
+ for (const name of readdirSync(toDir)) {
345
+ const slot = parseVolume(name, previousBase);
346
+ if (!slot) continue;
347
+ const next = volumeName(nextFolderBase, slot.day, slot.volume);
348
+ if (next === name) continue;
349
+ const target = join(toDir, next);
350
+ if (existsSync(target)) continue;
351
+ renameSync(join(toDir, name), target);
352
+ }
353
+ } catch {
354
+ /* best effort */
248
355
  }
249
356
 
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;
256
- } catch {
257
- return record.path;
357
+ folders[day] = toDir;
358
+ if (day === record.day) {
359
+ currentFolder = toDir;
360
+ const files = this.volumes(day, nextFolderBase);
361
+ currentPath = files.length ? files[0] : join(toDir, volumeName(nextFolderBase, 1, 0));
362
+ }
258
363
  }
364
+
365
+ this.state.sessions[sessionId] = { ...record, title: nextBase, folder: currentFolder, path: currentPath, folders };
366
+ this.save();
367
+ return currentPath;
259
368
  }
260
369
 
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
- */
370
+ /** Move files written by the flat layout into the folder layout. */
265
371
  migrateLayout() {
266
372
  if (this.countsAsFlag("layoutMigrated")) return 0;
267
373
  let moved = 0;
@@ -296,3 +402,4 @@ export class Archive {
296
402
  return moved;
297
403
  }
298
404
  }
405
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-memsearch-community",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
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",