@remnic/core 9.30.0 → 9.30.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.
@@ -22,30 +22,23 @@
22
22
  import { createHash } from "node:crypto";
23
23
  import { readFile, stat, unlink } from "node:fs/promises";
24
24
  import path from "node:path";
25
- import { BoxBuilder, type BoxFrontmatter } from "../boxes.js";
25
+ import { type BoxFrontmatter } from "../boxes.js";
26
26
  import { type CapabilitySet, type GraphConstructionCapabilitySet, type MemoryLifecycleCapabilitySet, resolveCapabilities, resolveCompressionCapabilities, resolveConsolidationCapabilities, resolveConversationContextCapabilities, resolveCreationMemoryCapabilities, resolveGraphConstructionCapabilities, resolveIdentityContinuityCapabilities, resolveIndexingCapabilities, resolveMemoryLifecycleCapabilities, resolveNamespaceCapabilities, resolveObjectiveStateCapabilities, resolvePipelineProcessingCapabilities, resolvePresentationCapabilities, resolveQmdCapabilities, resolveRecallAuxiliaryCapabilities, resolveRecallEnhancementCapabilities, resolveSecurityCapabilities } from "../capabilities.js";
27
- import { type CausalTrajectorySearchResult, searchCausalTrajectories } from "../causal-trajectory.js";
28
- import { CompoundingEngine } from "../compounding/engine.js";
27
+ import { searchCausalTrajectories } from "../causal-trajectory.js";
29
28
  import { buildEntityRecallSection, entityRecentTranscriptLookbackHours, readRecentEntityTranscriptEntries } from "../entity-retrieval.js";
30
- import type { EvalShadowRecallRecord } from "../evals.js";
31
29
  import { buildEventOrderRecallSection, shouldRecallEventOrderEvidence } from "../event-order-recall.js";
32
30
  import { buildExplicitCueRecallSection } from "../explicit-cue-recall.js";
33
31
  import { buildFocusedListRecallSection, shouldRecallFocusedListEvidence } from "../focused-list-recall.js";
34
32
  import { type HarmonicRetrievalResult, searchHarmonicRetrieval } from "../harmonic-retrieval.js";
35
- import { StorageManager } from "../index.js";
36
33
  import { inferIntentFromText, planRecallMode } from "../intent.js";
37
- import { LcmEngine } from "../lcm/index.js";
38
34
  import { log } from "../logger.js";
39
35
  import { isActiveMemoryStatus } from "../memory-lifecycle-ledger-utils.js";
40
36
  import { buildRetrievedMemoryProvenance } from "../memory-provenance.js";
41
- import { NamespaceCatalog } from "../namespaces/catalog.js";
42
37
  import { canReadNamespace, resolvePrincipal } from "../namespaces/principal.js";
43
- import { NamespaceStorageRouter } from "../namespaces/storage.js";
44
38
  import { collectNativeKnowledgeChunks, formatNativeKnowledgeSection, searchNativeKnowledge } from "../native-knowledge.js";
45
- import { type ObjectiveStateSearchResult, objectiveStateStoreOverrideForNamespace, searchObjectiveStateSnapshots } from "../objective-state.js";
39
+ import { objectiveStateStoreOverrideForNamespace, searchObjectiveStateSnapshots } from "../objective-state.js";
46
40
  import { type GraphRecallRankedResult, type GraphRecallShadowComparison, mergeGraphExpandedResults } from "./graph-recall-coordinator.js";
47
41
  import { buildProcedureRecallSection } from "../procedural/procedure-recall.js";
48
- import { ProfilingCollector } from "../profiling.js";
49
42
  import { buildQmdRecallCacheKey, getCachedQmdRecall, setCachedQmdRecall } from "../qmd-recall-cache.js";
50
43
  import { MEMORY_ID_PATTERN } from "../recall-handles.js";
51
44
  import {
@@ -54,29 +47,30 @@ import {
54
47
  } from "../recall-context-composition.js";
55
48
  import { createRecallSectionMetricRecorder } from "../recall-qos.js";
56
49
  import { buildRecallQueryPolicy } from "../recall-query-policy.js";
57
- import { type GraphRecallExpandedEntry, type LastRecallBudgetSummary, type LastRecallSnapshot, LastRecallStore, RecallHandleHistoryStore } from "../recall-state.js";
58
- import { type RecallFilterTrace, type RecallXrayResult, type RecallXrayScoreDecomposition, type RecallXraySnapshot, buildXraySnapshot } from "../recall-xray.js";
50
+ import { type GraphRecallExpandedEntry, type LastRecallSnapshot } from "../recall-state.js";
51
+ import {
52
+ type RecallFilterTrace,
53
+ type RecallXrayResult,
54
+ type RecallXrayScoreDecomposition,
55
+ buildXraySnapshot,
56
+ } from "../recall-xray.js";
59
57
  import { foldQueueWaitTiming, recordRecallTiming } from "../recall-timings.js";
60
58
  import { findUnresolvedEntityRefs } from "../reconstruct.js";
61
- import { RerankCache, rerankLocalOrNoop, reorderByRankedKeys } from "../rerank.js";
59
+ import { rerankLocalOrNoop, reorderByRankedKeys } from "../rerank.js";
62
60
  import { buildResponseGuidanceRecallSection, shouldRecallResponseGuidance } from "../response-guidance-recall.js";
63
61
  import { type ParallelSearchResult, mergeWithAgentResults, runDirectAgent, runTemporalAgent, shouldRunAgent } from "../retrieval-agents.js";
64
62
  import { resolveScopePlan } from "../scopes/scope-plan.js";
65
- import type { SearchBackend, SearchDegradation, SearchQueryOptions } from "../search/port.js";
63
+ import type { SearchDegradation } from "../search/port.js";
66
64
  import { type VerifiedSemanticRuleResult, compareVerifiedSemanticRuleResults, searchVerifiedSemanticRules } from "../semantic-rule-verifier.js";
67
- import { SharedContextManager } from "../shared-context/manager.js";
68
65
  import { isDisagreementPrompt } from "../signal.js";
69
- import { HourlySummarizer } from "../summarizer.js";
70
66
  import { buildTargetedFactRecallSection, shouldRecallTargetedFactEvidence } from "../targeted-fact-recall.js";
71
67
  import { shouldFilterSupersededFromRecall } from "../temporal-supersession.js";
72
68
  import { queryTemporalTimelineAsync } from "../temporal-index.js";
73
69
  import { buildTemporalTimelineRecallSection, type TemporalTimelineRecallItem } from "../temporal-timeline-recall.js";
74
70
  import { isValidAsOf } from "../temporal-validity.js";
75
- import { TmtBuilder } from "../tmt.js";
76
- import { TranscriptManager } from "../transcript.js";
77
71
  import { type TrustStageResultItem, projectTrustForXray } from "../trust-score-stage.js";
78
- import { type TrustZoneSearchResult, searchTrustZoneRecords } from "../trust-zones.js";
79
- import type { CodingContext, EngramTraceEvent, IdentityInjectionMode, MemoryFile, MemoryIntent, PluginConfig, QmdSearchResult, RecallPlanMode, RecallSectionConfig } from "../types.js";
72
+ import { searchTrustZoneRecords } from "../trust-zones.js";
73
+ import type { IdentityInjectionMode, MemoryFile, QmdSearchResult, RecallPlanMode } from "../types.js";
80
74
  import { type VerifiedEpisodeResult, compareVerifiedEpisodeResults, searchVerifiedEpisodes } from "../verified-recall.js";
81
75
  import { type WorkProductLedgerSearchResult, searchWorkProductLedgerEntries } from "../work-product-ledger.js";
82
76
  import { abortError } from "../abort-error.js";
@@ -96,365 +90,12 @@ import {
96
90
  throwIfRecallAborted,
97
91
  type GraphRecallSnapshot,
98
92
  type IntentDebugSnapshot,
99
- type QmdRecallSnapshot,
100
93
  type QueryAwarePrefilter,
101
94
  type RecallInvocationOptions,
102
95
  } from "../orchestrator.js";
103
96
  import { isGenericRecallExcludedPath } from "./generic-recall-paths.js";
104
-
105
- import type {
106
- RecallSectionAppendOptions,
107
- RecallSectionBuckets,
108
- } from "./recall-section-coordinator.js";
109
-
110
- export interface RecallInternalDeps {
111
- readonly _recallWorkspaceOverrides: Map<string, string>;
112
- appendRecallSection(
113
- sectionBuckets: RecallSectionBuckets,
114
- sectionId: string,
115
- content: string,
116
- options?: RecallSectionAppendOptions,
117
- ): boolean;
118
- applyColdFallbackPipeline(options: {
119
- prompt: string;
120
- recallNamespaces: string[];
121
- recallResultLimit: number;
122
- recallMode: RecallPlanMode;
123
- /**
124
- * Recall-operation capability gates resolved once at recall entry (#1523).
125
- * OPTIONAL and additive: the recall pipeline threads a resolved set, but
126
- * callers that omit it (e.g. direct unit-test invocations) get an
127
- * equivalent config-derived set — behavior-preserving.
128
- */
129
- caps?: CapabilitySet;
130
- /** Graph-construction gates resolved at recall entry (#1566 Cluster A). */
131
- graphCaps?: GraphConstructionCapabilitySet;
132
- queryAwarePrefilter?: QueryAwarePrefilter;
133
- abortSignal?: AbortSignal;
134
- /** Backend degradation observer — cold-tier QMD must report like hot (#1536). */
135
- onDegradation?: (degradation: SearchDegradation) => void;
136
- /** Issue #680 — historical recall point in ms-since-epoch. */
137
- asOfMs?: number;
138
- /**
139
- * Optional out-parameter that receives the pre-MMR / pre-truncation
140
- * pool size captured inside the pipeline (issue #570 PR 1). The
141
- * X-ray capture block in `recallInternal` passes a small sink so
142
- * the cold-fallback branch's pre-truncation pool size can be
143
- * attributed back to the branch when `recallSource === "cold_fallback"`.
144
- * Unset by default so existing call sites are unaffected.
145
- */
146
- xrayPoolSizeSink?: { size: number };
147
- /**
148
- * Issue #1577 — out-parameter that receives the TrustScore stage's
149
- * per-path trust map (admitted + quarantined) when the cold path runs
150
- * trust scoring. Mirrors the xrayPoolSizeSink pattern so recallInternal
151
- can propagate trust data for epistemic rendering and X-ray visibility
152
- without changing the cold pipeline's return type.
153
- */
154
- trustByPathSink?: { trustByPath: Map<string, TrustStageResultItem> | null };
155
- deadlineAtMs?: number | null;
156
- /** Issue #681 — when true, bypass graphTraversalConfidenceFloor. */
157
- includeLowConfidence?: boolean;
158
- }): Promise<QmdSearchResult[]>;
159
- applyTrustScoreToBranch(
160
- results: QmdSearchResult[],
161
- namespaces: string[],
162
- caps: CapabilitySet,
163
- label: string,
164
- preloadedFrontmatter?: ReadonlyMap<string, MemoryFile>,
165
- abortSignal?: AbortSignal,
166
- ): Promise<{
167
- results: QmdSearchResult[];
168
- trustByPath: Map<string, TrustStageResultItem> | null;
169
- }>;
170
- assembleRecallSections(
171
- sectionBuckets: RecallSectionBuckets,
172
- budgetOverride?: number,
173
- ): {
174
- sections: string[];
175
- includedIds: string[];
176
- omittedIds: string[];
177
- truncated: boolean;
178
- finalChars: number;
179
- includedMemoryIds: string[];
180
- includedMemoryPaths: string[];
181
- includedMemoryNamespaces: Array<string | undefined>;
182
- omittedMemoryIds: string[];
183
- };
184
- boostSearchResults(
185
- results: QmdSearchResult[],
186
- _recallNamespaces: string[],
187
- prompt?: string,
188
- preloadedMemoryMap?: Map<string, MemoryFile>,
189
- options?: {
190
- allowLifecycleFiltered?: boolean;
191
- allowDedicatedSurface?: boolean;
192
- /**
193
- * Historical recall point in ms-since-epoch (issue #680). When
194
- * set, drops candidates that were not authoritative at this
195
- * instant per `temporal-validity.isValidAsOf`. Caller is
196
- * responsible for parsing/validating the user-supplied ISO
197
- * string at the input boundary (CLI / HTTP / MCP).
198
- */
199
- asOfMs?: number;
200
- },
201
- ): Promise<QmdSearchResult[]>;
202
- boxBuilderFor(storage: StorageManager): BoxBuilder;
203
- buildCompressionGuidelineRecallSection(): Promise<string | null>;
204
- buildConfiguredQmdSearchOptions(
205
- queryText: string,
206
- ): SearchQueryOptions | undefined;
207
- buildGraphRecallRankedResults(
208
- results: QmdSearchResult[],
209
- sourceLabelResolver: (path: string) => string[],
210
- limit?: number,
211
- ): GraphRecallRankedResult[];
212
- buildIdentityContinuitySection(options: {
213
- storage: StorageManager;
214
- recallMode: RecallPlanMode;
215
- prompt: string;
216
- }): Promise<{
217
- section: string;
218
- mode: IdentityInjectionMode;
219
- injectedChars: number;
220
- truncated: boolean;
221
- } | null>;
222
- buildLastRecallBudgetSummary(options: {
223
- requestedTopK?: number;
224
- recallResultLimit: number;
225
- qmdFetchLimit: number;
226
- qmdHybridFetchLimit: number;
227
- finalContextChars?: number;
228
- truncated?: boolean;
229
- includedSections?: string[];
230
- omittedSections?: string[];
231
- includedMemoryIds?: string[];
232
- includedMemoryPaths?: string[];
233
- includedMemoryNamespaces?: Array<string | undefined>;
234
- omittedMemoryIds?: string[];
235
- }): LastRecallBudgetSummary;
236
- buildQueryAwarePrefilter(
237
- prompt: string,
238
- recallNamespaces: string[],
239
- ): Promise<QueryAwarePrefilter>;
240
- collectLastRecallSources(
241
- sectionBuckets: RecallSectionBuckets,
242
- recallSource:
243
- | "none"
244
- | "hot_qmd"
245
- | "hot_embedding"
246
- | "cold_fallback"
247
- | "recent_scan",
248
- ): string[];
249
- readonly compounding?: CompoundingEngine;
250
- readonly config: PluginConfig;
251
- currentPolicyVersion(): string;
252
- diversifyAndLimitRecallResults(
253
- sectionId: string,
254
- results: QmdSearchResult[],
255
- limit: number,
256
- retrievalQuery?: string,
257
- caps?: CapabilitySet,
258
- ): QmdSearchResult[];
259
- effectiveCronRecallInstructionHeavyTokenCap(): number;
260
- emitTrace(event: EngramTraceEvent): void;
261
- expandResultsViaGraph(options: {
262
- memoryResults: QmdSearchResult[];
263
- recallNamespaces: string[];
264
- recallResultLimit: number;
265
- deadlineAtMs?: number | null;
266
- includeLowConfidence?: boolean;
267
- }): Promise<{
268
- merged: QmdSearchResult[];
269
- seedPaths: string[];
270
- expandedPaths: GraphRecallExpandedEntry[];
271
- seedResults: QmdSearchResult[];
272
- }>;
273
- extractMemoryIdsFromResults(results: QmdSearchResult[]): string[];
274
- readonly fastLlmForRerank: {
275
- chatCompletion: (
276
- messages: Array<{ role: string; content: string }>,
277
- options?: { maxTokens?: number; temperature?: number; timeoutMs?: number; operation?: string; priority?: "recall-critical" | "background" },
278
- ) => Promise<{ content: string } | null>;
279
- };
280
- fetchQmdMemoryResultsWithArtifactTopUp(
281
- prompt: string,
282
- qmdFetchLimit: number,
283
- qmdHybridFetchLimit: number,
284
- options: {
285
- namespacesEnabled: boolean;
286
- recallNamespaces: string[];
287
- resolveNamespace: (path: string) => string;
288
- collection?: string;
289
- queryAwarePrefilter?: QueryAwarePrefilter;
290
- searchOptions?: SearchQueryOptions;
291
- onDebugSnapshot?: (snapshot: QmdRecallSnapshot) => Promise<void>;
292
- /** Backend degradation observer, threaded into every QMD call (#1536). */
293
- onDegradation?: (degradation: SearchDegradation) => void;
294
- abortSignal?: AbortSignal;
295
- },
296
- ): Promise<QmdSearchResult[]>;
297
- filterSearchResultsForRecall(
298
- results: QmdSearchResult[],
299
- preloadedMemoryMap?: Map<string, MemoryFile>,
300
- options?: {
301
- allowLifecycleFiltered?: boolean;
302
- allowDedicatedSurface?: boolean;
303
- asOfMs?: number;
304
- deadlineAtMs?: number | null;
305
- abortSignal?: AbortSignal;
306
- dropUnresolved?: boolean;
307
- recallNamespaces?: readonly string[];
308
- },
309
- ): Promise<{ results: QmdSearchResult[]; memoryByPath: Map<string, MemoryFile> }>;
310
- formatCausalTrajectoryResults(
311
- results: CausalTrajectorySearchResult[],
312
- ): string;
313
- formatConversationRecallSection(
314
- results: Array<{ path: string; snippet: string; score: number }>,
315
- maxChars: number,
316
- ): string | null;
317
- formatHarmonicRetrievalResults(
318
- results: HarmonicRetrievalResult[],
319
- ): string;
320
- formatObjectiveStateResults(
321
- results: ObjectiveStateSearchResult[],
322
- ): string;
323
- formatQmdResults(
324
- title: string,
325
- results: QmdSearchResult[],
326
- sessionKey?: string,
327
- trustByPath?: Map<string, TrustStageResultItem> | null,
328
- ): string;
329
- formatTrustZoneResults(results: TrustZoneSearchResult[]): string;
330
- formatVerifiedEpisodeResults(
331
- results: VerifiedEpisodeResult[],
332
- ): string;
333
- formatVerifiedSemanticRuleResults(
334
- results: VerifiedSemanticRuleResult[],
335
- ): string;
336
- formatWorkProductResults(
337
- results: WorkProductLedgerSearchResult[],
338
- ): string;
339
- getCodingContextForSession(sessionKey: string | undefined): CodingContext | null;
340
- getPeerIdForSession(sessionKey: string | undefined): string | null;
341
- getRecallBudgetChars(override?: number): number;
342
- getRecallSectionEntry(
343
- sectionId: string,
344
- ): RecallSectionConfig | undefined;
345
- getRecallSectionMaxChars(
346
- sectionId: string,
347
- ): number | null | undefined;
348
- getRecallSectionNumber(
349
- sectionId: string,
350
- key: keyof RecallSectionConfig,
351
- ): number | undefined;
352
- getStorage(namespace?: string): Promise<StorageManager>;
353
- readonly handleHistory: RecallHandleHistoryStore;
354
- trackMemoryAccess(
355
- memoryIds: string[],
356
- memoryPaths?: string[],
357
- memoryNamespaces?: Array<string | undefined>,
358
- ): void;
359
- trackRecallBackgroundWrite(promise: Promise<void>, label: string): void;
360
- isRecallSectionEnabled(
361
- sectionId: string,
362
- defaultEnabled?: boolean,
363
- ): boolean;
364
- isSpecializedRecallSectionEnabled(
365
- sectionId: string,
366
- topLevelEnabled: boolean,
367
- ): boolean;
368
- lastQmdReprobeAtMs: number;
369
- readonly lastRecall: LastRecallStore;
370
- lastXraySnapshot: RecallXraySnapshot | null;
371
- readonly lcmEngine: LcmEngine | null;
372
- readonly namespaceCatalog: NamespaceCatalog;
373
- namespaceFromPath(p: string): string;
374
- readonly profiler: ProfilingCollector;
375
- publishRecallResults(options: {
376
- title: string;
377
- results: QmdSearchResult[];
378
- sectionBuckets: RecallSectionBuckets;
379
- retrievalQuery: string;
380
- sessionKey: string | undefined;
381
- identityInjection?: {
382
- mode: IdentityInjectionMode | "none";
383
- injectedChars: number;
384
- truncated: boolean;
385
- };
386
- /**
387
- * Issue #1577 — per-recall trust map. When present, quarantined items
388
- * are filtered from injection on EVERY recall path (hot QMD, embedding
389
- * fallback, cold archive, recent) so a faithfulness-contradicted memory
390
- * cannot sneak in via a branch that bypasses trust scoring (review:
391
- * fallback paths bypass trust). The map is also threaded to
392
- * formatQmdResults for the epistemic hedge.
393
- */
394
- trustByPath?: Map<string, TrustStageResultItem> | null;
395
- }): void;
396
- readonly qmd: SearchBackend;
397
- queueEvalShadowRecall(
398
- record: Omit<EvalShadowRecallRecord, "schemaVersion">,
399
- ): void;
400
- readAllMemoriesForNamespaces(
401
- namespaces: string[],
402
- ): Promise<MemoryFile[]>;
403
- recallArtifactsAcrossNamespaces(
404
- prompt: string,
405
- recallNamespaces: string[],
406
- targetCount: number,
407
- ): Promise<MemoryFile[]>;
408
- recallAssemblyClockMs(): number;
409
- recordLastGraphRecallSnapshot(options: {
410
- storage: StorageManager;
411
- prompt: string;
412
- recallMode: RecallPlanMode;
413
- recallNamespaces: string[];
414
- seedPaths: string[];
415
- expandedPaths: GraphRecallExpandedEntry[];
416
- status: "completed" | "skipped" | "aborted";
417
- reason?: string;
418
- shadowMode?: boolean;
419
- queryIntent: MemoryIntent;
420
- seedResults?: GraphRecallRankedResult[];
421
- finalResults?: GraphRecallRankedResult[];
422
- shadowComparison?: GraphRecallShadowComparison;
423
- }): Promise<void>;
424
- recordLastIntentSnapshot(options: {
425
- storage: StorageManager;
426
- snapshot: IntentDebugSnapshot;
427
- }): Promise<void>;
428
- recordLastIntentSnapshotForNamespace(options: {
429
- namespace: string;
430
- snapshot: IntentDebugSnapshot;
431
- }): Promise<void>;
432
- recordLastQmdRecallSnapshot(options: {
433
- storage: StorageManager;
434
- snapshot: QmdRecallSnapshot;
435
- }): Promise<void>;
436
- readonly rerankCache: RerankCache;
437
- searchConversationRecallResults(
438
- retrievalQuery: string,
439
- topK: number,
440
- ): Promise<Array<{ path: string; snippet: string; score: number }>>;
441
- searchEmbeddingFallback(
442
- query: string,
443
- limit: number,
444
- ): Promise<QmdSearchResult[]>;
445
- readonly sharedContext?: SharedContextManager;
446
- readonly storage: StorageManager;
447
- readonly storageRouter: NamespaceStorageRouter;
448
- readonly summarizer: HourlySummarizer;
449
- readonly tmtBuilder: TmtBuilder;
450
- readonly transcript: TranscriptManager;
451
- truncateArtifactForRecall(text: string, maxChars?: number): string;
452
- truncateRecallSectionToBudget(
453
- content: string,
454
- maxChars: number,
455
- ): string;
456
- }
457
-
97
+ import type { RecallSectionBuckets } from "./recall-section-coordinator.js";
98
+ import type { RecallInternalDeps } from "./recall-internal-deps.js";
458
99
  export class RecallInternalCoordinator {
459
100
  constructor(
460
101
  private readonly deps: RecallInternalDeps,