@remnic/core 9.3.738 → 9.3.739

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.
@@ -0,0 +1,344 @@
1
+ /**
2
+ * Conversation index coordinator — extracted from the orchestrator (issue #1526).
3
+ *
4
+ * Owns the conversation-index subsystem: semantic recall over past
5
+ * conversations, plus the build / update / rebuild / inspect / health
6
+ * lifecycle of the on-disk chunk store and its pluggable search backend
7
+ * (qmd or faiss). Behavior-preserving move from orchestrator.ts — no logic
8
+ * changes; the orchestrator constructs one instance and keeps thin
9
+ * delegating methods so existing call sites and tests that exercise the
10
+ * private API continue to work.
11
+ *
12
+ * The backend and transcript are read through getters (not captured at
13
+ * construction) so that post-construction reassignment of the orchestrator's
14
+ * live fields — exercised by the conversation-index integration tests and by
15
+ * backend swap-in at deferred-init time — is honored. This mirrors the
16
+ * TierMigrationCoordinator accessor pattern.
17
+ */
18
+
19
+ import { readdir } from "node:fs/promises";
20
+ import path from "node:path";
21
+
22
+ import { resolveIndexingCapabilities } from "../capabilities.js";
23
+ import { cleanupConversationChunks } from "../conversation-index/cleanup.js";
24
+ import { chunkTranscriptEntries } from "../conversation-index/chunker.js";
25
+ import type { ConversationChunk } from "../conversation-index/chunker.js";
26
+ import { writeConversationChunks } from "../conversation-index/indexer.js";
27
+ import type {
28
+ ConversationIndexBackend,
29
+ ConversationIndexBackendHealth,
30
+ ConversationIndexBackendInspection,
31
+ } from "../conversation-index/backend.js";
32
+ import type { ConversationSearchResult } from "../conversation-index/search.js";
33
+ import type { TranscriptManager } from "../transcript.js";
34
+ import type { PluginConfig } from "../types.js";
35
+
36
+ /**
37
+ * Coordinator for the conversation-index subsystem.
38
+ *
39
+ * Holds the per-session last-update timestamps (previously an orchestrator
40
+ * field) and delegates chunk building / persistence / embedding to the
41
+ * configured backend.
42
+ */
43
+ export class ConversationIndexCoordinator {
44
+ private readonly config: PluginConfig;
45
+ private readonly getTranscript: () => TranscriptManager;
46
+ private readonly getBackend: () => ConversationIndexBackend | undefined;
47
+ private readonly indexDir: string;
48
+ private readonly lastUpdateAtMs = new Map<string, number>();
49
+
50
+ constructor(options: {
51
+ config: PluginConfig;
52
+ getTranscript: () => TranscriptManager;
53
+ getBackend: () => ConversationIndexBackend | undefined;
54
+ indexDir: string;
55
+ }) {
56
+ this.config = options.config;
57
+ this.getTranscript = options.getTranscript;
58
+ this.getBackend = options.getBackend;
59
+ this.indexDir = options.indexDir;
60
+ }
61
+
62
+ /** Semantic recall over past-conversation chunks (fail-open: empty on miss). */
63
+ async search(
64
+ retrievalQuery: string,
65
+ topK: number,
66
+ ): Promise<ConversationSearchResult[]> {
67
+ const backend = this.getBackend();
68
+ if (backend) {
69
+ return backend.search(retrievalQuery, topK);
70
+ }
71
+ return [];
72
+ }
73
+
74
+ /** Render conversation-recall search hits as a budgeted markdown section. */
75
+ formatRecallSection(
76
+ results: ConversationSearchResult[],
77
+ maxChars: number,
78
+ ): string | null {
79
+ if (!Array.isArray(results) || results.length === 0) return null;
80
+ const lines: string[] = ["## Semantic Recall (Past Conversations)", ""];
81
+ let used = 0;
82
+ for (const r of results) {
83
+ if (!r?.snippet) continue;
84
+ const chunk =
85
+ `### ${r.path}\n` +
86
+ `Score: ${r.score.toFixed(3)}\n\n` +
87
+ `${r.snippet.trim()}\n`;
88
+ if (used + chunk.length > maxChars) break;
89
+ lines.push(chunk);
90
+ used += chunk.length;
91
+ }
92
+ return used > 0 ? lines.join("\n") : null;
93
+ }
94
+
95
+ /** Recursively count `.md` chunk documents under a directory. */
96
+ async countChunkDocs(dir: string): Promise<number> {
97
+ try {
98
+ const entries = await readdir(dir, { withFileTypes: true });
99
+ let total = 0;
100
+ for (const entry of entries) {
101
+ const fullPath = path.join(dir, entry.name);
102
+ if (entry.isDirectory()) {
103
+ total += await this.countChunkDocs(fullPath);
104
+ continue;
105
+ }
106
+ if (entry.isFile() && entry.name.endsWith(".md")) {
107
+ total += 1;
108
+ }
109
+ }
110
+ return total;
111
+ } catch {
112
+ return 0;
113
+ }
114
+ }
115
+
116
+ /** Read recent transcript entries and chunk them for indexing. */
117
+ async buildChunks(
118
+ sessionKey?: string,
119
+ hours: number = 24,
120
+ ): Promise<ConversationChunk[]> {
121
+ const entries = await this.getTranscript().readRecent(hours, sessionKey);
122
+ const effectiveSessionKey = sessionKey ?? "all-sessions";
123
+ return chunkTranscriptEntries(effectiveSessionKey, entries, {
124
+ maxChars: this.config.conversationRecallMaxChars * 2,
125
+ maxTurns: Math.max(10, this.config.hourlySummariesMaxTurnsPerRun),
126
+ });
127
+ }
128
+
129
+ async getHealth(): Promise<{
130
+ enabled: boolean;
131
+ backend: "qmd" | "faiss";
132
+ status: "ok" | "degraded" | "disabled";
133
+ chunkDocCount: number;
134
+ lastUpdateAt: string | null;
135
+ qmdAvailable?: boolean;
136
+ faiss?: {
137
+ ok: boolean;
138
+ status: "ok" | "degraded" | "error";
139
+ indexPath: string;
140
+ message?: string;
141
+ manifest?: {
142
+ version: number;
143
+ modelId: string;
144
+ normalizedModelId: string;
145
+ dimension: number;
146
+ chunkCount: number;
147
+ updatedAt: string;
148
+ lastSuccessfulRebuildAt: string;
149
+ };
150
+ };
151
+ }> {
152
+ const chunkDocCount = await this.countChunkDocs(this.indexDir);
153
+ const lastUpdateAtMs = Math.max(0, ...this.lastUpdateAtMs.values());
154
+ const lastUpdateAt =
155
+ lastUpdateAtMs > 0 ? new Date(lastUpdateAtMs).toISOString() : null;
156
+
157
+ if (!resolveIndexingCapabilities(this.config).conversationIndex) {
158
+ return {
159
+ enabled: false,
160
+ backend: this.config.conversationIndexBackend,
161
+ status: "disabled",
162
+ chunkDocCount,
163
+ lastUpdateAt,
164
+ };
165
+ }
166
+ const backend = this.getBackend();
167
+ const backendHealth: ConversationIndexBackendHealth = backend
168
+ ? await backend.health()
169
+ : {
170
+ backend: this.config.conversationIndexBackend,
171
+ status: "degraded" as const,
172
+ };
173
+ return {
174
+ enabled: true,
175
+ chunkDocCount,
176
+ lastUpdateAt,
177
+ ...backendHealth,
178
+ };
179
+ }
180
+
181
+ async inspect(): Promise<
182
+ ConversationIndexBackendInspection & {
183
+ enabled: boolean;
184
+ chunkDocCount: number;
185
+ lastUpdateAt: string | null;
186
+ }
187
+ > {
188
+ const chunkDocCount = await this.countChunkDocs(this.indexDir);
189
+ const lastUpdateAtMs = Math.max(0, ...this.lastUpdateAtMs.values());
190
+ const lastUpdateAt =
191
+ lastUpdateAtMs > 0 ? new Date(lastUpdateAtMs).toISOString() : null;
192
+
193
+ if (!resolveIndexingCapabilities(this.config).conversationIndex) {
194
+ return {
195
+ enabled: false,
196
+ backend: this.config.conversationIndexBackend,
197
+ status: "disabled",
198
+ available: false,
199
+ indexPath: this.indexDir,
200
+ supportsIncrementalUpdate: true,
201
+ message: "Conversation index disabled by config",
202
+ metadata: {
203
+ chunkCount: chunkDocCount,
204
+ },
205
+ chunkDocCount,
206
+ lastUpdateAt,
207
+ };
208
+ }
209
+
210
+ const backend = this.getBackend();
211
+ const inspection: ConversationIndexBackendInspection = backend
212
+ ? await backend.inspect()
213
+ : {
214
+ backend: this.config.conversationIndexBackend,
215
+ status: "degraded" as const,
216
+ available: false,
217
+ indexPath: this.indexDir,
218
+ supportsIncrementalUpdate: true,
219
+ message: "Conversation index backend unavailable",
220
+ metadata: {
221
+ chunkCount: chunkDocCount,
222
+ },
223
+ };
224
+
225
+ return {
226
+ enabled: true,
227
+ chunkDocCount,
228
+ lastUpdateAt,
229
+ ...inspection,
230
+ };
231
+ }
232
+
233
+ async update(
234
+ sessionKey: string,
235
+ hours: number = 24,
236
+ opts?: { embed?: boolean; enforceMinInterval?: boolean },
237
+ ): Promise<{
238
+ chunks: number;
239
+ skipped: boolean;
240
+ reason?: string;
241
+ retryAfterMs?: number;
242
+ embedded?: boolean;
243
+ }> {
244
+ if (!resolveIndexingCapabilities(this.config).conversationIndex) {
245
+ return { chunks: 0, skipped: true, reason: "disabled", embedded: false };
246
+ }
247
+ const enforceMinInterval = opts?.enforceMinInterval !== false;
248
+ if (enforceMinInterval) {
249
+ const minIntervalMs = Math.max(
250
+ 0,
251
+ this.config.conversationIndexMinUpdateIntervalMs,
252
+ );
253
+ const now = Date.now();
254
+ const last = this.lastUpdateAtMs.get(sessionKey) ?? 0;
255
+ const elapsed = now - last;
256
+ if (minIntervalMs > 0 && elapsed < minIntervalMs) {
257
+ return {
258
+ chunks: 0,
259
+ skipped: true,
260
+ reason: "min_interval",
261
+ retryAfterMs: minIntervalMs - elapsed,
262
+ embedded: false,
263
+ };
264
+ }
265
+ }
266
+ const chunks = await this.buildChunks(sessionKey, hours);
267
+ await writeConversationChunks(this.indexDir, chunks);
268
+ const retentionCutoffMs =
269
+ Number.isFinite(this.config.conversationIndexRetentionDays) &&
270
+ this.config.conversationIndexRetentionDays > 0
271
+ ? Date.now() -
272
+ this.config.conversationIndexRetentionDays * 24 * 60 * 60 * 1000
273
+ : undefined;
274
+ await cleanupConversationChunks(
275
+ this.indexDir,
276
+ this.config.conversationIndexRetentionDays,
277
+ );
278
+ const shouldEmbed =
279
+ opts?.embed ?? this.config.conversationIndexEmbedOnUpdate;
280
+ let embedded = false;
281
+
282
+ const backend = this.getBackend();
283
+ if (backend) {
284
+ const result = await backend.update(chunks, {
285
+ embed: shouldEmbed,
286
+ ...(retentionCutoffMs !== undefined ? { retentionCutoffMs } : {}),
287
+ });
288
+ embedded = result.embedded;
289
+ }
290
+
291
+ this.lastUpdateAtMs.set(sessionKey, Date.now());
292
+ return { chunks: chunks.length, skipped: false, embedded };
293
+ }
294
+
295
+ async rebuild(
296
+ sessionKey?: string,
297
+ hours: number = 24,
298
+ opts?: { embed?: boolean },
299
+ ): Promise<{
300
+ chunks: number;
301
+ skipped: boolean;
302
+ reason?: string;
303
+ embedded?: boolean;
304
+ rebuilt?: boolean;
305
+ }> {
306
+ if (!resolveIndexingCapabilities(this.config).conversationIndex) {
307
+ return {
308
+ chunks: 0,
309
+ skipped: true,
310
+ reason: "disabled",
311
+ embedded: false,
312
+ rebuilt: false,
313
+ };
314
+ }
315
+
316
+ const chunks = await this.buildChunks(sessionKey, hours);
317
+ await writeConversationChunks(this.indexDir, chunks);
318
+ await cleanupConversationChunks(
319
+ this.indexDir,
320
+ this.config.conversationIndexRetentionDays,
321
+ );
322
+
323
+ const shouldEmbed =
324
+ opts?.embed ?? this.config.conversationIndexEmbedOnUpdate;
325
+ let embedded = false;
326
+ let rebuilt = false;
327
+ const backend = this.getBackend();
328
+ if (backend) {
329
+ const result = await backend.rebuild(chunks, {
330
+ embed: shouldEmbed,
331
+ });
332
+ embedded = result.embedded;
333
+ rebuilt = result.rebuilt;
334
+ }
335
+
336
+ const stamp = Date.now();
337
+ if (sessionKey) {
338
+ this.lastUpdateAtMs.set(sessionKey, stamp);
339
+ } else {
340
+ this.lastUpdateAtMs.set("__rebuild__", stamp);
341
+ }
342
+ return { chunks: chunks.length, skipped: false, embedded, rebuilt };
343
+ }
344
+ }