dsh-mnemon-source-documents 0.5.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,1034 @@
1
+ import { DOCUMENTS_ACTIVE_LIMIT_BYTES } from "./contracts.js";
2
+ import { createMemoryMutationReceipt, defineMemoryPlugin, defineMemorySource, installMemory, memoryConfigurationDigest, memoryInputRecord, memoryInputStringArray, memoryInputText, truncateMemoryText } from "dsh-mnemon/extension-sdk";
3
+ import { homedir } from "node:os";
4
+ import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import z from "schemastery";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { COMPOSABLE_MEMORY_API_VERSION } from "dsh-mnemon/contracts";
8
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
9
+ //#region src/config.ts
10
+ const Config = z.object({
11
+ dataDir: z.string(),
12
+ limitBytes: z.number().step(1).min(1).max(1073741824)
13
+ });
14
+ function documentsSourceConfig(value, instanceKey) {
15
+ const config = Config(value);
16
+ const dataDir = config.dataDir ?? join(homedir(), ".mnemon", "sources", encodeURIComponent(instanceKey));
17
+ if (!isAbsolute(dataDir)) throw new Error("Documents Source dataDir must be absolute");
18
+ return {
19
+ dataDir,
20
+ limitBytes: config.limitBytes ?? 10485760
21
+ };
22
+ }
23
+ //#endregion
24
+ //#region src/search-tokens.ts
25
+ /** Small deterministic tokenizer shared by local Document and Native recovery. */
26
+ function lexicalSearchTokens(value, maximum = 64) {
27
+ const normalized = value.normalize("NFKC").toLocaleLowerCase();
28
+ const tokens = [];
29
+ for (const segment of normalized.split(/(\p{Script=Han}+)/gu)) {
30
+ if (/^\p{Script=Han}+$/u.test(segment)) {
31
+ const characters = [...segment];
32
+ if (characters.length <= 2) tokens.push(segment);
33
+ else for (let index = 0; index < characters.length - 1; index += 1) tokens.push(`${characters[index]}${characters[index + 1]}`);
34
+ continue;
35
+ }
36
+ tokens.push(...(segment.match(/[\p{L}\p{N}_-]+/gu) ?? []).filter((token) => token.length >= 2));
37
+ }
38
+ return [...new Set(tokens)].slice(0, maximum);
39
+ }
40
+ /** Require broader coverage only after a query is focused enough to support it. */
41
+ function lexicalRequiredMatchCount(tokens) {
42
+ if (tokens.length === 0) return 0;
43
+ if (tokens.length < 4) return 1;
44
+ return Math.max(2, Math.ceil(tokens.length / 4));
45
+ }
46
+ //#endregion
47
+ //#region src/controller.ts
48
+ const MAX_DOCUMENT_BYTES = 2097152;
49
+ const LOCK_TIMEOUT_MS = 5e3;
50
+ const LOCK_STALE_MS = 3e4;
51
+ const LOCK_RETRY_MS = 20;
52
+ const MAX_EXCERPT_CACHE_ENTRIES = 2048;
53
+ var DocumentCapacityError = class extends Error {
54
+ projected;
55
+ limit;
56
+ candidates;
57
+ code = "document-capacity";
58
+ constructor(projected, limit, candidates) {
59
+ super(`Would exceed active document capacity: ${projected} bytes (limit ${limit}). Archive the least-recently-used active document before retrying.`);
60
+ this.projected = projected;
61
+ this.limit = limit;
62
+ this.candidates = candidates;
63
+ this.name = "DocumentCapacityError";
64
+ }
65
+ };
66
+ var DocumentConflictError = class extends Error {
67
+ code = "revision-conflict";
68
+ constructor() {
69
+ super("document changed while archival was running; the active copy was preserved");
70
+ this.name = "DocumentConflictError";
71
+ }
72
+ };
73
+ function isRecord(value) {
74
+ return typeof value === "object" && value !== null && !Array.isArray(value);
75
+ }
76
+ function normalizeLine(value, field, maximum, required) {
77
+ const normalized = value?.trim().replace(/\s+/gu, " ") ?? "";
78
+ if (required && normalized === "") throw new Error(`${field} is required`);
79
+ if (normalized.length > maximum) throw new Error(`${field} is too long (max ${maximum} characters)`);
80
+ return normalized;
81
+ }
82
+ function normalizeContent(value, required) {
83
+ if (value === void 0 && !required) return void 0;
84
+ const normalized = value?.replace(/\0/gu, "").trim() ?? "";
85
+ if (normalized === "") throw new Error("document content is required");
86
+ const size = Buffer.byteLength(normalized, "utf8");
87
+ if (size > MAX_DOCUMENT_BYTES) throw new Error(`document content is too large (${size} bytes; max ${MAX_DOCUMENT_BYTES})`);
88
+ return normalized;
89
+ }
90
+ function unique(values, maximum) {
91
+ return [...new Set(values.map((value) => value.trim()).filter(Boolean))].slice(0, maximum);
92
+ }
93
+ function hash(value) {
94
+ return createHash("sha256").update(value).digest("hex");
95
+ }
96
+ function indexRevision(index) {
97
+ return hash(JSON.stringify(index));
98
+ }
99
+ function copyIndex(index) {
100
+ return {
101
+ version: index.version,
102
+ documents: index.documents.map((record) => ({
103
+ ...record,
104
+ sourcePaths: [...record.sourcePaths],
105
+ sessionIds: [...record.sessionIds],
106
+ memoryBodyIds: [...record.memoryBodyIds]
107
+ }))
108
+ };
109
+ }
110
+ function slug(title) {
111
+ return title.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "").slice(0, 48) || "document";
112
+ }
113
+ function yamlString(value) {
114
+ return JSON.stringify(value);
115
+ }
116
+ function renderDocument(record, content) {
117
+ const sources = record.sourcePaths.length === 0 ? " []" : record.sourcePaths.map((path) => ` - ${yamlString(path)}`).join("\n");
118
+ const sessions = record.sessionIds.length === 0 ? " []" : record.sessionIds.map((id) => ` - ${yamlString(id)}`).join("\n");
119
+ const bodies = record.memoryBodyIds.length === 0 ? " []" : record.memoryBodyIds.map((id) => ` - ${yamlString(id)}`).join("\n");
120
+ return `---
121
+ id: ${yamlString(record.id)}
122
+ title: ${yamlString(record.title)}
123
+ description: ${yamlString(record.description)}
124
+ status: ${yamlString(record.status)}
125
+ created_at: ${yamlString(record.createdAt)}
126
+ updated_at: ${yamlString(record.updatedAt)}
127
+ content_hash: ${yamlString(record.contentHash)}
128
+ source_paths:
129
+ ${sources}
130
+ session_ids:
131
+ ${sessions}
132
+ memory_body_ids:
133
+ ${bodies}
134
+ ---
135
+
136
+ ${content.trim()}\n`;
137
+ }
138
+ function documentBody(markdown) {
139
+ if (!markdown.startsWith("---\n")) return markdown.trim();
140
+ const end = markdown.indexOf("\n---\n", 4);
141
+ return end < 0 ? markdown.trim() : markdown.slice(end + 5).trim();
142
+ }
143
+ function excerpt(content, maximum = 220) {
144
+ const normalized = content.replace(/[#>*_`\[\]]/gu, "").replace(/\s+/gu, " ").trim();
145
+ return normalized.length <= maximum ? normalized : `${normalized.slice(0, maximum - 1)}…`;
146
+ }
147
+ /** Include ctime and identity so restored mtimes and atomic replacements miss. */
148
+ function diskIdentity(stat) {
149
+ return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.mode}`;
150
+ }
151
+ function sleepSync(milliseconds) {
152
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
153
+ }
154
+ function parseRecord(value) {
155
+ if (!isRecord(value) || typeof value.id !== "string" || typeof value.title !== "string" || typeof value.description !== "string") return void 0;
156
+ if (value.status !== "active" && value.status !== "archived" || typeof value.filename !== "string" || typeof value.relativePath !== "string") return void 0;
157
+ if (typeof value.createdAt !== "string" || typeof value.updatedAt !== "string" || typeof value.lastAccessedAt !== "string") return void 0;
158
+ if (typeof value.revision !== "number" || typeof value.contentHash !== "string" || typeof value.sizeBytes !== "number") return void 0;
159
+ if (!Array.isArray(value.sourcePaths) || !Array.isArray(value.sessionIds) || !Array.isArray(value.memoryBodyIds)) return void 0;
160
+ return {
161
+ id: value.id,
162
+ title: value.title,
163
+ description: value.description,
164
+ status: value.status,
165
+ filename: value.filename,
166
+ relativePath: value.relativePath,
167
+ sourcePaths: value.sourcePaths.filter((entry) => typeof entry === "string"),
168
+ sessionIds: value.sessionIds.filter((entry) => typeof entry === "string"),
169
+ createdAt: value.createdAt,
170
+ updatedAt: value.updatedAt,
171
+ lastAccessedAt: value.lastAccessedAt,
172
+ revision: value.revision,
173
+ contentHash: value.contentHash,
174
+ sizeBytes: value.sizeBytes,
175
+ ...typeof value.archivedAt === "string" ? { archivedAt: value.archivedAt } : {},
176
+ ...typeof value.archiveSummary === "string" ? { archiveSummary: value.archiveSummary } : {},
177
+ memoryBodyIds: value.memoryBodyIds.filter((entry) => typeof entry === "string")
178
+ };
179
+ }
180
+ /** Project-scoped control plane for managed active and cold document copies. */
181
+ var DocumentController = class {
182
+ limitBytes;
183
+ now;
184
+ workspaceRoot;
185
+ storageRoot;
186
+ directory;
187
+ activeDirectory;
188
+ archivedDirectory;
189
+ indexPath;
190
+ lockPath;
191
+ managedRelativePrefix;
192
+ queue = Promise.resolve();
193
+ excerpts = /* @__PURE__ */ new Map();
194
+ indexCache;
195
+ indexRevisions = /* @__PURE__ */ new WeakMap();
196
+ constructor(workspaceRoot, limitBytes = DOCUMENTS_ACTIVE_LIMIT_BYTES, now = () => /* @__PURE__ */ new Date(), storageRoot) {
197
+ this.limitBytes = limitBytes;
198
+ this.now = now;
199
+ this.workspaceRoot = resolve(workspaceRoot);
200
+ if (!existsSync(this.workspaceRoot) || !statSync(this.workspaceRoot).isDirectory()) throw new Error(`document workspace is unavailable: ${this.workspaceRoot}`);
201
+ if (!Number.isSafeInteger(limitBytes) || limitBytes < 1) throw new Error("active document limit must be a positive integer");
202
+ this.storageRoot = storageRoot === void 0 ? join(this.workspaceRoot, ".mnemon") : resolve(storageRoot);
203
+ this.managedRelativePrefix = storageRoot === void 0 ? [".mnemon", "documents"].join("/") : "documents";
204
+ this.directory = join(this.storageRoot, "documents");
205
+ this.activeDirectory = join(this.directory, "active");
206
+ this.archivedDirectory = join(this.directory, "archived");
207
+ this.indexPath = join(this.directory, "index.json");
208
+ this.lockPath = join(this.directory, ".index.lock");
209
+ this.initialize();
210
+ }
211
+ snapshot() {
212
+ return this.withLock(() => this.snapshotUnlocked(this.readIndex()));
213
+ }
214
+ /** Source facts and read-grant membership need metadata, not every document body. */
215
+ catalog() {
216
+ return this.withLock(() => this.snapshotUnlocked(this.readIndex(), false));
217
+ }
218
+ revision() {
219
+ return this.withLock(() => this.revisionOf(this.readIndex()));
220
+ }
221
+ get(id) {
222
+ return this.withLock(() => this.view(this.requireDocument(this.readIndex(), id)));
223
+ }
224
+ capacityPlan(request) {
225
+ return this.withLock(() => {
226
+ const index = this.readIndex();
227
+ const active = index.documents.filter((record) => record.status === "active");
228
+ const used = active.reduce((sum, record) => sum + record.sizeBytes, 0);
229
+ let projected;
230
+ let excludeId;
231
+ if (request.action === "create") {
232
+ const now = this.now().toISOString();
233
+ const title = normalizeLine(request.title, "document title", 160, true);
234
+ const content = normalizeContent(request.content, true);
235
+ const id = crypto.randomUUID();
236
+ const record = {
237
+ id,
238
+ title,
239
+ description: normalizeLine(request.description, "document description", 600, false),
240
+ status: "active",
241
+ filename: `${slug(title)}-${id.slice(0, 8)}.md`,
242
+ relativePath: "",
243
+ sourcePaths: this.normalizeSourcePaths(request.sourcePaths ?? []),
244
+ sessionIds: unique(request.sessionIds ?? [], 20),
245
+ createdAt: now,
246
+ updatedAt: now,
247
+ lastAccessedAt: now,
248
+ revision: 1,
249
+ contentHash: hash(content),
250
+ sizeBytes: 0,
251
+ memoryBodyIds: []
252
+ };
253
+ projected = used + Buffer.byteLength(renderDocument(record, content), "utf8");
254
+ } else {
255
+ const current = this.requireDocument(index, request.id);
256
+ if (current.status !== "active") throw new Error("archived documents are immutable; create a new active revision instead");
257
+ const content = normalizeContent(request.content, false) ?? this.readBody(current);
258
+ const updated = {
259
+ ...current,
260
+ title: request.title === void 0 ? current.title : normalizeLine(request.title, "document title", 160, true),
261
+ description: request.description === void 0 ? current.description : normalizeLine(request.description, "document description", 600, false),
262
+ sourcePaths: request.sourcePaths === void 0 ? current.sourcePaths : this.normalizeSourcePaths(request.sourcePaths),
263
+ sessionIds: request.sessionIds === void 0 ? current.sessionIds : unique([...current.sessionIds, ...request.sessionIds], 20),
264
+ contentHash: hash(content),
265
+ revision: current.revision + 1
266
+ };
267
+ projected = used - current.sizeBytes + Buffer.byteLength(renderDocument(updated, content), "utf8");
268
+ excludeId = current.id;
269
+ }
270
+ const candidates = active.filter((record) => record.id !== excludeId).sort((left, right) => Date.parse(left.lastAccessedAt) - Date.parse(right.lastAccessedAt) || Date.parse(left.updatedAt) - Date.parse(right.updatedAt));
271
+ return {
272
+ projected,
273
+ limit: this.limitBytes,
274
+ fits: projected <= this.limitBytes,
275
+ candidates
276
+ };
277
+ });
278
+ }
279
+ search(query, options = {}) {
280
+ const operation = this.queue.then(() => this.withLock(() => {
281
+ const index = this.readIndex();
282
+ const normalized = query.trim().normalize("NFKC").toLocaleLowerCase();
283
+ const tokens = lexicalSearchTokens(normalized);
284
+ const requiredTokenMatches = lexicalRequiredMatchCount(tokens);
285
+ const includeArchived = options.includeArchived === true;
286
+ const limit = Math.max(1, Math.min(50, Math.trunc(options.limit ?? 20)));
287
+ const allowedIds = options.allowedIds === void 0 ? void 0 : new Set(options.allowedIds);
288
+ const ranked = index.documents.filter((record) => allowedIds === void 0 || allowedIds.has(record.id)).filter((record) => includeArchived || record.status === "active").map((record) => {
289
+ const view = this.view(record);
290
+ const title = view.title.normalize("NFKC").toLocaleLowerCase();
291
+ const description = view.description.normalize("NFKC").toLocaleLowerCase();
292
+ const content = view.content.normalize("NFKC").toLocaleLowerCase();
293
+ let score = normalized === "" ? 1 : title.includes(normalized) ? 12 : description.includes(normalized) ? 7 : content.includes(normalized) ? 4 : 0;
294
+ let tokenMatches = 0;
295
+ for (const token of tokens) {
296
+ const titleMatch = title.includes(token);
297
+ const descriptionMatch = description.includes(token);
298
+ const contentMatch = content.includes(token);
299
+ if (titleMatch || descriptionMatch || contentMatch) tokenMatches += 1;
300
+ score += titleMatch ? 4 : descriptionMatch ? 2 : contentMatch ? 1 : 0;
301
+ }
302
+ return {
303
+ result: {
304
+ ...view,
305
+ score,
306
+ excerpt: excerpt(view.content)
307
+ },
308
+ tokenMatches
309
+ };
310
+ }).filter((candidate) => normalized === "" || candidate.result.score > 0 && candidate.tokenMatches >= requiredTokenMatches).sort((left, right) => right.result.score - left.result.score || Date.parse(right.result.updatedAt) - Date.parse(left.result.updatedAt)).slice(0, limit).map((candidate) => candidate.result);
311
+ if (ranked.length > 0) {
312
+ const accessedAt = this.now().toISOString();
313
+ const ids = new Set(ranked.map((result) => result.id));
314
+ index.documents = index.documents.map((record) => ids.has(record.id) ? {
315
+ ...record,
316
+ lastAccessedAt: accessedAt
317
+ } : record);
318
+ this.persistIndex(index);
319
+ }
320
+ return {
321
+ query: query.trim(),
322
+ includeArchived,
323
+ total: ranked.length,
324
+ generatedAt: this.now().toISOString(),
325
+ results: ranked
326
+ };
327
+ }));
328
+ this.queue = operation.catch(() => void 0);
329
+ return operation;
330
+ }
331
+ mutate(request, expectedRevision) {
332
+ const operation = this.queue.then(() => this.withLock(() => this.mutateLocked(request, expectedRevision)));
333
+ this.queue = operation.catch(() => void 0);
334
+ return operation;
335
+ }
336
+ archive(id, expectedRevision, details) {
337
+ const operation = this.queue.then(() => this.withLock(() => {
338
+ const index = this.readIndex();
339
+ const current = this.requireDocument(index, id);
340
+ if (current.status !== "active") throw new Error("only active documents can be archived");
341
+ if (current.revision !== expectedRevision) throw new DocumentConflictError();
342
+ const source = this.pathFor(current);
343
+ const now = this.now().toISOString();
344
+ const updated = {
345
+ ...current,
346
+ status: "archived",
347
+ relativePath: this.relativeManagedPath("archived", current.filename),
348
+ updatedAt: now,
349
+ lastAccessedAt: now,
350
+ revision: current.revision + 1,
351
+ archivedAt: now,
352
+ archiveSummary: normalizeLine(details.summary, "archive summary", 1e3, true),
353
+ memoryBodyIds: unique(details.memoryBodyIds, 20)
354
+ };
355
+ const content = this.readBody(current);
356
+ const rendered = renderDocument(updated, content);
357
+ updated.sizeBytes = Buffer.byteLength(rendered, "utf8");
358
+ const destination = this.pathFor(updated);
359
+ renameSync(source, destination);
360
+ try {
361
+ writeFileSync(destination, rendered, "utf8");
362
+ index.documents = index.documents.map((record) => record.id === id ? updated : record);
363
+ this.persistIndex(index);
364
+ } catch (error) {
365
+ if (existsSync(destination)) renameSync(destination, source);
366
+ throw error;
367
+ }
368
+ return {
369
+ success: true,
370
+ action: "archived",
371
+ document: {
372
+ ...updated,
373
+ content
374
+ },
375
+ snapshot: this.snapshotUnlocked(index)
376
+ };
377
+ }));
378
+ this.queue = operation.catch(() => void 0);
379
+ return operation;
380
+ }
381
+ mutateLocked(request, expectedRevision) {
382
+ const index = this.readIndex();
383
+ if (expectedRevision !== void 0 && this.revisionOf(index) !== expectedRevision) throw new DocumentConflictError();
384
+ const now = this.now().toISOString();
385
+ if (request.action === "create") {
386
+ const title = normalizeLine(request.title, "document title", 160, true);
387
+ const description = normalizeLine(request.description, "document description", 600, false);
388
+ const content = normalizeContent(request.content, true);
389
+ const id = crypto.randomUUID();
390
+ const filename = `${slug(title)}-${id.slice(0, 8)}.md`;
391
+ const record = {
392
+ id,
393
+ title,
394
+ description,
395
+ status: "active",
396
+ filename,
397
+ relativePath: this.relativeManagedPath("active", filename),
398
+ sourcePaths: this.normalizeSourcePaths(request.sourcePaths ?? []),
399
+ sessionIds: unique(request.sessionIds ?? [], 20),
400
+ createdAt: now,
401
+ updatedAt: now,
402
+ lastAccessedAt: now,
403
+ revision: 1,
404
+ contentHash: hash(content),
405
+ sizeBytes: 0,
406
+ memoryBodyIds: []
407
+ };
408
+ const rendered = renderDocument(record, content);
409
+ record.sizeBytes = Buffer.byteLength(rendered, "utf8");
410
+ this.assertCapacity(index, record.sizeBytes);
411
+ this.persistDocument(record, content);
412
+ index.documents.push(record);
413
+ this.persistIndex(index);
414
+ return {
415
+ success: true,
416
+ action: "created",
417
+ document: {
418
+ ...record,
419
+ content
420
+ },
421
+ snapshot: this.snapshotUnlocked(index)
422
+ };
423
+ }
424
+ const current = this.requireDocument(index, request.id);
425
+ if (current.status !== "active") throw new Error("archived documents are immutable; create a new active revision instead");
426
+ const content = normalizeContent(request.content, false) ?? this.readBody(current);
427
+ const updated = {
428
+ ...current,
429
+ title: request.title === void 0 ? current.title : normalizeLine(request.title, "document title", 160, true),
430
+ description: request.description === void 0 ? current.description : normalizeLine(request.description, "document description", 600, false),
431
+ sourcePaths: request.sourcePaths === void 0 ? current.sourcePaths : this.normalizeSourcePaths(request.sourcePaths),
432
+ sessionIds: request.sessionIds === void 0 ? current.sessionIds : unique([...current.sessionIds, ...request.sessionIds], 20),
433
+ updatedAt: now,
434
+ lastAccessedAt: now,
435
+ revision: current.revision + 1,
436
+ contentHash: hash(content)
437
+ };
438
+ const rendered = renderDocument(updated, content);
439
+ updated.sizeBytes = Buffer.byteLength(rendered, "utf8");
440
+ this.assertCapacity(index, updated.sizeBytes - current.sizeBytes, current.id);
441
+ this.persistDocument(updated, content);
442
+ index.documents = index.documents.map((record) => record.id === current.id ? updated : record);
443
+ this.persistIndex(index);
444
+ return {
445
+ success: true,
446
+ action: "updated",
447
+ document: {
448
+ ...updated,
449
+ content
450
+ },
451
+ snapshot: this.snapshotUnlocked(index)
452
+ };
453
+ }
454
+ initialize() {
455
+ mkdirSync(this.activeDirectory, { recursive: true });
456
+ mkdirSync(this.archivedDirectory, { recursive: true });
457
+ if (!existsSync(this.indexPath)) this.atomicWrite(this.indexPath, `${JSON.stringify({
458
+ version: 1,
459
+ documents: []
460
+ }, null, 2)}\n`);
461
+ this.readIndex();
462
+ }
463
+ readIndex() {
464
+ const identity = diskIdentity(statSync(this.indexPath, { bigint: true }));
465
+ if (this.indexCache?.identity === identity) {
466
+ const index = copyIndex(this.indexCache.index);
467
+ this.indexRevisions.set(index, this.indexCache.revision);
468
+ return index;
469
+ }
470
+ this.indexCache = void 0;
471
+ const raw = JSON.parse(readFileSync(this.indexPath, "utf8"));
472
+ if (!isRecord(raw) || raw.version !== 1 || !Array.isArray(raw.documents)) throw new Error(`invalid document index: ${this.indexPath}`);
473
+ const documents = raw.documents.map(parseRecord);
474
+ if (documents.some((record) => record === void 0)) throw new Error(`invalid document record in ${this.indexPath}`);
475
+ const index = {
476
+ version: 1,
477
+ documents
478
+ };
479
+ const revision = indexRevision(index);
480
+ this.indexRevisions.set(index, revision);
481
+ try {
482
+ if (diskIdentity(statSync(this.indexPath, { bigint: true })) === identity) this.indexCache = {
483
+ identity,
484
+ index: copyIndex(index),
485
+ revision
486
+ };
487
+ } catch {}
488
+ return index;
489
+ }
490
+ revisionOf(index) {
491
+ return this.indexRevisions.get(index) ?? indexRevision(index);
492
+ }
493
+ snapshotUnlocked(index, includeExcerpts = true) {
494
+ const cachedPaths = includeExcerpts ? index.documents.slice(0, MAX_EXCERPT_CACHE_ENTRIES).map((record) => this.pathFor(record)) : void 0;
495
+ const eligiblePaths = cachedPaths === void 0 ? void 0 : new Set(cachedPaths);
496
+ if (eligiblePaths !== void 0) {
497
+ for (const path of this.excerpts.keys()) if (!eligiblePaths.has(path)) this.excerpts.delete(path);
498
+ }
499
+ const documents = index.documents.map((record, position) => {
500
+ const path = cachedPaths?.[position] ?? this.pathFor(record);
501
+ let stat;
502
+ try {
503
+ stat = statSync(path, { bigint: true });
504
+ } catch {
505
+ this.excerpts.delete(path);
506
+ return {
507
+ ...record,
508
+ healthy: false,
509
+ excerpt: ""
510
+ };
511
+ }
512
+ return {
513
+ ...record,
514
+ healthy: true,
515
+ excerpt: includeExcerpts ? this.bodyExcerpt(record, path, stat, eligiblePaths.has(path)) : ""
516
+ };
517
+ });
518
+ const active = documents.filter((record) => record.status === "active");
519
+ return {
520
+ workspaceRoot: this.workspaceRoot,
521
+ directory: this.directory,
522
+ indexPath: this.indexPath,
523
+ generatedAt: this.now().toISOString(),
524
+ revision: this.revisionOf(index),
525
+ limitBytes: this.limitBytes,
526
+ activeBytes: active.reduce((sum, record) => sum + record.sizeBytes, 0),
527
+ activeCount: active.length,
528
+ archivedCount: documents.length - active.length,
529
+ total: documents.length,
530
+ documents
531
+ };
532
+ }
533
+ /** Cache only presentation excerpts; reads/search and each health check stay live. */
534
+ bodyExcerpt(record, path, stat, cacheable) {
535
+ if (!cacheable) return excerpt(this.readBody(record));
536
+ const identity = diskIdentity(stat);
537
+ const cached = this.excerpts.get(path);
538
+ if (cached?.identity === identity) return cached.value;
539
+ this.excerpts.delete(path);
540
+ const value = excerpt(this.readBody(record));
541
+ try {
542
+ if (diskIdentity(statSync(path, { bigint: true })) === identity) this.excerpts.set(path, {
543
+ identity,
544
+ value
545
+ });
546
+ } catch {}
547
+ return value;
548
+ }
549
+ requireDocument(index, rawId) {
550
+ const id = rawId.trim();
551
+ const record = index.documents.find((document) => document.id === id);
552
+ if (record === void 0) throw new Error(`document not found: ${id}`);
553
+ return record;
554
+ }
555
+ assertCapacity(index, delta, excludeId) {
556
+ const active = index.documents.filter((record) => record.status === "active");
557
+ const projected = active.reduce((sum, record) => sum + record.sizeBytes, 0) + delta;
558
+ if (projected <= this.limitBytes) return;
559
+ const candidates = active.filter((record) => record.id !== excludeId).sort((left, right) => Date.parse(left.lastAccessedAt) - Date.parse(right.lastAccessedAt) || Date.parse(left.updatedAt) - Date.parse(right.updatedAt));
560
+ throw new DocumentCapacityError(projected, this.limitBytes, candidates);
561
+ }
562
+ normalizeSourcePaths(paths) {
563
+ return unique(paths, 50).map((value) => {
564
+ const absolute = resolve(this.workspaceRoot, value);
565
+ const workspaceRelative = relative(this.workspaceRoot, absolute);
566
+ if (workspaceRelative === ".." || workspaceRelative.startsWith(`..${sep}`) || isAbsolute(workspaceRelative)) throw new Error(`source path must stay inside the workspace: ${value}`);
567
+ if (absolute === this.directory || absolute.startsWith(`${this.directory}${sep}`)) throw new Error("managed document paths cannot be used as source paths");
568
+ return workspaceRelative.split(sep).join("/") || ".";
569
+ });
570
+ }
571
+ relativeManagedPath(status, filename) {
572
+ return [
573
+ this.managedRelativePrefix,
574
+ status,
575
+ basename(filename)
576
+ ].join("/");
577
+ }
578
+ pathFor(record) {
579
+ const legacyPrefix = [".mnemon", "documents"].join("/");
580
+ const relativePath = record.relativePath === legacyPrefix || record.relativePath.startsWith(`${legacyPrefix}/`) ? record.relativePath.slice(8) : record.relativePath;
581
+ const path = resolve(this.storageRoot, relativePath);
582
+ const managedRoot = `${resolve(this.directory)}${sep}`;
583
+ if (!path.startsWith(managedRoot)) throw new Error("document index contains an unsafe managed path");
584
+ return path;
585
+ }
586
+ readBody(record) {
587
+ return documentBody(readFileSync(this.pathFor(record), "utf8"));
588
+ }
589
+ view(record) {
590
+ return {
591
+ ...record,
592
+ content: this.readBody(record)
593
+ };
594
+ }
595
+ persistDocument(record, content) {
596
+ this.atomicWrite(this.pathFor(record), renderDocument(record, content));
597
+ }
598
+ persistIndex(index) {
599
+ this.indexCache = void 0;
600
+ this.indexRevisions.delete(index);
601
+ this.atomicWrite(this.indexPath, `${JSON.stringify(index, null, 2)}\n`);
602
+ }
603
+ atomicWrite(path, content) {
604
+ const temporary = `${path}.${process.pid}.${crypto.randomUUID()}.tmp`;
605
+ writeFileSync(temporary, content, {
606
+ encoding: "utf8",
607
+ mode: 384
608
+ });
609
+ renameSync(temporary, path);
610
+ }
611
+ withLock(callback) {
612
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
613
+ let descriptor;
614
+ while (descriptor === void 0) try {
615
+ descriptor = openSync(this.lockPath, "wx", 384);
616
+ } catch (error) {
617
+ if (error.code !== "EEXIST") throw error;
618
+ try {
619
+ if (Date.now() - statSync(this.lockPath).mtimeMs > LOCK_STALE_MS) rmSync(this.lockPath, { force: true });
620
+ } catch {}
621
+ if (Date.now() >= deadline) throw new Error(`timed out waiting for document lock: ${this.lockPath}`);
622
+ sleepSync(LOCK_RETRY_MS);
623
+ }
624
+ try {
625
+ return callback();
626
+ } finally {
627
+ closeSync(descriptor);
628
+ rmSync(this.lockPath, { force: true });
629
+ }
630
+ }
631
+ };
632
+ /** Resolves one cached controller per canonical DSH workspace. */
633
+ var DocumentManager = class {
634
+ limitBytes;
635
+ now;
636
+ storageRoot;
637
+ controllers = /* @__PURE__ */ new Map();
638
+ constructor(limitBytes = DOCUMENTS_ACTIVE_LIMIT_BYTES, now = () => /* @__PURE__ */ new Date(), storageRoot) {
639
+ this.limitBytes = limitBytes;
640
+ this.now = now;
641
+ this.storageRoot = storageRoot;
642
+ }
643
+ forWorkspace(workspaceRoot) {
644
+ const root = resolve(workspaceRoot);
645
+ const storageRoot = this.storageRoot?.();
646
+ const key = storageRoot === void 0 ? root : `${resolve(storageRoot)}\0${root}`;
647
+ let controller = this.controllers.get(key);
648
+ if (controller === void 0) {
649
+ controller = new DocumentController(root, this.limitBytes, this.now, storageRoot);
650
+ this.controllers.set(key, controller);
651
+ }
652
+ return controller;
653
+ }
654
+ forAgent(agent) {
655
+ const cwd = agent.session.header?.cwd;
656
+ if (cwd === void 0 || cwd.trim() === "") throw new Error("the current DSH session has no workspace for Mnemon Documents");
657
+ return this.forWorkspace(cwd);
658
+ }
659
+ };
660
+ //#endregion
661
+ //#region src/evidence.ts
662
+ /** Preserve query-local evidence under the Source's per-document budget. */
663
+ function documentEvidence(content, query, maximum) {
664
+ if (maximum <= 0) return "";
665
+ if (content.length <= maximum) return content;
666
+ const normalized = content.toLocaleLowerCase();
667
+ const matched = [query.trim(), ...query.match(/[\p{L}\p{N}_-]+/gu) ?? []].map((term) => term.toLocaleLowerCase()).filter(Boolean).sort((left, right) => right.length - left.length).map((term) => normalized.indexOf(term)).find((index) => index >= 0) ?? 0;
668
+ const projectedStart = Math.max(0, Math.min(content.length - maximum, matched - 400));
669
+ const prefix = projectedStart === 0 ? "" : "[earlier content omitted]\n";
670
+ const suffix = projectedStart + maximum >= content.length ? "" : "\n[later content omitted]";
671
+ if (maximum <= prefix.length + suffix.length) return truncateMemoryText(content.slice(matched), maximum);
672
+ const bodyLength = maximum - prefix.length - suffix.length;
673
+ let start = suffix === "" ? content.length - bodyLength : projectedStart;
674
+ if (/[\uDC00-\uDFFF]/u.test(content[start])) start++;
675
+ let end = Math.min(content.length, start + bodyLength);
676
+ if (/[\uD800-\uDBFF]/u.test(content[end - 1])) end--;
677
+ return `${prefix}${content.slice(start, end)}${suffix}`;
678
+ }
679
+ //#endregion
680
+ //#region src/source.ts
681
+ function workspace(scope) {
682
+ const value = scope.workspaceId?.trim();
683
+ return value === void 0 || value === "" ? void 0 : value;
684
+ }
685
+ function grantIds(grant, includeArchived = false) {
686
+ const value = memoryInputRecord(grant.value, "Documents ReadGrant");
687
+ return [...memoryInputStringArray(value.documentIds, "documentIds", 1e4) ?? [], ...includeArchived ? memoryInputStringArray(value.archivedDocumentIds, "archivedDocumentIds", 1e4) ?? [] : []];
688
+ }
689
+ function documentMutation(value, allowedIds) {
690
+ const input = memoryInputRecord(value, "Documents mutation");
691
+ const action = memoryInputText(input.action, "action", 20);
692
+ let mutation;
693
+ if (action === "create") mutation = {
694
+ action,
695
+ title: memoryInputText(input.title, "title", 160),
696
+ content: memoryInputText(input.content, "content", 1e6),
697
+ ...memoryInputText(input.description, "description", 600, false) === void 0 ? {} : { description: memoryInputText(input.description, "description", 600, false) },
698
+ ...input.sourcePaths === void 0 ? {} : { sourcePaths: memoryInputStringArray(input.sourcePaths, "sourcePaths") ?? [] },
699
+ ...input.sessionIds === void 0 ? {} : { sessionIds: memoryInputStringArray(input.sessionIds, "sessionIds", 20) ?? [] }
700
+ };
701
+ else if (action === "update") {
702
+ const id = memoryInputText(input.id, "id", 300);
703
+ if (allowedIds !== void 0 && !allowedIds.includes(id)) throw new Error("Documents update target is outside this View ReadGrant");
704
+ mutation = {
705
+ action,
706
+ id,
707
+ ...memoryInputText(input.title, "title", 160, false) === void 0 ? {} : { title: memoryInputText(input.title, "title", 160, false) },
708
+ ...memoryInputText(input.description, "description", 600, false) === void 0 ? {} : { description: memoryInputText(input.description, "description", 600, false) },
709
+ ...memoryInputText(input.content, "content", 1e6, false) === void 0 ? {} : { content: memoryInputText(input.content, "content", 1e6, false) },
710
+ ...input.sourcePaths === void 0 ? {} : { sourcePaths: memoryInputStringArray(input.sourcePaths, "sourcePaths") ?? [] },
711
+ ...input.sessionIds === void 0 ? {} : { sessionIds: memoryInputStringArray(input.sessionIds, "sessionIds", 20) ?? [] }
712
+ };
713
+ } else throw new Error(`unsupported Documents action: ${action}`);
714
+ return mutation;
715
+ }
716
+ function createDocumentsMemorySource(config = {}) {
717
+ const configured = Object.freeze({ ...config });
718
+ return defineMemorySource({
719
+ manifest: {
720
+ apiVersion: COMPOSABLE_MEMORY_API_VERSION,
721
+ kind: "source",
722
+ typeId: "documents",
723
+ packageName: "dsh-mnemon-source-documents",
724
+ role: "narrative",
725
+ capabilities: [
726
+ "status",
727
+ "project",
728
+ "search",
729
+ "read",
730
+ "write"
731
+ ],
732
+ consistency: "namespace-pinned-live-read",
733
+ routes: [{
734
+ id: "search",
735
+ description: "Search only the project Documents pinned into this View.",
736
+ capability: "search",
737
+ inputSchema: {
738
+ type: "object",
739
+ required: ["query"],
740
+ additionalProperties: false,
741
+ properties: {
742
+ query: { type: "string" },
743
+ limit: { type: "integer" },
744
+ includeArchived: { type: "boolean" }
745
+ }
746
+ },
747
+ maxCalls: 4,
748
+ maxResults: 20,
749
+ maxCharacters: 16e3
750
+ }],
751
+ actions: [{
752
+ id: "manage",
753
+ description: "Create a project Document or update a Document pinned into this View.",
754
+ capability: "write",
755
+ inputSchema: {
756
+ type: "object",
757
+ required: ["action"],
758
+ additionalProperties: false,
759
+ properties: {
760
+ action: {
761
+ type: "string",
762
+ enum: ["create", "update"]
763
+ },
764
+ id: { type: "string" },
765
+ title: { type: "string" },
766
+ description: { type: "string" },
767
+ content: { type: "string" },
768
+ sourcePaths: { type: "array" },
769
+ sessionIds: { type: "array" }
770
+ }
771
+ }
772
+ }],
773
+ management: {
774
+ label: "Project Documents",
775
+ description: "Workspace-scoped narrative memory with namespace-pinned reads."
776
+ }
777
+ },
778
+ create(context) {
779
+ const effective = documentsSourceConfig({
780
+ ...context.configuration,
781
+ ...configured
782
+ }, context.sourceInstanceKey);
783
+ const documents = new DocumentManager(effective.limitBytes, void 0, () => effective.dataDir);
784
+ const snapshot = (workspaceId) => workspaceId === void 0 ? void 0 : documents.forWorkspace(workspaceId).catalog();
785
+ const prepared = /* @__PURE__ */ new WeakMap();
786
+ return {
787
+ facts(request) {
788
+ const root = workspace(request.scope);
789
+ if (root === void 0) return {
790
+ sourceInstanceKey: context.sourceInstanceKey,
791
+ sourceTypeId: "documents",
792
+ role: "narrative",
793
+ availability: "unavailable",
794
+ revision: "unavailable:no-workspace",
795
+ capabilities: ["status"],
796
+ routeIds: [],
797
+ actionIds: [],
798
+ hints: { reason: "no-workspace" }
799
+ };
800
+ if (request.scenario.startsWith("management.") && request.scenario !== "management.catalog") return {
801
+ sourceInstanceKey: context.sourceInstanceKey,
802
+ sourceTypeId: "documents",
803
+ role: "narrative",
804
+ availability: "ready",
805
+ revision: documents.forWorkspace(root).revision(),
806
+ capabilities: [
807
+ "status",
808
+ "project",
809
+ "search",
810
+ "read",
811
+ "write"
812
+ ],
813
+ routeIds: ["search"],
814
+ actionIds: ["manage"]
815
+ };
816
+ const current = snapshot(root);
817
+ prepared.set(request.scope, current);
818
+ const active = current.documents.filter((document) => document.status === "active" && document.healthy);
819
+ return {
820
+ sourceInstanceKey: context.sourceInstanceKey,
821
+ sourceTypeId: "documents",
822
+ role: "narrative",
823
+ availability: "ready",
824
+ revision: current.revision,
825
+ capabilities: [
826
+ "status",
827
+ "project",
828
+ "search",
829
+ "read",
830
+ "write"
831
+ ],
832
+ routeIds: ["search"],
833
+ actionIds: ["manage"],
834
+ hints: { activeCount: active.length }
835
+ };
836
+ },
837
+ project(request) {
838
+ const root = workspace(request.scope);
839
+ if (root === void 0) return { fragments: [] };
840
+ const current = prepared.get(request.scope) ?? snapshot(root);
841
+ prepared.delete(request.scope);
842
+ if (current.revision !== request.expectedRevision) throw new Error("Documents projection revision changed during composition");
843
+ const active = current.documents.filter((document) => document.status === "active" && document.healthy).sort((a, b) => a.id.localeCompare(b.id));
844
+ const readGrant = {
845
+ id: `${context.sourceInstanceKey}/grant/${current.revision}`,
846
+ sourceInstanceKey: context.sourceInstanceKey,
847
+ schema: "dsh-mnemon.documents/v1",
848
+ value: {
849
+ workspaceRoot: root,
850
+ documentIds: active.map((document) => document.id),
851
+ archivedDocumentIds: current.documents.filter((document) => document.status === "archived" && document.healthy).map((document) => document.id).sort()
852
+ },
853
+ revision: current.revision,
854
+ consistency: "namespace-pinned-live-read"
855
+ };
856
+ return {
857
+ fragments: request.includeProjection ? [{
858
+ id: `${context.sourceInstanceKey}/projection`,
859
+ sourceInstanceKey: context.sourceInstanceKey,
860
+ mode: request.mode,
861
+ text: truncateMemoryText(`${active.length} active project Document${active.length === 1 ? "" : "s"} available through the documents/search route.`, request.maxCharacters),
862
+ revision: current.revision,
863
+ provenance: { sourceTypeId: "documents" }
864
+ }] : [],
865
+ readGrant,
866
+ presentation: {
867
+ visibleItems: active.length,
868
+ totalItems: current.documents.length,
869
+ items: [...active].sort((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt) || left.id.localeCompare(right.id)).slice(0, 24).map((document) => ({
870
+ id: document.id,
871
+ title: truncateMemoryText(document.title, 160),
872
+ ...(document.description || document.excerpt).trim() === "" ? {} : { excerpt: truncateMemoryText(document.description || document.excerpt, 600) }
873
+ }))
874
+ }
875
+ };
876
+ },
877
+ async query(request) {
878
+ const root = workspace(request.view.scope);
879
+ if (root === void 0) throw new Error("Documents Route requires a workspace-scoped View");
880
+ const input = memoryInputRecord(request.input, "Documents search");
881
+ const query = memoryInputText(input.query, "query", 2e3, false) ?? "";
882
+ const limitValue = input.limit;
883
+ const limit = Math.min(request.route.maxResults ?? 20, typeof limitValue === "number" && Number.isInteger(limitValue) ? Math.max(1, Math.min(20, limitValue)) : 10);
884
+ const controller = documents.forWorkspace(root);
885
+ const allowedIds = grantIds(request.grant, input.includeArchived === true);
886
+ const result = await controller.search(query, {
887
+ limit,
888
+ allowedIds,
889
+ includeArchived: input.includeArchived === true
890
+ });
891
+ const suggestions = result.results.length === 0 && query !== "" ? controller.snapshot().documents.filter((document) => allowedIds.includes(document.id) && (input.includeArchived === true || document.status === "active")).sort((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt)).slice(0, Math.min(3, limit)) : [];
892
+ let remaining = request.route.maxCharacters ?? 16e3;
893
+ const items = [];
894
+ let truncated = result.total > limit;
895
+ for (const document of result.results) {
896
+ if (remaining <= 0) {
897
+ truncated = true;
898
+ break;
899
+ }
900
+ const content = documentEvidence(document.content, query, Math.min(2600, remaining));
901
+ remaining -= content.length;
902
+ truncated ||= content !== document.content;
903
+ items.push({
904
+ id: document.id,
905
+ text: content,
906
+ score: document.score,
907
+ revision: String(document.revision),
908
+ provenance: {
909
+ kind: "match",
910
+ documentId: document.id,
911
+ title: document.title,
912
+ description: document.description,
913
+ status: document.status,
914
+ relativePath: document.relativePath,
915
+ sourcePaths: document.sourcePaths.slice(0, 8)
916
+ }
917
+ });
918
+ }
919
+ for (const document of suggestions) {
920
+ if (remaining <= 0) {
921
+ truncated = true;
922
+ break;
923
+ }
924
+ const excerpt = truncateMemoryText(document.excerpt, Math.min(1e3, remaining));
925
+ remaining -= excerpt.length;
926
+ items.push({
927
+ id: document.id,
928
+ score: 0,
929
+ text: excerpt,
930
+ provenance: {
931
+ kind: "suggestion",
932
+ documentId: document.id,
933
+ title: document.title,
934
+ description: document.description,
935
+ status: document.status
936
+ }
937
+ });
938
+ }
939
+ return {
940
+ metadata: {
941
+ query: result.query,
942
+ includeArchived: result.includeArchived,
943
+ total: result.total
944
+ },
945
+ id: `evidence:${randomUUID()}`,
946
+ viewId: request.view.id,
947
+ routeId: request.route.id,
948
+ sourceInstanceKey: context.sourceInstanceKey,
949
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
950
+ truncated,
951
+ items
952
+ };
953
+ },
954
+ async manage(request) {
955
+ const root = workspace(request.scope);
956
+ if (root === void 0) throw new Error("Documents management requires a workspace");
957
+ const controller = documents.forWorkspace(root);
958
+ const input = request.input === null ? {} : memoryInputRecord(request.input, "Documents management");
959
+ let value;
960
+ if (request.mode === "read") switch (request.operation) {
961
+ case "snapshot":
962
+ value = controller.snapshot();
963
+ break;
964
+ case "document":
965
+ value = controller.get(memoryInputText(input.id, "id", 300));
966
+ break;
967
+ case "capacity-plan":
968
+ value = controller.capacityPlan(documentMutation(request.input));
969
+ break;
970
+ case "search":
971
+ value = await controller.search(memoryInputText(input.query, "query", 2e3, false) ?? "", {
972
+ includeArchived: input.includeArchived === true,
973
+ ...input.limit === void 0 ? {} : { limit: Math.min(100, Math.max(1, Number(input.limit) || 50)) }
974
+ });
975
+ break;
976
+ default: throw new Error("unsupported Documents management read operation: " + request.operation);
977
+ }
978
+ else {
979
+ if (!request.confirmed) throw new Error("Documents management mutation requires explicit confirmation");
980
+ if (request.operation === "mutate") value = await controller.mutate(documentMutation(request.input), request.expectedRevision);
981
+ else if (request.operation === "archive") {
982
+ const document = controller.get(memoryInputText(input.id, "id", 300));
983
+ const revision = input.documentRevision === void 0 ? document.revision : input.documentRevision;
984
+ if (typeof revision !== "number" || !Number.isInteger(revision)) throw new Error("documentRevision must be an integer");
985
+ value = await controller.archive(document.id, revision, {
986
+ summary: memoryInputText(input.summary, "summary", 1e4, false) ?? "Archived locally by the user.",
987
+ memoryBodyIds: memoryInputStringArray(input.memoryBodyIds, "memoryBodyIds", 100) ?? []
988
+ });
989
+ } else throw new Error("unsupported Documents management mutation operation: " + request.operation);
990
+ }
991
+ const completed = value;
992
+ return {
993
+ revision: completed.snapshot?.revision ?? (typeof completed.revision === "string" ? completed.revision : controller.revision()),
994
+ value
995
+ };
996
+ },
997
+ async mutate(request) {
998
+ const root = workspace(request.view.scope);
999
+ if (root === void 0) throw new Error("Documents Action requires a workspace-scoped View");
1000
+ const grant = request.grant;
1001
+ const mutation = documentMutation(request.input, grant === void 0 ? [] : grantIds(grant));
1002
+ const result = await documents.forWorkspace(root).mutate(mutation);
1003
+ return createMemoryMutationReceipt(request.view.id, request.offer.id, context.sourceInstanceKey, result.snapshot.revision, result, "committed");
1004
+ }
1005
+ };
1006
+ }
1007
+ });
1008
+ }
1009
+ const DOCUMENTS_MEMORY_SOURCE = createDocumentsMemorySource();
1010
+ //#endregion
1011
+ //#region src/index.ts
1012
+ const name = "dsh-mnemon-source-documents";
1013
+ const inject = ["mnemonMemory"];
1014
+ const memoryPlugin = defineMemoryPlugin({
1015
+ packageName: name,
1016
+ label: {
1017
+ en: "Documents",
1018
+ "zh-CN": "档案"
1019
+ },
1020
+ description: {
1021
+ en: "Searchable project records and narrative memory.",
1022
+ "zh-CN": "可检索的项目档案与叙事记忆。"
1023
+ },
1024
+ roles: ["source"],
1025
+ provides: [{ id: "source" }, { id: "source.narrative" }]
1026
+ });
1027
+ function apply(ctx, config = {}) {
1028
+ installMemory(ctx, {
1029
+ plugin: memoryPlugin,
1030
+ sources: [createDocumentsMemorySource(config)]
1031
+ }, { effectiveDigest: memoryConfigurationDigest(config) });
1032
+ }
1033
+ //#endregion
1034
+ export { Config, DOCUMENTS_MEMORY_SOURCE, apply, createDocumentsMemorySource, inject, memoryPlugin, name };