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.
- package/LICENSE +21 -0
- package/README.md +247 -2
- package/cordis.patch.yml +27 -0
- package/docs/DETAIL.md +13 -0
- package/docs/DETAIL.zh.md +17 -0
- package/icon.svg +1 -0
- package/lib/backfill.js +273 -0
- package/lib/citations.js +305 -0
- package/lib/client.js +1550 -0
- package/lib/config.js +736 -0
- package/lib/consolidate.js +1119 -0
- package/lib/extract.js +570 -0
- package/lib/gate.js +137 -0
- package/lib/git-origin.js +224 -0
- package/lib/index.js +4475 -0
- package/lib/log.js +260 -0
- package/lib/loops.js +186 -0
- package/lib/notices.js +195 -0
- package/lib/notify.js +33 -0
- package/lib/persona.js +112 -0
- package/lib/query.js +93 -0
- package/lib/raw-recall.js +286 -0
- package/lib/reflection.js +291 -0
- package/lib/remote.js +455 -0
- package/lib/render.js +678 -0
- package/lib/retention.js +64 -0
- package/lib/schedule.js +245 -0
- package/lib/search.js +1068 -0
- package/lib/skills.js +220 -0
- package/lib/state.js +701 -0
- package/lib/storage.js +1424 -0
- package/lib/sync-runtime.js +268 -0
- package/lib/sync.js +620 -0
- package/lib/test/activity.test.js +74 -0
- package/lib/test/archive.test.js +182 -0
- package/lib/test/backfill.test.js +144 -0
- package/lib/test/citations.test.js +91 -0
- package/lib/test/client-wiring.test.js +134 -0
- package/lib/test/consolidate-job.test.js +95 -0
- package/lib/test/consolidate.test.js +430 -0
- package/lib/test/consolidation-selection.test.js +152 -0
- package/lib/test/dedupe-keys.test.js +230 -0
- package/lib/test/delta.test.js +93 -0
- package/lib/test/derived.test.js +110 -0
- package/lib/test/disputes-panel.test.js +314 -0
- package/lib/test/eval.test.js +171 -0
- package/lib/test/expand.test.js +164 -0
- package/lib/test/extract.test.js +1020 -0
- package/lib/test/git-origin.test.js +189 -0
- package/lib/test/injection.test.js +440 -0
- package/lib/test/kind-filter.test.js +49 -0
- package/lib/test/legacy-state.test.js +69 -0
- package/lib/test/log.test.js +156 -0
- package/lib/test/loops.test.js +86 -0
- package/lib/test/memory.test.js +855 -0
- package/lib/test/notices.test.js +140 -0
- package/lib/test/persona.test.js +73 -0
- package/lib/test/prefilter.test.js +73 -0
- package/lib/test/preset.test.js +77 -0
- package/lib/test/raw-recall.test.js +186 -0
- package/lib/test/recall.test.js +433 -0
- package/lib/test/reflection.test.js +64 -0
- package/lib/test/remote.test.js +227 -0
- package/lib/test/retention.test.js +117 -0
- package/lib/test/retrieval.test.js +142 -0
- package/lib/test/rotation.test.js +228 -0
- package/lib/test/schedule.test.js +112 -0
- package/lib/test/settings-card.test.js +58 -0
- package/lib/test/skills.test.js +129 -0
- package/lib/test/state.test.js +212 -0
- package/lib/test/subagent-contract.test.js +139 -0
- package/lib/test/sweep.test.js +159 -0
- package/lib/test/sync.test.js +314 -0
- package/lib/test/time.test.js +171 -0
- package/lib/time.js +303 -0
- package/lib/tool.js +330 -0
- package/lib/types/backfill.d.ts +96 -0
- package/lib/types/citations.d.ts +105 -0
- package/lib/types/config.d.ts +811 -0
- package/lib/types/consolidate.d.ts +742 -0
- package/lib/types/extract.d.ts +352 -0
- package/lib/types/gate.d.ts +83 -0
- package/lib/types/git-origin.d.ts +23 -0
- package/lib/types/index.d.ts +1316 -0
- package/lib/types/log.d.ts +144 -0
- package/lib/types/loops.d.ts +82 -0
- package/lib/types/notices.d.ts +117 -0
- package/lib/types/notify.d.ts +12 -0
- package/lib/types/persona.d.ts +43 -0
- package/lib/types/query.d.ts +45 -0
- package/lib/types/raw-recall.d.ts +84 -0
- package/lib/types/reflection.d.ts +122 -0
- package/lib/types/remote.d.ts +233 -0
- package/lib/types/render.d.ts +286 -0
- package/lib/types/retention.d.ts +66 -0
- package/lib/types/schedule.d.ts +116 -0
- package/lib/types/search.d.ts +583 -0
- package/lib/types/skills.d.ts +71 -0
- package/lib/types/state.d.ts +294 -0
- package/lib/types/storage.d.ts +458 -0
- package/lib/types/sync-runtime.d.ts +103 -0
- package/lib/types/sync.d.ts +222 -0
- package/lib/types/test/activity.test.d.ts +1 -0
- package/lib/types/test/archive.test.d.ts +1 -0
- package/lib/types/test/backfill.test.d.ts +1 -0
- package/lib/types/test/citations.test.d.ts +1 -0
- package/lib/types/test/client-wiring.test.d.ts +1 -0
- package/lib/types/test/consolidate-job.test.d.ts +1 -0
- package/lib/types/test/consolidate.test.d.ts +1 -0
- package/lib/types/test/consolidation-selection.test.d.ts +1 -0
- package/lib/types/test/dedupe-keys.test.d.ts +1 -0
- package/lib/types/test/delta.test.d.ts +1 -0
- package/lib/types/test/derived.test.d.ts +1 -0
- package/lib/types/test/disputes-panel.test.d.ts +1 -0
- package/lib/types/test/eval.test.d.ts +1 -0
- package/lib/types/test/expand.test.d.ts +1 -0
- package/lib/types/test/extract.test.d.ts +1 -0
- package/lib/types/test/git-origin.test.d.ts +1 -0
- package/lib/types/test/injection.test.d.ts +1 -0
- package/lib/types/test/kind-filter.test.d.ts +1 -0
- package/lib/types/test/legacy-state.test.d.ts +1 -0
- package/lib/types/test/log.test.d.ts +1 -0
- package/lib/types/test/loops.test.d.ts +1 -0
- package/lib/types/test/memory.test.d.ts +1 -0
- package/lib/types/test/notices.test.d.ts +1 -0
- package/lib/types/test/persona.test.d.ts +1 -0
- package/lib/types/test/prefilter.test.d.ts +1 -0
- package/lib/types/test/preset.test.d.ts +1 -0
- package/lib/types/test/raw-recall.test.d.ts +1 -0
- package/lib/types/test/recall.test.d.ts +1 -0
- package/lib/types/test/reflection.test.d.ts +1 -0
- package/lib/types/test/remote.test.d.ts +1 -0
- package/lib/types/test/retention.test.d.ts +1 -0
- package/lib/types/test/retrieval.test.d.ts +1 -0
- package/lib/types/test/rotation.test.d.ts +1 -0
- package/lib/types/test/schedule.test.d.ts +1 -0
- package/lib/types/test/settings-card.test.d.ts +1 -0
- package/lib/types/test/skills.test.d.ts +1 -0
- package/lib/types/test/state.test.d.ts +1 -0
- package/lib/types/test/subagent-contract.test.d.ts +1 -0
- package/lib/types/test/sweep.test.d.ts +1 -0
- package/lib/types/test/sync.test.d.ts +1 -0
- package/lib/types/test/time.test.d.ts +1 -0
- package/lib/types/time.d.ts +67 -0
- package/lib/types/tool.d.ts +9 -0
- package/lib/types/types.d.ts +374 -0
- package/lib/types/workspace.d.ts +20 -0
- package/lib/types.js +47 -0
- package/lib/workspace.js +65 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +126 -4
package/lib/storage.js
ADDED
|
@@ -0,0 +1,1424 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable memory storage.
|
|
3
|
+
*
|
|
4
|
+
* Layout under `<memoriesDir>`:
|
|
5
|
+
*
|
|
6
|
+
* ```text
|
|
7
|
+
* memories/
|
|
8
|
+
* index.json # global scope index (a rebuildable cache)
|
|
9
|
+
* entries/<id>.md # one file per global entry
|
|
10
|
+
* projects/<slug>/index.json # project scope index
|
|
11
|
+
* projects/<slug>/entries/*.md
|
|
12
|
+
* projects/<slug>/project.json # how the slug was derived (diagnostics)
|
|
13
|
+
* skills/<name>/SKILL.md # staged skill drafts, not yet promoted
|
|
14
|
+
* state.db # SQLite: watermarks, jobs, usage counters
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Entry files are the source of truth: an index is a rebuildable cache, so a
|
|
18
|
+
* hand-edited or deleted index self-heals on the next read. Every write is
|
|
19
|
+
* atomic (temp file + rename).
|
|
20
|
+
*
|
|
21
|
+
* @module dsh-cross-memory/storage
|
|
22
|
+
*/
|
|
23
|
+
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
24
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
25
|
+
import { hostname } from 'node:os';
|
|
26
|
+
import { gitOrigin } from './git-origin.js';
|
|
27
|
+
import { toMemoryDurability, toMemoryKind } from './types.js';
|
|
28
|
+
/** Frontmatter fence used by every entry file. */
|
|
29
|
+
const FENCE = '---';
|
|
30
|
+
/** Whether a filesystem error means "absent". */
|
|
31
|
+
function isMissing(error) {
|
|
32
|
+
return typeof error === 'object' && error !== null && 'code' in error
|
|
33
|
+
&& (error.code === 'ENOENT' || error.code === 'ENOTDIR');
|
|
34
|
+
}
|
|
35
|
+
/** Read a UTF-8 file, or `undefined` when it does not exist. */
|
|
36
|
+
async function readText(path) {
|
|
37
|
+
try {
|
|
38
|
+
return await readFile(path, 'utf8');
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (isMissing(error))
|
|
42
|
+
return undefined;
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** Whether one path exists. */
|
|
47
|
+
async function exists(path) {
|
|
48
|
+
try {
|
|
49
|
+
await stat(path);
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (isMissing(error))
|
|
54
|
+
return false;
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Write a file atomically: a sibling temp file is renamed over the target, so a
|
|
60
|
+
* reader never observes a partial document.
|
|
61
|
+
* @param path - destination path.
|
|
62
|
+
* @param content - exact UTF-8 content.
|
|
63
|
+
*/
|
|
64
|
+
async function writeAtomic(path, content) {
|
|
65
|
+
await mkdir(dirname(path), { recursive: true });
|
|
66
|
+
const temp = `${path}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
67
|
+
await writeFile(temp, content, 'utf8');
|
|
68
|
+
try {
|
|
69
|
+
await rename(temp, path);
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
await rm(temp, { force: true }).catch(() => undefined);
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** Turn arbitrary text into a stable lowercase slug. */
|
|
77
|
+
export function slugify(value) {
|
|
78
|
+
const slug = value
|
|
79
|
+
.normalize('NFKD')
|
|
80
|
+
.toLowerCase()
|
|
81
|
+
.replace(/[\u0300-\u036f]/gu, '')
|
|
82
|
+
.replace(/[^a-z0-9\u4e00-\u9fff]+/gu, '-')
|
|
83
|
+
.replace(/^-+|-+$/gu, '')
|
|
84
|
+
.slice(0, 64);
|
|
85
|
+
return slug.length > 0 ? slug : 'memory';
|
|
86
|
+
}
|
|
87
|
+
/** Normalize one tag: lowercase, slug-ish, non-empty, deduplicated by the caller. */
|
|
88
|
+
export function normalizeTag(value) {
|
|
89
|
+
return value.trim().toLowerCase().replace(/\s+/gu, '-').slice(0, 32);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Derive the directory slug of one project from its **name**, not its path.
|
|
93
|
+
*
|
|
94
|
+
* Memory is about the project, and one project is usually checked out at a
|
|
95
|
+
* different absolute path on every machine (`/Users/x/Code/alpha` here,
|
|
96
|
+
* `C:/Users/you/Code/alpha` there). Deriving the slug from the resolved path
|
|
97
|
+
* split that one project's memories into one directory per machine, which made
|
|
98
|
+
* "the same repo, remembered twice" the normal case. The name is the identity
|
|
99
|
+
* both machines agree on.
|
|
100
|
+
*
|
|
101
|
+
* Two unrelated projects that happen to share a basename therefore share one
|
|
102
|
+
* directory. That is the accepted trade: the directory records every root that
|
|
103
|
+
* ever used it under `hosts/`, so a collision is visible rather than silent.
|
|
104
|
+
*
|
|
105
|
+
* @param root - absolute workspace root.
|
|
106
|
+
* @returns The slugified basename.
|
|
107
|
+
*/
|
|
108
|
+
export function projectSlug(root) {
|
|
109
|
+
return slugify(root.replace(/[\\/]+$/u, '').split(/[\\/]/u).pop() ?? 'workspace');
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The legacy slug shape: `<name>-<8 hex chars of sha1(resolved root)>`.
|
|
113
|
+
*
|
|
114
|
+
* Only migration reads this: a directory matching it was named by the old
|
|
115
|
+
* path-derived scheme and has to be re-homed onto {@link projectSlug}.
|
|
116
|
+
*/
|
|
117
|
+
export const LEGACY_PROJECT_SLUG = /^.+?-[0-9a-f]{8}$/u;
|
|
118
|
+
/** Serialize one entry as a markdown file with frontmatter. */
|
|
119
|
+
export function formatEntry(entry) {
|
|
120
|
+
const tags = entry.tags.length > 0 ? `tags: ${entry.tags.join(', ')}` : 'tags:';
|
|
121
|
+
const keys = entry.keys.length > 0 ? `keys: ${entry.keys.join(', ')}` : undefined;
|
|
122
|
+
return [
|
|
123
|
+
FENCE,
|
|
124
|
+
`id: ${entry.id}`,
|
|
125
|
+
`scope: ${entry.scope}`,
|
|
126
|
+
`kind: ${entry.kind}`,
|
|
127
|
+
`title: ${entry.title}`,
|
|
128
|
+
tags,
|
|
129
|
+
...keys === undefined ? [] : [keys],
|
|
130
|
+
...entry.appliesTo !== undefined && entry.appliesTo.length > 0 ? [`appliesTo: ${entry.appliesTo}`] : [],
|
|
131
|
+
...entry.durability === 'snapshot' ? ['durability: snapshot'] : [],
|
|
132
|
+
...entry.durability === 'snapshot' && entry.asOf !== undefined ? [`asOf: ${new Date(entry.asOf).toISOString()}`] : [],
|
|
133
|
+
...entry.pinned === true ? ['pinned: true'] : [],
|
|
134
|
+
...entry.permanent === true ? ['permanent: true'] : [],
|
|
135
|
+
...entry.voice === 'user' ? ['voice: user'] : [],
|
|
136
|
+
...entry.supersedes !== undefined && entry.supersedes.length > 0 ? [`supersedes: ${entry.supersedes}`] : [],
|
|
137
|
+
...entry.sourceSession !== undefined && entry.sourceSession.length > 0 ? [`session: ${entry.sourceSession}`] : [],
|
|
138
|
+
...entry.quote !== undefined && entry.quote.length > 0 ? [`quote: ${entry.quote}`] : [],
|
|
139
|
+
...entry.evidenceSeq !== undefined && entry.evidenceSeq > 0 ? [`evidenceSeq: ${entry.evidenceSeq}`] : [],
|
|
140
|
+
...entry.derivedFrom !== undefined && entry.derivedFrom.length > 0 ? [`derivedFrom: ${entry.derivedFrom.join(', ')}`] : [],
|
|
141
|
+
`created: ${new Date(entry.createdAt).toISOString()}`,
|
|
142
|
+
`updated: ${new Date(entry.updatedAt).toISOString()}`,
|
|
143
|
+
`source: ${entry.source}`,
|
|
144
|
+
`uses: ${entry.uses}`,
|
|
145
|
+
`lastUsed: ${entry.lastUsedAt > 0 ? new Date(entry.lastUsedAt).toISOString() : 'never'}`,
|
|
146
|
+
`lastSurfaced: ${entry.lastSurfacedAt > 0 ? new Date(entry.lastSurfacedAt).toISOString() : 'never'}`,
|
|
147
|
+
FENCE,
|
|
148
|
+
'',
|
|
149
|
+
entry.body,
|
|
150
|
+
'',
|
|
151
|
+
].join('\n');
|
|
152
|
+
}
|
|
153
|
+
/** Parse a frontmatter timestamp written as ISO text or raw epoch milliseconds. */
|
|
154
|
+
function parseTime(value, fallback) {
|
|
155
|
+
if (value === undefined)
|
|
156
|
+
return fallback;
|
|
157
|
+
const numeric = Number(value);
|
|
158
|
+
if (Number.isFinite(numeric) && numeric > 0)
|
|
159
|
+
return numeric;
|
|
160
|
+
const parsed = Date.parse(value);
|
|
161
|
+
return Number.isFinite(parsed) ? parsed : fallback;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Parse one entry file. Unparseable files are reported by returning
|
|
165
|
+
* `undefined` so one corrupt file cannot take the whole store down.
|
|
166
|
+
* @param text - file content.
|
|
167
|
+
* @param scope - scope the file belongs to (the directory is authoritative).
|
|
168
|
+
* @param fallbackId - id derived from the file name.
|
|
169
|
+
* @returns the parsed entry, or `undefined` when the file is not an entry.
|
|
170
|
+
*/
|
|
171
|
+
export function parseEntry(text, scope, fallbackId) {
|
|
172
|
+
const normalized = text.replace(/^\uFEFF/u, '');
|
|
173
|
+
if (!normalized.startsWith(FENCE))
|
|
174
|
+
return undefined;
|
|
175
|
+
const end = normalized.indexOf(`\n${FENCE}`, FENCE.length);
|
|
176
|
+
if (end < 0)
|
|
177
|
+
return undefined;
|
|
178
|
+
const header = normalized.slice(FENCE.length, end);
|
|
179
|
+
const body = normalized.slice(end + FENCE.length + 1).replace(/^\n+/u, '').trimEnd();
|
|
180
|
+
const fields = new Map();
|
|
181
|
+
for (const line of header.split('\n')) {
|
|
182
|
+
const separator = line.indexOf(':');
|
|
183
|
+
if (separator < 0)
|
|
184
|
+
continue;
|
|
185
|
+
fields.set(line.slice(0, separator).trim().toLowerCase(), line.slice(separator + 1).trim());
|
|
186
|
+
}
|
|
187
|
+
const title = fields.get('title');
|
|
188
|
+
if (title === undefined || title.length === 0)
|
|
189
|
+
return undefined;
|
|
190
|
+
const rawSource = fields.get('source');
|
|
191
|
+
const source = rawSource === 'tool' || rawSource === 'user' || rawSource === 'auto' || rawSource === 'system'
|
|
192
|
+
? rawSource
|
|
193
|
+
: 'system';
|
|
194
|
+
const updatedAt = parseTime(fields.get('updated'), Date.now());
|
|
195
|
+
const rawUses = Number(fields.get('uses') ?? '0');
|
|
196
|
+
const appliesTo = fields.get('appliesto');
|
|
197
|
+
const durability = toMemoryDurability(fields.get('durability'));
|
|
198
|
+
const asOf = parseTime(fields.get('asof'), 0);
|
|
199
|
+
const pinned = fields.get('pinned') === 'true';
|
|
200
|
+
const permanent = fields.get('permanent') === 'true';
|
|
201
|
+
const voice = fields.get('voice') === 'user' ? 'user' : undefined;
|
|
202
|
+
const supersedes = fields.get('supersedes');
|
|
203
|
+
const sourceSession = fields.get('session');
|
|
204
|
+
const quote = fields.get('quote');
|
|
205
|
+
const rawEvidenceSeq = Number(fields.get('evidenceseq') ?? '0');
|
|
206
|
+
const evidenceSeq = Number.isFinite(rawEvidenceSeq) && rawEvidenceSeq > 0 ? Math.trunc(rawEvidenceSeq) : undefined;
|
|
207
|
+
// A list of ids in one comma-separated line, the same shape `tags` and `keys`
|
|
208
|
+
// use; an entry written before the field existed simply has none.
|
|
209
|
+
const derivedFrom = (fields.get('derivedfrom') ?? '').split(',').map((value) => value.trim()).filter((value) => value.length > 0);
|
|
210
|
+
const keys = (fields.get('keys') ?? '').split(',').map(normalizeKey).filter((key) => key.length > 0);
|
|
211
|
+
return {
|
|
212
|
+
id: fields.get('id') ?? fallbackId,
|
|
213
|
+
scope,
|
|
214
|
+
// An entry written before kinds existed is a plain fact; the schema grew
|
|
215
|
+
// without a migration because the default is the old behaviour.
|
|
216
|
+
kind: toMemoryKind(fields.get('kind')),
|
|
217
|
+
title,
|
|
218
|
+
body,
|
|
219
|
+
tags: (fields.get('tags') ?? '').split(',').map(normalizeTag).filter((tag) => tag.length > 0),
|
|
220
|
+
keys,
|
|
221
|
+
...appliesTo !== undefined && appliesTo.length > 0 ? { appliesTo } : {},
|
|
222
|
+
...durability === 'snapshot' ? { durability, ...asOf > 0 ? { asOf } : {} } : {},
|
|
223
|
+
...pinned ? { pinned: true } : {},
|
|
224
|
+
...permanent ? { permanent: true } : {},
|
|
225
|
+
...voice === undefined ? {} : { voice },
|
|
226
|
+
...supersedes !== undefined && supersedes.length > 0 ? { supersedes } : {},
|
|
227
|
+
...sourceSession !== undefined && sourceSession.length > 0 ? { sourceSession } : {},
|
|
228
|
+
...quote !== undefined && quote.length > 0 ? { quote } : {},
|
|
229
|
+
...evidenceSeq !== undefined ? { evidenceSeq } : {},
|
|
230
|
+
...derivedFrom.length > 0 ? { derivedFrom } : {},
|
|
231
|
+
createdAt: parseTime(fields.get('created'), updatedAt),
|
|
232
|
+
updatedAt,
|
|
233
|
+
uses: Number.isFinite(rawUses) && rawUses > 0 ? Math.trunc(rawUses) : 0,
|
|
234
|
+
lastUsedAt: parseTime(fields.get('lastused'), 0),
|
|
235
|
+
lastSurfacedAt: parseTime(fields.get('lastsurfaced'), 0),
|
|
236
|
+
source,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Normalize one search key: lowercase, comma-free, length-capped.
|
|
241
|
+
*
|
|
242
|
+
* Keys are the aliases and keyphrases a memory should also be found by, so they
|
|
243
|
+
* are stored comma-separated beside the tags and matched by the same scorer.
|
|
244
|
+
* @param value - the raw key.
|
|
245
|
+
* @returns the normalized key.
|
|
246
|
+
*/
|
|
247
|
+
export function normalizeKey(value) {
|
|
248
|
+
return value.trim().toLowerCase().replace(/[,\s]+/gu, ' ').trim().slice(0, 48);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Split text into a token set for similarity comparison.
|
|
252
|
+
*
|
|
253
|
+
* Single-character tokens are kept, deliberately. Dropping them is tempting —
|
|
254
|
+
* "a", "1", "9" all look like noise — but they are exactly what distinguishes
|
|
255
|
+
* two memories that share the rest of their wording, and this token set decides
|
|
256
|
+
* whether one of them gets deleted. With them gone, "Old fact 1" and "Old fact
|
|
257
|
+
* 2" both reduce to {old, fact} and are treated as one memory; measured on a
|
|
258
|
+
* real store, nine of twenty distinct numbered entries were destroyed that way,
|
|
259
|
+
* and the same shape covers "端口 3080" against "端口 8080". A missed merge costs
|
|
260
|
+
* one slot in the summary; a false merge costs nothing permanent any more,
|
|
261
|
+
* because the loser is archived rather than deleted and `/memories restore`
|
|
262
|
+
* brings it back — but a false merge still costs a slot until someone notices,
|
|
263
|
+
* so the rule stays narrow.
|
|
264
|
+
*
|
|
265
|
+
* @param value - raw text.
|
|
266
|
+
* @returns its lowercase word tokens, with CJK indexed as characters and pairs.
|
|
267
|
+
*/
|
|
268
|
+
function tokenSet(value) {
|
|
269
|
+
const tokens = new Set();
|
|
270
|
+
for (const raw of value.toLowerCase().split(/[^\p{L}\p{N}_]+/u)) {
|
|
271
|
+
if (raw.length === 0)
|
|
272
|
+
continue;
|
|
273
|
+
if (LATIN_RUN.test(raw)) {
|
|
274
|
+
tokens.add(raw);
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
// CJK has no word boundaries: index single characters and adjacent pairs, so
|
|
278
|
+
// a paraphrase still shares most of its shingles. Splitting on non-letters
|
|
279
|
+
// left a whole Chinese sentence as one enormous token, which made every pair
|
|
280
|
+
// of Chinese memories incomparable — measured on a real store, two entries
|
|
281
|
+
// with character-for-character identical titles survived as two memories
|
|
282
|
+
// because one body was Chinese and the other English.
|
|
283
|
+
const chars = [...raw];
|
|
284
|
+
for (const char of chars)
|
|
285
|
+
tokens.add(char);
|
|
286
|
+
for (let index = 0; index + 1 < chars.length; index += 1)
|
|
287
|
+
tokens.add(`${chars[index]}${chars[index + 1]}`);
|
|
288
|
+
}
|
|
289
|
+
return tokens;
|
|
290
|
+
}
|
|
291
|
+
/** A token that is already a word: Latin letters, digits, and underscores. */
|
|
292
|
+
const LATIN_RUN = /^[0-9a-z_]+$/u;
|
|
293
|
+
/** Jaccard overlap of two token sets; `0` when either side is empty. */
|
|
294
|
+
export function overlap(left, right) {
|
|
295
|
+
if (left.size === 0 || right.size === 0)
|
|
296
|
+
return 0;
|
|
297
|
+
let shared = 0;
|
|
298
|
+
for (const token of left)
|
|
299
|
+
if (right.has(token))
|
|
300
|
+
shared += 1;
|
|
301
|
+
return shared / (left.size + right.size - shared);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Whether two memories are close enough to be one memory re-worded.
|
|
305
|
+
*
|
|
306
|
+
* Both halves must agree. Titles that overlap while bodies do not are two
|
|
307
|
+
* different lessons that happen to be named alike, and collapsing those loses
|
|
308
|
+
* what no later pass can recover.
|
|
309
|
+
* @param left - one memory, or a draft.
|
|
310
|
+
* @param right - the other.
|
|
311
|
+
* @param threshold - minimum title overlap; the body must reach half of it.
|
|
312
|
+
* @returns true when the two should be treated as the same memory.
|
|
313
|
+
*/
|
|
314
|
+
export function isNearDuplicate(left, right, threshold) {
|
|
315
|
+
if (threshold <= 0)
|
|
316
|
+
return false;
|
|
317
|
+
if (overlap(tokenSet(left.title), tokenSet(right.title)) < threshold)
|
|
318
|
+
return false;
|
|
319
|
+
return overlap(tokenSet(left.body), tokenSet(right.body)) >= Math.min(0.5, threshold);
|
|
320
|
+
}
|
|
321
|
+
/** Normalize text for duplicate detection: case- and whitespace-insensitive. */
|
|
322
|
+
function fingerprint(value) {
|
|
323
|
+
return value.toLowerCase().replace(/\s+/gu, ' ').trim();
|
|
324
|
+
}
|
|
325
|
+
/** A character that is part of a Latin or digit word, for phrase boundaries. */
|
|
326
|
+
const WORD_CHAR = /[0-9a-z]/iu;
|
|
327
|
+
/**
|
|
328
|
+
* Whether one normalized field contains another as a whole phrase.
|
|
329
|
+
*
|
|
330
|
+
* A plain `includes` is wrong here, and expensively so: losers of this rule are
|
|
331
|
+
* DELETED, not archived. "Old fact 19" contains "Old fact 1", so a numbered
|
|
332
|
+
* family of memories collapses into whichever member is longest — measured on a
|
|
333
|
+
* real store, four distinct entries became two.
|
|
334
|
+
*
|
|
335
|
+
* CJK has no word boundaries, so a CJK neighbour does not block a match (記憶
|
|
336
|
+
* inside 記憶庫 is still the same phrase); a Latin or digit neighbour does.
|
|
337
|
+
*
|
|
338
|
+
* @param haystack - the normalized field, longer or shorter.
|
|
339
|
+
* @param needle - the normalized phrase to look for.
|
|
340
|
+
* @returns true when the phrase occurs with boundaries on both sides.
|
|
341
|
+
*/
|
|
342
|
+
function containsPhrase(haystack, needle) {
|
|
343
|
+
if (needle.length === 0)
|
|
344
|
+
return false;
|
|
345
|
+
for (let at = haystack.indexOf(needle); at >= 0; at = haystack.indexOf(needle, at + 1)) {
|
|
346
|
+
const before = at === 0 ? undefined : haystack[at - 1];
|
|
347
|
+
const after = haystack[at + needle.length];
|
|
348
|
+
if ((before === undefined || !WORD_CHAR.test(before)) && (after === undefined || !WORD_CHAR.test(after)))
|
|
349
|
+
return true;
|
|
350
|
+
}
|
|
351
|
+
return false;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Collapse entries that say the same thing under different ids.
|
|
355
|
+
*
|
|
356
|
+
* Ids come from titles, so a re-worded title creates a second file. Left alone
|
|
357
|
+
* the store would slowly fill with near-copies that all compete for the bounded
|
|
358
|
+
* summary budget. Two entries collide when their normalized titles are equal
|
|
359
|
+
* (regardless of body, because that is one memory written twice), when BOTH
|
|
360
|
+
* normalized title and body match, when one contains the other's title and body
|
|
361
|
+
* as phrases, or when title and body token overlap both clear `similarity` — a
|
|
362
|
+
* deliberately narrow rule, because collapsing on the body alone would merge
|
|
363
|
+
* genuinely distinct memories that share wording, and a plain substring test
|
|
364
|
+
* would swallow "Old fact 1" into "Old fact 19". The most recently updated entry
|
|
365
|
+
* wins and the losers are archived, not deleted: a judgement made without a
|
|
366
|
+
* model's help must be reversible.
|
|
367
|
+
*
|
|
368
|
+
* @param entries - entries in one scope, newest first.
|
|
369
|
+
* @param store - owning store, used to archive the losers.
|
|
370
|
+
* @param scope - the scope being deduplicated.
|
|
371
|
+
* @param projectRoot - workspace root for a project scope.
|
|
372
|
+
* @param keep - ids that must survive regardless of collisions.
|
|
373
|
+
* @param similarity - title/body token overlap above which two entries collide.
|
|
374
|
+
* @returns the surviving entries, newest first.
|
|
375
|
+
*/
|
|
376
|
+
async function dedupeEntries(entries, store, scope, projectRoot, keep, similarity) {
|
|
377
|
+
const winners = [];
|
|
378
|
+
const losers = [];
|
|
379
|
+
for (const entry of entries) {
|
|
380
|
+
const title = fingerprint(entry.title);
|
|
381
|
+
const body = fingerprint(entry.body);
|
|
382
|
+
// Two different rules live here and they deserve different trust. An equal
|
|
383
|
+
// normalized title is the same memory written twice, and merging it is the
|
|
384
|
+
// identity rule itself. Everything else is a guess about wording — phrase
|
|
385
|
+
// containment or token overlap — and a guess may only collapse the pair when
|
|
386
|
+
// the newer entry carries the older one's material forward. Without that gate
|
|
387
|
+
// a lossy rewrite archived the only copy that still had the qualifiers.
|
|
388
|
+
const exact = winners.find((candidate) => candidate.title === title);
|
|
389
|
+
const guess = exact === undefined
|
|
390
|
+
? winners.find((candidate) => (candidate.title.length > 0 && containsPhrase(title, candidate.title) && containsPhrase(body, candidate.body))
|
|
391
|
+
|| (title.length > 0 && containsPhrase(candidate.title, title) && containsPhrase(candidate.body, body))
|
|
392
|
+
|| (similarity > 0 && isNearDuplicate(entry, candidate.entry, similarity)))
|
|
393
|
+
: undefined;
|
|
394
|
+
// Whichever of the two is about to survive must carry the other's material.
|
|
395
|
+
// (The kept-id branch below can promote the older entry, so the survivor is
|
|
396
|
+
// not simply the newest one.)
|
|
397
|
+
let clash = exact;
|
|
398
|
+
if (clash === undefined && guess !== undefined) {
|
|
399
|
+
const preferEntry = keep.has(entry.id) && !keep.has(guess.entry.id);
|
|
400
|
+
const survivor = preferEntry ? entry : guess.entry;
|
|
401
|
+
const dying = preferEntry ? guess.entry : entry;
|
|
402
|
+
if (carriesForward(dying, {
|
|
403
|
+
scope: survivor.scope,
|
|
404
|
+
title: survivor.title,
|
|
405
|
+
body: survivor.body,
|
|
406
|
+
tags: survivor.tags,
|
|
407
|
+
keys: survivor.keys,
|
|
408
|
+
}))
|
|
409
|
+
clash = guess;
|
|
410
|
+
}
|
|
411
|
+
if (clash === undefined) {
|
|
412
|
+
winners.push({ title, body, entry });
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
// Entries are newest-first, so `clash` is already the newer of the two; an
|
|
416
|
+
// explicitly kept entry always outranks it.
|
|
417
|
+
if (keep.has(entry.id) && !keep.has(clash.entry.id)) {
|
|
418
|
+
losers.push(clash.entry);
|
|
419
|
+
winners.splice(winners.indexOf(clash), 1, { title, body, entry });
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
losers.push(entry);
|
|
423
|
+
}
|
|
424
|
+
if (losers.length === 0)
|
|
425
|
+
return [...entries];
|
|
426
|
+
for (const loser of losers) {
|
|
427
|
+
// Archived rather than removed: this pass runs without a model's judgement,
|
|
428
|
+
// and a wrong call must stay recoverable with `/memories restore`. Removal is
|
|
429
|
+
// reserved for `/memories forget`, where a person asked for it.
|
|
430
|
+
const archived = await store.archive(scope, projectRoot, loser.id, Date.now(), 'near-duplicate').catch(() => false);
|
|
431
|
+
if (!archived)
|
|
432
|
+
await rm(join(store.entriesDirOf(scope, projectRoot), `${loser.id}.md`), { force: true });
|
|
433
|
+
}
|
|
434
|
+
const dropped = new Set(losers.map((loser) => loser.id));
|
|
435
|
+
return entries.filter((entry) => !dropped.has(entry.id));
|
|
436
|
+
}
|
|
437
|
+
/** How long a cached index is trusted before the directory is re-scanned. */
|
|
438
|
+
const INDEX_TTL_MS = 2_000;
|
|
439
|
+
/** How many per-session evidence notes the store keeps before the oldest go. */
|
|
440
|
+
export const SESSION_NOTE_LIMIT = 200;
|
|
441
|
+
/**
|
|
442
|
+
* Encode one frontmatter value as a YAML double-quoted scalar.
|
|
443
|
+
*
|
|
444
|
+
* A plain scalar breaks the document as soon as the value contains a mapping
|
|
445
|
+
* colon, a leading indicator, or a newline, and both readers here respond by
|
|
446
|
+
* ignoring the file. Quoting makes every value safe.
|
|
447
|
+
*
|
|
448
|
+
* @param value - the raw text.
|
|
449
|
+
* @returns a double-quoted YAML scalar with the escapes YAML defines.
|
|
450
|
+
*/
|
|
451
|
+
export function yamlScalar(value) {
|
|
452
|
+
return `"${value
|
|
453
|
+
.replace(/\\/gu, '\\\\')
|
|
454
|
+
.replace(/"/gu, '\\"')
|
|
455
|
+
.replace(/\r\n|\r|\n/gu, '\\n')
|
|
456
|
+
.replace(/\t/gu, '\\t')}"`;
|
|
457
|
+
}
|
|
458
|
+
/** Where per-session evidence notes live inside the memory store. */
|
|
459
|
+
export function sessionNotesDir(memoriesDir) {
|
|
460
|
+
return join(memoriesDir, 'sessions');
|
|
461
|
+
}
|
|
462
|
+
/** Read the first field of one note's frontmatter block. */
|
|
463
|
+
function noteField(header, name) {
|
|
464
|
+
for (const line of header.split('\n')) {
|
|
465
|
+
const separator = line.indexOf(':');
|
|
466
|
+
if (separator < 0)
|
|
467
|
+
continue;
|
|
468
|
+
if (line.slice(0, separator).trim().toLowerCase() !== name)
|
|
469
|
+
continue;
|
|
470
|
+
const raw = line.slice(separator + 1).trim();
|
|
471
|
+
if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) {
|
|
472
|
+
return raw.slice(1, -1)
|
|
473
|
+
.replace(/\\n/gu, '\n')
|
|
474
|
+
.replace(/\\t/gu, '\t')
|
|
475
|
+
.replace(/\\"/gu, '"')
|
|
476
|
+
.replace(/\\\\/gu, '\\');
|
|
477
|
+
}
|
|
478
|
+
return raw;
|
|
479
|
+
}
|
|
480
|
+
return undefined;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Parse one evidence note.
|
|
484
|
+
* @param text - file content.
|
|
485
|
+
* @param fallbackSession - session id derived from the file name.
|
|
486
|
+
* @returns the note, or `undefined` when the file is not a note.
|
|
487
|
+
*/
|
|
488
|
+
export function parseSessionNote(text, fallbackSession) {
|
|
489
|
+
const normalized = text.replace(/^\uFEFF/u, '');
|
|
490
|
+
if (!normalized.startsWith(FENCE))
|
|
491
|
+
return undefined;
|
|
492
|
+
const end = normalized.indexOf(`\n${FENCE}`, FENCE.length);
|
|
493
|
+
if (end < 0)
|
|
494
|
+
return undefined;
|
|
495
|
+
const header = normalized.slice(FENCE.length, end);
|
|
496
|
+
const body = normalized.slice(end + FENCE.length + 1).replace(/^\n+/u, '').trim();
|
|
497
|
+
const session = noteField(header, 'session') ?? fallbackSession;
|
|
498
|
+
const memories = (noteField(header, 'memories') ?? '').split(',').map((id) => id.trim()).filter((id) => id.length > 0);
|
|
499
|
+
const project = noteField(header, 'project');
|
|
500
|
+
return {
|
|
501
|
+
session,
|
|
502
|
+
at: parseTime(noteField(header, 'at'), 0),
|
|
503
|
+
...project === undefined || project.length === 0 ? {} : { project },
|
|
504
|
+
summary: body,
|
|
505
|
+
memories,
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* A memory store rooted at one harness home.
|
|
510
|
+
*
|
|
511
|
+
* Reads are cached for {@link INDEX_TTL_MS}; writes invalidate the owning scope
|
|
512
|
+
* immediately. Every method is safe to call concurrently: entry writes are
|
|
513
|
+
* atomic and the index is a rebuildable cache.
|
|
514
|
+
*/
|
|
515
|
+
/** Path-shaped runs in a body: what a later reader is meant to be able to check. */
|
|
516
|
+
const CITATION_PATTERN = /(?:[A-Za-z]:\\|~?\/)[^\s'"`)]+/gu;
|
|
517
|
+
/**
|
|
518
|
+
* Count the file paths a body cites.
|
|
519
|
+
* @param text - the body.
|
|
520
|
+
* @returns how many path-shaped runs it contains.
|
|
521
|
+
*/
|
|
522
|
+
function citationCount(text) {
|
|
523
|
+
return (text.match(CITATION_PATTERN) ?? []).length;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Whether a near-duplicate rewrite still carries the material it replaces.
|
|
527
|
+
*
|
|
528
|
+
* Conservative on purpose: refusing to supersede costs one extra entry for the
|
|
529
|
+
* consolidation pass to fold, while superseding wrongly destroys the only copy
|
|
530
|
+
* of a qualifier. A rewrite may therefore lose no citation, no length, no tag and
|
|
531
|
+
* no key.
|
|
532
|
+
*
|
|
533
|
+
* @param previous - the entry the implicit match proposes to replace.
|
|
534
|
+
* @param draft - the incoming rewrite.
|
|
535
|
+
* @returns true when the rewrite is a superset of what it replaces.
|
|
536
|
+
*/
|
|
537
|
+
export function carriesForward(previous, draft) {
|
|
538
|
+
if (citationCount(draft.body) < citationCount(previous.body))
|
|
539
|
+
return false;
|
|
540
|
+
if (draft.body.trim().length < previous.body.trim().length)
|
|
541
|
+
return false;
|
|
542
|
+
const tags = new Set(draft.tags.map((tag) => tag.toLowerCase()));
|
|
543
|
+
for (const tag of previous.tags)
|
|
544
|
+
if (!tags.has(tag.toLowerCase()))
|
|
545
|
+
return false;
|
|
546
|
+
const keys = new Set((draft.keys ?? []).map((key) => key.toLowerCase()));
|
|
547
|
+
for (const key of previous.keys)
|
|
548
|
+
if (!keys.has(key.toLowerCase()))
|
|
549
|
+
return false;
|
|
550
|
+
return true;
|
|
551
|
+
}
|
|
552
|
+
export class MemoryStore {
|
|
553
|
+
memoriesDir;
|
|
554
|
+
cache = new Map();
|
|
555
|
+
pending = new Map();
|
|
556
|
+
constructor(memoriesDir) {
|
|
557
|
+
this.memoriesDir = resolve(memoriesDir);
|
|
558
|
+
}
|
|
559
|
+
/** Absolute directory of one scope. */
|
|
560
|
+
scopeDir(scope, projectRoot) {
|
|
561
|
+
if (scope === 'global')
|
|
562
|
+
return this.memoriesDir;
|
|
563
|
+
if (projectRoot === undefined)
|
|
564
|
+
throw new Error('dsh-cross-memory: a project scope requires a workspace root');
|
|
565
|
+
return join(this.memoriesDir, 'projects', projectSlug(projectRoot));
|
|
566
|
+
}
|
|
567
|
+
/** Entries directory of one scope (public for the dedupe helper). */
|
|
568
|
+
entriesDirOf(scope, projectRoot) {
|
|
569
|
+
return this.entriesDir(scope, projectRoot);
|
|
570
|
+
}
|
|
571
|
+
/** Entries directory of one scope. */
|
|
572
|
+
entriesDir(scope, projectRoot) {
|
|
573
|
+
return join(this.scopeDir(scope, projectRoot), 'entries');
|
|
574
|
+
}
|
|
575
|
+
/** Index path of one scope. */
|
|
576
|
+
indexPath(scope, projectRoot) {
|
|
577
|
+
return join(this.scopeDir(scope, projectRoot), 'index.json');
|
|
578
|
+
}
|
|
579
|
+
/** Resolve the model-facing target for one scope. */
|
|
580
|
+
target(scope, projectRoot) {
|
|
581
|
+
const dir = this.scopeDir(scope, projectRoot);
|
|
582
|
+
const label = scope === 'global'
|
|
583
|
+
? 'global'
|
|
584
|
+
: `project:${projectRoot === undefined ? 'unknown' : slugify(projectRoot.replace(/[\\/]+$/u, '').split(/[\\/]/u).pop() ?? 'workspace')}`;
|
|
585
|
+
return { scope, dir, label };
|
|
586
|
+
}
|
|
587
|
+
/** Record how one project slug was derived, for diagnostics. */
|
|
588
|
+
async writeProjectDescriptor(projectRoot, now = Date.now()) {
|
|
589
|
+
const slug = projectSlug(projectRoot);
|
|
590
|
+
const name = projectRoot.replace(/[\\/]+$/u, '').split(/[\\/]/u).pop() ?? 'workspace';
|
|
591
|
+
// The origin is diagnostic evidence, not a reason to fail a memory write: an
|
|
592
|
+
// unreadable or unusual checkout simply records no origin.
|
|
593
|
+
const origin = await gitOrigin(projectRoot).catch(() => undefined);
|
|
594
|
+
const descriptor = {
|
|
595
|
+
root: resolve(projectRoot),
|
|
596
|
+
name,
|
|
597
|
+
slug,
|
|
598
|
+
updatedAt: now,
|
|
599
|
+
...origin === undefined ? {} : { origin },
|
|
600
|
+
};
|
|
601
|
+
await writeAtomic(join(this.memoriesDir, 'projects', slug, 'project.json'), `${JSON.stringify(descriptor, undefined, 2)}\n`);
|
|
602
|
+
await this.writeHostDescriptor(slug, projectRoot, now).catch(() => undefined);
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* Record that this machine uses one project directory.
|
|
606
|
+
*
|
|
607
|
+
* One file per host (`hosts/<hostname>.json`) rather than one shared file: the
|
|
608
|
+
* store is synced between machines, and a single descriptor rewritten by both
|
|
609
|
+
* would make every sync a conflict over fields neither party changed.
|
|
610
|
+
*
|
|
611
|
+
* @param slug - project slug, the directory the file lives under.
|
|
612
|
+
* @param projectRoot - this machine's checkout of that project.
|
|
613
|
+
* @param now - write time.
|
|
614
|
+
*/
|
|
615
|
+
async writeHostDescriptor(slug, projectRoot, now = Date.now()) {
|
|
616
|
+
const dir = join(this.memoriesDir, 'projects', slug, 'hosts');
|
|
617
|
+
const file = join(dir, `${slugify(hostname())}.json`);
|
|
618
|
+
let firstSeen = now;
|
|
619
|
+
try {
|
|
620
|
+
const existing = JSON.parse(await readFile(file, 'utf8'));
|
|
621
|
+
if (typeof existing.firstSeen === 'number')
|
|
622
|
+
firstSeen = existing.firstSeen;
|
|
623
|
+
}
|
|
624
|
+
catch {
|
|
625
|
+
// first write on this machine
|
|
626
|
+
}
|
|
627
|
+
const origin = await gitOrigin(projectRoot).catch(() => undefined);
|
|
628
|
+
const descriptor = {
|
|
629
|
+
host: hostname(),
|
|
630
|
+
platform: process.platform,
|
|
631
|
+
root: resolve(projectRoot),
|
|
632
|
+
firstSeen,
|
|
633
|
+
lastSeen: now,
|
|
634
|
+
...origin === undefined ? {} : { origin },
|
|
635
|
+
};
|
|
636
|
+
await mkdir(dir, { recursive: true });
|
|
637
|
+
await writeAtomic(file, `${JSON.stringify(descriptor, undefined, 2)}\n`);
|
|
638
|
+
}
|
|
639
|
+
/** Every host that has used one project slug, newest write first. */
|
|
640
|
+
async listHostDescriptors(slug) {
|
|
641
|
+
const dir = join(this.memoriesDir, 'projects', slug, 'hosts');
|
|
642
|
+
let names;
|
|
643
|
+
try {
|
|
644
|
+
names = (await readdir(dir)).filter((name) => name.endsWith('.json'));
|
|
645
|
+
}
|
|
646
|
+
catch {
|
|
647
|
+
return [];
|
|
648
|
+
}
|
|
649
|
+
const hosts = [];
|
|
650
|
+
for (const name of names) {
|
|
651
|
+
try {
|
|
652
|
+
hosts.push(JSON.parse(await readFile(join(dir, name), 'utf8')));
|
|
653
|
+
}
|
|
654
|
+
catch {
|
|
655
|
+
// unreadable host file: absence is honest, a fabricated root is not
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return hosts.sort((a, b) => b.lastSeen - a.lastSeen);
|
|
659
|
+
}
|
|
660
|
+
/** Read a project descriptor, when present. */
|
|
661
|
+
async readProjectDescriptor(slug) {
|
|
662
|
+
const text = await readText(join(this.memoriesDir, 'projects', slug, 'project.json'));
|
|
663
|
+
if (text === undefined)
|
|
664
|
+
return undefined;
|
|
665
|
+
try {
|
|
666
|
+
return JSON.parse(text);
|
|
667
|
+
}
|
|
668
|
+
catch {
|
|
669
|
+
return undefined;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
/** List every project slug present on disk. */
|
|
673
|
+
async listProjects() {
|
|
674
|
+
try {
|
|
675
|
+
const dirents = await readdir(join(this.memoriesDir, 'projects'), { withFileTypes: true });
|
|
676
|
+
return dirents.filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name).sort();
|
|
677
|
+
}
|
|
678
|
+
catch (error) {
|
|
679
|
+
if (isMissing(error))
|
|
680
|
+
return [];
|
|
681
|
+
throw error;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Every distinct repository origin recorded for one project slug.
|
|
686
|
+
*
|
|
687
|
+
* The canonical descriptor and each machine's host file are merged because no
|
|
688
|
+
* single one of them is authoritative across machines: `project.json` is
|
|
689
|
+
* rewritten by whichever checkout wrote last, while `hosts/<hostname>.json`
|
|
690
|
+
* keeps one machine's view and is never overwritten by another machine.
|
|
691
|
+
* A directory that was never a git checkout records nothing and yields `[]`.
|
|
692
|
+
*
|
|
693
|
+
* @param slug - project slug directory.
|
|
694
|
+
* @returns the distinct non-empty origins, sorted for a stable report.
|
|
695
|
+
*/
|
|
696
|
+
async projectOrigins(slug) {
|
|
697
|
+
const origins = new Set();
|
|
698
|
+
const descriptor = await this.readProjectDescriptor(slug);
|
|
699
|
+
if (typeof descriptor?.origin === 'string' && descriptor.origin.length > 0)
|
|
700
|
+
origins.add(descriptor.origin);
|
|
701
|
+
for (const host of await this.listHostDescriptors(slug)) {
|
|
702
|
+
if (typeof host.origin === 'string' && host.origin.length > 0)
|
|
703
|
+
origins.add(host.origin);
|
|
704
|
+
}
|
|
705
|
+
return [...origins].sort();
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* Report every project slug that two different repositories share.
|
|
709
|
+
*
|
|
710
|
+
* {@link projectSlug} keys a project by its name, so `<a>/alpha` and
|
|
711
|
+
* `<b>/alpha` share `projects/alpha` and their memories are silently merged.
|
|
712
|
+
* Two recorded origins are the proof of that collision; one origin (or none,
|
|
713
|
+
* for a non-checkout) is a project used from several roots, which is the
|
|
714
|
+
* normal case and is not reported.
|
|
715
|
+
*
|
|
716
|
+
* @returns one row per conflicting slug, sorted by slug.
|
|
717
|
+
*/
|
|
718
|
+
async originConflicts() {
|
|
719
|
+
const conflicts = [];
|
|
720
|
+
for (const slug of await this.listProjects()) {
|
|
721
|
+
const origins = await this.projectOrigins(slug);
|
|
722
|
+
if (origins.length >= 2)
|
|
723
|
+
conflicts.push({ slug, origins });
|
|
724
|
+
}
|
|
725
|
+
return conflicts;
|
|
726
|
+
}
|
|
727
|
+
/** Drop the cached index of one scope. */
|
|
728
|
+
invalidate(scope, projectRoot) {
|
|
729
|
+
this.cache.delete(this.scopeDir(scope, projectRoot));
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Delete project directories that hold nothing recoverable.
|
|
733
|
+
*
|
|
734
|
+
* A workspace that is renamed, moved, or simply never produces a memory leaves
|
|
735
|
+
* its slug behind: measured on a real store, 12 of 19 project directories were
|
|
736
|
+
* empty and 6 of those had no descriptor at all — one workspace even existed
|
|
737
|
+
* under two slugs, its memories split between them.
|
|
738
|
+
*
|
|
739
|
+
* The test is "no markdown anywhere under the directory", which covers entries,
|
|
740
|
+
* archives, and anything a future version files there. An archive alone is
|
|
741
|
+
* enough to keep the directory: that is the file a human would restore from.
|
|
742
|
+
* Recreating a slug is free, because it is derived from the workspace path, so
|
|
743
|
+
* deleting an empty one cannot lose anything that a later write would not
|
|
744
|
+
* recreate.
|
|
745
|
+
*
|
|
746
|
+
* @returns the slugs that were removed, for the caller to report.
|
|
747
|
+
*/
|
|
748
|
+
async pruneEmptyProjects() {
|
|
749
|
+
const removed = [];
|
|
750
|
+
for (const slug of await this.listProjects()) {
|
|
751
|
+
const dir = join(this.memoriesDir, 'projects', slug);
|
|
752
|
+
let files;
|
|
753
|
+
try {
|
|
754
|
+
const dirents = await readdir(dir, { recursive: true, withFileTypes: true });
|
|
755
|
+
files = dirents.filter((dirent) => dirent.isFile()).map((dirent) => dirent.name);
|
|
756
|
+
}
|
|
757
|
+
catch (error) {
|
|
758
|
+
if (isMissing(error))
|
|
759
|
+
continue;
|
|
760
|
+
throw error;
|
|
761
|
+
}
|
|
762
|
+
if (files.some((name) => name.endsWith('.md')))
|
|
763
|
+
continue;
|
|
764
|
+
try {
|
|
765
|
+
await rm(dir, { recursive: true, force: true });
|
|
766
|
+
}
|
|
767
|
+
catch {
|
|
768
|
+
// A directory another process is holding open is reported as kept, not as
|
|
769
|
+
// pruned: this count is the only thing a reader sees, and a sweep that
|
|
770
|
+
// claims work it did not do is worse than one that does nothing.
|
|
771
|
+
continue;
|
|
772
|
+
}
|
|
773
|
+
this.cache.delete(dir);
|
|
774
|
+
removed.push(slug);
|
|
775
|
+
}
|
|
776
|
+
return removed;
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Move every project scope whose directory name is not the slug its own root
|
|
780
|
+
* derives onto the canonical directory, merging entries when both exist.
|
|
781
|
+
*
|
|
782
|
+
* Two reasons a misspelled directory appears, and the second is the common one:
|
|
783
|
+
*
|
|
784
|
+
* 1. A slug derived by an older scheme. Before 0.2.1 the slug carried a hash of
|
|
785
|
+
* the resolved path, so the same project checked out at two paths wrote two
|
|
786
|
+
* directories.
|
|
787
|
+
* 2. The same project on two machines. The slug is now the project name, so the
|
|
788
|
+
* directories converge — and the first device to see the other's copy merges
|
|
789
|
+
* them here.
|
|
790
|
+
*
|
|
791
|
+
* Merging is safe because an entry is one memory identified by its id: the same
|
|
792
|
+
* id in both directories is the same memory with two revisions, so the newer
|
|
793
|
+
* `updated` wins and the older text is simply dropped (it stays in the git
|
|
794
|
+
* history of the synced store). `index.json` is a rebuildable cache and is not
|
|
795
|
+
* copied.
|
|
796
|
+
*
|
|
797
|
+
* @returns the slug pairs that were re-homed, for the caller to report.
|
|
798
|
+
*/
|
|
799
|
+
async adoptMisnamedProjects() {
|
|
800
|
+
const moved = [];
|
|
801
|
+
for (const slug of await this.listProjects()) {
|
|
802
|
+
const dir = join(this.memoriesDir, 'projects', slug);
|
|
803
|
+
let descriptor;
|
|
804
|
+
try {
|
|
805
|
+
descriptor = JSON.parse(await readFile(join(dir, 'project.json'), 'utf8'));
|
|
806
|
+
}
|
|
807
|
+
catch {
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
if (typeof descriptor.root !== 'string' || descriptor.root.length === 0)
|
|
811
|
+
continue;
|
|
812
|
+
const canonical = projectSlug(descriptor.root);
|
|
813
|
+
if (canonical === slug)
|
|
814
|
+
continue;
|
|
815
|
+
const target = join(this.memoriesDir, 'projects', canonical);
|
|
816
|
+
try {
|
|
817
|
+
await mkdir(target, { recursive: true });
|
|
818
|
+
const dirents = await readdir(dir, { recursive: true, withFileTypes: true });
|
|
819
|
+
for (const dirent of dirents) {
|
|
820
|
+
if (!dirent.isFile())
|
|
821
|
+
continue;
|
|
822
|
+
const from = join(dirent.parentPath, dirent.name);
|
|
823
|
+
const rel = relative(dir, from);
|
|
824
|
+
if (rel === 'index.json')
|
|
825
|
+
continue;
|
|
826
|
+
const to = join(target, rel);
|
|
827
|
+
if (rel === 'project.json') {
|
|
828
|
+
// Keep the canonical descriptor when one exists: its root is the path
|
|
829
|
+
// this machine actually resolves, and either root derives the same slug.
|
|
830
|
+
if (!(await exists(to))) {
|
|
831
|
+
await mkdir(dirname(to), { recursive: true });
|
|
832
|
+
await rename(from, to);
|
|
833
|
+
}
|
|
834
|
+
continue;
|
|
835
|
+
}
|
|
836
|
+
if (!(await exists(to))) {
|
|
837
|
+
await mkdir(dirname(to), { recursive: true });
|
|
838
|
+
await rename(from, to);
|
|
839
|
+
continue;
|
|
840
|
+
}
|
|
841
|
+
// Same file on both sides: for entries keep the newer revision.
|
|
842
|
+
if (!rel.startsWith('entries' + sep) || !rel.endsWith('.md'))
|
|
843
|
+
continue;
|
|
844
|
+
const incoming = await this.entryTimeOf(from);
|
|
845
|
+
const existing = await this.entryTimeOf(to);
|
|
846
|
+
if (incoming > existing)
|
|
847
|
+
await rename(from, to);
|
|
848
|
+
}
|
|
849
|
+
await rm(dir, { recursive: true, force: true });
|
|
850
|
+
}
|
|
851
|
+
catch {
|
|
852
|
+
// A directory another process holds open stays where it is and is simply
|
|
853
|
+
// not reported: a sweep that claims work it did not do is worse than one
|
|
854
|
+
// that does nothing.
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
this.cache.delete(dir);
|
|
858
|
+
this.cache.delete(target);
|
|
859
|
+
moved.push({ from: slug, to: canonical });
|
|
860
|
+
}
|
|
861
|
+
return moved;
|
|
862
|
+
}
|
|
863
|
+
/** The `updated` stamp of one entry file, or its mtime when it has none. */
|
|
864
|
+
async entryTimeOf(file) {
|
|
865
|
+
const text = await readText(file);
|
|
866
|
+
if (text !== undefined) {
|
|
867
|
+
const entry = parseEntry(text, 'project', basename(file, '.md'));
|
|
868
|
+
if (entry !== undefined && Number.isFinite(entry.updatedAt))
|
|
869
|
+
return entry.updatedAt;
|
|
870
|
+
}
|
|
871
|
+
try {
|
|
872
|
+
return (await stat(file)).mtimeMs;
|
|
873
|
+
}
|
|
874
|
+
catch {
|
|
875
|
+
return 0;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* List one scope's entries, newest-updated first. The on-disk `index.json` is
|
|
880
|
+
* preferred while it agrees with the directory's file count; otherwise the
|
|
881
|
+
* directory is re-scanned and the index rewritten.
|
|
882
|
+
* @param scope - scope to read.
|
|
883
|
+
* @param projectRoot - workspace root for a project scope.
|
|
884
|
+
* @param options - `fresh` bypasses the in-memory cache.
|
|
885
|
+
* @returns every parsed entry in the scope.
|
|
886
|
+
*/
|
|
887
|
+
async list(scope, projectRoot, options = {}) {
|
|
888
|
+
const dir = this.scopeDir(scope, projectRoot);
|
|
889
|
+
if (options.fresh !== true) {
|
|
890
|
+
const cached = this.cache.get(dir);
|
|
891
|
+
if (cached !== undefined && Date.now() - cached.loadedAt < INDEX_TTL_MS)
|
|
892
|
+
return cached.entries;
|
|
893
|
+
const inflight = this.pending.get(dir);
|
|
894
|
+
if (inflight !== undefined)
|
|
895
|
+
return inflight;
|
|
896
|
+
}
|
|
897
|
+
const load = this.load(scope, projectRoot).finally(() => this.pending.delete(dir));
|
|
898
|
+
this.pending.set(dir, load);
|
|
899
|
+
return load;
|
|
900
|
+
}
|
|
901
|
+
/** Scan one scope directory and refresh both the cache and the index file. */
|
|
902
|
+
async load(scope, projectRoot) {
|
|
903
|
+
const dir = this.scopeDir(scope, projectRoot);
|
|
904
|
+
const entriesDir = this.entriesDir(scope, projectRoot);
|
|
905
|
+
let names;
|
|
906
|
+
try {
|
|
907
|
+
const dirents = await readdir(entriesDir, { withFileTypes: true });
|
|
908
|
+
names = dirents.filter((dirent) => dirent.isFile() && dirent.name.endsWith('.md')).map((dirent) => dirent.name);
|
|
909
|
+
}
|
|
910
|
+
catch (error) {
|
|
911
|
+
if (!isMissing(error))
|
|
912
|
+
throw error;
|
|
913
|
+
names = [];
|
|
914
|
+
}
|
|
915
|
+
const entries = [];
|
|
916
|
+
for (const name of names.sort()) {
|
|
917
|
+
const text = await readText(join(entriesDir, name));
|
|
918
|
+
if (text === undefined)
|
|
919
|
+
continue;
|
|
920
|
+
const entry = parseEntry(text, scope, name.replace(/\.md$/u, ''));
|
|
921
|
+
if (entry !== undefined)
|
|
922
|
+
entries.push(entry);
|
|
923
|
+
}
|
|
924
|
+
entries.sort((left, right) => right.updatedAt - left.updatedAt || left.id.localeCompare(right.id));
|
|
925
|
+
const deduped = await dedupeEntries(entries, this, scope, projectRoot, this.keepIds, this.similarityLimit());
|
|
926
|
+
this.cache.set(dir, { entries: deduped, loadedAt: Date.now() });
|
|
927
|
+
await this.writeIndex(scope, projectRoot, deduped).catch(() => undefined);
|
|
928
|
+
return deduped;
|
|
929
|
+
}
|
|
930
|
+
/** Rewrite one scope's index cache file. */
|
|
931
|
+
async writeIndex(scope, projectRoot, entries) {
|
|
932
|
+
const document = {
|
|
933
|
+
version: 1,
|
|
934
|
+
scope,
|
|
935
|
+
updatedAt: new Date().toISOString(),
|
|
936
|
+
count: entries.length,
|
|
937
|
+
entries: entries.map((entry) => ({
|
|
938
|
+
id: entry.id,
|
|
939
|
+
kind: entry.kind,
|
|
940
|
+
title: entry.title,
|
|
941
|
+
tags: entry.tags,
|
|
942
|
+
...entry.appliesTo === undefined ? {} : { appliesTo: entry.appliesTo },
|
|
943
|
+
...entry.durability === 'snapshot' ? { durability: entry.durability, ...entry.asOf === undefined ? {} : { asOf: entry.asOf } } : {},
|
|
944
|
+
...entry.pinned === true ? { pinned: true } : {},
|
|
945
|
+
...entry.permanent === true ? { permanent: true } : {},
|
|
946
|
+
...entry.voice === undefined ? {} : { voice: entry.voice },
|
|
947
|
+
...entry.supersedes === undefined ? {} : { supersedes: entry.supersedes },
|
|
948
|
+
createdAt: entry.createdAt,
|
|
949
|
+
updatedAt: entry.updatedAt,
|
|
950
|
+
uses: entry.uses,
|
|
951
|
+
lastUsedAt: entry.lastUsedAt,
|
|
952
|
+
source: entry.source,
|
|
953
|
+
bytes: Buffer.byteLength(entry.body, 'utf8'),
|
|
954
|
+
})),
|
|
955
|
+
};
|
|
956
|
+
await writeAtomic(this.indexPath(scope, projectRoot), `${JSON.stringify(document, undefined, 2)}\n`);
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* Path of one entry file, tolerating ids a slug cannot round-trip.
|
|
960
|
+
*
|
|
961
|
+
* An id is a slugified title, but a collision suffix can leave a trailing `-`
|
|
962
|
+
* that {@link slugify} strips on the way back in. For such an id the canonical
|
|
963
|
+
* `<slugify(id)>.md` spelling does not exist on disk, so every id-addressed
|
|
964
|
+
* operation — read, remove, archive, restore — silently misses it. Measured on
|
|
965
|
+
* a real store, two entries were unreachable that way (one of them a duplicate
|
|
966
|
+
* that could not be archived). The exact name wins whenever it is present.
|
|
967
|
+
*
|
|
968
|
+
* @param scope - owning scope.
|
|
969
|
+
* @param projectRoot - workspace root for a project scope.
|
|
970
|
+
* @param id - entry id as stored.
|
|
971
|
+
* @returns the path to read or write.
|
|
972
|
+
*/
|
|
973
|
+
async entryFile(scope, projectRoot, id) {
|
|
974
|
+
const dir = this.entriesDir(scope, projectRoot);
|
|
975
|
+
const canonical = `${slugify(id)}.md`;
|
|
976
|
+
if (`${id}.md` === canonical)
|
|
977
|
+
return join(dir, canonical);
|
|
978
|
+
const exact = join(dir, `${id}.md`);
|
|
979
|
+
return await exists(exact) ? exact : join(dir, canonical);
|
|
980
|
+
}
|
|
981
|
+
/** Read one entry by id. */
|
|
982
|
+
async read(scope, projectRoot, id) {
|
|
983
|
+
const text = await readText(await this.entryFile(scope, projectRoot, id));
|
|
984
|
+
if (text === undefined)
|
|
985
|
+
return undefined;
|
|
986
|
+
return parseEntry(text, scope, slugify(id));
|
|
987
|
+
}
|
|
988
|
+
/**
|
|
989
|
+
* Mirror usage counters into the entry file.
|
|
990
|
+
*
|
|
991
|
+
* The authoritative counter lives in the state database, which updates it
|
|
992
|
+
* atomically; this write only keeps the markdown a complete picture for a
|
|
993
|
+
* human reader. Deliberately best-effort: a failed mirror never fails the
|
|
994
|
+
* caller's read.
|
|
995
|
+
* @param entry - the entry that was used.
|
|
996
|
+
* @param projectRoot - workspace root for a project entry.
|
|
997
|
+
* @param counters - the counters the state store just committed.
|
|
998
|
+
* @returns the updated entry, or the original when the write failed.
|
|
999
|
+
*/
|
|
1000
|
+
async writeCounters(entry, projectRoot, counters) {
|
|
1001
|
+
const updated = {
|
|
1002
|
+
...entry,
|
|
1003
|
+
uses: counters.uses,
|
|
1004
|
+
lastUsedAt: counters.lastUsedAt,
|
|
1005
|
+
// A caller that mirrors only read counters must not erase a newer
|
|
1006
|
+
// surfaced mark.
|
|
1007
|
+
lastSurfacedAt: counters.surfacedAt ?? entry.lastSurfacedAt,
|
|
1008
|
+
};
|
|
1009
|
+
try {
|
|
1010
|
+
await writeAtomic(await this.entryFile(entry.scope, projectRoot, entry.id), formatEntry(updated));
|
|
1011
|
+
this.invalidate(entry.scope, projectRoot);
|
|
1012
|
+
}
|
|
1013
|
+
catch {
|
|
1014
|
+
return entry;
|
|
1015
|
+
}
|
|
1016
|
+
return updated;
|
|
1017
|
+
}
|
|
1018
|
+
/**
|
|
1019
|
+
* Insert or update one draft. The id is derived from the title, so writing
|
|
1020
|
+
* the same lesson twice updates the stored entry and preserves `createdAt`.
|
|
1021
|
+
* @param draft - the memory to persist.
|
|
1022
|
+
* @param projectRoot - workspace root for a project draft.
|
|
1023
|
+
* @param source - provenance recorded on the entry.
|
|
1024
|
+
* @param now - injected clock for deterministic tests.
|
|
1025
|
+
* @param keepId - write over this exact id instead of deriving one from the
|
|
1026
|
+
* title; used by consolidation, where a rewritten memory keeps its identity.
|
|
1027
|
+
* @returns the stored entry and whether it was created or updated.
|
|
1028
|
+
*/
|
|
1029
|
+
async upsert(draft, projectRoot, source, now = Date.now(), keepId) {
|
|
1030
|
+
const id = slugify(keepId ?? draft.title);
|
|
1031
|
+
// Look the entry up by the id the caller gave, not by its slug: a `keepId`
|
|
1032
|
+
// that ends in `-` names a file whose slug is a different string, and
|
|
1033
|
+
// slugifying first would miss the file that is actually there.
|
|
1034
|
+
const existing = await this.read(draft.scope, projectRoot, keepId ?? id);
|
|
1035
|
+
// A rewrite keeps the file it already lives in. Writing `${id}.md` blindly
|
|
1036
|
+
// would put a second file beside an id whose name a slug cannot round-trip
|
|
1037
|
+
// (a trailing `-`), turning an update into a duplicate.
|
|
1038
|
+
const target = keepId === undefined || existing === undefined
|
|
1039
|
+
? join(this.entriesDir(draft.scope, projectRoot), `${id}.md`)
|
|
1040
|
+
: await this.entryFile(draft.scope, projectRoot, keepId);
|
|
1041
|
+
const tags = [...new Set(draft.tags.map(normalizeTag).filter((tag) => tag.length > 0))].slice(0, 12);
|
|
1042
|
+
const keys = [...new Set((draft.keys ?? existing?.keys ?? []).map(normalizeKey).filter((key) => key.length > 0))].slice(0, 12);
|
|
1043
|
+
// A rewrite that omits `appliesTo` KEEPS the existing one, exactly like
|
|
1044
|
+
// `kind` and `keys`. Dropping it silently is a leak nothing downstream can
|
|
1045
|
+
// undo: measured on a real store, one background consolidation erased the
|
|
1046
|
+
// trigger phrase from 32 of 163 memories — the field that on-demand recall
|
|
1047
|
+
// gates on (recallMinTerms) — and the store cannot tell "left out" from
|
|
1048
|
+
// "meant to remove". A caller that really wants it gone can pass an empty
|
|
1049
|
+
// string, which is explicit.
|
|
1050
|
+
const appliesTo = draft.appliesTo === undefined ? existing?.appliesTo?.trim() : draft.appliesTo.trim();
|
|
1051
|
+
// Same rule as `appliesTo`: an omitted field means "unchanged". A snapshot
|
|
1052
|
+
// that a rewrite turned durable (or the reverse) has to say so explicitly,
|
|
1053
|
+
// and `durability: 'durable'` is how a caller clears it.
|
|
1054
|
+
const durability = draft.durability ?? existing?.durability ?? 'durable';
|
|
1055
|
+
const asOf = durability === 'snapshot' ? (draft.asOf ?? existing?.asOf) : undefined;
|
|
1056
|
+
const pinned = draft.pinned ?? existing?.pinned ?? false;
|
|
1057
|
+
// Same rule as `pinned`: a rewrite that does not mention permanence keeps it.
|
|
1058
|
+
const permanent = draft.permanent ?? existing?.permanent ?? false;
|
|
1059
|
+
// And whose words it is: a consolidation that re-words a memory must not
|
|
1060
|
+
// quietly turn the user's own statement into the assistant's conclusion.
|
|
1061
|
+
const voice = draft.voice ?? existing?.voice;
|
|
1062
|
+
const sourceSession = draft.sourceSession?.trim() ?? existing?.sourceSession;
|
|
1063
|
+
// The merge trail. A draft may name what it was folded from (a consolidation
|
|
1064
|
+
// does), and a supersede is itself evidence: the entry this one replaces is
|
|
1065
|
+
// one of the things it was built from. Carried through a rewrite rather than
|
|
1066
|
+
// recomputed, so re-wording a merged memory does not erase its sources, and
|
|
1067
|
+
// never allowed to name the entry itself.
|
|
1068
|
+
const derivedFrom = [...new Set([
|
|
1069
|
+
...(draft.derivedFrom ?? existing?.derivedFrom ?? []),
|
|
1070
|
+
...(draft.supersedes?.trim() !== undefined && draft.supersedes.trim().length > 0 ? [draft.supersedes.trim()] : []),
|
|
1071
|
+
])].filter((source) => source.length > 0 && source !== id);
|
|
1072
|
+
// An explicit `supersedes` always wins; otherwise a near-identical memory
|
|
1073
|
+
// already in the scope is treated as the thing this one rewrites, so a
|
|
1074
|
+
// re-worded lesson replaces its predecessor instead of joining it.
|
|
1075
|
+
const explicit = draft.supersedes?.trim();
|
|
1076
|
+
const similar = explicit !== undefined && explicit.length > 0
|
|
1077
|
+
? undefined
|
|
1078
|
+
: existing === undefined ? await this.findSimilar(draft, projectRoot, id) : undefined;
|
|
1079
|
+
// A null return means "do not treat this as a rewrite". The implicit match is
|
|
1080
|
+
// a guess about wording, and the archive it used to trigger is irreversible
|
|
1081
|
+
// from the model's side: the predecessor stops being retrievable. Measured on
|
|
1082
|
+
// the real store, one rewording turned "提交推送规矩:公开仓库直接 push,
|
|
1083
|
+
// 私有或新建仓库先问" into "提交后默认直接 push,不用再问" and the only copy
|
|
1084
|
+
// that carried the two qualifiers went to `archive/`. So the guess may only
|
|
1085
|
+
// replace its predecessor when it keeps what made it useful; otherwise both
|
|
1086
|
+
// stay and consolidation — which can read both — decides with far more context.
|
|
1087
|
+
let supersedes;
|
|
1088
|
+
if (explicit !== undefined && explicit.length > 0)
|
|
1089
|
+
supersedes = explicit;
|
|
1090
|
+
else if (similar !== undefined) {
|
|
1091
|
+
const previous = await this.read(draft.scope, projectRoot, similar);
|
|
1092
|
+
supersedes = previous !== undefined && carriesForward(previous, draft) ? similar : undefined;
|
|
1093
|
+
}
|
|
1094
|
+
// Evidence binding is tied to the exact body it supported. A draft that
|
|
1095
|
+
// carries a verified quote (automatic extraction) sets it; a rewrite that
|
|
1096
|
+
// leaves the body alone keeps the existing one; a rewrite that changes the
|
|
1097
|
+
// body drops it, because the old excerpt no longer supports the new claim.
|
|
1098
|
+
// Keeping a stale quote would be worse than having none: it would look like
|
|
1099
|
+
// proof while pointing at a sentence the entry no longer restates.
|
|
1100
|
+
const bodyChanged = existing === undefined || existing.body.trim() !== draft.body.trim();
|
|
1101
|
+
const draftQuote = draft.quote === undefined ? undefined : draft.quote.trim();
|
|
1102
|
+
const quote = draftQuote !== undefined && draftQuote.length > 0
|
|
1103
|
+
? draftQuote
|
|
1104
|
+
: existing !== undefined && !bodyChanged ? existing.quote : undefined;
|
|
1105
|
+
const evidenceSeq = draftQuote !== undefined && draftQuote.length > 0
|
|
1106
|
+
? draft.evidenceSeq
|
|
1107
|
+
: existing !== undefined && !bodyChanged ? existing.evidenceSeq : undefined;
|
|
1108
|
+
const entry = {
|
|
1109
|
+
id,
|
|
1110
|
+
scope: draft.scope,
|
|
1111
|
+
// A rewrite that omits the kind keeps the existing one rather than
|
|
1112
|
+
// silently demoting a preference to a fact.
|
|
1113
|
+
kind: draft.kind ?? existing?.kind ?? 'fact',
|
|
1114
|
+
title: draft.title.trim(),
|
|
1115
|
+
body: draft.body.trim(),
|
|
1116
|
+
tags,
|
|
1117
|
+
keys,
|
|
1118
|
+
...appliesTo !== undefined && appliesTo.length > 0 ? { appliesTo } : {},
|
|
1119
|
+
...durability === 'snapshot' ? { durability, ...asOf === undefined || asOf <= 0 ? { asOf: now } : { asOf } } : {},
|
|
1120
|
+
...pinned ? { pinned: true } : {},
|
|
1121
|
+
...permanent ? { permanent: true } : {},
|
|
1122
|
+
...voice === undefined ? {} : { voice },
|
|
1123
|
+
...supersedes !== undefined && supersedes.length > 0 ? { supersedes } : {},
|
|
1124
|
+
// Provenance survives a rewrite: a consolidation that re-words an entry
|
|
1125
|
+
// must not erase which conversation it came from.
|
|
1126
|
+
...sourceSession !== undefined && sourceSession.length > 0 ? { sourceSession } : {},
|
|
1127
|
+
...quote !== undefined && quote.length > 0 ? { quote } : {},
|
|
1128
|
+
...evidenceSeq !== undefined && evidenceSeq > 0 ? { evidenceSeq } : {},
|
|
1129
|
+
...derivedFrom.length > 0 ? { derivedFrom } : {},
|
|
1130
|
+
createdAt: existing?.createdAt ?? now,
|
|
1131
|
+
updatedAt: now,
|
|
1132
|
+
uses: existing?.uses ?? 0,
|
|
1133
|
+
lastUsedAt: existing?.lastUsedAt ?? 0,
|
|
1134
|
+
lastSurfacedAt: existing?.lastSurfacedAt ?? 0,
|
|
1135
|
+
source,
|
|
1136
|
+
};
|
|
1137
|
+
await writeAtomic(target, formatEntry(entry));
|
|
1138
|
+
if (draft.scope === 'project' && projectRoot !== undefined)
|
|
1139
|
+
await this.writeProjectDescriptor(projectRoot, now);
|
|
1140
|
+
// Honour `supersedes`: the entry this one replaces is retired, in the same
|
|
1141
|
+
// scope, unless it IS this entry (an id can never supersede itself).
|
|
1142
|
+
// ARCHIVED, not removed. The near-duplicate pass already treats its loser as
|
|
1143
|
+
// recoverable, and an explicit rewrite has no better claim to destroy a
|
|
1144
|
+
// memory outright — `/memories forget` is the only deletion a caller can ask
|
|
1145
|
+
// for. Measured: the two paths disagreed, so a re-worded memory surviving its
|
|
1146
|
+
// predecessor depended on which of the two happened to fire.
|
|
1147
|
+
if (entry.supersedes !== undefined && entry.supersedes !== id) {
|
|
1148
|
+
await this.archive(draft.scope, projectRoot, entry.supersedes, now, 'superseded').catch(() => false);
|
|
1149
|
+
}
|
|
1150
|
+
this.invalidate(draft.scope, projectRoot);
|
|
1151
|
+
const limit = this.entryLimit();
|
|
1152
|
+
if (limit > 0)
|
|
1153
|
+
await this.evict(draft.scope, projectRoot, limit);
|
|
1154
|
+
this.keepIds = new Set([id]);
|
|
1155
|
+
try {
|
|
1156
|
+
const entries = await this.list(draft.scope, projectRoot, { fresh: true });
|
|
1157
|
+
await this.writeIndex(draft.scope, projectRoot, entries).catch(() => undefined);
|
|
1158
|
+
}
|
|
1159
|
+
finally {
|
|
1160
|
+
this.keepIds = new Set();
|
|
1161
|
+
}
|
|
1162
|
+
return { entry, action: existing === undefined ? 'created' : 'updated' };
|
|
1163
|
+
}
|
|
1164
|
+
/** Delete one entry. Returns whether a file was removed. */
|
|
1165
|
+
async remove(scope, projectRoot, id) {
|
|
1166
|
+
const path = await this.entryFile(scope, projectRoot, id);
|
|
1167
|
+
if (!(await exists(path)))
|
|
1168
|
+
return false;
|
|
1169
|
+
await rm(path, { force: true });
|
|
1170
|
+
await this.reindex(scope, projectRoot);
|
|
1171
|
+
return true;
|
|
1172
|
+
}
|
|
1173
|
+
/**
|
|
1174
|
+
* Move one entry out of the live store without destroying it.
|
|
1175
|
+
*
|
|
1176
|
+
* Consolidation retires memories it judges stale and the per-scope cap
|
|
1177
|
+
* evicts the least recently updated; either judgement can be wrong. Deleting
|
|
1178
|
+
* the file would make a wrong judgement irreversible, so the entry is stamped
|
|
1179
|
+
* and moved to `archive/` beside its scope, where {@link restore} can bring it
|
|
1180
|
+
* back. The archive is bounded, so this is not an unbounded second store.
|
|
1181
|
+
*
|
|
1182
|
+
* @param scope - owning scope.
|
|
1183
|
+
* @param projectRoot - workspace root for a project scope.
|
|
1184
|
+
* @param id - entry id.
|
|
1185
|
+
* @param now - clock recorded in the archive stamp.
|
|
1186
|
+
* @returns whether an entry was archived.
|
|
1187
|
+
*/
|
|
1188
|
+
async archive(scope, projectRoot, id, now = Date.now(), reason = 'retention') {
|
|
1189
|
+
const source = await this.entryFile(scope, projectRoot, id);
|
|
1190
|
+
const text = await readText(source);
|
|
1191
|
+
if (text === undefined)
|
|
1192
|
+
return false;
|
|
1193
|
+
const stamped = text.replace(/^---\r?\n/u, `---\narchived: ${new Date(now).toISOString()}\n`);
|
|
1194
|
+
await writeAtomic(join(this.archiveDir(scope, projectRoot), `${slugify(id)}.md`), stamped);
|
|
1195
|
+
await rm(source, { force: true });
|
|
1196
|
+
await this.reindex(scope, projectRoot);
|
|
1197
|
+
await this.evictArchive(scope, projectRoot);
|
|
1198
|
+
this.reportRetire(scope, projectRoot, id, reason);
|
|
1199
|
+
return true;
|
|
1200
|
+
}
|
|
1201
|
+
/** Report one archival to the owner. A broken reporter must not undo the archival. */
|
|
1202
|
+
reportRetire(scope, projectRoot, id, reason) {
|
|
1203
|
+
try {
|
|
1204
|
+
this.onRetire?.({
|
|
1205
|
+
scope,
|
|
1206
|
+
id,
|
|
1207
|
+
reason,
|
|
1208
|
+
...projectRoot === undefined ? {} : { projectRoot },
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
catch {
|
|
1212
|
+
// Losing the log line is better than losing the write it was about.
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
/** Move one archived entry back into the live store. */
|
|
1216
|
+
async restore(scope, projectRoot, id) {
|
|
1217
|
+
const archived = join(this.archiveDir(scope, projectRoot), `${slugify(id)}.md`);
|
|
1218
|
+
const text = await readText(archived);
|
|
1219
|
+
if (text === undefined)
|
|
1220
|
+
return false;
|
|
1221
|
+
const target = join(this.entriesDir(scope, projectRoot), `${slugify(id)}.md`);
|
|
1222
|
+
if (await exists(target))
|
|
1223
|
+
return false;
|
|
1224
|
+
await writeAtomic(target, text.replace(/^(---\n)archived: [^\n]*\n/u, '$1'));
|
|
1225
|
+
await rm(archived, { force: true });
|
|
1226
|
+
await this.reindex(scope, projectRoot);
|
|
1227
|
+
return true;
|
|
1228
|
+
}
|
|
1229
|
+
/** Every archived entry in one scope, for the human-facing commands. */
|
|
1230
|
+
async listArchived(scope, projectRoot) {
|
|
1231
|
+
const dir = this.archiveDir(scope, projectRoot);
|
|
1232
|
+
let names;
|
|
1233
|
+
try {
|
|
1234
|
+
const dirents = await readdir(dir, { withFileTypes: true });
|
|
1235
|
+
names = dirents.filter((dirent) => dirent.isFile() && dirent.name.endsWith('.md')).map((dirent) => dirent.name);
|
|
1236
|
+
}
|
|
1237
|
+
catch (error) {
|
|
1238
|
+
if (isMissing(error))
|
|
1239
|
+
return [];
|
|
1240
|
+
throw error;
|
|
1241
|
+
}
|
|
1242
|
+
const entries = [];
|
|
1243
|
+
for (const name of names.sort()) {
|
|
1244
|
+
const text = await readText(join(dir, name));
|
|
1245
|
+
if (text === undefined)
|
|
1246
|
+
continue;
|
|
1247
|
+
const entry = parseEntry(text, scope, name.replace(/\.md$/u, ''));
|
|
1248
|
+
if (entry !== undefined)
|
|
1249
|
+
entries.push(entry);
|
|
1250
|
+
}
|
|
1251
|
+
return entries.sort((left, right) => left.id.localeCompare(right.id));
|
|
1252
|
+
}
|
|
1253
|
+
/** Rebuild one scope's cache and index after its entries directory changed. */
|
|
1254
|
+
async reindex(scope, projectRoot) {
|
|
1255
|
+
this.invalidate(scope, projectRoot);
|
|
1256
|
+
const entries = await this.list(scope, projectRoot, { fresh: true });
|
|
1257
|
+
await this.writeIndex(scope, projectRoot, entries).catch(() => undefined);
|
|
1258
|
+
}
|
|
1259
|
+
/** Directory holding one scope's archived entries. */
|
|
1260
|
+
archiveDir(scope, projectRoot) {
|
|
1261
|
+
return join(this.scopeDir(scope, projectRoot), 'archive');
|
|
1262
|
+
}
|
|
1263
|
+
/** Keep one scope's archive bounded: the newest 500 files survive. */
|
|
1264
|
+
async evictArchive(scope, projectRoot, limit = 500) {
|
|
1265
|
+
const dir = this.archiveDir(scope, projectRoot);
|
|
1266
|
+
let names;
|
|
1267
|
+
try {
|
|
1268
|
+
const dirents = await readdir(dir, { withFileTypes: true });
|
|
1269
|
+
names = dirents.filter((dirent) => dirent.isFile() && dirent.name.endsWith('.md')).map((dirent) => dirent.name);
|
|
1270
|
+
}
|
|
1271
|
+
catch (error) {
|
|
1272
|
+
if (isMissing(error))
|
|
1273
|
+
return;
|
|
1274
|
+
throw error;
|
|
1275
|
+
}
|
|
1276
|
+
if (names.length <= limit)
|
|
1277
|
+
return;
|
|
1278
|
+
const stamped = [];
|
|
1279
|
+
for (const name of names) {
|
|
1280
|
+
const stat_ = await stat(join(dir, name)).catch(() => undefined);
|
|
1281
|
+
stamped.push({ name, at: stat_?.mtimeMs ?? 0 });
|
|
1282
|
+
}
|
|
1283
|
+
for (const row of stamped.sort((left, right) => right.at - left.at).slice(limit)) {
|
|
1284
|
+
await rm(join(dir, row.name), { force: true });
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
/**
|
|
1288
|
+
* Enforce the per-scope cap, archiving the least recently updated entries.
|
|
1289
|
+
*
|
|
1290
|
+
* Pinned entries and entries a person wrote are skipped. Retention has always
|
|
1291
|
+
* protected both (`planRetention`), and a cap that did not would evict exactly
|
|
1292
|
+
* the rules somebody asked to keep — silently, because a cap is not a
|
|
1293
|
+
* judgement. Skipping them can leave a scope above its cap; that is the
|
|
1294
|
+
* intended trade, since the alternative is trading a person's decision for an
|
|
1295
|
+
* extractor's guess. Measured on the real store before this guard: the two
|
|
1296
|
+
* most-used pinned rules sat 29 and 33 writes away from being evicted.
|
|
1297
|
+
*/
|
|
1298
|
+
async evict(scope, projectRoot, limit) {
|
|
1299
|
+
const entries = await this.list(scope, projectRoot, { fresh: true });
|
|
1300
|
+
const excess = entries.length - limit;
|
|
1301
|
+
if (excess <= 0)
|
|
1302
|
+
return;
|
|
1303
|
+
// Oldest ATTENTION first, not oldest edit. `updatedAt` alone made the cap a
|
|
1304
|
+
// recency window: a memory sessions kept reading lost to one that merely got
|
|
1305
|
+
// rewritten, and the real store evicted entries read minutes earlier.
|
|
1306
|
+
const attention = (entry) => Math.max(entry.updatedAt, entry.lastUsedAt, entry.lastSurfacedAt);
|
|
1307
|
+
const oldestFirst = entries.slice().sort((left, right) => attention(left) - attention(right) || left.id.localeCompare(right.id));
|
|
1308
|
+
let archived = 0;
|
|
1309
|
+
for (const entry of oldestFirst) {
|
|
1310
|
+
if (archived >= excess)
|
|
1311
|
+
break;
|
|
1312
|
+
if (entry.pinned === true || entry.permanent === true || entry.source === 'user')
|
|
1313
|
+
continue;
|
|
1314
|
+
if (await this.archive(scope, projectRoot, entry.id, Date.now(), 'evict'))
|
|
1315
|
+
archived += 1;
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Find an existing memory the draft appears to rewrite.
|
|
1320
|
+
*
|
|
1321
|
+
* The id comes from the title, so a re-worded title creates a second file and
|
|
1322
|
+
* the store slowly fills with near-copies. The rule stays deliberately narrow
|
|
1323
|
+
* — see {@link isNearDuplicate} — because merging two genuinely distinct
|
|
1324
|
+
* memories loses information no later pass can recover.
|
|
1325
|
+
*
|
|
1326
|
+
* @param draft - the incoming memory.
|
|
1327
|
+
* @param projectRoot - workspace root for a project draft.
|
|
1328
|
+
* @param exclude - id to ignore, so a draft can never supersede itself.
|
|
1329
|
+
* @returns the id to supersede, or `undefined` when the draft is new.
|
|
1330
|
+
*/
|
|
1331
|
+
async findSimilar(draft, projectRoot, exclude) {
|
|
1332
|
+
if (this.similarityLimit() <= 0)
|
|
1333
|
+
return undefined;
|
|
1334
|
+
const threshold = this.similarityLimit();
|
|
1335
|
+
const entries = await this.list(draft.scope, projectRoot);
|
|
1336
|
+
for (const entry of entries) {
|
|
1337
|
+
if (entry.id === exclude)
|
|
1338
|
+
continue;
|
|
1339
|
+
if (isNearDuplicate(draft, entry, threshold))
|
|
1340
|
+
return entry.id;
|
|
1341
|
+
}
|
|
1342
|
+
return undefined;
|
|
1343
|
+
}
|
|
1344
|
+
/**
|
|
1345
|
+
* Write one mined session's evidence note.
|
|
1346
|
+
*
|
|
1347
|
+
* This is the layer Codex keeps as `rollout_summaries/`: a memory says WHAT
|
|
1348
|
+
* was learned, and this note says what the conversation was about, so a reader
|
|
1349
|
+
* can judge whether the memory still applies — or go and re-read it.
|
|
1350
|
+
*
|
|
1351
|
+
* @param note - the note to persist.
|
|
1352
|
+
* @returns the absolute path written.
|
|
1353
|
+
*/
|
|
1354
|
+
async writeSessionNote(note) {
|
|
1355
|
+
const dir = sessionNotesDir(this.memoriesDir);
|
|
1356
|
+
const path = join(dir, `${slugify(note.session)}.md`);
|
|
1357
|
+
const header = [
|
|
1358
|
+
FENCE,
|
|
1359
|
+
`session: ${yamlScalar(note.session)}`,
|
|
1360
|
+
`at: ${new Date(note.at).toISOString()}`,
|
|
1361
|
+
...note.project === undefined ? [] : [`project: ${yamlScalar(note.project)}`],
|
|
1362
|
+
...note.memories.length === 0 ? [] : [`memories: ${note.memories.join(', ')}`],
|
|
1363
|
+
FENCE,
|
|
1364
|
+
'',
|
|
1365
|
+
].join('\n');
|
|
1366
|
+
await writeAtomic(path, `${header}${note.summary.trim()}\n`);
|
|
1367
|
+
await this.evictNotes();
|
|
1368
|
+
return path;
|
|
1369
|
+
}
|
|
1370
|
+
/** Read one session's evidence note. */
|
|
1371
|
+
async readSessionNote(session) {
|
|
1372
|
+
const text = await readText(join(sessionNotesDir(this.memoriesDir), `${slugify(session)}.md`));
|
|
1373
|
+
if (text === undefined)
|
|
1374
|
+
return undefined;
|
|
1375
|
+
return parseSessionNote(text, session);
|
|
1376
|
+
}
|
|
1377
|
+
/** Every evidence note's session id, newest write first. */
|
|
1378
|
+
async listSessionNotes() {
|
|
1379
|
+
const dir = sessionNotesDir(this.memoriesDir);
|
|
1380
|
+
let names;
|
|
1381
|
+
try {
|
|
1382
|
+
const dirents = await readdir(dir, { withFileTypes: true });
|
|
1383
|
+
names = dirents.filter((dirent) => dirent.isFile() && dirent.name.endsWith('.md')).map((dirent) => dirent.name);
|
|
1384
|
+
}
|
|
1385
|
+
catch (error) {
|
|
1386
|
+
if (isMissing(error))
|
|
1387
|
+
return [];
|
|
1388
|
+
throw error;
|
|
1389
|
+
}
|
|
1390
|
+
const stamped = [];
|
|
1391
|
+
for (const name of names) {
|
|
1392
|
+
const stat_ = await stat(join(dir, name)).catch(() => undefined);
|
|
1393
|
+
stamped.push({ id: name.replace(/\.md$/u, ''), at: stat_?.mtimeMs ?? 0 });
|
|
1394
|
+
}
|
|
1395
|
+
return stamped.sort((left, right) => right.at - left.at).map((row) => row.id);
|
|
1396
|
+
}
|
|
1397
|
+
/** Keep the note store bounded: one small file per mined session, newest kept. */
|
|
1398
|
+
async evictNotes() {
|
|
1399
|
+
const ids = await this.listSessionNotes();
|
|
1400
|
+
for (const id of ids.slice(SESSION_NOTE_LIMIT)) {
|
|
1401
|
+
await rm(join(sessionNotesDir(this.memoriesDir), `${id}.md`), { force: true });
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
/**
|
|
1405
|
+
* Per-scope entry cap, read at write time so a settings change applies to the
|
|
1406
|
+
* very next write. The plugin installs its live settings thunk here.
|
|
1407
|
+
*/
|
|
1408
|
+
entryLimit = () => 0;
|
|
1409
|
+
/**
|
|
1410
|
+
* Near-duplicate threshold, read at load and write time so a settings change
|
|
1411
|
+
* applies to the very next operation. `0` keeps only the exact-match rule.
|
|
1412
|
+
*/
|
|
1413
|
+
similarityLimit = () => 0;
|
|
1414
|
+
/**
|
|
1415
|
+
* Called for every entry this store retires.
|
|
1416
|
+
*
|
|
1417
|
+
* The store does not log: it has no logger and no deployment facts. The plugin
|
|
1418
|
+
* installs a reporter here, so "a memory disappeared" stops being a silent
|
|
1419
|
+
* event. A reporter that throws must never fail the write that retired it.
|
|
1420
|
+
*/
|
|
1421
|
+
onRetire;
|
|
1422
|
+
/** Ids that must survive the next dedupe pass (the entry just written). */
|
|
1423
|
+
keepIds = new Set();
|
|
1424
|
+
}
|