dsh-cross-memory 0.0.0-stage → 0.2.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 (152) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +247 -2
  3. package/cordis.patch.yml +27 -0
  4. package/docs/DETAIL.md +13 -0
  5. package/docs/DETAIL.zh.md +17 -0
  6. package/icon.svg +1 -0
  7. package/lib/backfill.js +273 -0
  8. package/lib/citations.js +305 -0
  9. package/lib/client.js +1550 -0
  10. package/lib/config.js +736 -0
  11. package/lib/consolidate.js +1119 -0
  12. package/lib/extract.js +570 -0
  13. package/lib/gate.js +137 -0
  14. package/lib/git-origin.js +224 -0
  15. package/lib/index.js +4475 -0
  16. package/lib/log.js +260 -0
  17. package/lib/loops.js +186 -0
  18. package/lib/notices.js +195 -0
  19. package/lib/notify.js +33 -0
  20. package/lib/persona.js +112 -0
  21. package/lib/query.js +93 -0
  22. package/lib/raw-recall.js +286 -0
  23. package/lib/reflection.js +291 -0
  24. package/lib/remote.js +455 -0
  25. package/lib/render.js +678 -0
  26. package/lib/retention.js +64 -0
  27. package/lib/schedule.js +245 -0
  28. package/lib/search.js +1068 -0
  29. package/lib/skills.js +220 -0
  30. package/lib/state.js +701 -0
  31. package/lib/storage.js +1424 -0
  32. package/lib/sync-runtime.js +268 -0
  33. package/lib/sync.js +620 -0
  34. package/lib/test/activity.test.js +74 -0
  35. package/lib/test/archive.test.js +182 -0
  36. package/lib/test/backfill.test.js +144 -0
  37. package/lib/test/citations.test.js +91 -0
  38. package/lib/test/client-wiring.test.js +134 -0
  39. package/lib/test/consolidate-job.test.js +95 -0
  40. package/lib/test/consolidate.test.js +430 -0
  41. package/lib/test/consolidation-selection.test.js +152 -0
  42. package/lib/test/dedupe-keys.test.js +230 -0
  43. package/lib/test/delta.test.js +93 -0
  44. package/lib/test/derived.test.js +110 -0
  45. package/lib/test/disputes-panel.test.js +314 -0
  46. package/lib/test/eval.test.js +171 -0
  47. package/lib/test/expand.test.js +164 -0
  48. package/lib/test/extract.test.js +1020 -0
  49. package/lib/test/git-origin.test.js +189 -0
  50. package/lib/test/injection.test.js +440 -0
  51. package/lib/test/kind-filter.test.js +49 -0
  52. package/lib/test/legacy-state.test.js +69 -0
  53. package/lib/test/log.test.js +156 -0
  54. package/lib/test/loops.test.js +86 -0
  55. package/lib/test/memory.test.js +855 -0
  56. package/lib/test/notices.test.js +140 -0
  57. package/lib/test/persona.test.js +73 -0
  58. package/lib/test/prefilter.test.js +73 -0
  59. package/lib/test/preset.test.js +77 -0
  60. package/lib/test/raw-recall.test.js +186 -0
  61. package/lib/test/recall.test.js +433 -0
  62. package/lib/test/reflection.test.js +64 -0
  63. package/lib/test/remote.test.js +227 -0
  64. package/lib/test/retention.test.js +117 -0
  65. package/lib/test/retrieval.test.js +142 -0
  66. package/lib/test/rotation.test.js +228 -0
  67. package/lib/test/schedule.test.js +112 -0
  68. package/lib/test/settings-card.test.js +58 -0
  69. package/lib/test/skills.test.js +129 -0
  70. package/lib/test/state.test.js +212 -0
  71. package/lib/test/subagent-contract.test.js +139 -0
  72. package/lib/test/sweep.test.js +159 -0
  73. package/lib/test/sync.test.js +314 -0
  74. package/lib/test/time.test.js +171 -0
  75. package/lib/time.js +303 -0
  76. package/lib/tool.js +330 -0
  77. package/lib/types/backfill.d.ts +96 -0
  78. package/lib/types/citations.d.ts +105 -0
  79. package/lib/types/config.d.ts +811 -0
  80. package/lib/types/consolidate.d.ts +742 -0
  81. package/lib/types/extract.d.ts +352 -0
  82. package/lib/types/gate.d.ts +83 -0
  83. package/lib/types/git-origin.d.ts +23 -0
  84. package/lib/types/index.d.ts +1316 -0
  85. package/lib/types/log.d.ts +144 -0
  86. package/lib/types/loops.d.ts +82 -0
  87. package/lib/types/notices.d.ts +117 -0
  88. package/lib/types/notify.d.ts +12 -0
  89. package/lib/types/persona.d.ts +43 -0
  90. package/lib/types/query.d.ts +45 -0
  91. package/lib/types/raw-recall.d.ts +84 -0
  92. package/lib/types/reflection.d.ts +122 -0
  93. package/lib/types/remote.d.ts +233 -0
  94. package/lib/types/render.d.ts +286 -0
  95. package/lib/types/retention.d.ts +66 -0
  96. package/lib/types/schedule.d.ts +116 -0
  97. package/lib/types/search.d.ts +583 -0
  98. package/lib/types/skills.d.ts +71 -0
  99. package/lib/types/state.d.ts +294 -0
  100. package/lib/types/storage.d.ts +458 -0
  101. package/lib/types/sync-runtime.d.ts +103 -0
  102. package/lib/types/sync.d.ts +222 -0
  103. package/lib/types/test/activity.test.d.ts +1 -0
  104. package/lib/types/test/archive.test.d.ts +1 -0
  105. package/lib/types/test/backfill.test.d.ts +1 -0
  106. package/lib/types/test/citations.test.d.ts +1 -0
  107. package/lib/types/test/client-wiring.test.d.ts +1 -0
  108. package/lib/types/test/consolidate-job.test.d.ts +1 -0
  109. package/lib/types/test/consolidate.test.d.ts +1 -0
  110. package/lib/types/test/consolidation-selection.test.d.ts +1 -0
  111. package/lib/types/test/dedupe-keys.test.d.ts +1 -0
  112. package/lib/types/test/delta.test.d.ts +1 -0
  113. package/lib/types/test/derived.test.d.ts +1 -0
  114. package/lib/types/test/disputes-panel.test.d.ts +1 -0
  115. package/lib/types/test/eval.test.d.ts +1 -0
  116. package/lib/types/test/expand.test.d.ts +1 -0
  117. package/lib/types/test/extract.test.d.ts +1 -0
  118. package/lib/types/test/git-origin.test.d.ts +1 -0
  119. package/lib/types/test/injection.test.d.ts +1 -0
  120. package/lib/types/test/kind-filter.test.d.ts +1 -0
  121. package/lib/types/test/legacy-state.test.d.ts +1 -0
  122. package/lib/types/test/log.test.d.ts +1 -0
  123. package/lib/types/test/loops.test.d.ts +1 -0
  124. package/lib/types/test/memory.test.d.ts +1 -0
  125. package/lib/types/test/notices.test.d.ts +1 -0
  126. package/lib/types/test/persona.test.d.ts +1 -0
  127. package/lib/types/test/prefilter.test.d.ts +1 -0
  128. package/lib/types/test/preset.test.d.ts +1 -0
  129. package/lib/types/test/raw-recall.test.d.ts +1 -0
  130. package/lib/types/test/recall.test.d.ts +1 -0
  131. package/lib/types/test/reflection.test.d.ts +1 -0
  132. package/lib/types/test/remote.test.d.ts +1 -0
  133. package/lib/types/test/retention.test.d.ts +1 -0
  134. package/lib/types/test/retrieval.test.d.ts +1 -0
  135. package/lib/types/test/rotation.test.d.ts +1 -0
  136. package/lib/types/test/schedule.test.d.ts +1 -0
  137. package/lib/types/test/settings-card.test.d.ts +1 -0
  138. package/lib/types/test/skills.test.d.ts +1 -0
  139. package/lib/types/test/state.test.d.ts +1 -0
  140. package/lib/types/test/subagent-contract.test.d.ts +1 -0
  141. package/lib/types/test/sweep.test.d.ts +1 -0
  142. package/lib/types/test/sync.test.d.ts +1 -0
  143. package/lib/types/test/time.test.d.ts +1 -0
  144. package/lib/types/time.d.ts +67 -0
  145. package/lib/types/tool.d.ts +9 -0
  146. package/lib/types/types.d.ts +374 -0
  147. package/lib/types/workspace.d.ts +20 -0
  148. package/lib/types.js +47 -0
  149. package/lib/workspace.js +65 -0
  150. package/locale/en.json +7 -0
  151. package/locale/zh.json +7 -0
  152. package/package.json +126 -4
@@ -0,0 +1,458 @@
1
+ import type { MemoryDraft, MemoryEntry, MemoryScope, ScopeTarget, UpsertResult } from './types.js';
2
+ /** Project descriptor written beside a project scope's entries. */
3
+ export interface ProjectDescriptor {
4
+ /** Absolute workspace root the slug was derived from. */
5
+ readonly root: string;
6
+ /** Directory basename of that root, for display. */
7
+ readonly name: string;
8
+ /** Slug directory name under `projects/`. */
9
+ readonly slug: string;
10
+ /** Unix epoch milliseconds of the last write. */
11
+ readonly updatedAt: number;
12
+ /**
13
+ * Normalized `origin` remote of the checkout, when one could be read.
14
+ *
15
+ * Optional because it is the one field a directory can honestly lack: a
16
+ * workspace that is not a git checkout has no repository identity, and a
17
+ * descriptor written before this field existed must stay readable. "Absent"
18
+ * therefore means "unknown", never an empty identity.
19
+ */
20
+ readonly origin?: string;
21
+ }
22
+ /**
23
+ * One machine's view of a project directory.
24
+ *
25
+ * Stored as `projects/<slug>/hosts/<hostname>.json`. The point is honesty about
26
+ * the trade in {@link projectSlug}: a slug is now the project *name*, so two
27
+ * unrelated projects sharing a basename share one directory, and this file is
28
+ * how a reader sees that a directory has been used from more than one root.
29
+ */
30
+ export interface ProjectHostDescriptor {
31
+ /** Machine that wrote this file. */
32
+ readonly host: string;
33
+ /** `process.platform` of that machine. */
34
+ readonly platform: string;
35
+ /** That machine's absolute checkout of the project. */
36
+ readonly root: string;
37
+ /** First time this machine used the directory. */
38
+ readonly firstSeen: number;
39
+ /** Last time this machine used the directory. */
40
+ readonly lastSeen: number;
41
+ /**
42
+ * Normalized `origin` remote of that checkout, when one could be read.
43
+ *
44
+ * This is what makes a basename collision visible across machines: two hosts
45
+ * recording different origins for one slug are two repositories sharing one
46
+ * memory directory, not one project checked out twice.
47
+ */
48
+ readonly origin?: string;
49
+ }
50
+ /**
51
+ * One project slug whose recorded origins disagree.
52
+ *
53
+ * The slug is the project name, so a second, unrelated repository of the same
54
+ * name lands in the same `projects/<slug>` directory. Every host that ever used
55
+ * it recorded its own origin; two different origins prove the collision.
56
+ */
57
+ export interface OriginConflict {
58
+ /** Slug directory under `projects/` shared by both checkouts. */
59
+ readonly slug: string;
60
+ /** Every distinct normalized origin recorded for that slug, sorted. */
61
+ readonly origins: readonly string[];
62
+ }
63
+ /** Turn arbitrary text into a stable lowercase slug. */
64
+ export declare function slugify(value: string): string;
65
+ /** Normalize one tag: lowercase, slug-ish, non-empty, deduplicated by the caller. */
66
+ export declare function normalizeTag(value: string): string;
67
+ /**
68
+ * Derive the directory slug of one project from its **name**, not its path.
69
+ *
70
+ * Memory is about the project, and one project is usually checked out at a
71
+ * different absolute path on every machine (`/Users/x/Code/alpha` here,
72
+ * `C:/Users/you/Code/alpha` there). Deriving the slug from the resolved path
73
+ * split that one project's memories into one directory per machine, which made
74
+ * "the same repo, remembered twice" the normal case. The name is the identity
75
+ * both machines agree on.
76
+ *
77
+ * Two unrelated projects that happen to share a basename therefore share one
78
+ * directory. That is the accepted trade: the directory records every root that
79
+ * ever used it under `hosts/`, so a collision is visible rather than silent.
80
+ *
81
+ * @param root - absolute workspace root.
82
+ * @returns The slugified basename.
83
+ */
84
+ export declare function projectSlug(root: string): string;
85
+ /**
86
+ * The legacy slug shape: `<name>-<8 hex chars of sha1(resolved root)>`.
87
+ *
88
+ * Only migration reads this: a directory matching it was named by the old
89
+ * path-derived scheme and has to be re-homed onto {@link projectSlug}.
90
+ */
91
+ export declare const LEGACY_PROJECT_SLUG: RegExp;
92
+ /** Serialize one entry as a markdown file with frontmatter. */
93
+ export declare function formatEntry(entry: MemoryEntry): string;
94
+ /**
95
+ * Parse one entry file. Unparseable files are reported by returning
96
+ * `undefined` so one corrupt file cannot take the whole store down.
97
+ * @param text - file content.
98
+ * @param scope - scope the file belongs to (the directory is authoritative).
99
+ * @param fallbackId - id derived from the file name.
100
+ * @returns the parsed entry, or `undefined` when the file is not an entry.
101
+ */
102
+ export declare function parseEntry(text: string, scope: MemoryScope, fallbackId: string): MemoryEntry | undefined;
103
+ /**
104
+ * Normalize one search key: lowercase, comma-free, length-capped.
105
+ *
106
+ * Keys are the aliases and keyphrases a memory should also be found by, so they
107
+ * are stored comma-separated beside the tags and matched by the same scorer.
108
+ * @param value - the raw key.
109
+ * @returns the normalized key.
110
+ */
111
+ export declare function normalizeKey(value: string): string;
112
+ /** Jaccard overlap of two token sets; `0` when either side is empty. */
113
+ export declare function overlap(left: ReadonlySet<string>, right: ReadonlySet<string>): number;
114
+ /**
115
+ * Whether two memories are close enough to be one memory re-worded.
116
+ *
117
+ * Both halves must agree. Titles that overlap while bodies do not are two
118
+ * different lessons that happen to be named alike, and collapsing those loses
119
+ * what no later pass can recover.
120
+ * @param left - one memory, or a draft.
121
+ * @param right - the other.
122
+ * @param threshold - minimum title overlap; the body must reach half of it.
123
+ * @returns true when the two should be treated as the same memory.
124
+ */
125
+ export declare function isNearDuplicate(left: {
126
+ title: string;
127
+ body: string;
128
+ }, right: {
129
+ title: string;
130
+ body: string;
131
+ }, threshold: number): boolean;
132
+ /** How many per-session evidence notes the store keeps before the oldest go. */
133
+ export declare const SESSION_NOTE_LIMIT = 200;
134
+ /**
135
+ * Encode one frontmatter value as a YAML double-quoted scalar.
136
+ *
137
+ * A plain scalar breaks the document as soon as the value contains a mapping
138
+ * colon, a leading indicator, or a newline, and both readers here respond by
139
+ * ignoring the file. Quoting makes every value safe.
140
+ *
141
+ * @param value - the raw text.
142
+ * @returns a double-quoted YAML scalar with the escapes YAML defines.
143
+ */
144
+ export declare function yamlScalar(value: string): string;
145
+ /**
146
+ * One mined session's evidence note.
147
+ *
148
+ * The counterpart of Codex's `rollout_summaries/`: a memory records WHAT was
149
+ * learned, and this records what the conversation was about, so a reader can
150
+ * judge whether the memory still applies.
151
+ */
152
+ export interface SessionNote {
153
+ /** Session the note describes. */
154
+ readonly session: string;
155
+ /** Unix epoch milliseconds when the note was written. */
156
+ readonly at: number;
157
+ /** Scope label of the workspace it was mined in, when it had one. */
158
+ readonly project?: string;
159
+ /** What the session was about, in the model's words. */
160
+ readonly summary: string;
161
+ /** Ids of the entries this session contributed. */
162
+ readonly memories: readonly string[];
163
+ }
164
+ /** Where per-session evidence notes live inside the memory store. */
165
+ export declare function sessionNotesDir(memoriesDir: string): string;
166
+ /**
167
+ * Parse one evidence note.
168
+ * @param text - file content.
169
+ * @param fallbackSession - session id derived from the file name.
170
+ * @returns the note, or `undefined` when the file is not a note.
171
+ */
172
+ export declare function parseSessionNote(text: string, fallbackSession: string): SessionNote | undefined;
173
+ /**
174
+ * Whether a near-duplicate rewrite still carries the material it replaces.
175
+ *
176
+ * Conservative on purpose: refusing to supersede costs one extra entry for the
177
+ * consolidation pass to fold, while superseding wrongly destroys the only copy
178
+ * of a qualifier. A rewrite may therefore lose no citation, no length, no tag and
179
+ * no key.
180
+ *
181
+ * @param previous - the entry the implicit match proposes to replace.
182
+ * @param draft - the incoming rewrite.
183
+ * @returns true when the rewrite is a superset of what it replaces.
184
+ */
185
+ export declare function carriesForward(previous: MemoryEntry, draft: MemoryDraft): boolean;
186
+ /** Why one entry left the live store. Recorded so an irreversible action stays explainable. */
187
+ export type RetireReason = 'evict' | 'superseded' | 'near-duplicate' | 'retention' | 'consolidation';
188
+ /** One retirement, reported to whoever owns the store and therefore owns the log. */
189
+ export interface RetireInfo {
190
+ readonly scope: MemoryScope;
191
+ readonly id: string;
192
+ readonly reason: RetireReason;
193
+ readonly projectRoot?: string;
194
+ }
195
+ export declare class MemoryStore {
196
+ readonly memoriesDir: string;
197
+ private readonly cache;
198
+ private readonly pending;
199
+ constructor(memoriesDir: string);
200
+ /** Absolute directory of one scope. */
201
+ scopeDir(scope: MemoryScope, projectRoot: string | undefined): string;
202
+ /** Entries directory of one scope (public for the dedupe helper). */
203
+ entriesDirOf(scope: MemoryScope, projectRoot: string | undefined): string;
204
+ /** Entries directory of one scope. */
205
+ private entriesDir;
206
+ /** Index path of one scope. */
207
+ private indexPath;
208
+ /** Resolve the model-facing target for one scope. */
209
+ target(scope: MemoryScope, projectRoot: string | undefined): ScopeTarget;
210
+ /** Record how one project slug was derived, for diagnostics. */
211
+ writeProjectDescriptor(projectRoot: string, now?: number): Promise<void>;
212
+ /**
213
+ * Record that this machine uses one project directory.
214
+ *
215
+ * One file per host (`hosts/<hostname>.json`) rather than one shared file: the
216
+ * store is synced between machines, and a single descriptor rewritten by both
217
+ * would make every sync a conflict over fields neither party changed.
218
+ *
219
+ * @param slug - project slug, the directory the file lives under.
220
+ * @param projectRoot - this machine's checkout of that project.
221
+ * @param now - write time.
222
+ */
223
+ writeHostDescriptor(slug: string, projectRoot: string, now?: number): Promise<void>;
224
+ /** Every host that has used one project slug, newest write first. */
225
+ listHostDescriptors(slug: string): Promise<readonly ProjectHostDescriptor[]>;
226
+ /** Read a project descriptor, when present. */
227
+ readProjectDescriptor(slug: string): Promise<ProjectDescriptor | undefined>;
228
+ /** List every project slug present on disk. */
229
+ listProjects(): Promise<readonly string[]>;
230
+ /**
231
+ * Every distinct repository origin recorded for one project slug.
232
+ *
233
+ * The canonical descriptor and each machine's host file are merged because no
234
+ * single one of them is authoritative across machines: `project.json` is
235
+ * rewritten by whichever checkout wrote last, while `hosts/<hostname>.json`
236
+ * keeps one machine's view and is never overwritten by another machine.
237
+ * A directory that was never a git checkout records nothing and yields `[]`.
238
+ *
239
+ * @param slug - project slug directory.
240
+ * @returns the distinct non-empty origins, sorted for a stable report.
241
+ */
242
+ projectOrigins(slug: string): Promise<readonly string[]>;
243
+ /**
244
+ * Report every project slug that two different repositories share.
245
+ *
246
+ * {@link projectSlug} keys a project by its name, so `<a>/alpha` and
247
+ * `<b>/alpha` share `projects/alpha` and their memories are silently merged.
248
+ * Two recorded origins are the proof of that collision; one origin (or none,
249
+ * for a non-checkout) is a project used from several roots, which is the
250
+ * normal case and is not reported.
251
+ *
252
+ * @returns one row per conflicting slug, sorted by slug.
253
+ */
254
+ originConflicts(): Promise<readonly OriginConflict[]>;
255
+ /** Drop the cached index of one scope. */
256
+ invalidate(scope: MemoryScope, projectRoot: string | undefined): void;
257
+ /**
258
+ * Delete project directories that hold nothing recoverable.
259
+ *
260
+ * A workspace that is renamed, moved, or simply never produces a memory leaves
261
+ * its slug behind: measured on a real store, 12 of 19 project directories were
262
+ * empty and 6 of those had no descriptor at all — one workspace even existed
263
+ * under two slugs, its memories split between them.
264
+ *
265
+ * The test is "no markdown anywhere under the directory", which covers entries,
266
+ * archives, and anything a future version files there. An archive alone is
267
+ * enough to keep the directory: that is the file a human would restore from.
268
+ * Recreating a slug is free, because it is derived from the workspace path, so
269
+ * deleting an empty one cannot lose anything that a later write would not
270
+ * recreate.
271
+ *
272
+ * @returns the slugs that were removed, for the caller to report.
273
+ */
274
+ pruneEmptyProjects(): Promise<readonly string[]>;
275
+ /**
276
+ * Move every project scope whose directory name is not the slug its own root
277
+ * derives onto the canonical directory, merging entries when both exist.
278
+ *
279
+ * Two reasons a misspelled directory appears, and the second is the common one:
280
+ *
281
+ * 1. A slug derived by an older scheme. Before 0.2.1 the slug carried a hash of
282
+ * the resolved path, so the same project checked out at two paths wrote two
283
+ * directories.
284
+ * 2. The same project on two machines. The slug is now the project name, so the
285
+ * directories converge — and the first device to see the other's copy merges
286
+ * them here.
287
+ *
288
+ * Merging is safe because an entry is one memory identified by its id: the same
289
+ * id in both directories is the same memory with two revisions, so the newer
290
+ * `updated` wins and the older text is simply dropped (it stays in the git
291
+ * history of the synced store). `index.json` is a rebuildable cache and is not
292
+ * copied.
293
+ *
294
+ * @returns the slug pairs that were re-homed, for the caller to report.
295
+ */
296
+ adoptMisnamedProjects(): Promise<readonly {
297
+ from: string;
298
+ to: string;
299
+ }[]>;
300
+ /** The `updated` stamp of one entry file, or its mtime when it has none. */
301
+ private entryTimeOf;
302
+ /**
303
+ * List one scope's entries, newest-updated first. The on-disk `index.json` is
304
+ * preferred while it agrees with the directory's file count; otherwise the
305
+ * directory is re-scanned and the index rewritten.
306
+ * @param scope - scope to read.
307
+ * @param projectRoot - workspace root for a project scope.
308
+ * @param options - `fresh` bypasses the in-memory cache.
309
+ * @returns every parsed entry in the scope.
310
+ */
311
+ list(scope: MemoryScope, projectRoot: string | undefined, options?: {
312
+ fresh?: boolean;
313
+ }): Promise<readonly MemoryEntry[]>;
314
+ /** Scan one scope directory and refresh both the cache and the index file. */
315
+ private load;
316
+ /** Rewrite one scope's index cache file. */
317
+ private writeIndex;
318
+ /**
319
+ * Path of one entry file, tolerating ids a slug cannot round-trip.
320
+ *
321
+ * An id is a slugified title, but a collision suffix can leave a trailing `-`
322
+ * that {@link slugify} strips on the way back in. For such an id the canonical
323
+ * `<slugify(id)>.md` spelling does not exist on disk, so every id-addressed
324
+ * operation — read, remove, archive, restore — silently misses it. Measured on
325
+ * a real store, two entries were unreachable that way (one of them a duplicate
326
+ * that could not be archived). The exact name wins whenever it is present.
327
+ *
328
+ * @param scope - owning scope.
329
+ * @param projectRoot - workspace root for a project scope.
330
+ * @param id - entry id as stored.
331
+ * @returns the path to read or write.
332
+ */
333
+ private entryFile;
334
+ /** Read one entry by id. */
335
+ read(scope: MemoryScope, projectRoot: string | undefined, id: string): Promise<MemoryEntry | undefined>;
336
+ /**
337
+ * Mirror usage counters into the entry file.
338
+ *
339
+ * The authoritative counter lives in the state database, which updates it
340
+ * atomically; this write only keeps the markdown a complete picture for a
341
+ * human reader. Deliberately best-effort: a failed mirror never fails the
342
+ * caller's read.
343
+ * @param entry - the entry that was used.
344
+ * @param projectRoot - workspace root for a project entry.
345
+ * @param counters - the counters the state store just committed.
346
+ * @returns the updated entry, or the original when the write failed.
347
+ */
348
+ writeCounters(entry: MemoryEntry, projectRoot: string | undefined, counters: {
349
+ uses: number;
350
+ lastUsedAt: number;
351
+ surfacedAt?: number;
352
+ }): Promise<MemoryEntry>;
353
+ /**
354
+ * Insert or update one draft. The id is derived from the title, so writing
355
+ * the same lesson twice updates the stored entry and preserves `createdAt`.
356
+ * @param draft - the memory to persist.
357
+ * @param projectRoot - workspace root for a project draft.
358
+ * @param source - provenance recorded on the entry.
359
+ * @param now - injected clock for deterministic tests.
360
+ * @param keepId - write over this exact id instead of deriving one from the
361
+ * title; used by consolidation, where a rewritten memory keeps its identity.
362
+ * @returns the stored entry and whether it was created or updated.
363
+ */
364
+ upsert(draft: MemoryDraft, projectRoot: string | undefined, source: MemoryEntry['source'], now?: number, keepId?: string): Promise<UpsertResult>;
365
+ /** Delete one entry. Returns whether a file was removed. */
366
+ remove(scope: MemoryScope, projectRoot: string | undefined, id: string): Promise<boolean>;
367
+ /**
368
+ * Move one entry out of the live store without destroying it.
369
+ *
370
+ * Consolidation retires memories it judges stale and the per-scope cap
371
+ * evicts the least recently updated; either judgement can be wrong. Deleting
372
+ * the file would make a wrong judgement irreversible, so the entry is stamped
373
+ * and moved to `archive/` beside its scope, where {@link restore} can bring it
374
+ * back. The archive is bounded, so this is not an unbounded second store.
375
+ *
376
+ * @param scope - owning scope.
377
+ * @param projectRoot - workspace root for a project scope.
378
+ * @param id - entry id.
379
+ * @param now - clock recorded in the archive stamp.
380
+ * @returns whether an entry was archived.
381
+ */
382
+ archive(scope: MemoryScope, projectRoot: string | undefined, id: string, now?: number, reason?: RetireReason): Promise<boolean>;
383
+ /** Report one archival to the owner. A broken reporter must not undo the archival. */
384
+ private reportRetire;
385
+ /** Move one archived entry back into the live store. */
386
+ restore(scope: MemoryScope, projectRoot: string | undefined, id: string): Promise<boolean>;
387
+ /** Every archived entry in one scope, for the human-facing commands. */
388
+ listArchived(scope: MemoryScope, projectRoot: string | undefined): Promise<readonly MemoryEntry[]>;
389
+ /** Rebuild one scope's cache and index after its entries directory changed. */
390
+ private reindex;
391
+ /** Directory holding one scope's archived entries. */
392
+ private archiveDir;
393
+ /** Keep one scope's archive bounded: the newest 500 files survive. */
394
+ private evictArchive;
395
+ /**
396
+ * Enforce the per-scope cap, archiving the least recently updated entries.
397
+ *
398
+ * Pinned entries and entries a person wrote are skipped. Retention has always
399
+ * protected both (`planRetention`), and a cap that did not would evict exactly
400
+ * the rules somebody asked to keep — silently, because a cap is not a
401
+ * judgement. Skipping them can leave a scope above its cap; that is the
402
+ * intended trade, since the alternative is trading a person's decision for an
403
+ * extractor's guess. Measured on the real store before this guard: the two
404
+ * most-used pinned rules sat 29 and 33 writes away from being evicted.
405
+ */
406
+ private evict;
407
+ /**
408
+ * Find an existing memory the draft appears to rewrite.
409
+ *
410
+ * The id comes from the title, so a re-worded title creates a second file and
411
+ * the store slowly fills with near-copies. The rule stays deliberately narrow
412
+ * — see {@link isNearDuplicate} — because merging two genuinely distinct
413
+ * memories loses information no later pass can recover.
414
+ *
415
+ * @param draft - the incoming memory.
416
+ * @param projectRoot - workspace root for a project draft.
417
+ * @param exclude - id to ignore, so a draft can never supersede itself.
418
+ * @returns the id to supersede, or `undefined` when the draft is new.
419
+ */
420
+ private findSimilar;
421
+ /**
422
+ * Write one mined session's evidence note.
423
+ *
424
+ * This is the layer Codex keeps as `rollout_summaries/`: a memory says WHAT
425
+ * was learned, and this note says what the conversation was about, so a reader
426
+ * can judge whether the memory still applies — or go and re-read it.
427
+ *
428
+ * @param note - the note to persist.
429
+ * @returns the absolute path written.
430
+ */
431
+ writeSessionNote(note: SessionNote): Promise<string>;
432
+ /** Read one session's evidence note. */
433
+ readSessionNote(session: string): Promise<SessionNote | undefined>;
434
+ /** Every evidence note's session id, newest write first. */
435
+ listSessionNotes(): Promise<readonly string[]>;
436
+ /** Keep the note store bounded: one small file per mined session, newest kept. */
437
+ private evictNotes;
438
+ /**
439
+ * Per-scope entry cap, read at write time so a settings change applies to the
440
+ * very next write. The plugin installs its live settings thunk here.
441
+ */
442
+ entryLimit: () => number;
443
+ /**
444
+ * Near-duplicate threshold, read at load and write time so a settings change
445
+ * applies to the very next operation. `0` keeps only the exact-match rule.
446
+ */
447
+ similarityLimit: () => number;
448
+ /**
449
+ * Called for every entry this store retires.
450
+ *
451
+ * The store does not log: it has no logger and no deployment facts. The plugin
452
+ * installs a reporter here, so "a memory disappeared" stops being a silent
453
+ * event. A reporter that throws must never fail the write that retired it.
454
+ */
455
+ onRetire?: (info: RetireInfo) => void;
456
+ /** Ids that must survive the next dedupe pass (the entry just written). */
457
+ private keepIds;
458
+ }
@@ -0,0 +1,103 @@
1
+ import type { LlmRuntime } from '@deepseek-ai/dsh-llm';
2
+ import type { ConsolidationDispute, ConsolidationPlan } from './consolidate.js';
3
+ import type { SyncLog } from './sync.js';
4
+ import type { MemoriesSettings } from './config.js';
5
+ /** What the sync service needs from the plugin, all resolved lazily. */
6
+ export interface StoreSyncHost {
7
+ /** The memory store directory. */
8
+ readonly memoriesDir: string;
9
+ /** Tunables in force right now. */
10
+ readonly settings: () => MemoriesSettings;
11
+ /** The LLM runtime, when one is provided. */
12
+ readonly llm: () => LlmRuntime | undefined;
13
+ /** Plugin logger. */
14
+ readonly log: SyncLog;
15
+ }
16
+ /**
17
+ * Owns the store's {@link MemorySync} for one plugin instance.
18
+ *
19
+ * Starting is idempotent because the settings watcher restarts it on every
20
+ * commit; stopping is safe at any time.
21
+ */
22
+ /**
23
+ * The instruction that turns a consolidation pass into a one-entry merge.
24
+ *
25
+ * Same vocabulary as the consolidation pass, so the model does not have to learn
26
+ * a second output shape: a sync conflict is one memory with two revisions.
27
+ */
28
+ export declare function renderConflictPrompt(id: string, ours: string, theirs: string): string;
29
+ /**
30
+ * What a conflict merge produced: the merged file, or the questions it raised.
31
+ *
32
+ * The disputed branch carries the plan fragment that would apply those rows: a
33
+ * row staged without it cannot be accepted at all, and an older version of this
34
+ * module staged every sync dispute with an empty plan, so the panel reported an
35
+ * apply that changed nothing.
36
+ */
37
+ export type ConflictMerge = {
38
+ readonly text: string;
39
+ readonly merged: true;
40
+ } | {
41
+ readonly text?: undefined;
42
+ readonly disputes: readonly ConsolidationDispute[];
43
+ readonly upserts?: ConsolidationPlan['upserts'];
44
+ };
45
+ /**
46
+ * Turn a model reply into the merged entry file, or into the disputes it raised.
47
+ *
48
+ * Pure so the arbitration is testable without an LLM: the caller hands in the
49
+ * reply and both revisions, and this decides with the same rules the
50
+ * consolidation pass obeys (`parsePlan` for shape, `classifyPlan` for loss).
51
+ */
52
+ export declare function applyConflictPlan(reply: string, oursText: string, theirsText: string): ConflictMerge;
53
+ /**
54
+ * Whether a store path is a retired entry's file rather than a live one.
55
+ *
56
+ * Retirements are archived, not deleted, and a store sync merges an archived
57
+ * file exactly like a live one — but applying a plan always writes into
58
+ * `entries/`. A question staged for an archived file would therefore let
59
+ * "accept" resurrect a memory somebody retired, so those conflicts stay on the
60
+ * timestamp rule instead of becoming a decision.
61
+ *
62
+ * @param path - store-relative path of the conflicting file.
63
+ * @returns true for `archive/<id>.md` and `projects/<slug>/archive/<id>.md`.
64
+ */
65
+ export declare function isArchivedEntryPath(path: string): boolean;
66
+ /**
67
+ * Resolve this machine's checkout of the project a conflicting entry lives in.
68
+ *
69
+ * A project entry is written back through the workspace root the store keys
70
+ * that project by, and a sync conflict only carries store-relative paths. The
71
+ * host descriptor is the primary source because `project.json` is rewritten by
72
+ * whichever machine synced last, while `hosts/<host>.json` keeps THIS machine's
73
+ * checkout and is never overwritten by another machine. The host file is named
74
+ * after the same slug `writeHostDescriptor` uses, not the raw hostname.
75
+ *
76
+ * @param memoriesDir - the memory store root.
77
+ * @param path - the conflicting entry path relative to the store.
78
+ * @returns the checkout root to write through, or `undefined` for a global entry
79
+ * or when no descriptor names one.
80
+ */
81
+ export declare function projectRootOf(memoriesDir: string, path: string): Promise<string | undefined>;
82
+ export declare class StoreSyncService {
83
+ private readonly host;
84
+ private sync;
85
+ constructor(host: StoreSyncHost);
86
+ /** Start (or restart) sync from the current settings. */
87
+ start(): void;
88
+ /** Stop the timer and any queued commit. */
89
+ stop(): void;
90
+ /** Note that the store changed; the commit happens on the debounce timer. */
91
+ markChanged(): void;
92
+ /** Commit, pull and push once, now. */
93
+ runNow(): Promise<void>;
94
+ /**
95
+ * Merge two revisions of one memory through the consolidation machinery.
96
+ *
97
+ * Every failure path returns undefined, which makes `sync.ts` fall back to the
98
+ * newer revision. A merge the loss rules call risky is not written at all: it is
99
+ * staged in the pending proposal, so a sync conflict is answered in the same
100
+ * place as every other consolidation question.
101
+ */
102
+ private resolve;
103
+ }