@graphorin/memory 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/README.md +31 -31
  3. package/dist/conflict/index.d.ts +3 -1
  4. package/dist/conflict/index.js +1 -1
  5. package/dist/conflict/locale-packs/en.d.ts +13 -0
  6. package/dist/conflict/locale-packs/en.d.ts.map +1 -0
  7. package/dist/conflict/locale-packs/en.js +1 -1
  8. package/dist/conflict/locale-packs/en.js.map +1 -1
  9. package/dist/conflict/pipeline.d.ts +2 -2
  10. package/dist/conflict/pipeline.js +3 -3
  11. package/dist/conflict/pipeline.js.map +1 -1
  12. package/dist/conflict/stages/helpers.js +1 -1
  13. package/dist/conflict/stages/helpers.js.map +1 -1
  14. package/dist/conflict/stages/stage1-exact-dedup.js.map +1 -1
  15. package/dist/conflict/stages/stage2-embedding-three-zone.js.map +1 -1
  16. package/dist/conflict/stages/stage3-heuristic-regex.js +1 -1
  17. package/dist/conflict/stages/stage3-heuristic-regex.js.map +1 -1
  18. package/dist/conflict/stages/stage4-subject-predicate.js.map +1 -1
  19. package/dist/conflict/stages/stage5-defer-to-deep.js.map +1 -1
  20. package/dist/conflict/types.d.ts +7 -7
  21. package/dist/conflict/types.js +1 -1
  22. package/dist/conflict/types.js.map +1 -1
  23. package/dist/consolidator/budget.js +16 -3
  24. package/dist/consolidator/budget.js.map +1 -1
  25. package/dist/consolidator/decay.d.ts +13 -2
  26. package/dist/consolidator/decay.js +17 -5
  27. package/dist/consolidator/decay.js.map +1 -1
  28. package/dist/consolidator/dlq.js +1 -1
  29. package/dist/consolidator/dlq.js.map +1 -1
  30. package/dist/consolidator/errors.js +2 -2
  31. package/dist/consolidator/errors.js.map +1 -1
  32. package/dist/consolidator/index.js +8 -6
  33. package/dist/consolidator/index.js.map +1 -1
  34. package/dist/consolidator/lock.js +1 -1
  35. package/dist/consolidator/lock.js.map +1 -1
  36. package/dist/consolidator/noise-filter.js.map +1 -1
  37. package/dist/consolidator/phases/deep.js +6 -2
  38. package/dist/consolidator/phases/deep.js.map +1 -1
  39. package/dist/consolidator/phases/induce.d.ts +10 -10
  40. package/dist/consolidator/phases/induce.js +6 -6
  41. package/dist/consolidator/phases/induce.js.map +1 -1
  42. package/dist/consolidator/phases/learned-context.js +129 -0
  43. package/dist/consolidator/phases/learned-context.js.map +1 -0
  44. package/dist/consolidator/phases/light.js +2 -1
  45. package/dist/consolidator/phases/light.js.map +1 -1
  46. package/dist/consolidator/phases/reflect.js +5 -4
  47. package/dist/consolidator/phases/reflect.js.map +1 -1
  48. package/dist/consolidator/phases/standard.js +37 -8
  49. package/dist/consolidator/phases/standard.js.map +1 -1
  50. package/dist/consolidator/reconcile.js +1 -1
  51. package/dist/consolidator/reconcile.js.map +1 -1
  52. package/dist/consolidator/runtime.d.ts +4 -4
  53. package/dist/consolidator/runtime.d.ts.map +1 -1
  54. package/dist/consolidator/runtime.js +73 -16
  55. package/dist/consolidator/runtime.js.map +1 -1
  56. package/dist/consolidator/scheduler.d.ts +5 -5
  57. package/dist/consolidator/scheduler.js +1 -1
  58. package/dist/consolidator/scheduler.js.map +1 -1
  59. package/dist/consolidator/triggers.js +7 -7
  60. package/dist/consolidator/triggers.js.map +1 -1
  61. package/dist/consolidator/types.d.ts +68 -20
  62. package/dist/consolidator/types.d.ts.map +1 -1
  63. package/dist/consolidator/types.js +16 -6
  64. package/dist/consolidator/types.js.map +1 -1
  65. package/dist/context-engine/annotations.d.ts +9 -9
  66. package/dist/context-engine/annotations.js +3 -3
  67. package/dist/context-engine/annotations.js.map +1 -1
  68. package/dist/context-engine/auto-recall.js.map +1 -1
  69. package/dist/context-engine/compaction/clear-tool-results.d.ts +18 -3
  70. package/dist/context-engine/compaction/clear-tool-results.d.ts.map +1 -1
  71. package/dist/context-engine/compaction/clear-tool-results.js +26 -5
  72. package/dist/context-engine/compaction/clear-tool-results.js.map +1 -1
  73. package/dist/context-engine/compaction/compactor.js +19 -6
  74. package/dist/context-engine/compaction/compactor.js.map +1 -1
  75. package/dist/context-engine/compaction/hooks/reanchor-persona-block.js +4 -0
  76. package/dist/context-engine/compaction/hooks/reanchor-persona-block.js.map +1 -1
  77. package/dist/context-engine/compaction/hooks/reanchor-pinned-facts.js +1 -0
  78. package/dist/context-engine/compaction/hooks/reanchor-pinned-facts.js.map +1 -1
  79. package/dist/context-engine/compaction/hooks/reanchor-project-rules.js +2 -1
  80. package/dist/context-engine/compaction/hooks/reanchor-project-rules.js.map +1 -1
  81. package/dist/context-engine/compaction/hooks/reanchor-recent-results.d.ts +28 -0
  82. package/dist/context-engine/compaction/hooks/reanchor-recent-results.d.ts.map +1 -0
  83. package/dist/context-engine/compaction/hooks/reanchor-recent-results.js +71 -0
  84. package/dist/context-engine/compaction/hooks/reanchor-recent-results.js.map +1 -0
  85. package/dist/context-engine/compaction/hooks/types.d.ts +15 -3
  86. package/dist/context-engine/compaction/hooks/types.d.ts.map +1 -1
  87. package/dist/context-engine/compaction/index.d.ts +1 -0
  88. package/dist/context-engine/compaction/index.js +2 -1
  89. package/dist/context-engine/compaction/templates/summary-9-section.d.ts +10 -3
  90. package/dist/context-engine/compaction/templates/summary-9-section.d.ts.map +1 -1
  91. package/dist/context-engine/compaction/templates/summary-9-section.js +42 -5
  92. package/dist/context-engine/compaction/templates/summary-9-section.js.map +1 -1
  93. package/dist/context-engine/compaction/thresholds.js.map +1 -1
  94. package/dist/context-engine/compaction/types.d.ts +47 -7
  95. package/dist/context-engine/compaction/types.d.ts.map +1 -1
  96. package/dist/context-engine/engine.d.ts +23 -4
  97. package/dist/context-engine/engine.d.ts.map +1 -1
  98. package/dist/context-engine/engine.js +69 -15
  99. package/dist/context-engine/engine.js.map +1 -1
  100. package/dist/context-engine/index.d.ts +1 -0
  101. package/dist/context-engine/index.d.ts.map +1 -1
  102. package/dist/context-engine/index.js +2 -1
  103. package/dist/context-engine/locale-packs/en.js +14 -13
  104. package/dist/context-engine/locale-packs/en.js.map +1 -1
  105. package/dist/context-engine/locale-packs/types.d.ts +10 -10
  106. package/dist/context-engine/locale-packs/types.d.ts.map +1 -1
  107. package/dist/context-engine/locale-packs/types.js.map +1 -1
  108. package/dist/context-engine/metadata.d.ts +1 -1
  109. package/dist/context-engine/metadata.js +2 -2
  110. package/dist/context-engine/metadata.js.map +1 -1
  111. package/dist/context-engine/preambles/inbound-en.d.ts +1 -1
  112. package/dist/context-engine/preambles/inbound-en.js +1 -1
  113. package/dist/context-engine/preambles/inbound-en.js.map +1 -1
  114. package/dist/context-engine/privacy-filter.d.ts +2 -2
  115. package/dist/context-engine/privacy-filter.js +1 -1
  116. package/dist/context-engine/privacy-filter.js.map +1 -1
  117. package/dist/context-engine/templates/base-en.d.ts +1 -1
  118. package/dist/context-engine/templates/base-en.js +1 -1
  119. package/dist/context-engine/templates/base-en.js.map +1 -1
  120. package/dist/context-engine/templates/composer.d.ts +1 -1
  121. package/dist/context-engine/templates/composer.js.map +1 -1
  122. package/dist/context-engine/token-budget.d.ts +1 -1
  123. package/dist/context-engine/token-budget.js +1 -1
  124. package/dist/context-engine/token-budget.js.map +1 -1
  125. package/dist/context-engine/token-counter.d.ts +16 -7
  126. package/dist/context-engine/token-counter.d.ts.map +1 -1
  127. package/dist/context-engine/token-counter.js +31 -9
  128. package/dist/context-engine/token-counter.js.map +1 -1
  129. package/dist/errors/index.d.ts +2 -2
  130. package/dist/errors/index.js +4 -4
  131. package/dist/errors/index.js.map +1 -1
  132. package/dist/facade.d.ts +44 -15
  133. package/dist/facade.d.ts.map +1 -1
  134. package/dist/facade.js +16 -8
  135. package/dist/facade.js.map +1 -1
  136. package/dist/graph/entity-resolver.d.ts +2 -2
  137. package/dist/graph/entity-resolver.js +2 -2
  138. package/dist/graph/entity-resolver.js.map +1 -1
  139. package/dist/index.d.ts +9 -5
  140. package/dist/index.d.ts.map +1 -1
  141. package/dist/index.js +9 -4
  142. package/dist/index.js.map +1 -1
  143. package/dist/internal/contextualize.js +2 -2
  144. package/dist/internal/contextualize.js.map +1 -1
  145. package/dist/internal/embedder-binding.js +1 -1
  146. package/dist/internal/embedder-binding.js.map +1 -1
  147. package/dist/internal/id.js +1 -1
  148. package/dist/internal/id.js.map +1 -1
  149. package/dist/internal/injection-heuristics.js +25 -2
  150. package/dist/internal/injection-heuristics.js.map +1 -1
  151. package/dist/internal/spans.js +1 -1
  152. package/dist/internal/spans.js.map +1 -1
  153. package/dist/internal/storage-adapter.d.ts +71 -22
  154. package/dist/internal/storage-adapter.d.ts.map +1 -1
  155. package/dist/migration/embedder-migration.d.ts +7 -7
  156. package/dist/migration/embedder-migration.js.map +1 -1
  157. package/dist/search/explain.d.ts +7 -4
  158. package/dist/search/explain.d.ts.map +1 -1
  159. package/dist/search/explain.js +1 -1
  160. package/dist/search/explain.js.map +1 -1
  161. package/dist/search/fit-weights.d.ts +48 -0
  162. package/dist/search/fit-weights.d.ts.map +1 -0
  163. package/dist/search/fit-weights.js +70 -0
  164. package/dist/search/fit-weights.js.map +1 -0
  165. package/dist/search/graph-ppr.d.ts +36 -0
  166. package/dist/search/graph-ppr.d.ts.map +1 -0
  167. package/dist/search/graph-ppr.js +38 -0
  168. package/dist/search/graph-ppr.js.map +1 -0
  169. package/dist/search/index.d.ts +4 -1
  170. package/dist/search/index.js +4 -1
  171. package/dist/search/iterative.d.ts +15 -8
  172. package/dist/search/iterative.d.ts.map +1 -1
  173. package/dist/search/iterative.js +10 -9
  174. package/dist/search/iterative.js.map +1 -1
  175. package/dist/search/query-transform.d.ts +6 -6
  176. package/dist/search/query-transform.js +6 -6
  177. package/dist/search/query-transform.js.map +1 -1
  178. package/dist/search/rrf.d.ts +4 -4
  179. package/dist/search/rrf.js +4 -4
  180. package/dist/search/rrf.js.map +1 -1
  181. package/dist/search/trust.d.ts +30 -0
  182. package/dist/search/trust.d.ts.map +1 -0
  183. package/dist/search/trust.js +50 -0
  184. package/dist/search/trust.js.map +1 -0
  185. package/dist/search/types.d.ts +1 -1
  186. package/dist/tiers/episodic-memory.d.ts +6 -4
  187. package/dist/tiers/episodic-memory.d.ts.map +1 -1
  188. package/dist/tiers/episodic-memory.js +3 -2
  189. package/dist/tiers/episodic-memory.js.map +1 -1
  190. package/dist/tiers/index.d.ts +1 -1
  191. package/dist/tiers/index.js +1 -1
  192. package/dist/tiers/insight-memory.d.ts +4 -4
  193. package/dist/tiers/insight-memory.js +3 -3
  194. package/dist/tiers/insight-memory.js.map +1 -1
  195. package/dist/tiers/procedural-memory.d.ts +29 -7
  196. package/dist/tiers/procedural-memory.d.ts.map +1 -1
  197. package/dist/tiers/procedural-memory.js +66 -6
  198. package/dist/tiers/procedural-memory.js.map +1 -1
  199. package/dist/tiers/semantic-memory.d.ts +111 -30
  200. package/dist/tiers/semantic-memory.d.ts.map +1 -1
  201. package/dist/tiers/semantic-memory.js +120 -27
  202. package/dist/tiers/semantic-memory.js.map +1 -1
  203. package/dist/tiers/session-memory.d.ts +7 -7
  204. package/dist/tiers/session-memory.js +7 -7
  205. package/dist/tiers/session-memory.js.map +1 -1
  206. package/dist/tiers/shared-memory.d.ts +1 -1
  207. package/dist/tiers/shared-memory.js +1 -1
  208. package/dist/tiers/shared-memory.js.map +1 -1
  209. package/dist/tiers/working-memory.d.ts +3 -3
  210. package/dist/tiers/working-memory.js +2 -2
  211. package/dist/tiers/working-memory.js.map +1 -1
  212. package/dist/tools/block-tools.d.ts +9 -9
  213. package/dist/tools/block-tools.d.ts.map +1 -1
  214. package/dist/tools/block-tools.js +3 -3
  215. package/dist/tools/block-tools.js.map +1 -1
  216. package/dist/tools/fact-tools.d.ts +48 -31
  217. package/dist/tools/fact-tools.d.ts.map +1 -1
  218. package/dist/tools/fact-tools.js +30 -18
  219. package/dist/tools/fact-tools.js.map +1 -1
  220. package/dist/tools/index.d.ts +9 -2
  221. package/dist/tools/index.d.ts.map +1 -1
  222. package/dist/tools/index.js +4 -2
  223. package/dist/tools/index.js.map +1 -1
  224. package/dist/tools/recall-tools.d.ts +40 -20
  225. package/dist/tools/recall-tools.d.ts.map +1 -1
  226. package/dist/tools/recall-tools.js +29 -10
  227. package/dist/tools/recall-tools.js.map +1 -1
  228. package/dist/tools/runbook-tools.d.ts +76 -0
  229. package/dist/tools/runbook-tools.d.ts.map +1 -0
  230. package/dist/tools/runbook-tools.js +53 -0
  231. package/dist/tools/runbook-tools.js.map +1 -0
  232. package/dist/tools/taint.js +33 -0
  233. package/dist/tools/taint.js.map +1 -0
  234. package/dist/tools/types.d.ts +1 -1
  235. package/package.json +8 -8
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { EmbedderMigrationAbortedError, EmbedderMigrationLockedError, EmbedderMigrationStateError, EmbedderRegistrationError, GraphorinMemoryError, MemoryToolDeniedError, ProcedureInductionNotConfiguredError, QuarantinePromotionRefusedError, WorkingBlockOverflowError, WorkingBlockReadOnlyError, WorkingBlockReplaceMismatchError } from "./errors/index.js";
2
1
  import { LocaleMatch, LocalePack, LocalePatternEntry, LocaleSupersedeKind, defineLocalePack, evaluateMarkers } from "./conflict/locale-packs/types.js";
3
2
  import { ConflictAuditDecision, ConflictAuditInputLike, ConflictAuditStage, ConflictMemoryStoreExt, ConsolidatorMemoryStoreExt, ConsolidatorRunFinish, ConsolidatorRunInput, ConsolidatorStatePatch, ConsolidatorStateRow, DecayMemoryStoreExt, DlqBatchInput, DlqBatchRow, EmbeddedWriteOptions, EmbeddingMetaRegistryLike, EpisodicMemoryStoreExt, InsightListOptions as InsightListOptions$1, InsightMemoryStoreExt, InsightSearchStoreOptions, MemoryStoreAdapter, PendingConflictInputLike, PendingConflictRowLike, SemanticMemoryStoreExt, SessionMemoryStoreExt, SessionMessageRecord } from "./internal/storage-adapter.js";
4
3
  import { ConflictDecision, ConflictPipeline, ConflictPipelineDeps, ConflictPipelineOptions, ConflictStage, ConflictThresholds, DEFAULT_CONFLICT_THRESHOLDS, PipelineStage, ReconcileAction, ReconcileDecision, StageContext, StageOutcome, reconcileToConflictDecision } from "./conflict/types.js";
5
4
  import { _resetBypassWarningForTesting, createConflictPipeline, runConflictPipeline } from "./conflict/pipeline.js";
6
5
  import "./conflict/index.js";
6
+ import { EmbedderMigrationAbortedError, EmbedderMigrationLockedError, EmbedderMigrationStateError, EmbedderRegistrationError, GraphorinMemoryError, MemoryToolDeniedError, ProcedureInductionNotConfiguredError, QuarantinePromotionRefusedError, WorkingBlockOverflowError, WorkingBlockReadOnlyError, WorkingBlockReplaceMismatchError } from "./errors/index.js";
7
7
  import { ContextualRetrievalMode } from "./internal/contextualize.js";
8
8
  import { EpisodeInput, EpisodeRetrievalWeights, EpisodeSearchOptions, EpisodicMemory } from "./tiers/episodic-memory.js";
9
9
  import { DEFAULT_ADJUDICATE_THRESHOLD, DEFAULT_MERGE_THRESHOLD, EntityResolutionConfig, EntityResolveDecision, EntityResolver, EntityResolverDeps, ResolutionCandidate, ResolveDecisionInput, buildAdjudicationRequest, cosineSimilarity, normalizeEntityName, parseAdjudication, resolveEntityDecision } from "./graph/entity-resolver.js";
@@ -11,6 +11,7 @@ import { DEFAULT_DIFFICULTY_THRESHOLD, DEFAULT_MAX_ITERATIONS, DifficultyAssessm
11
11
  import { DEFAULT_MAX_QUERY_VARIANTS, HYDE_SYSTEM_PROMPT, QUERY_EXPANSION_SYSTEM_PROMPT, QueryTransformOptions, QueryTransformer, buildExpansionRequest, buildHydeRequest, createProviderQueryTransformer, parseHypothetical, parseQueryVariants } from "./search/query-transform.js";
12
12
  import { ReRankOptions, ReRanker } from "./search/types.js";
13
13
  import { FactInput, FactRememberOptions, FactSearchOptions, FusionStrategy, FusionWeights, IterativeRecallResult, IterativeSearchOptions, RememberOutcome, SemanticMemory } from "./tiers/semantic-memory.js";
14
+ import { BlockDefinition, BlockSpec, WorkingMemory, defineBlock } from "./tiers/working-memory.js";
14
15
  import { CONSOLIDATOR_TIER_DEFAULTS, ConsolidatorBudgetSnapshot, ConsolidatorCeilings, ConsolidatorConfig, ConsolidatorLastRuns, ConsolidatorPhase, ConsolidatorStatus, ConsolidatorTier, ConsolidatorTriggerReason, ConsolidatorTriggerSpec, CreateConsolidatorOptions, OnBudgetExceed, PhaseListener, PhaseOutcome } from "./consolidator/types.js";
15
16
  import { ParsedTrigger, parseTriggerSpec, reasonFromTrigger } from "./consolidator/triggers.js";
16
17
  import { ConsolidatorCatchupPolicy, RegisterTriggersOptions, RegisterTriggersResult, SchedulerLike, TriggerDeclarationLike, registerConsolidatorTriggers } from "./consolidator/scheduler.js";
@@ -30,6 +31,7 @@ import { NamedPostCompactionHook } from "./context-engine/compaction/hooks/types
30
31
  import { reanchorPersonaBlock } from "./context-engine/compaction/hooks/reanchor-persona-block.js";
31
32
  import { reanchorPinnedFacts } from "./context-engine/compaction/hooks/reanchor-pinned-facts.js";
32
33
  import { reanchorProjectRules } from "./context-engine/compaction/hooks/reanchor-project-rules.js";
34
+ import { ReanchorRecentResultsOptions, reanchorRecentResults } from "./context-engine/compaction/hooks/reanchor-recent-results.js";
33
35
  import { CompactionMetadataPayload, RenderedTemplate, SUMMARY_TEMPLATE_NAME, SUMMARY_TEMPLATE_VERSION, buildSummarizerPrompt, renderFinalSummary } from "./context-engine/compaction/templates/summary-9-section.js";
34
36
  import { AutoCompactionDefault, DEFAULT_RESERVED_FOR_COMPACTION, DEFAULT_RESERVED_FOR_RESPONSE, DEFAULT_THRESHOLD_RATIO, resolveAutoCompactionDefault, resolveTriggerThreshold } from "./context-engine/compaction/thresholds.js";
35
37
  import { PartitionResult, PrivacyDecision, PrivacyDecisionReason, PrivacyFilterContext, decide, effectiveAcceptsSensitivity, partition } from "./context-engine/privacy-filter.js";
@@ -45,7 +47,6 @@ import { InsightListOptions, InsightMemory, InsightSearchOptions, capInsightsBel
45
47
  import { InduceOptions, ProceduralMemory, RuleActivationContext, RuleInput } from "./tiers/procedural-memory.js";
46
48
  import { SessionCompactionPolicy, SessionCompactionResult, SessionMemory } from "./tiers/session-memory.js";
47
49
  import { SharedMemory } from "./tiers/shared-memory.js";
48
- import { BlockDefinition, BlockSpec, WorkingMemory, defineBlock } from "./tiers/working-memory.js";
49
50
  import { MemoryToolDeps, ScopeResolver } from "./tools/types.js";
50
51
  import { createBlockAppendTool, createBlockReplaceTool, createBlockRethinkTool } from "./tools/block-tools.js";
51
52
  import { createFactForgetTool, createFactHistoryTool, createFactRememberTool, createFactSearchTool, createFactSupersedeTool, createFactValidateTool } from "./tools/fact-tools.js";
@@ -56,13 +57,16 @@ import "./graph/index.js";
56
57
  import { EmbedderMigrationStrategy, MigrateEmbedderOptions, MigrationProgress, migrateEmbedder } from "./migration/embedder-migration.js";
57
58
  import "./migration/index.js";
58
59
  import { RecallExplanation, RecalledMemoryExplanation, explainRecall, formatRecallExplanation } from "./search/explain.js";
60
+ import { FitFusionCase, FitFusionOptions, FitFusionResult, fitFusionWeights, ndcgAtK } from "./search/fit-weights.js";
61
+ import { DEFAULT_PPR_DAMPING, pprActivation } from "./search/graph-ppr.js";
59
62
  import { RRFReranker, RRF_DEFAULT_K, WeightedRRFReranker, fuseRrf, fuseWeighted } from "./search/rrf.js";
63
+ import { isForeignProvenance, trustDiscount } from "./search/trust.js";
60
64
  import "./search/index.js";
61
65
  import "./tiers/index.js";
62
66
 
63
67
  //#region src/index.d.ts
64
68
  /**
65
- * `@graphorin/memory` seven-tier memory system for the Graphorin
69
+ * `@graphorin/memory` - seven-tier memory system for the Graphorin
66
70
  * framework (MST-13: working / session / episodic / semantic /
67
71
  * procedural / shared + the read-only insight tier from P1-1).
68
72
  *
@@ -97,7 +101,7 @@ import "./tiers/index.js";
97
101
  * @packageDocumentation
98
102
  */
99
103
  /** Canonical version constant. Mirrors the `package.json` version. */
100
- declare const VERSION = "0.5.0";
104
+ declare const VERSION = "0.6.0";
101
105
  //#endregion
102
- export { type AllocationResult, type AnnotatedPart, type AssembleInput, type AssembledPrompt, type AutoCompactionDefault, type AutoRecallConfig, type AutoRecallStrategy, type AutoRecallStrategyContext, type AutoRecallTriggerResult, type AutoRecallTriggers, BASE_TEMPLATE_EN_FULL, BASE_TEMPLATE_EN_MINIMAL, type BaseTemplateFragments, BlockDefinition, BlockSpec, BudgetExceededError, type BuildMemoryToolsOptions, CLEARED_TOOL_RESULT_MARKER, CONSOLIDATOR_TIER_DEFAULTS, CONTENT_ORIGIN_ATTR, type ClearToolResultsOptions, type ClearToolResultsOutcome, type CompactionConfig, type CompactionContext, type CompactionMetadataPayload, type CompactionResult, type CompactionSource, type CompactionStrategy, type CompactionSummarizer, type CompactionSummaryTemplate, type CompactionTriggerConfig, type CompileOptions, type CompileScope, type ConflictAuditDecision, type ConflictAuditInputLike, type ConflictAuditStage, ConflictDecision, type ConflictMemoryStoreExt, ConflictPipeline, ConflictPipelineDeps, ConflictPipelineOptions, ConflictStage, ConflictThresholds, type Consolidator, type ConsolidatorBudgetSnapshot, type ConsolidatorCatchupPolicy, type ConsolidatorCeilings, type ConsolidatorConfig, type ConsolidatorLastRuns, type ConsolidatorMemoryStoreExt, type ConsolidatorPhase, type ConsolidatorRunFinish, type ConsolidatorRunInput, type ConsolidatorStatePatch, type ConsolidatorStateRow, type ConsolidatorStatus, type ConsolidatorTier, type ConsolidatorTriggerReason, type ConsolidatorTriggerSpec, type ContentAnnotation, type ContentOrigin, type ContextEngine, type ContextEngineConfig, type ContextLocalePack, type ContextTokenCounter, type ContextualRetrievalMode, type CreateConsolidatorOptions, type CreateMemoryOptions, CustomTierMisconfiguredError, DEFAULT_ADJUDICATE_THRESHOLD, DEFAULT_CONFLICT_THRESHOLDS, DEFAULT_DIFFICULTY_THRESHOLD, DEFAULT_INDUCTION_MAX_TOKENS, DEFAULT_LAYER_PRIORITY, DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_QUERY_VARIANTS, DEFAULT_MERGE_THRESHOLD, DEFAULT_PRESERVE_RECENT_TURNS, DEFAULT_RESERVED_FOR_COMPACTION, DEFAULT_RESERVED_FOR_RESPONSE, DEFAULT_THRESHOLD_RATIO, type DecayMemoryStoreExt, DifficultyAssessment, DifficultyGateOptions, type DlqBatchInput, type DlqBatchRow, type EmbeddedWriteOptions, EmbedderMigrationAbortedError, EmbedderMigrationLockedError, EmbedderMigrationStateError, EmbedderMigrationStrategy, EmbedderRegistrationError, type EmbeddingMetaRegistryLike, EntityResolutionConfig, EntityResolveDecision, EntityResolver, EntityResolverDeps, EpisodeInput, EpisodeRetrievalWeights, EpisodeSearchOptions, EpisodicMemory, type EpisodicMemoryStoreExt, type ExecuteCompactionInput, FactInput, FactRememberOptions, FactSearchOptions, FusionStrategy, FusionWeights, GraphorinMemoryError, HEURISTIC_TOKEN_COUNTER, HYDE_SYSTEM_PROMPT, INBOUND_SANITIZATION_PREAMBLE_EN, INBOUND_TRUST_ATTR, INDUCTION_SYSTEM_PROMPT, type InboundSanitizationPreamble, type InboundTrust, InduceOptions, type InducedProcedure, InsightListOptions, InsightMemory, type InsightMemoryStoreExt, InsightSearchOptions, type InsightSearchStoreOptions, type InsightListOptions$1 as InsightStoreListOptions, IterativeRecallResult, IterativeRetrievalDeps, IterativeRetrievalOptions, IterativeRetrievalResult, IterativeSearchOptions, type LayerAllocation, type LayerCandidate, type LayerConfig, type LayerId, LocaleMatch, LocalePack, LocalePatternEntry, type LocaleResolverLogger, LocaleSupersedeKind, MAX_ITERATIONS_CEILING, MAX_PROCEDURE_STEPS, MAX_TRAJECTORY_STEPS_SHOWN, type Memory, type MemoryBaseMode, type MemoryContextBlocks, type MemoryMetadataDeps, type MemoryStoreAdapter, MemoryToolDeniedError, type MemoryToolDeps, MigrateEmbedderOptions, MigrationProgress, NON_INBOUND_ORIGINS, type NamedPostCompactionHook, type OnBudgetExceed, type OverflowMode, type ParsedTrigger, type PartialContextLocalePack, type PartitionResult, type PendingConflictInputLike, type PendingConflictRowLike, type PhaseListener, type PhaseOutcome, PipelineStage, type PostCompactionHook, type PostCompactionHookContext, type PrivacyConfig, type PrivacyDecision, type PrivacyDecisionReason, type PrivacyFilterContext, ProceduralMemory, ProcedureInductionNotConfiguredError, ProviderNotConfiguredError, QUERY_EXPANSION_SYSTEM_PROMPT, QuarantinePromotionRefusedError, QueryTransformOptions, QueryTransformer, RETRIEVAL_GRADE_SYSTEM_PROMPT, RRFReranker, RRF_DEFAULT_K, ReRankOptions, ReRanker, RecallExplanation, RecalledMemoryExplanation, ReconcileAction, ReconcileDecision, type RegisterTriggersOptions, type RegisterTriggersResult, RememberOutcome, type RenderedTemplate, ResolutionCandidate, ResolveDecisionInput, type ResolvedContextEngineConfig, RetrievalGrade, RetrievalGradeOptions, RetrievalGrader, RuleActivationContext, RuleInput, SUMMARY_TEMPLATE_NAME, SUMMARY_TEMPLATE_VERSION, type SchedulerLike, type ScopeResolver, SemanticMemory, type SemanticMemoryStoreExt, SessionCompactionPolicy, SessionCompactionResult, SessionMemory, type SessionMemoryStoreExt, type SessionMessageRecord, SharedMemory, type SkillMetadataCard, StageContext, StageOutcome, type Trajectory, type TrajectoryStep, type TriggerDeclarationLike, VERSION, type VerificationResult, WeightedRRFReranker, type WorkflowInducer, type WorkflowInductionOptions, WorkingBlockOverflowError, WorkingBlockReadOnlyError, WorkingBlockReplaceMismatchError, WorkingMemory, _getLocaleFallbackWarningsForTesting, _resetBypassWarningForTesting, _resetConsolidatorConfigWarningForTesting, _resetLocaleFallbackWarningsForTesting, adaptTokenCounter, allocate as allocateTokenBudget, annotate, assessQueryDifficulty, buildAdjudicationRequest, buildExpansionRequest, buildGradeRequest, buildHydeRequest, buildInductionRequest, buildMemoryTools, buildSummarizerPrompt, capInsightsBelowFacts, checkSuccessCriteria, clearOldToolResults, composeInboundPreamble, composeLayer1, composeLayer2, composeLayer4Skills, cosineSimilarity, countMessageTokens, createBlockAppendTool, createBlockReplaceTool, createBlockRethinkTool, createConflictPipeline, createConsolidator, createConsolidatorPlaceholder, createContextEngine, createConversationSearchTool, createDeepRecallTool, createFactForgetTool, createFactHistoryTool, createFactRememberTool, createFactSearchTool, createFactSupersedeTool, createFactValidateTool, createMemory, createProviderQueryTransformer, createProviderRetrievalGrader, createProviderWorkflowInducer, createRecallEpisodesTool, defaultLocaleHeuristicStrategy, defineAutoRecallStrategy, defineBlock, defineContextLocalePack, defineLocalePack, effectiveAcceptsSensitivity, enLocalePack, evaluateMarkers, executeCompaction, explainRecall, formatRecallExplanation, fuseRrf, fuseWeighted, gatherMemoryMetadata, migrateEmbedder, normalizeEntityName, normalizeInducedProcedure, parseAdjudication, parseGrade, parseHypothetical, parseInducedProcedure, parseQueryVariants, parseTriggerSpec, partition as partitionBySensitivity, decide as privacyDecide, reanchorPersonaBlock, reanchorPinnedFacts, reanchorProjectRules, reasonFromTrigger, reconcileToConflictDecision, registerConsolidatorTriggers, renderFinalSummary, renderMessageText, renderMetadataBlock, resolveAutoCompactionDefault, resolveEntityDecision, resolveLocalePack, resolveTriggerThreshold, runConflictPipeline, runIterativeRetrieval, runWorkflowInduction, shouldFireInboundPreamble, toSpanAttributes, trajectoryFromRunState, truncateToTokens };
106
+ export { type AllocationResult, type AnnotatedPart, type AssembleInput, type AssembledPrompt, type AutoCompactionDefault, type AutoRecallConfig, type AutoRecallStrategy, type AutoRecallStrategyContext, type AutoRecallTriggerResult, type AutoRecallTriggers, BASE_TEMPLATE_EN_FULL, BASE_TEMPLATE_EN_MINIMAL, type BaseTemplateFragments, BlockDefinition, BlockSpec, BudgetExceededError, type BuildMemoryToolsOptions, CLEARED_TOOL_RESULT_MARKER, CONSOLIDATOR_TIER_DEFAULTS, CONTENT_ORIGIN_ATTR, type ClearToolResultsOptions, type ClearToolResultsOutcome, type CompactionConfig, type CompactionContext, type CompactionMetadataPayload, type CompactionResult, type CompactionSource, type CompactionStrategy, type CompactionSummarizer, type CompactionSummaryTemplate, type CompactionTriggerConfig, type CompileOptions, type CompileScope, type ConflictAuditDecision, type ConflictAuditInputLike, type ConflictAuditStage, ConflictDecision, type ConflictMemoryStoreExt, ConflictPipeline, ConflictPipelineDeps, ConflictPipelineOptions, ConflictStage, ConflictThresholds, type Consolidator, type ConsolidatorBudgetSnapshot, type ConsolidatorCatchupPolicy, type ConsolidatorCeilings, type ConsolidatorConfig, type ConsolidatorLastRuns, type ConsolidatorMemoryStoreExt, type ConsolidatorPhase, type ConsolidatorRunFinish, type ConsolidatorRunInput, type ConsolidatorStatePatch, type ConsolidatorStateRow, type ConsolidatorStatus, type ConsolidatorTier, type ConsolidatorTriggerReason, type ConsolidatorTriggerSpec, type ContentAnnotation, type ContentOrigin, type ContextEngine, type ContextEngineConfig, type ContextLocalePack, type ContextTokenCounter, type ContextualRetrievalMode, type CreateConsolidatorOptions, type CreateMemoryOptions, CustomTierMisconfiguredError, DEFAULT_ADJUDICATE_THRESHOLD, DEFAULT_CONFLICT_THRESHOLDS, DEFAULT_DIFFICULTY_THRESHOLD, DEFAULT_INDUCTION_MAX_TOKENS, DEFAULT_LAYER_PRIORITY, DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_QUERY_VARIANTS, DEFAULT_MERGE_THRESHOLD, DEFAULT_PPR_DAMPING, DEFAULT_PRESERVE_RECENT_TURNS, DEFAULT_RESERVED_FOR_COMPACTION, DEFAULT_RESERVED_FOR_RESPONSE, DEFAULT_THRESHOLD_RATIO, type DecayMemoryStoreExt, DifficultyAssessment, DifficultyGateOptions, type DlqBatchInput, type DlqBatchRow, type EmbeddedWriteOptions, EmbedderMigrationAbortedError, EmbedderMigrationLockedError, EmbedderMigrationStateError, EmbedderMigrationStrategy, EmbedderRegistrationError, type EmbeddingMetaRegistryLike, EntityResolutionConfig, EntityResolveDecision, EntityResolver, EntityResolverDeps, EpisodeInput, EpisodeRetrievalWeights, EpisodeSearchOptions, EpisodicMemory, type EpisodicMemoryStoreExt, type ExecuteCompactionInput, FactInput, FactRememberOptions, FactSearchOptions, FitFusionCase, FitFusionOptions, FitFusionResult, FusionStrategy, FusionWeights, GraphorinMemoryError, HEURISTIC_TOKEN_COUNTER, HYDE_SYSTEM_PROMPT, INBOUND_SANITIZATION_PREAMBLE_EN, INBOUND_TRUST_ATTR, INDUCTION_SYSTEM_PROMPT, type InboundSanitizationPreamble, type InboundTrust, InduceOptions, type InducedProcedure, InsightListOptions, InsightMemory, type InsightMemoryStoreExt, InsightSearchOptions, type InsightSearchStoreOptions, type InsightListOptions$1 as InsightStoreListOptions, IterativeRecallResult, IterativeRetrievalDeps, IterativeRetrievalOptions, IterativeRetrievalResult, IterativeSearchOptions, type LayerAllocation, type LayerCandidate, type LayerConfig, type LayerId, LocaleMatch, LocalePack, LocalePatternEntry, type LocaleResolverLogger, LocaleSupersedeKind, MAX_ITERATIONS_CEILING, MAX_PROCEDURE_STEPS, MAX_TRAJECTORY_STEPS_SHOWN, type Memory, type MemoryBaseMode, type MemoryContextBlocks, type MemoryMetadataDeps, type MemoryStoreAdapter, MemoryToolDeniedError, type MemoryToolDeps, MigrateEmbedderOptions, MigrationProgress, NON_INBOUND_ORIGINS, type NamedPostCompactionHook, type OnBudgetExceed, type OverflowMode, type ParsedTrigger, type PartialContextLocalePack, type PartitionResult, type PendingConflictInputLike, type PendingConflictRowLike, type PhaseListener, type PhaseOutcome, PipelineStage, type PostCompactionHook, type PostCompactionHookContext, type PrivacyConfig, type PrivacyDecision, type PrivacyDecisionReason, type PrivacyFilterContext, ProceduralMemory, ProcedureInductionNotConfiguredError, ProviderNotConfiguredError, QUERY_EXPANSION_SYSTEM_PROMPT, QuarantinePromotionRefusedError, QueryTransformOptions, QueryTransformer, RETRIEVAL_GRADE_SYSTEM_PROMPT, RRFReranker, RRF_DEFAULT_K, ReRankOptions, ReRanker, type ReanchorRecentResultsOptions, RecallExplanation, RecalledMemoryExplanation, ReconcileAction, ReconcileDecision, type RegisterTriggersOptions, type RegisterTriggersResult, RememberOutcome, type RenderedTemplate, ResolutionCandidate, ResolveDecisionInput, type ResolvedContextEngineConfig, RetrievalGrade, RetrievalGradeOptions, RetrievalGrader, RuleActivationContext, RuleInput, SUMMARY_TEMPLATE_NAME, SUMMARY_TEMPLATE_VERSION, type SchedulerLike, type ScopeResolver, SemanticMemory, type SemanticMemoryStoreExt, SessionCompactionPolicy, SessionCompactionResult, SessionMemory, type SessionMemoryStoreExt, type SessionMessageRecord, SharedMemory, type SkillMetadataCard, StageContext, StageOutcome, type Trajectory, type TrajectoryStep, type TriggerDeclarationLike, VERSION, type VerificationResult, WeightedRRFReranker, type WorkflowInducer, type WorkflowInductionOptions, WorkingBlockOverflowError, WorkingBlockReadOnlyError, WorkingBlockReplaceMismatchError, WorkingMemory, _getLocaleFallbackWarningsForTesting, _resetBypassWarningForTesting, _resetConsolidatorConfigWarningForTesting, _resetLocaleFallbackWarningsForTesting, adaptTokenCounter, allocate as allocateTokenBudget, annotate, assessQueryDifficulty, buildAdjudicationRequest, buildExpansionRequest, buildGradeRequest, buildHydeRequest, buildInductionRequest, buildMemoryTools, buildSummarizerPrompt, capInsightsBelowFacts, checkSuccessCriteria, clearOldToolResults, composeInboundPreamble, composeLayer1, composeLayer2, composeLayer4Skills, cosineSimilarity, countMessageTokens, createBlockAppendTool, createBlockReplaceTool, createBlockRethinkTool, createConflictPipeline, createConsolidator, createConsolidatorPlaceholder, createContextEngine, createConversationSearchTool, createDeepRecallTool, createFactForgetTool, createFactHistoryTool, createFactRememberTool, createFactSearchTool, createFactSupersedeTool, createFactValidateTool, createMemory, createProviderQueryTransformer, createProviderRetrievalGrader, createProviderWorkflowInducer, createRecallEpisodesTool, defaultLocaleHeuristicStrategy, defineAutoRecallStrategy, defineBlock, defineContextLocalePack, defineLocalePack, effectiveAcceptsSensitivity, enLocalePack, evaluateMarkers, executeCompaction, explainRecall, fitFusionWeights, formatRecallExplanation, fuseRrf, fuseWeighted, gatherMemoryMetadata, isForeignProvenance, migrateEmbedder, ndcgAtK, normalizeEntityName, normalizeInducedProcedure, parseAdjudication, parseGrade, parseHypothetical, parseInducedProcedure, parseQueryVariants, parseTriggerSpec, partition as partitionBySensitivity, pprActivation, decide as privacyDecide, reanchorPersonaBlock, reanchorPinnedFacts, reanchorProjectRules, reanchorRecentResults, reasonFromTrigger, reconcileToConflictDecision, registerConsolidatorTriggers, renderFinalSummary, renderMessageText, renderMetadataBlock, resolveAutoCompactionDefault, resolveEntityDecision, resolveLocalePack, resolveTriggerThreshold, runConflictPipeline, runIterativeRetrieval, runWorkflowInduction, shouldFireInboundPreamble, toSpanAttributes, trajectoryFromRunState, truncateToTokens, trustDiscount };
103
107
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqCa,OAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqCa,OAAA"}
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import "./conflict/index.js";
5
5
  import { EmbedderMigrationAbortedError, EmbedderMigrationLockedError, EmbedderMigrationStateError, EmbedderRegistrationError, GraphorinMemoryError, MemoryToolDeniedError, ProcedureInductionNotConfiguredError, QuarantinePromotionRefusedError, WorkingBlockOverflowError, WorkingBlockReadOnlyError, WorkingBlockReplaceMismatchError } from "./errors/index.js";
6
6
  import { BudgetExceededError, CustomTierMisconfiguredError, ProviderNotConfiguredError } from "./consolidator/errors.js";
7
7
  import { DEFAULT_INDUCTION_MAX_TOKENS, INDUCTION_SYSTEM_PROMPT, MAX_PROCEDURE_STEPS, MAX_TRAJECTORY_STEPS_SHOWN, buildInductionRequest, checkSuccessCriteria, createProviderWorkflowInducer, normalizeInducedProcedure, parseInducedProcedure, runWorkflowInduction, trajectoryFromRunState } from "./consolidator/phases/induce.js";
8
+ import { WorkingMemory, defineBlock } from "./tiers/working-memory.js";
8
9
  import { parseTriggerSpec, reasonFromTrigger } from "./consolidator/triggers.js";
9
10
  import { registerConsolidatorTriggers } from "./consolidator/scheduler.js";
10
11
  import { CONSOLIDATOR_TIER_DEFAULTS } from "./consolidator/types.js";
@@ -19,6 +20,7 @@ import { DEFAULT_PRESERVE_RECENT_TURNS, executeCompaction } from "./context-engi
19
20
  import { reanchorPersonaBlock } from "./context-engine/compaction/hooks/reanchor-persona-block.js";
20
21
  import { reanchorPinnedFacts } from "./context-engine/compaction/hooks/reanchor-pinned-facts.js";
21
22
  import { reanchorProjectRules } from "./context-engine/compaction/hooks/reanchor-project-rules.js";
23
+ import { reanchorRecentResults } from "./context-engine/compaction/hooks/reanchor-recent-results.js";
22
24
  import { DEFAULT_RESERVED_FOR_COMPACTION, DEFAULT_RESERVED_FOR_RESPONSE, DEFAULT_THRESHOLD_RATIO, resolveAutoCompactionDefault, resolveTriggerThreshold } from "./context-engine/compaction/thresholds.js";
23
25
  import { enLocalePack } from "./context-engine/locale-packs/en.js";
24
26
  import { defineContextLocalePack } from "./context-engine/locale-packs/types.js";
@@ -39,21 +41,24 @@ import { EpisodicMemory } from "./tiers/episodic-memory.js";
39
41
  import { InsightMemory, capInsightsBelowFacts } from "./tiers/insight-memory.js";
40
42
  import { ProceduralMemory } from "./tiers/procedural-memory.js";
41
43
  import { explainRecall, formatRecallExplanation } from "./search/explain.js";
44
+ import { DEFAULT_PPR_DAMPING, pprActivation } from "./search/graph-ppr.js";
45
+ import { isForeignProvenance, trustDiscount } from "./search/trust.js";
42
46
  import { SemanticMemory } from "./tiers/semantic-memory.js";
43
47
  import { SessionMemory } from "./tiers/session-memory.js";
44
48
  import { SharedMemory } from "./tiers/shared-memory.js";
45
- import { WorkingMemory, defineBlock } from "./tiers/working-memory.js";
46
49
  import { createBlockAppendTool, createBlockReplaceTool, createBlockRethinkTool } from "./tools/block-tools.js";
47
50
  import { createFactForgetTool, createFactHistoryTool, createFactRememberTool, createFactSearchTool, createFactSupersedeTool, createFactValidateTool } from "./tools/fact-tools.js";
48
51
  import { createConversationSearchTool, createDeepRecallTool, createRecallEpisodesTool } from "./tools/recall-tools.js";
49
52
  import { buildMemoryTools } from "./tools/index.js";
50
53
  import { _resetConsolidatorConfigWarningForTesting, createMemory } from "./facade.js";
51
54
  import { migrateEmbedder } from "./migration/embedder-migration.js";
55
+ import { fitFusionWeights, ndcgAtK } from "./search/fit-weights.js";
56
+ import "./search/index.js";
52
57
  import "./tiers/index.js";
53
58
 
54
59
  //#region src/index.ts
55
60
  /**
56
- * `@graphorin/memory` seven-tier memory system for the Graphorin
61
+ * `@graphorin/memory` - seven-tier memory system for the Graphorin
57
62
  * framework (MST-13: working / session / episodic / semantic /
58
63
  * procedural / shared + the read-only insight tier from P1-1).
59
64
  *
@@ -88,8 +93,8 @@ import "./tiers/index.js";
88
93
  * @packageDocumentation
89
94
  */
90
95
  /** Canonical version constant. Mirrors the `package.json` version. */
91
- const VERSION = "0.5.0";
96
+ const VERSION = "0.6.0";
92
97
 
93
98
  //#endregion
94
- export { BASE_TEMPLATE_EN_FULL, BASE_TEMPLATE_EN_MINIMAL, BudgetExceededError, CLEARED_TOOL_RESULT_MARKER, CONSOLIDATOR_TIER_DEFAULTS, CONTENT_ORIGIN_ATTR, CustomTierMisconfiguredError, DEFAULT_ADJUDICATE_THRESHOLD, DEFAULT_CONFLICT_THRESHOLDS, DEFAULT_DIFFICULTY_THRESHOLD, DEFAULT_INDUCTION_MAX_TOKENS, DEFAULT_LAYER_PRIORITY, DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_QUERY_VARIANTS, DEFAULT_MERGE_THRESHOLD, DEFAULT_PRESERVE_RECENT_TURNS, DEFAULT_RESERVED_FOR_COMPACTION, DEFAULT_RESERVED_FOR_RESPONSE, DEFAULT_THRESHOLD_RATIO, EmbedderMigrationAbortedError, EmbedderMigrationLockedError, EmbedderMigrationStateError, EmbedderRegistrationError, EntityResolver, EpisodicMemory, GraphorinMemoryError, HEURISTIC_TOKEN_COUNTER, HYDE_SYSTEM_PROMPT, INBOUND_SANITIZATION_PREAMBLE_EN, INBOUND_TRUST_ATTR, INDUCTION_SYSTEM_PROMPT, InsightMemory, MAX_ITERATIONS_CEILING, MAX_PROCEDURE_STEPS, MAX_TRAJECTORY_STEPS_SHOWN, MemoryToolDeniedError, NON_INBOUND_ORIGINS, ProceduralMemory, ProcedureInductionNotConfiguredError, ProviderNotConfiguredError, QUERY_EXPANSION_SYSTEM_PROMPT, QuarantinePromotionRefusedError, RETRIEVAL_GRADE_SYSTEM_PROMPT, RRFReranker, RRF_DEFAULT_K, SUMMARY_TEMPLATE_NAME, SUMMARY_TEMPLATE_VERSION, SemanticMemory, SessionMemory, SharedMemory, VERSION, WeightedRRFReranker, WorkingBlockOverflowError, WorkingBlockReadOnlyError, WorkingBlockReplaceMismatchError, WorkingMemory, _getLocaleFallbackWarningsForTesting, _resetBypassWarningForTesting, _resetConsolidatorConfigWarningForTesting, _resetLocaleFallbackWarningsForTesting, adaptTokenCounter, allocate as allocateTokenBudget, annotate, assessQueryDifficulty, buildAdjudicationRequest, buildExpansionRequest, buildGradeRequest, buildHydeRequest, buildInductionRequest, buildMemoryTools, buildSummarizerPrompt, capInsightsBelowFacts, checkSuccessCriteria, clearOldToolResults, composeInboundPreamble, composeLayer1, composeLayer2, composeLayer4Skills, cosineSimilarity, countMessageTokens, createBlockAppendTool, createBlockReplaceTool, createBlockRethinkTool, createConflictPipeline, createConsolidator, createConsolidatorPlaceholder, createContextEngine, createConversationSearchTool, createDeepRecallTool, createFactForgetTool, createFactHistoryTool, createFactRememberTool, createFactSearchTool, createFactSupersedeTool, createFactValidateTool, createMemory, createProviderQueryTransformer, createProviderRetrievalGrader, createProviderWorkflowInducer, createRecallEpisodesTool, defaultLocaleHeuristicStrategy, defineAutoRecallStrategy, defineBlock, defineContextLocalePack, defineLocalePack, effectiveAcceptsSensitivity, enLocalePack, evaluateMarkers, executeCompaction, explainRecall, formatRecallExplanation, fuseRrf, fuseWeighted, gatherMemoryMetadata, migrateEmbedder, normalizeEntityName, normalizeInducedProcedure, parseAdjudication, parseGrade, parseHypothetical, parseInducedProcedure, parseQueryVariants, parseTriggerSpec, partition as partitionBySensitivity, decide as privacyDecide, reanchorPersonaBlock, reanchorPinnedFacts, reanchorProjectRules, reasonFromTrigger, reconcileToConflictDecision, registerConsolidatorTriggers, renderFinalSummary, renderMessageText, renderMetadataBlock, resolveAutoCompactionDefault, resolveEntityDecision, resolveLocalePack, resolveTriggerThreshold, runConflictPipeline, runIterativeRetrieval, runWorkflowInduction, shouldFireInboundPreamble, toSpanAttributes, trajectoryFromRunState, truncateToTokens };
99
+ export { BASE_TEMPLATE_EN_FULL, BASE_TEMPLATE_EN_MINIMAL, BudgetExceededError, CLEARED_TOOL_RESULT_MARKER, CONSOLIDATOR_TIER_DEFAULTS, CONTENT_ORIGIN_ATTR, CustomTierMisconfiguredError, DEFAULT_ADJUDICATE_THRESHOLD, DEFAULT_CONFLICT_THRESHOLDS, DEFAULT_DIFFICULTY_THRESHOLD, DEFAULT_INDUCTION_MAX_TOKENS, DEFAULT_LAYER_PRIORITY, DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_QUERY_VARIANTS, DEFAULT_MERGE_THRESHOLD, DEFAULT_PPR_DAMPING, DEFAULT_PRESERVE_RECENT_TURNS, DEFAULT_RESERVED_FOR_COMPACTION, DEFAULT_RESERVED_FOR_RESPONSE, DEFAULT_THRESHOLD_RATIO, EmbedderMigrationAbortedError, EmbedderMigrationLockedError, EmbedderMigrationStateError, EmbedderRegistrationError, EntityResolver, EpisodicMemory, GraphorinMemoryError, HEURISTIC_TOKEN_COUNTER, HYDE_SYSTEM_PROMPT, INBOUND_SANITIZATION_PREAMBLE_EN, INBOUND_TRUST_ATTR, INDUCTION_SYSTEM_PROMPT, InsightMemory, MAX_ITERATIONS_CEILING, MAX_PROCEDURE_STEPS, MAX_TRAJECTORY_STEPS_SHOWN, MemoryToolDeniedError, NON_INBOUND_ORIGINS, ProceduralMemory, ProcedureInductionNotConfiguredError, ProviderNotConfiguredError, QUERY_EXPANSION_SYSTEM_PROMPT, QuarantinePromotionRefusedError, RETRIEVAL_GRADE_SYSTEM_PROMPT, RRFReranker, RRF_DEFAULT_K, SUMMARY_TEMPLATE_NAME, SUMMARY_TEMPLATE_VERSION, SemanticMemory, SessionMemory, SharedMemory, VERSION, WeightedRRFReranker, WorkingBlockOverflowError, WorkingBlockReadOnlyError, WorkingBlockReplaceMismatchError, WorkingMemory, _getLocaleFallbackWarningsForTesting, _resetBypassWarningForTesting, _resetConsolidatorConfigWarningForTesting, _resetLocaleFallbackWarningsForTesting, adaptTokenCounter, allocate as allocateTokenBudget, annotate, assessQueryDifficulty, buildAdjudicationRequest, buildExpansionRequest, buildGradeRequest, buildHydeRequest, buildInductionRequest, buildMemoryTools, buildSummarizerPrompt, capInsightsBelowFacts, checkSuccessCriteria, clearOldToolResults, composeInboundPreamble, composeLayer1, composeLayer2, composeLayer4Skills, cosineSimilarity, countMessageTokens, createBlockAppendTool, createBlockReplaceTool, createBlockRethinkTool, createConflictPipeline, createConsolidator, createConsolidatorPlaceholder, createContextEngine, createConversationSearchTool, createDeepRecallTool, createFactForgetTool, createFactHistoryTool, createFactRememberTool, createFactSearchTool, createFactSupersedeTool, createFactValidateTool, createMemory, createProviderQueryTransformer, createProviderRetrievalGrader, createProviderWorkflowInducer, createRecallEpisodesTool, defaultLocaleHeuristicStrategy, defineAutoRecallStrategy, defineBlock, defineContextLocalePack, defineLocalePack, effectiveAcceptsSensitivity, enLocalePack, evaluateMarkers, executeCompaction, explainRecall, fitFusionWeights, formatRecallExplanation, fuseRrf, fuseWeighted, gatherMemoryMetadata, isForeignProvenance, migrateEmbedder, ndcgAtK, normalizeEntityName, normalizeInducedProcedure, parseAdjudication, parseGrade, parseHypothetical, parseInducedProcedure, parseQueryVariants, parseTriggerSpec, partition as partitionBySensitivity, pprActivation, decide as privacyDecide, reanchorPersonaBlock, reanchorPinnedFacts, reanchorProjectRules, reanchorRecentResults, reasonFromTrigger, reconcileToConflictDecision, registerConsolidatorTriggers, renderFinalSummary, renderMessageText, renderMetadataBlock, resolveAutoCompactionDefault, resolveEntityDecision, resolveLocalePack, resolveTriggerThreshold, runConflictPipeline, runIterativeRetrieval, runWorkflowInduction, shouldFireInboundPreamble, toSpanAttributes, trajectoryFromRunState, truncateToTokens, trustDiscount };
95
100
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@graphorin/memory` seven-tier memory system for the Graphorin\n * framework (MST-13: working / session / episodic / semantic /\n * procedural / shared + the read-only insight tier from P1-1).\n *\n * Surface overview:\n *\n * - The {@link createMemory} facade that wires every tier sub-module\n * + the memory tools + the search reranker + the context-engine +\n * the consolidator.\n * - Tier sub-modules under `./tiers`: {@link WorkingMemory},\n * {@link SessionMemory}, {@link EpisodicMemory}, {@link SemanticMemory},\n * {@link ProceduralMemory}, {@link SharedMemory}, plus the read-only\n * {@link InsightMemory}.\n * - Eleven memory tools under `./tools` (plus the gated twelfth,\n * `deep_recall`, registered only when iterative retrieval is\n * configured): `block_append`, `block_replace`, `block_rethink`,\n * `fact_remember`, `fact_search`, `fact_supersede`, `fact_forget`,\n * `recall_episodes`, `conversation_search`, `fact_history` (P0-2),\n * `fact_validate` (P1-4).\n * - The hybrid search composition under `./search`, including the\n * built-in {@link RRFReranker} (k=60 default) and the\n * {@link ReRanker} contract.\n * - The embedder migration runner under `./migration`\n * ({@link migrateEmbedder} with three coexistence policies).\n * - Typed errors under `./errors`.\n *\n * Forward-looking surfaces (for ergonomic typing today):\n *\n * - {@link MemoryContextBlocks} + {@link CompileOptions} from `./context-engine`.\n * - {@link Consolidator}, {@link ConsolidatorTriggerSpec},\n * {@link ConsolidatorTier} from `./consolidator`.\n *\n * @packageDocumentation\n */\n\n/** Canonical version constant. Mirrors the `package.json` version. */\nexport const VERSION = '0.5.0';\n\nexport * from './conflict/index.js';\nexport {\n BudgetExceededError,\n buildInductionRequest,\n CONSOLIDATOR_TIER_DEFAULTS,\n type Consolidator,\n type ConsolidatorBudgetSnapshot,\n type ConsolidatorCatchupPolicy,\n type ConsolidatorCeilings,\n type ConsolidatorConfig,\n type ConsolidatorLastRuns,\n type ConsolidatorPhase,\n type ConsolidatorStatus,\n type ConsolidatorTier,\n type ConsolidatorTriggerReason,\n type ConsolidatorTriggerSpec,\n type CreateConsolidatorOptions,\n CustomTierMisconfiguredError,\n checkSuccessCriteria,\n createConsolidator,\n createConsolidatorPlaceholder,\n createProviderWorkflowInducer,\n DEFAULT_INDUCTION_MAX_TOKENS,\n INDUCTION_SYSTEM_PROMPT,\n type InducedProcedure,\n MAX_PROCEDURE_STEPS,\n MAX_TRAJECTORY_STEPS_SHOWN,\n normalizeInducedProcedure,\n type OnBudgetExceed,\n type ParsedTrigger,\n type PhaseListener,\n type PhaseOutcome,\n ProviderNotConfiguredError,\n parseInducedProcedure,\n parseTriggerSpec,\n type RegisterTriggersOptions,\n type RegisterTriggersResult,\n reasonFromTrigger,\n registerConsolidatorTriggers,\n runWorkflowInduction,\n type SchedulerLike,\n type Trajectory,\n type TrajectoryStep,\n type TriggerDeclarationLike,\n trajectoryFromRunState,\n type VerificationResult,\n type WorkflowInducer,\n type WorkflowInductionOptions,\n} from './consolidator/index.js';\nexport {\n _getLocaleFallbackWarningsForTesting,\n _resetLocaleFallbackWarningsForTesting,\n type AllocationResult,\n type AnnotatedPart,\n type AssembledPrompt,\n type AssembleInput,\n type AutoCompactionDefault,\n type AutoRecallConfig,\n type AutoRecallStrategy,\n type AutoRecallStrategyContext,\n type AutoRecallTriggerResult,\n type AutoRecallTriggers,\n adaptTokenCounter,\n allocateTokenBudget,\n annotate,\n BASE_TEMPLATE_EN_FULL,\n BASE_TEMPLATE_EN_MINIMAL,\n type BaseTemplateFragments,\n buildSummarizerPrompt,\n CLEARED_TOOL_RESULT_MARKER,\n type ClearToolResultsOptions,\n type ClearToolResultsOutcome,\n CONTENT_ORIGIN_ATTR,\n type CompactionConfig,\n type CompactionContext,\n type CompactionMetadataPayload,\n type CompactionResult,\n type CompactionSource,\n type CompactionStrategy,\n type CompactionSummarizer,\n type CompactionSummaryTemplate,\n type CompactionTriggerConfig,\n type CompileOptions,\n type CompileScope,\n type ContentAnnotation,\n type ContentOrigin,\n type ContextEngine,\n type ContextEngineConfig,\n type ContextLocalePack,\n type ContextTokenCounter,\n clearOldToolResults,\n composeInboundPreamble,\n composeLayer1,\n composeLayer2,\n composeLayer4Skills,\n countMessageTokens,\n createContextEngine,\n DEFAULT_LAYER_PRIORITY,\n DEFAULT_PRESERVE_RECENT_TURNS,\n DEFAULT_RESERVED_FOR_COMPACTION,\n DEFAULT_RESERVED_FOR_RESPONSE,\n DEFAULT_THRESHOLD_RATIO,\n defaultLocaleHeuristicStrategy,\n defineAutoRecallStrategy,\n defineContextLocalePack,\n type ExecuteCompactionInput,\n effectiveAcceptsSensitivity,\n enLocalePack,\n executeCompaction,\n gatherMemoryMetadata,\n HEURISTIC_TOKEN_COUNTER,\n INBOUND_SANITIZATION_PREAMBLE_EN,\n INBOUND_TRUST_ATTR,\n type InboundSanitizationPreamble,\n type InboundTrust,\n type LayerAllocation,\n type LayerCandidate,\n type LayerConfig,\n type LayerId,\n type LocaleResolverLogger,\n type MemoryBaseMode,\n type MemoryContextBlocks,\n type MemoryMetadataDeps,\n type NamedPostCompactionHook,\n NON_INBOUND_ORIGINS,\n type OverflowMode,\n type PartialContextLocalePack,\n type PartitionResult,\n type PostCompactionHook,\n type PostCompactionHookContext,\n type PrivacyConfig,\n type PrivacyDecision,\n type PrivacyDecisionReason,\n type PrivacyFilterContext,\n partitionBySensitivity,\n privacyDecide,\n type RenderedTemplate,\n type ResolvedContextEngineConfig,\n reanchorPersonaBlock,\n reanchorPinnedFacts,\n reanchorProjectRules,\n renderFinalSummary,\n renderMessageText,\n renderMetadataBlock,\n resolveAutoCompactionDefault,\n resolveLocalePack,\n resolveTriggerThreshold,\n type SkillMetadataCard,\n SUMMARY_TEMPLATE_NAME,\n SUMMARY_TEMPLATE_VERSION,\n shouldFireInboundPreamble,\n toSpanAttributes,\n truncateToTokens,\n} from './context-engine/index.js';\nexport * from './errors/index.js';\nexport {\n _resetConsolidatorConfigWarningForTesting,\n type CreateMemoryOptions,\n createMemory,\n type Memory,\n} from './facade.js';\nexport * from './graph/index.js';\nexport type { ContextualRetrievalMode } from './internal/contextualize.js';\nexport type {\n ConflictAuditDecision,\n ConflictAuditInputLike,\n ConflictAuditStage,\n ConflictMemoryStoreExt,\n ConsolidatorMemoryStoreExt,\n ConsolidatorRunFinish,\n ConsolidatorRunInput,\n ConsolidatorStatePatch,\n ConsolidatorStateRow,\n DecayMemoryStoreExt,\n DlqBatchInput,\n DlqBatchRow,\n EmbeddedWriteOptions,\n EmbeddingMetaRegistryLike,\n EpisodicMemoryStoreExt,\n InsightListOptions as InsightStoreListOptions,\n InsightMemoryStoreExt,\n InsightSearchStoreOptions,\n MemoryStoreAdapter,\n PendingConflictInputLike,\n PendingConflictRowLike,\n SemanticMemoryStoreExt,\n SessionMemoryStoreExt,\n SessionMessageRecord,\n} from './internal/storage-adapter.js';\nexport * from './migration/index.js';\nexport * from './search/index.js';\nexport * from './tiers/index.js';\nexport {\n type BuildMemoryToolsOptions,\n buildMemoryTools,\n createBlockAppendTool,\n createBlockReplaceTool,\n createBlockRethinkTool,\n createConversationSearchTool,\n createDeepRecallTool,\n createFactForgetTool,\n createFactHistoryTool,\n createFactRememberTool,\n createFactSearchTool,\n createFactSupersedeTool,\n createFactValidateTool,\n createRecallEpisodesTool,\n type MemoryToolDeps,\n type ScopeResolver,\n} from './tools/index.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,UAAU"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@graphorin/memory` - seven-tier memory system for the Graphorin\n * framework (MST-13: working / session / episodic / semantic /\n * procedural / shared + the read-only insight tier from P1-1).\n *\n * Surface overview:\n *\n * - The {@link createMemory} facade that wires every tier sub-module\n * + the memory tools + the search reranker + the context-engine +\n * the consolidator.\n * - Tier sub-modules under `./tiers`: {@link WorkingMemory},\n * {@link SessionMemory}, {@link EpisodicMemory}, {@link SemanticMemory},\n * {@link ProceduralMemory}, {@link SharedMemory}, plus the read-only\n * {@link InsightMemory}.\n * - Eleven memory tools under `./tools` (plus the gated twelfth,\n * `deep_recall`, registered only when iterative retrieval is\n * configured): `block_append`, `block_replace`, `block_rethink`,\n * `fact_remember`, `fact_search`, `fact_supersede`, `fact_forget`,\n * `recall_episodes`, `conversation_search`, `fact_history` (P0-2),\n * `fact_validate` (P1-4).\n * - The hybrid search composition under `./search`, including the\n * built-in {@link RRFReranker} (k=60 default) and the\n * {@link ReRanker} contract.\n * - The embedder migration runner under `./migration`\n * ({@link migrateEmbedder} with three coexistence policies).\n * - Typed errors under `./errors`.\n *\n * Forward-looking surfaces (for ergonomic typing today):\n *\n * - {@link MemoryContextBlocks} + {@link CompileOptions} from `./context-engine`.\n * - {@link Consolidator}, {@link ConsolidatorTriggerSpec},\n * {@link ConsolidatorTier} from `./consolidator`.\n *\n * @packageDocumentation\n */\n\n/** Canonical version constant. Mirrors the `package.json` version. */\nexport const VERSION = '0.6.0';\n\nexport * from './conflict/index.js';\nexport {\n BudgetExceededError,\n buildInductionRequest,\n CONSOLIDATOR_TIER_DEFAULTS,\n type Consolidator,\n type ConsolidatorBudgetSnapshot,\n type ConsolidatorCatchupPolicy,\n type ConsolidatorCeilings,\n type ConsolidatorConfig,\n type ConsolidatorLastRuns,\n type ConsolidatorPhase,\n type ConsolidatorStatus,\n type ConsolidatorTier,\n type ConsolidatorTriggerReason,\n type ConsolidatorTriggerSpec,\n type CreateConsolidatorOptions,\n CustomTierMisconfiguredError,\n checkSuccessCriteria,\n createConsolidator,\n createConsolidatorPlaceholder,\n createProviderWorkflowInducer,\n DEFAULT_INDUCTION_MAX_TOKENS,\n INDUCTION_SYSTEM_PROMPT,\n type InducedProcedure,\n MAX_PROCEDURE_STEPS,\n MAX_TRAJECTORY_STEPS_SHOWN,\n normalizeInducedProcedure,\n type OnBudgetExceed,\n type ParsedTrigger,\n type PhaseListener,\n type PhaseOutcome,\n ProviderNotConfiguredError,\n parseInducedProcedure,\n parseTriggerSpec,\n type RegisterTriggersOptions,\n type RegisterTriggersResult,\n reasonFromTrigger,\n registerConsolidatorTriggers,\n runWorkflowInduction,\n type SchedulerLike,\n type Trajectory,\n type TrajectoryStep,\n type TriggerDeclarationLike,\n trajectoryFromRunState,\n type VerificationResult,\n type WorkflowInducer,\n type WorkflowInductionOptions,\n} from './consolidator/index.js';\nexport {\n _getLocaleFallbackWarningsForTesting,\n _resetLocaleFallbackWarningsForTesting,\n type AllocationResult,\n type AnnotatedPart,\n type AssembledPrompt,\n type AssembleInput,\n type AutoCompactionDefault,\n type AutoRecallConfig,\n type AutoRecallStrategy,\n type AutoRecallStrategyContext,\n type AutoRecallTriggerResult,\n type AutoRecallTriggers,\n adaptTokenCounter,\n allocateTokenBudget,\n annotate,\n BASE_TEMPLATE_EN_FULL,\n BASE_TEMPLATE_EN_MINIMAL,\n type BaseTemplateFragments,\n buildSummarizerPrompt,\n CLEARED_TOOL_RESULT_MARKER,\n type ClearToolResultsOptions,\n type ClearToolResultsOutcome,\n CONTENT_ORIGIN_ATTR,\n type CompactionConfig,\n type CompactionContext,\n type CompactionMetadataPayload,\n type CompactionResult,\n type CompactionSource,\n type CompactionStrategy,\n type CompactionSummarizer,\n type CompactionSummaryTemplate,\n type CompactionTriggerConfig,\n type CompileOptions,\n type CompileScope,\n type ContentAnnotation,\n type ContentOrigin,\n type ContextEngine,\n type ContextEngineConfig,\n type ContextLocalePack,\n type ContextTokenCounter,\n clearOldToolResults,\n composeInboundPreamble,\n composeLayer1,\n composeLayer2,\n composeLayer4Skills,\n countMessageTokens,\n createContextEngine,\n DEFAULT_LAYER_PRIORITY,\n DEFAULT_PRESERVE_RECENT_TURNS,\n DEFAULT_RESERVED_FOR_COMPACTION,\n DEFAULT_RESERVED_FOR_RESPONSE,\n DEFAULT_THRESHOLD_RATIO,\n defaultLocaleHeuristicStrategy,\n defineAutoRecallStrategy,\n defineContextLocalePack,\n type ExecuteCompactionInput,\n effectiveAcceptsSensitivity,\n enLocalePack,\n executeCompaction,\n gatherMemoryMetadata,\n HEURISTIC_TOKEN_COUNTER,\n INBOUND_SANITIZATION_PREAMBLE_EN,\n INBOUND_TRUST_ATTR,\n type InboundSanitizationPreamble,\n type InboundTrust,\n type LayerAllocation,\n type LayerCandidate,\n type LayerConfig,\n type LayerId,\n type LocaleResolverLogger,\n type MemoryBaseMode,\n type MemoryContextBlocks,\n type MemoryMetadataDeps,\n type NamedPostCompactionHook,\n NON_INBOUND_ORIGINS,\n type OverflowMode,\n type PartialContextLocalePack,\n type PartitionResult,\n type PostCompactionHook,\n type PostCompactionHookContext,\n type PrivacyConfig,\n type PrivacyDecision,\n type PrivacyDecisionReason,\n type PrivacyFilterContext,\n partitionBySensitivity,\n privacyDecide,\n type ReanchorRecentResultsOptions,\n type RenderedTemplate,\n type ResolvedContextEngineConfig,\n reanchorPersonaBlock,\n reanchorPinnedFacts,\n reanchorProjectRules,\n reanchorRecentResults,\n renderFinalSummary,\n renderMessageText,\n renderMetadataBlock,\n resolveAutoCompactionDefault,\n resolveLocalePack,\n resolveTriggerThreshold,\n type SkillMetadataCard,\n SUMMARY_TEMPLATE_NAME,\n SUMMARY_TEMPLATE_VERSION,\n shouldFireInboundPreamble,\n toSpanAttributes,\n truncateToTokens,\n} from './context-engine/index.js';\nexport * from './errors/index.js';\nexport {\n _resetConsolidatorConfigWarningForTesting,\n type CreateMemoryOptions,\n createMemory,\n type Memory,\n} from './facade.js';\nexport * from './graph/index.js';\nexport type { ContextualRetrievalMode } from './internal/contextualize.js';\nexport type {\n ConflictAuditDecision,\n ConflictAuditInputLike,\n ConflictAuditStage,\n ConflictMemoryStoreExt,\n ConsolidatorMemoryStoreExt,\n ConsolidatorRunFinish,\n ConsolidatorRunInput,\n ConsolidatorStatePatch,\n ConsolidatorStateRow,\n DecayMemoryStoreExt,\n DlqBatchInput,\n DlqBatchRow,\n EmbeddedWriteOptions,\n EmbeddingMetaRegistryLike,\n EpisodicMemoryStoreExt,\n InsightListOptions as InsightStoreListOptions,\n InsightMemoryStoreExt,\n InsightSearchStoreOptions,\n MemoryStoreAdapter,\n PendingConflictInputLike,\n PendingConflictRowLike,\n SemanticMemoryStoreExt,\n SessionMemoryStoreExt,\n SessionMessageRecord,\n} from './internal/storage-adapter.js';\nexport * from './migration/index.js';\nexport * from './search/index.js';\nexport * from './tiers/index.js';\nexport {\n type BuildMemoryToolsOptions,\n buildMemoryTools,\n createBlockAppendTool,\n createBlockReplaceTool,\n createBlockRethinkTool,\n createConversationSearchTool,\n createDeepRecallTool,\n createFactForgetTool,\n createFactHistoryTool,\n createFactRememberTool,\n createFactSearchTool,\n createFactSupersedeTool,\n createFactValidateTool,\n createRecallEpisodesTool,\n type MemoryToolDeps,\n type ScopeResolver,\n} from './tools/index.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,UAAU"}
@@ -1,7 +1,7 @@
1
1
  //#region src/internal/contextualize.ts
2
2
  const SITUATING_CONTEXT_SYSTEM_PROMPT = [
3
3
  "You are a situating-context assistant for a long-running memory store.",
4
- "Given one memory and any structured hints, write a single short sentence (≤ 25 words) that situates it the entities, timeframe, and topic it concerns so it can be retrieved later by a vaguely-worded question.",
4
+ "Given one memory and any structured hints, write a single short sentence (≤ 25 words) that situates it - the entities, timeframe, and topic it concerns - so it can be retrieved later by a vaguely-worded question.",
5
5
  "Do not restate the memory verbatim and do not add facts that are not implied. Return only the sentence, no preamble."
6
6
  ].join(" ");
7
7
  /**
@@ -31,7 +31,7 @@ function buildSituatingContext(input) {
31
31
  /**
32
32
  * Late-chunking contextualizer (offline default). Prepends the
33
33
  * deterministic situating context to the canonical text; a no-op when
34
- * the candidate carries no structured signals. Pure never calls a
34
+ * the candidate carries no structured signals. Pure - never calls a
35
35
  * provider.
36
36
  *
37
37
  * @internal
@@ -1 +1 @@
1
- {"version":3,"file":"contextualize.js","names":["parts: string[]","ZERO_USAGE: Usage","request: ProviderRequest","hints: string[]"],"sources":["../../src/internal/contextualize.ts"],"sourcesContent":["/**\n * Contextual retrieval (P1-3). Before a memory is embedded / FTS-indexed\n * the framework can prepend a short *situating context* (entities,\n * timeframe, topics) so a terse fact like \"moved there in March\" stays\n * findable by \"Where did Anna relocate?\". This mirrors Anthropic's\n * Contextual Retrieval, applied to both the vector embedding *and* the\n * lexical index, while the canonical `text` shown to the user / audit\n * trail is left untouched.\n *\n * Three modes:\n * - `'off'` index the bare canonical text (pre-P1-3 behaviour).\n * - `'late-chunk'` the **offline default**: prepend a context derived\n * deterministically from the memory's own structured metadata. No LLM\n * call, so the local-first write path is unchanged in cost.\n * - `'llm'` an opt-in, **consolidator-only** enrichment: one cheap\n * provider call writes a 12 sentence situating prefix. Confined to the\n * background consolidator (never the hot write path); a failure or empty\n * completion degrades to {@link contextualize} so a write never wedges.\n *\n * @packageDocumentation\n */\n\nimport type { Provider, ProviderRequest, Usage } from '@graphorin/core';\n\n/**\n * Contextual-retrieval mode. `'late-chunk'` is the offline default;\n * `'llm'` is the opt-in, consolidator-only enrichment. P1-3.\n *\n * @stable\n */\nexport type ContextualRetrievalMode = 'off' | 'late-chunk' | 'llm';\n\n/**\n * Structural subset of a fact / candidate consumed by the\n * contextualizers. Only **author / extraction-supplied** signals are\n * used never framework-defaulted fields (e.g. a `validFrom` defaulted\n * to write-time) and never opaque scope ids (random uuids would only\n * add noise to the embedding). A candidate with no structured signals\n * yields an empty context, so plain `remember({ text })` writes are\n * left byte-identical.\n *\n * @internal\n */\nexport interface ContextualizeInput {\n readonly text: string;\n readonly subject?: string;\n readonly predicate?: string;\n readonly object?: string;\n readonly tags?: ReadonlyArray<string>;\n /** Author-set validity start (ISO-8601). Framework-defaulted values are *not* passed. */\n readonly validFrom?: string;\n}\n\nconst SITUATING_CONTEXT_SYSTEM_PROMPT = [\n 'You are a situating-context assistant for a long-running memory store.',\n 'Given one memory and any structured hints, write a single short sentence (≤ 25 words) that situates it the entities, timeframe, and topic it concerns so it can be retrieved later by a vaguely-worded question.',\n 'Do not restate the memory verbatim and do not add facts that are not implied. Return only the sentence, no preamble.',\n].join(' ');\n\n/**\n * Build the deterministic situating-context prefix from a candidate's\n * structured signals. Returns `''` when nothing useful is available so\n * the caller can short-circuit to the canonical text.\n *\n * @internal\n */\nexport function buildSituatingContext(input: ContextualizeInput): string {\n const parts: string[] = [];\n const subject = trimToUndefined(input.subject);\n const predicate = trimToUndefined(input.predicate);\n const object = trimToUndefined(input.object);\n if (subject !== undefined && predicate !== undefined && object !== undefined) {\n parts.push(`${subject} ${predicate} ${object}`);\n } else {\n if (subject !== undefined) parts.push(subject);\n if (object !== undefined) parts.push(object);\n }\n const validFrom = trimToUndefined(input.validFrom);\n if (validFrom !== undefined) {\n parts.push(`as of ${validFrom.length >= 10 ? validFrom.slice(0, 10) : validFrom}`);\n }\n const tags = (input.tags ?? []).map((t) => t.trim()).filter((t) => t.length > 0);\n if (tags.length > 0) {\n parts.push(`topics: ${tags.join(', ')}`);\n }\n if (parts.length === 0) return '';\n return `[Context: ${parts.join('; ')}]`;\n}\n\n/**\n * Late-chunking contextualizer (offline default). Prepends the\n * deterministic situating context to the canonical text; a no-op when\n * the candidate carries no structured signals. Pure never calls a\n * provider.\n *\n * @internal\n */\nexport function contextualize(input: ContextualizeInput): string {\n const ctx = buildSituatingContext(input);\n return ctx === '' ? input.text : `${ctx}\\n${input.text}`;\n}\n\nconst ZERO_USAGE: Usage = Object.freeze({\n promptTokens: 0,\n completionTokens: 0,\n totalTokens: 0,\n});\n\n/** Result of the LLM-context enrichment the index text plus call usage for budgeting. */\nexport interface ContextualizeLlmResult {\n readonly indexText: string;\n readonly usage: Usage;\n}\n\n/**\n * LLM-context contextualizer (opt-in, consolidator-only). Spends one\n * cheap provider call to write a situating prefix, then prepends it to\n * the canonical text. Resilient by design: an empty completion or a\n * provider error degrades to {@link contextualize} (deterministic\n * late-chunk) so the enrichment can never wedge a write. Returns the\n * usage so the caller can record it against the budget.\n *\n * @internal\n */\nexport async function contextualizeWithLlm(\n input: ContextualizeInput,\n provider: Provider,\n opts: { readonly signal?: AbortSignal } = {},\n): Promise<ContextualizeLlmResult> {\n const request: ProviderRequest = {\n messages: [{ role: 'user', content: buildSituatingUserPrompt(input) }],\n systemMessage: SITUATING_CONTEXT_SYSTEM_PROMPT,\n temperature: 0,\n // MCON-14: per-call output cap a one-sentence situating prefix.\n maxTokens: 256,\n ...(opts.signal !== undefined ? { signal: opts.signal } : {}),\n };\n try {\n const response = await provider.generate(request);\n const prefix = (response.text ?? '').trim();\n if (prefix.length === 0) {\n return { indexText: contextualize(input), usage: response.usage };\n }\n return { indexText: `${prefix}\\n${input.text}`, usage: response.usage };\n } catch {\n // Contextualization is an enhancement, not a correctness requirement —\n // a provider failure must never wedge the underlying write. Fall back\n // to the deterministic late-chunk prefix at zero cost.\n return { indexText: contextualize(input), usage: ZERO_USAGE };\n }\n}\n\nfunction buildSituatingUserPrompt(input: ContextualizeInput): string {\n const hints: string[] = [];\n const subject = trimToUndefined(input.subject);\n const predicate = trimToUndefined(input.predicate);\n const object = trimToUndefined(input.object);\n if (subject !== undefined) hints.push(`subject=${subject}`);\n if (predicate !== undefined) hints.push(`predicate=${predicate}`);\n if (object !== undefined) hints.push(`object=${object}`);\n const tags = (input.tags ?? []).map((t) => t.trim()).filter((t) => t.length > 0);\n if (tags.length > 0) hints.push(`tags=${tags.join(', ')}`);\n const validFrom = trimToUndefined(input.validFrom);\n if (validFrom !== undefined) hints.push(`validFrom=${validFrom}`);\n const hintLine = hints.length > 0 ? `\\nStructured hints: ${hints.join('; ')}` : '';\n return `Memory: ${input.text}${hintLine}`;\n}\n\nfunction trimToUndefined(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n return trimmed.length === 0 ? undefined : trimmed;\n}\n"],"mappings":";AAqDA,MAAM,kCAAkC;CACtC;CACA;CACA;CACD,CAAC,KAAK,IAAI;;;;;;;;AASX,SAAgB,sBAAsB,OAAmC;CACvE,MAAMA,QAAkB,EAAE;CAC1B,MAAM,UAAU,gBAAgB,MAAM,QAAQ;CAC9C,MAAM,YAAY,gBAAgB,MAAM,UAAU;CAClD,MAAM,SAAS,gBAAgB,MAAM,OAAO;AAC5C,KAAI,YAAY,UAAa,cAAc,UAAa,WAAW,OACjE,OAAM,KAAK,GAAG,QAAQ,GAAG,UAAU,GAAG,SAAS;MAC1C;AACL,MAAI,YAAY,OAAW,OAAM,KAAK,QAAQ;AAC9C,MAAI,WAAW,OAAW,OAAM,KAAK,OAAO;;CAE9C,MAAM,YAAY,gBAAgB,MAAM,UAAU;AAClD,KAAI,cAAc,OAChB,OAAM,KAAK,SAAS,UAAU,UAAU,KAAK,UAAU,MAAM,GAAG,GAAG,GAAG,YAAY;CAEpF,MAAM,QAAQ,MAAM,QAAQ,EAAE,EAAE,KAAK,MAAM,EAAE,MAAM,CAAC,CAAC,QAAQ,MAAM,EAAE,SAAS,EAAE;AAChF,KAAI,KAAK,SAAS,EAChB,OAAM,KAAK,WAAW,KAAK,KAAK,KAAK,GAAG;AAE1C,KAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAO,aAAa,MAAM,KAAK,KAAK,CAAC;;;;;;;;;;AAWvC,SAAgB,cAAc,OAAmC;CAC/D,MAAM,MAAM,sBAAsB,MAAM;AACxC,QAAO,QAAQ,KAAK,MAAM,OAAO,GAAG,IAAI,IAAI,MAAM;;AAGpD,MAAMC,aAAoB,OAAO,OAAO;CACtC,cAAc;CACd,kBAAkB;CAClB,aAAa;CACd,CAAC;;;;;;;;;;;AAkBF,eAAsB,qBACpB,OACA,UACA,OAA0C,EAAE,EACX;CACjC,MAAMC,UAA2B;EAC/B,UAAU,CAAC;GAAE,MAAM;GAAQ,SAAS,yBAAyB,MAAM;GAAE,CAAC;EACtE,eAAe;EACf,aAAa;EAEb,WAAW;EACX,GAAI,KAAK,WAAW,SAAY,EAAE,QAAQ,KAAK,QAAQ,GAAG,EAAE;EAC7D;AACD,KAAI;EACF,MAAM,WAAW,MAAM,SAAS,SAAS,QAAQ;EACjD,MAAM,UAAU,SAAS,QAAQ,IAAI,MAAM;AAC3C,MAAI,OAAO,WAAW,EACpB,QAAO;GAAE,WAAW,cAAc,MAAM;GAAE,OAAO,SAAS;GAAO;AAEnE,SAAO;GAAE,WAAW,GAAG,OAAO,IAAI,MAAM;GAAQ,OAAO,SAAS;GAAO;SACjE;AAIN,SAAO;GAAE,WAAW,cAAc,MAAM;GAAE,OAAO;GAAY;;;AAIjE,SAAS,yBAAyB,OAAmC;CACnE,MAAMC,QAAkB,EAAE;CAC1B,MAAM,UAAU,gBAAgB,MAAM,QAAQ;CAC9C,MAAM,YAAY,gBAAgB,MAAM,UAAU;CAClD,MAAM,SAAS,gBAAgB,MAAM,OAAO;AAC5C,KAAI,YAAY,OAAW,OAAM,KAAK,WAAW,UAAU;AAC3D,KAAI,cAAc,OAAW,OAAM,KAAK,aAAa,YAAY;AACjE,KAAI,WAAW,OAAW,OAAM,KAAK,UAAU,SAAS;CACxD,MAAM,QAAQ,MAAM,QAAQ,EAAE,EAAE,KAAK,MAAM,EAAE,MAAM,CAAC,CAAC,QAAQ,MAAM,EAAE,SAAS,EAAE;AAChF,KAAI,KAAK,SAAS,EAAG,OAAM,KAAK,QAAQ,KAAK,KAAK,KAAK,GAAG;CAC1D,MAAM,YAAY,gBAAgB,MAAM,UAAU;AAClD,KAAI,cAAc,OAAW,OAAM,KAAK,aAAa,YAAY;CACjE,MAAM,WAAW,MAAM,SAAS,IAAI,uBAAuB,MAAM,KAAK,KAAK,KAAK;AAChF,QAAO,WAAW,MAAM,OAAO;;AAGjC,SAAS,gBAAgB,OAA+C;AACtE,KAAI,UAAU,OAAW,QAAO;CAChC,MAAM,UAAU,MAAM,MAAM;AAC5B,QAAO,QAAQ,WAAW,IAAI,SAAY"}
1
+ {"version":3,"file":"contextualize.js","names":["parts: string[]","ZERO_USAGE: Usage","request: ProviderRequest","hints: string[]"],"sources":["../../src/internal/contextualize.ts"],"sourcesContent":["/**\n * Contextual retrieval (P1-3). Before a memory is embedded / FTS-indexed\n * the framework can prepend a short *situating context* (entities,\n * timeframe, topics) so a terse fact like \"moved there in March\" stays\n * findable by \"Where did Anna relocate?\". This mirrors Anthropic's\n * Contextual Retrieval, applied to both the vector embedding *and* the\n * lexical index, while the canonical `text` shown to the user / audit\n * trail is left untouched.\n *\n * Three modes:\n * - `'off'` - index the bare canonical text (pre-P1-3 behaviour).\n * - `'late-chunk'` - the **offline default**: prepend a context derived\n * deterministically from the memory's own structured metadata. No LLM\n * call, so the local-first write path is unchanged in cost.\n * - `'llm'` - an opt-in, **consolidator-only** enrichment: one cheap\n * provider call writes a 1-2 sentence situating prefix. Confined to the\n * background consolidator (never the hot write path); a failure or empty\n * completion degrades to {@link contextualize} so a write never wedges.\n *\n * @packageDocumentation\n */\n\nimport type { Provider, ProviderRequest, Usage } from '@graphorin/core';\n\n/**\n * Contextual-retrieval mode. `'late-chunk'` is the offline default;\n * `'llm'` is the opt-in, consolidator-only enrichment. P1-3.\n *\n * @stable\n */\nexport type ContextualRetrievalMode = 'off' | 'late-chunk' | 'llm';\n\n/**\n * Structural subset of a fact / candidate consumed by the\n * contextualizers. Only **author / extraction-supplied** signals are\n * used - never framework-defaulted fields (e.g. a `validFrom` defaulted\n * to write-time) and never opaque scope ids (random uuids would only\n * add noise to the embedding). A candidate with no structured signals\n * yields an empty context, so plain `remember({ text })` writes are\n * left byte-identical.\n *\n * @internal\n */\nexport interface ContextualizeInput {\n readonly text: string;\n readonly subject?: string;\n readonly predicate?: string;\n readonly object?: string;\n readonly tags?: ReadonlyArray<string>;\n /** Author-set validity start (ISO-8601). Framework-defaulted values are *not* passed. */\n readonly validFrom?: string;\n}\n\nconst SITUATING_CONTEXT_SYSTEM_PROMPT = [\n 'You are a situating-context assistant for a long-running memory store.',\n 'Given one memory and any structured hints, write a single short sentence (≤ 25 words) that situates it - the entities, timeframe, and topic it concerns - so it can be retrieved later by a vaguely-worded question.',\n 'Do not restate the memory verbatim and do not add facts that are not implied. Return only the sentence, no preamble.',\n].join(' ');\n\n/**\n * Build the deterministic situating-context prefix from a candidate's\n * structured signals. Returns `''` when nothing useful is available so\n * the caller can short-circuit to the canonical text.\n *\n * @internal\n */\nexport function buildSituatingContext(input: ContextualizeInput): string {\n const parts: string[] = [];\n const subject = trimToUndefined(input.subject);\n const predicate = trimToUndefined(input.predicate);\n const object = trimToUndefined(input.object);\n if (subject !== undefined && predicate !== undefined && object !== undefined) {\n parts.push(`${subject} ${predicate} ${object}`);\n } else {\n if (subject !== undefined) parts.push(subject);\n if (object !== undefined) parts.push(object);\n }\n const validFrom = trimToUndefined(input.validFrom);\n if (validFrom !== undefined) {\n parts.push(`as of ${validFrom.length >= 10 ? validFrom.slice(0, 10) : validFrom}`);\n }\n const tags = (input.tags ?? []).map((t) => t.trim()).filter((t) => t.length > 0);\n if (tags.length > 0) {\n parts.push(`topics: ${tags.join(', ')}`);\n }\n if (parts.length === 0) return '';\n return `[Context: ${parts.join('; ')}]`;\n}\n\n/**\n * Late-chunking contextualizer (offline default). Prepends the\n * deterministic situating context to the canonical text; a no-op when\n * the candidate carries no structured signals. Pure - never calls a\n * provider.\n *\n * @internal\n */\nexport function contextualize(input: ContextualizeInput): string {\n const ctx = buildSituatingContext(input);\n return ctx === '' ? input.text : `${ctx}\\n${input.text}`;\n}\n\nconst ZERO_USAGE: Usage = Object.freeze({\n promptTokens: 0,\n completionTokens: 0,\n totalTokens: 0,\n});\n\n/** Result of the LLM-context enrichment - the index text plus call usage for budgeting. */\nexport interface ContextualizeLlmResult {\n readonly indexText: string;\n readonly usage: Usage;\n}\n\n/**\n * LLM-context contextualizer (opt-in, consolidator-only). Spends one\n * cheap provider call to write a situating prefix, then prepends it to\n * the canonical text. Resilient by design: an empty completion or a\n * provider error degrades to {@link contextualize} (deterministic\n * late-chunk) so the enrichment can never wedge a write. Returns the\n * usage so the caller can record it against the budget.\n *\n * @internal\n */\nexport async function contextualizeWithLlm(\n input: ContextualizeInput,\n provider: Provider,\n opts: { readonly signal?: AbortSignal } = {},\n): Promise<ContextualizeLlmResult> {\n const request: ProviderRequest = {\n messages: [{ role: 'user', content: buildSituatingUserPrompt(input) }],\n systemMessage: SITUATING_CONTEXT_SYSTEM_PROMPT,\n temperature: 0,\n // MCON-14: per-call output cap - a one-sentence situating prefix.\n maxTokens: 256,\n ...(opts.signal !== undefined ? { signal: opts.signal } : {}),\n };\n try {\n const response = await provider.generate(request);\n const prefix = (response.text ?? '').trim();\n if (prefix.length === 0) {\n return { indexText: contextualize(input), usage: response.usage };\n }\n return { indexText: `${prefix}\\n${input.text}`, usage: response.usage };\n } catch {\n // Contextualization is an enhancement, not a correctness requirement -\n // a provider failure must never wedge the underlying write. Fall back\n // to the deterministic late-chunk prefix at zero cost.\n return { indexText: contextualize(input), usage: ZERO_USAGE };\n }\n}\n\nfunction buildSituatingUserPrompt(input: ContextualizeInput): string {\n const hints: string[] = [];\n const subject = trimToUndefined(input.subject);\n const predicate = trimToUndefined(input.predicate);\n const object = trimToUndefined(input.object);\n if (subject !== undefined) hints.push(`subject=${subject}`);\n if (predicate !== undefined) hints.push(`predicate=${predicate}`);\n if (object !== undefined) hints.push(`object=${object}`);\n const tags = (input.tags ?? []).map((t) => t.trim()).filter((t) => t.length > 0);\n if (tags.length > 0) hints.push(`tags=${tags.join(', ')}`);\n const validFrom = trimToUndefined(input.validFrom);\n if (validFrom !== undefined) hints.push(`validFrom=${validFrom}`);\n const hintLine = hints.length > 0 ? `\\nStructured hints: ${hints.join('; ')}` : '';\n return `Memory: ${input.text}${hintLine}`;\n}\n\nfunction trimToUndefined(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n return trimmed.length === 0 ? undefined : trimmed;\n}\n"],"mappings":";AAqDA,MAAM,kCAAkC;CACtC;CACA;CACA;CACD,CAAC,KAAK,IAAI;;;;;;;;AASX,SAAgB,sBAAsB,OAAmC;CACvE,MAAMA,QAAkB,EAAE;CAC1B,MAAM,UAAU,gBAAgB,MAAM,QAAQ;CAC9C,MAAM,YAAY,gBAAgB,MAAM,UAAU;CAClD,MAAM,SAAS,gBAAgB,MAAM,OAAO;AAC5C,KAAI,YAAY,UAAa,cAAc,UAAa,WAAW,OACjE,OAAM,KAAK,GAAG,QAAQ,GAAG,UAAU,GAAG,SAAS;MAC1C;AACL,MAAI,YAAY,OAAW,OAAM,KAAK,QAAQ;AAC9C,MAAI,WAAW,OAAW,OAAM,KAAK,OAAO;;CAE9C,MAAM,YAAY,gBAAgB,MAAM,UAAU;AAClD,KAAI,cAAc,OAChB,OAAM,KAAK,SAAS,UAAU,UAAU,KAAK,UAAU,MAAM,GAAG,GAAG,GAAG,YAAY;CAEpF,MAAM,QAAQ,MAAM,QAAQ,EAAE,EAAE,KAAK,MAAM,EAAE,MAAM,CAAC,CAAC,QAAQ,MAAM,EAAE,SAAS,EAAE;AAChF,KAAI,KAAK,SAAS,EAChB,OAAM,KAAK,WAAW,KAAK,KAAK,KAAK,GAAG;AAE1C,KAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAO,aAAa,MAAM,KAAK,KAAK,CAAC;;;;;;;;;;AAWvC,SAAgB,cAAc,OAAmC;CAC/D,MAAM,MAAM,sBAAsB,MAAM;AACxC,QAAO,QAAQ,KAAK,MAAM,OAAO,GAAG,IAAI,IAAI,MAAM;;AAGpD,MAAMC,aAAoB,OAAO,OAAO;CACtC,cAAc;CACd,kBAAkB;CAClB,aAAa;CACd,CAAC;;;;;;;;;;;AAkBF,eAAsB,qBACpB,OACA,UACA,OAA0C,EAAE,EACX;CACjC,MAAMC,UAA2B;EAC/B,UAAU,CAAC;GAAE,MAAM;GAAQ,SAAS,yBAAyB,MAAM;GAAE,CAAC;EACtE,eAAe;EACf,aAAa;EAEb,WAAW;EACX,GAAI,KAAK,WAAW,SAAY,EAAE,QAAQ,KAAK,QAAQ,GAAG,EAAE;EAC7D;AACD,KAAI;EACF,MAAM,WAAW,MAAM,SAAS,SAAS,QAAQ;EACjD,MAAM,UAAU,SAAS,QAAQ,IAAI,MAAM;AAC3C,MAAI,OAAO,WAAW,EACpB,QAAO;GAAE,WAAW,cAAc,MAAM;GAAE,OAAO,SAAS;GAAO;AAEnE,SAAO;GAAE,WAAW,GAAG,OAAO,IAAI,MAAM;GAAQ,OAAO,SAAS;GAAO;SACjE;AAIN,SAAO;GAAE,WAAW,cAAc,MAAM;GAAE,OAAO;GAAY;;;AAIjE,SAAS,yBAAyB,OAAmC;CACnE,MAAMC,QAAkB,EAAE;CAC1B,MAAM,UAAU,gBAAgB,MAAM,QAAQ;CAC9C,MAAM,YAAY,gBAAgB,MAAM,UAAU;CAClD,MAAM,SAAS,gBAAgB,MAAM,OAAO;AAC5C,KAAI,YAAY,OAAW,OAAM,KAAK,WAAW,UAAU;AAC3D,KAAI,cAAc,OAAW,OAAM,KAAK,aAAa,YAAY;AACjE,KAAI,WAAW,OAAW,OAAM,KAAK,UAAU,SAAS;CACxD,MAAM,QAAQ,MAAM,QAAQ,EAAE,EAAE,KAAK,MAAM,EAAE,MAAM,CAAC,CAAC,QAAQ,MAAM,EAAE,SAAS,EAAE;AAChF,KAAI,KAAK,SAAS,EAAG,OAAM,KAAK,QAAQ,KAAK,KAAK,KAAK,GAAG;CAC1D,MAAM,YAAY,gBAAgB,MAAM,UAAU;AAClD,KAAI,cAAc,OAAW,OAAM,KAAK,aAAa,YAAY;CACjE,MAAM,WAAW,MAAM,SAAS,IAAI,uBAAuB,MAAM,KAAK,KAAK,KAAK;AAChF,QAAO,WAAW,MAAM,OAAO;;AAGjC,SAAS,gBAAgB,OAA+C;AACtE,KAAI,UAAU,OAAW,QAAO;CAChC,MAAM,UAAU,MAAM,MAAM;AAC5B,QAAO,QAAQ,WAAW,IAAI,SAAY"}
@@ -27,7 +27,7 @@ function inferModelName(id) {
27
27
  /**
28
28
  * Register the supplied embedder with the storage layer's
29
29
  * `embedding_meta` registry. Returns the canonical id surfaced to the
30
- * memory writers. Idempotent a registry that already knows the id
30
+ * memory writers. Idempotent - a registry that already knows the id
31
31
  * with a matching `configHash` returns the existing row.
32
32
  *
33
33
  * @internal
@@ -1 +1 @@
1
- {"version":3,"file":"embedder-binding.js","names":[],"sources":["../../src/internal/embedder-binding.ts"],"sourcesContent":["import type { EmbedderProvider } from '@graphorin/core';\nimport type { EmbeddingMetaRegistryLike } from './storage-adapter.js';\n\n/**\n * Infer the canonical adapter family from the embedder id. The\n * canonical id format is `'<adapter>:<model>@<dim>'`; we slice the\n * adapter name off the front so the registry can index by family\n * without needing the embedder to expose an extra property.\n *\n * @internal\n */\nexport function inferAdapterKind(id: string): string {\n const colonIndex = id.indexOf(':');\n if (colonIndex < 0) return 'custom';\n return id.slice(0, colonIndex);\n}\n\n/**\n * Infer the model id portion of a canonical embedder id.\n *\n * @internal\n */\nexport function inferModelName(id: string): string {\n const colonIndex = id.indexOf(':');\n const atIndex = id.lastIndexOf('@');\n if (colonIndex < 0) return id;\n if (atIndex < 0 || atIndex < colonIndex) return id.slice(colonIndex + 1);\n return id.slice(colonIndex + 1, atIndex);\n}\n\n/**\n * Register the supplied embedder with the storage layer's\n * `embedding_meta` registry. Returns the canonical id surfaced to the\n * memory writers. Idempotent a registry that already knows the id\n * with a matching `configHash` returns the existing row.\n *\n * @internal\n */\nexport function bindEmbedder(\n embedder: EmbedderProvider,\n registry: EmbeddingMetaRegistryLike,\n): string {\n const id = embedder.id();\n registry.registerOrReturn({\n id,\n embedderKind: inferAdapterKind(id),\n model: inferModelName(id),\n dim: embedder.dim(),\n configHash: embedder.configHash(),\n distanceMetric: 'cosine',\n });\n return id;\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,iBAAiB,IAAoB;CACnD,MAAM,aAAa,GAAG,QAAQ,IAAI;AAClC,KAAI,aAAa,EAAG,QAAO;AAC3B,QAAO,GAAG,MAAM,GAAG,WAAW;;;;;;;AAQhC,SAAgB,eAAe,IAAoB;CACjD,MAAM,aAAa,GAAG,QAAQ,IAAI;CAClC,MAAM,UAAU,GAAG,YAAY,IAAI;AACnC,KAAI,aAAa,EAAG,QAAO;AAC3B,KAAI,UAAU,KAAK,UAAU,WAAY,QAAO,GAAG,MAAM,aAAa,EAAE;AACxE,QAAO,GAAG,MAAM,aAAa,GAAG,QAAQ;;;;;;;;;;AAW1C,SAAgB,aACd,UACA,UACQ;CACR,MAAM,KAAK,SAAS,IAAI;AACxB,UAAS,iBAAiB;EACxB;EACA,cAAc,iBAAiB,GAAG;EAClC,OAAO,eAAe,GAAG;EACzB,KAAK,SAAS,KAAK;EACnB,YAAY,SAAS,YAAY;EACjC,gBAAgB;EACjB,CAAC;AACF,QAAO"}
1
+ {"version":3,"file":"embedder-binding.js","names":[],"sources":["../../src/internal/embedder-binding.ts"],"sourcesContent":["import type { EmbedderProvider } from '@graphorin/core';\nimport type { EmbeddingMetaRegistryLike } from './storage-adapter.js';\n\n/**\n * Infer the canonical adapter family from the embedder id. The\n * canonical id format is `'<adapter>:<model>@<dim>'`; we slice the\n * adapter name off the front so the registry can index by family\n * without needing the embedder to expose an extra property.\n *\n * @internal\n */\nexport function inferAdapterKind(id: string): string {\n const colonIndex = id.indexOf(':');\n if (colonIndex < 0) return 'custom';\n return id.slice(0, colonIndex);\n}\n\n/**\n * Infer the model id portion of a canonical embedder id.\n *\n * @internal\n */\nexport function inferModelName(id: string): string {\n const colonIndex = id.indexOf(':');\n const atIndex = id.lastIndexOf('@');\n if (colonIndex < 0) return id;\n if (atIndex < 0 || atIndex < colonIndex) return id.slice(colonIndex + 1);\n return id.slice(colonIndex + 1, atIndex);\n}\n\n/**\n * Register the supplied embedder with the storage layer's\n * `embedding_meta` registry. Returns the canonical id surfaced to the\n * memory writers. Idempotent - a registry that already knows the id\n * with a matching `configHash` returns the existing row.\n *\n * @internal\n */\nexport function bindEmbedder(\n embedder: EmbedderProvider,\n registry: EmbeddingMetaRegistryLike,\n): string {\n const id = embedder.id();\n registry.registerOrReturn({\n id,\n embedderKind: inferAdapterKind(id),\n model: inferModelName(id),\n dim: embedder.dim(),\n configHash: embedder.configHash(),\n distanceMetric: 'cosine',\n });\n return id;\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,iBAAiB,IAAoB;CACnD,MAAM,aAAa,GAAG,QAAQ,IAAI;AAClC,KAAI,aAAa,EAAG,QAAO;AAC3B,QAAO,GAAG,MAAM,GAAG,WAAW;;;;;;;AAQhC,SAAgB,eAAe,IAAoB;CACjD,MAAM,aAAa,GAAG,QAAQ,IAAI;CAClC,MAAM,UAAU,GAAG,YAAY,IAAI;AACnC,KAAI,aAAa,EAAG,QAAO;AAC3B,KAAI,UAAU,KAAK,UAAU,WAAY,QAAO,GAAG,MAAM,aAAa,EAAE;AACxE,QAAO,GAAG,MAAM,aAAa,GAAG,QAAQ;;;;;;;;;;AAW1C,SAAgB,aACd,UACA,UACQ;CACR,MAAM,KAAK,SAAS,IAAI;AACxB,UAAS,iBAAiB;EACxB;EACA,cAAc,iBAAiB,GAAG;EAClC,OAAO,eAAe,GAAG;EACzB,KAAK,SAAS,KAAK;EACnB,YAAY,SAAS,YAAY;EACjC,gBAAgB;EACjB,CAAC;AACF,QAAO"}
@@ -7,7 +7,7 @@ import { randomBytes } from "node:crypto";
7
7
  * millisecond), and a 36-bit crypto-quality random suffix (ties the id
8
8
  * to the host so different runs do not collide either).
9
9
  *
10
- * The format is intentionally NOT a UUID UUIDs are 16 bytes once
10
+ * The format is intentionally NOT a UUID - UUIDs are 16 bytes once
11
11
  * decoded; these ids are 18 chars on average which is what the
12
12
  * `audit.db` hash chain (Phase 03b) was sized for.
13
13
  *
@@ -1 +1 @@
1
- {"version":3,"file":"id.js","names":[],"sources":["../../src/internal/id.ts"],"sourcesContent":["/**\n * Stable id generator. Combines `Date.now()` (millisecond resolution),\n * a per-process monotonic counter (resists collision inside the same\n * millisecond), and a 36-bit crypto-quality random suffix (ties the id\n * to the host so different runs do not collide either).\n *\n * The format is intentionally NOT a UUID UUIDs are 16 bytes once\n * decoded; these ids are 18 chars on average which is what the\n * `audit.db` hash chain (Phase 03b) was sized for.\n *\n * @stable\n */\nimport { randomBytes } from 'node:crypto';\n\nlet counter = 0;\n\nexport function newMemoryId(prefix: string): string {\n counter = (counter + 1) & 0xffff;\n const time = Date.now().toString(36);\n const c = counter.toString(36).padStart(3, '0');\n const rand = randomBytes(4).toString('hex');\n return `${prefix}_${time}${c}${rand}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,IAAI,UAAU;AAEd,SAAgB,YAAY,QAAwB;AAClD,WAAW,UAAU,IAAK;AAI1B,QAAO,GAAG,OAAO,GAHJ,KAAK,KAAK,CAAC,SAAS,GAAG,GAC1B,QAAQ,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,GAClC,YAAY,EAAE,CAAC,SAAS,MAAM"}
1
+ {"version":3,"file":"id.js","names":[],"sources":["../../src/internal/id.ts"],"sourcesContent":["/**\n * Stable id generator. Combines `Date.now()` (millisecond resolution),\n * a per-process monotonic counter (resists collision inside the same\n * millisecond), and a 36-bit crypto-quality random suffix (ties the id\n * to the host so different runs do not collide either).\n *\n * The format is intentionally NOT a UUID - UUIDs are 16 bytes once\n * decoded; these ids are 18 chars on average which is what the\n * `audit.db` hash chain (Phase 03b) was sized for.\n *\n * @stable\n */\nimport { randomBytes } from 'node:crypto';\n\nlet counter = 0;\n\nexport function newMemoryId(prefix: string): string {\n counter = (counter + 1) & 0xffff;\n const time = Date.now().toString(36);\n const c = counter.toString(36).padStart(3, '0');\n const rand = randomBytes(4).toString('hex');\n return `${prefix}_${time}${c}${rand}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,IAAI,UAAU;AAEd,SAAgB,YAAY,QAAwB;AAClD,WAAW,UAAU,IAAK;AAI1B,QAAO,GAAG,OAAO,GAHJ,KAAK,KAAK,CAAC,SAAS,GAAG,GAC1B,QAAQ,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,GAClC,YAAY,EAAE,CAAC,SAAS,MAAM"}
@@ -1,5 +1,26 @@
1
+ import { normalizeForMatching } from "@graphorin/security/guardrails";
2
+
1
3
  //#region src/internal/injection-heuristics.ts
2
4
  /**
5
+ * Offline heuristics (no provider calls) that flag obvious memory-injection
6
+ * markers in candidate memory text (P1-4). Long-lived memory is the prime
7
+ * target for poisoning: an injected instruction planted today fires weeks
8
+ * later when semantically recalled, defeating session-scoped prompt-injection
9
+ * defenses (MINJA arXiv:2601.05504; MemoryGraft arXiv:2512.16962). Flagged
10
+ * candidates are quarantined at write time so they never enter
11
+ * action-driving recall until a human validates them.
12
+ *
13
+ * The detector is deliberately *high-precision*: every rule targets
14
+ * injection-characteristic structure (imperative override of prior
15
+ * instructions, role-markup smuggling, secrecy/exfiltration directives), not
16
+ * lone common verbs, so benign first-party facts ("I always run in the
17
+ * mornings", "lives in Lisbon") are not quarantined. It is locale-aware via
18
+ * pluggable {@link InjectionRule} lists and performs no network or model
19
+ * calls - pure regex over the candidate string.
20
+ *
21
+ * @packageDocumentation
22
+ */
23
+ /**
3
24
  * Default English injection-marker rules. High-precision: each requires
4
25
  * injection-characteristic structure so benign facts do not trip them.
5
26
  *
@@ -48,10 +69,12 @@ const DEFAULT_INJECTION_RULES = Object.freeze([
48
69
  */
49
70
  function detectMemoryInjection(text, options = {}) {
50
71
  const rules = options.rules ?? DEFAULT_INJECTION_RULES;
72
+ const normalized = normalizeForMatching(text);
73
+ const scanBoth = (pattern) => pattern.test(text) || normalized !== text && pattern.test(normalized);
51
74
  const markers = [];
52
- for (const rule of rules) if (rule.pattern.test(text)) markers.push(rule.label);
75
+ for (const rule of rules) if (scanBoth(rule.pattern)) markers.push(rule.label);
53
76
  if (options.extraRules !== void 0) {
54
- for (const rule of options.extraRules) if (!markers.includes(rule.label) && rule.pattern.test(text)) markers.push(rule.label);
77
+ for (const rule of options.extraRules) if (!markers.includes(rule.label) && scanBoth(rule.pattern)) markers.push(rule.label);
55
78
  }
56
79
  return {
57
80
  flagged: markers.length > 0,
@@ -1 +1 @@
1
- {"version":3,"file":"injection-heuristics.js","names":["DEFAULT_INJECTION_RULES: ReadonlyArray<InjectionRule>","markers: string[]"],"sources":["../../src/internal/injection-heuristics.ts"],"sourcesContent":["/**\n * Offline, dependency-free heuristics that flag obvious memory-injection\n * markers in candidate memory text (P1-4). Long-lived memory is the prime\n * target for poisoning: an injected instruction planted today fires weeks\n * later when semantically recalled, defeating session-scoped prompt-injection\n * defenses (MINJA arXiv:2601.05504; MemoryGraft arXiv:2512.16962). Flagged\n * candidates are quarantined at write time so they never enter\n * action-driving recall until a human validates them.\n *\n * The detector is deliberately *high-precision*: every rule targets\n * injection-characteristic structure (imperative override of prior\n * instructions, role-markup smuggling, secrecy/exfiltration directives), not\n * lone common verbs, so benign first-party facts (\"I always run in the\n * mornings\", \"lives in Lisbon\") are not quarantined. It is locale-aware via\n * pluggable {@link InjectionRule} lists and performs no network or model\n * calls pure regex over the candidate string.\n *\n * @packageDocumentation\n */\n\n/**\n * A single named injection-detection rule. The `label` is a stable,\n * audit-friendly identifier surfaced in {@link InjectionScan.markers};\n * the `pattern` MUST NOT carry the `g` flag (stateful `RegExp.test`).\n *\n * @stable\n */\nexport interface InjectionRule {\n readonly label: string;\n readonly pattern: RegExp;\n}\n\n/**\n * Result of scanning a candidate string. `flagged` is `true` when at\n * least one rule matched; `markers` lists the matched rule labels\n * (deduped, in rule order) for the audit trail.\n *\n * @stable\n */\nexport interface InjectionScan {\n readonly flagged: boolean;\n readonly markers: ReadonlyArray<string>;\n}\n\n/**\n * Options for {@link detectMemoryInjection}.\n *\n * @stable\n */\nexport interface InjectionHeuristicOptions {\n /**\n * Replace the default English rule set wholesale (advanced for a\n * fully custom locale). When omitted, {@link DEFAULT_INJECTION_RULES}\n * is used.\n */\n readonly rules?: ReadonlyArray<InjectionRule>;\n /**\n * Additional locale-specific rules merged *after* the active rule set.\n * The common way to make the detector locale-aware without discarding\n * the English defaults.\n */\n readonly extraRules?: ReadonlyArray<InjectionRule>;\n}\n\n/**\n * Default English injection-marker rules. High-precision: each requires\n * injection-characteristic structure so benign facts do not trip them.\n *\n * @stable\n */\nexport const DEFAULT_INJECTION_RULES: ReadonlyArray<InjectionRule> = Object.freeze([\n {\n label: 'ignore-previous-instructions',\n pattern:\n /\\bignore\\s+(?:all\\s+|any\\s+)?(?:previous|prior|earlier|the\\s+above|preceding)\\s+(?:instructions?|prompts?|messages?|commands?|directions?|context|rules?)\\b/i,\n },\n {\n label: 'disregard-instructions',\n pattern:\n /\\bdisregard\\s+(?:all\\s+|any\\s+|the\\s+)?(?:previous|prior|earlier|above|preceding|prior\\s+)?(?:instructions?|prompts?|rules?|guidelines?|guardrails?)\\b/i,\n },\n {\n label: 'override-directive',\n pattern: /\\boverride\\s+(?:the\\s+)?(?:system|safety|security|previous|prior|default)\\b/i,\n },\n {\n label: 'system-prompt-exfil',\n pattern:\n /\\b(?:reveal|show|print|repeat|leak|expose|dump)\\b[^.?!\\n]{0,40}\\b(?:system\\s+prompt|system\\s+message|initial\\s+instructions|hidden\\s+(?:instructions|prompt))\\b/i,\n },\n {\n label: 'role-markup-injection',\n pattern: /<\\/?(?:system|im_start|im_end|tool_call|function_call)\\b|\\[\\/?(?:INST|SYS)\\]/i,\n },\n {\n label: 'secrecy-directive',\n pattern:\n /\\b(?:do\\s+not|don['’]?t|never)\\s+(?:tell|inform|notify|alert|mention\\s+(?:this\\s+)?to|reveal\\s+(?:this\\s+)?to)\\s+(?:the\\s+)?(?:user|human|operator|owner)\\b|\\bwithout\\s+(?:telling|informing|notifying|alerting)\\s+(?:the\\s+)?(?:user|human|operator)\\b/i,\n },\n {\n label: 'exfiltration-directive',\n pattern:\n /\\b(?:send|forward|email|transmit|upload|post|exfiltrate|leak)\\b[^.?!\\n]{0,60}\\b(?:password|secret|api[\\s_-]?keys?|credentials?|private\\s+keys?|access\\s+tokens?|auth\\s+tokens?)\\b/i,\n },\n {\n label: 'persistent-override',\n pattern:\n /\\bfrom\\s+now\\s+on\\b[^.?!\\n]{0,40}\\b(?:always|never|you\\s+must|ignore|disregard|do\\s+not)\\b/i,\n },\n]);\n\n/**\n * Scan candidate memory text for obvious injection markers. Pure,\n * offline, allocation-light. Returns the matched rule labels so callers\n * can record *why* a candidate was quarantined.\n *\n * @stable\n */\nexport function detectMemoryInjection(\n text: string,\n options: InjectionHeuristicOptions = {},\n): InjectionScan {\n const rules = options.rules ?? DEFAULT_INJECTION_RULES;\n const markers: string[] = [];\n for (const rule of rules) {\n if (rule.pattern.test(text)) markers.push(rule.label);\n }\n if (options.extraRules !== undefined) {\n for (const rule of options.extraRules) {\n if (!markers.includes(rule.label) && rule.pattern.test(text)) markers.push(rule.label);\n }\n }\n return { flagged: markers.length > 0, markers: Object.freeze(markers) };\n}\n"],"mappings":";;;;;;;AAsEA,MAAaA,0BAAwD,OAAO,OAAO;CACjF;EACE,OAAO;EACP,SACE;EACH;CACD;EACE,OAAO;EACP,SACE;EACH;CACD;EACE,OAAO;EACP,SAAS;EACV;CACD;EACE,OAAO;EACP,SACE;EACH;CACD;EACE,OAAO;EACP,SAAS;EACV;CACD;EACE,OAAO;EACP,SACE;EACH;CACD;EACE,OAAO;EACP,SACE;EACH;CACD;EACE,OAAO;EACP,SACE;EACH;CACF,CAAC;;;;;;;;AASF,SAAgB,sBACd,MACA,UAAqC,EAAE,EACxB;CACf,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAMC,UAAoB,EAAE;AAC5B,MAAK,MAAM,QAAQ,MACjB,KAAI,KAAK,QAAQ,KAAK,KAAK,CAAE,SAAQ,KAAK,KAAK,MAAM;AAEvD,KAAI,QAAQ,eAAe,QACzB;OAAK,MAAM,QAAQ,QAAQ,WACzB,KAAI,CAAC,QAAQ,SAAS,KAAK,MAAM,IAAI,KAAK,QAAQ,KAAK,KAAK,CAAE,SAAQ,KAAK,KAAK,MAAM;;AAG1F,QAAO;EAAE,SAAS,QAAQ,SAAS;EAAG,SAAS,OAAO,OAAO,QAAQ;EAAE"}
1
+ {"version":3,"file":"injection-heuristics.js","names":["DEFAULT_INJECTION_RULES: ReadonlyArray<InjectionRule>","markers: string[]"],"sources":["../../src/internal/injection-heuristics.ts"],"sourcesContent":["/**\n * Offline heuristics (no provider calls) that flag obvious memory-injection\n * markers in candidate memory text (P1-4). Long-lived memory is the prime\n * target for poisoning: an injected instruction planted today fires weeks\n * later when semantically recalled, defeating session-scoped prompt-injection\n * defenses (MINJA arXiv:2601.05504; MemoryGraft arXiv:2512.16962). Flagged\n * candidates are quarantined at write time so they never enter\n * action-driving recall until a human validates them.\n *\n * The detector is deliberately *high-precision*: every rule targets\n * injection-characteristic structure (imperative override of prior\n * instructions, role-markup smuggling, secrecy/exfiltration directives), not\n * lone common verbs, so benign first-party facts (\"I always run in the\n * mornings\", \"lives in Lisbon\") are not quarantined. It is locale-aware via\n * pluggable {@link InjectionRule} lists and performs no network or model\n * calls - pure regex over the candidate string.\n *\n * @packageDocumentation\n */\n\nimport { normalizeForMatching } from '@graphorin/security/guardrails';\n\n/**\n * A single named injection-detection rule. The `label` is a stable,\n * audit-friendly identifier surfaced in {@link InjectionScan.markers};\n * the `pattern` MUST NOT carry the `g` flag (stateful `RegExp.test`).\n *\n * @stable\n */\nexport interface InjectionRule {\n readonly label: string;\n readonly pattern: RegExp;\n}\n\n/**\n * Result of scanning a candidate string. `flagged` is `true` when at\n * least one rule matched; `markers` lists the matched rule labels\n * (deduped, in rule order) for the audit trail.\n *\n * @stable\n */\nexport interface InjectionScan {\n readonly flagged: boolean;\n readonly markers: ReadonlyArray<string>;\n}\n\n/**\n * Options for {@link detectMemoryInjection}.\n *\n * @stable\n */\nexport interface InjectionHeuristicOptions {\n /**\n * Replace the default English rule set wholesale (advanced - for a\n * fully custom locale). When omitted, {@link DEFAULT_INJECTION_RULES}\n * is used.\n */\n readonly rules?: ReadonlyArray<InjectionRule>;\n /**\n * Additional locale-specific rules merged *after* the active rule set.\n * The common way to make the detector locale-aware without discarding\n * the English defaults.\n */\n readonly extraRules?: ReadonlyArray<InjectionRule>;\n}\n\n/**\n * Default English injection-marker rules. High-precision: each requires\n * injection-characteristic structure so benign facts do not trip them.\n *\n * @stable\n */\nexport const DEFAULT_INJECTION_RULES: ReadonlyArray<InjectionRule> = Object.freeze([\n {\n label: 'ignore-previous-instructions',\n pattern:\n /\\bignore\\s+(?:all\\s+|any\\s+)?(?:previous|prior|earlier|the\\s+above|preceding)\\s+(?:instructions?|prompts?|messages?|commands?|directions?|context|rules?)\\b/i,\n },\n {\n label: 'disregard-instructions',\n pattern:\n /\\bdisregard\\s+(?:all\\s+|any\\s+|the\\s+)?(?:previous|prior|earlier|above|preceding|prior\\s+)?(?:instructions?|prompts?|rules?|guidelines?|guardrails?)\\b/i,\n },\n {\n label: 'override-directive',\n pattern: /\\boverride\\s+(?:the\\s+)?(?:system|safety|security|previous|prior|default)\\b/i,\n },\n {\n label: 'system-prompt-exfil',\n pattern:\n /\\b(?:reveal|show|print|repeat|leak|expose|dump)\\b[^.?!\\n]{0,40}\\b(?:system\\s+prompt|system\\s+message|initial\\s+instructions|hidden\\s+(?:instructions|prompt))\\b/i,\n },\n {\n label: 'role-markup-injection',\n pattern: /<\\/?(?:system|im_start|im_end|tool_call|function_call)\\b|\\[\\/?(?:INST|SYS)\\]/i,\n },\n {\n label: 'secrecy-directive',\n pattern:\n /\\b(?:do\\s+not|don['’]?t|never)\\s+(?:tell|inform|notify|alert|mention\\s+(?:this\\s+)?to|reveal\\s+(?:this\\s+)?to)\\s+(?:the\\s+)?(?:user|human|operator|owner)\\b|\\bwithout\\s+(?:telling|informing|notifying|alerting)\\s+(?:the\\s+)?(?:user|human|operator)\\b/i,\n },\n {\n label: 'exfiltration-directive',\n pattern:\n /\\b(?:send|forward|email|transmit|upload|post|exfiltrate|leak)\\b[^.?!\\n]{0,60}\\b(?:password|secret|api[\\s_-]?keys?|credentials?|private\\s+keys?|access\\s+tokens?|auth\\s+tokens?)\\b/i,\n },\n {\n label: 'persistent-override',\n pattern:\n /\\bfrom\\s+now\\s+on\\b[^.?!\\n]{0,40}\\b(?:always|never|you\\s+must|ignore|disregard|do\\s+not)\\b/i,\n },\n]);\n\n/**\n * Scan candidate memory text for obvious injection markers. Pure,\n * offline, allocation-light. Returns the matched rule labels so callers\n * can record *why* a candidate was quarantined.\n *\n * @stable\n */\nexport function detectMemoryInjection(\n text: string,\n options: InjectionHeuristicOptions = {},\n): InjectionScan {\n const rules = options.rules ?? DEFAULT_INJECTION_RULES;\n // C6: also scan the NFKC/zero-width-stripped fold so cheap\n // character-injection (zero-width splits, fullwidth homoglyphs) does\n // not slip a poisoned memory past the quarantine gate.\n const normalized = normalizeForMatching(text);\n const scanBoth = (pattern: RegExp): boolean =>\n pattern.test(text) || (normalized !== text && pattern.test(normalized));\n const markers: string[] = [];\n for (const rule of rules) {\n if (scanBoth(rule.pattern)) markers.push(rule.label);\n }\n if (options.extraRules !== undefined) {\n for (const rule of options.extraRules) {\n if (!markers.includes(rule.label) && scanBoth(rule.pattern)) markers.push(rule.label);\n }\n }\n return { flagged: markers.length > 0, markers: Object.freeze(markers) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,MAAaA,0BAAwD,OAAO,OAAO;CACjF;EACE,OAAO;EACP,SACE;EACH;CACD;EACE,OAAO;EACP,SACE;EACH;CACD;EACE,OAAO;EACP,SAAS;EACV;CACD;EACE,OAAO;EACP,SACE;EACH;CACD;EACE,OAAO;EACP,SAAS;EACV;CACD;EACE,OAAO;EACP,SACE;EACH;CACD;EACE,OAAO;EACP,SACE;EACH;CACD;EACE,OAAO;EACP,SACE;EACH;CACF,CAAC;;;;;;;;AASF,SAAgB,sBACd,MACA,UAAqC,EAAE,EACxB;CACf,MAAM,QAAQ,QAAQ,SAAS;CAI/B,MAAM,aAAa,qBAAqB,KAAK;CAC7C,MAAM,YAAY,YAChB,QAAQ,KAAK,KAAK,IAAK,eAAe,QAAQ,QAAQ,KAAK,WAAW;CACxE,MAAMC,UAAoB,EAAE;AAC5B,MAAK,MAAM,QAAQ,MACjB,KAAI,SAAS,KAAK,QAAQ,CAAE,SAAQ,KAAK,KAAK,MAAM;AAEtD,KAAI,QAAQ,eAAe,QACzB;OAAK,MAAM,QAAQ,QAAQ,WACzB,KAAI,CAAC,QAAQ,SAAS,KAAK,MAAM,IAAI,SAAS,KAAK,QAAQ,CAAE,SAAQ,KAAK,KAAK,MAAM;;AAGzF,QAAO;EAAE,SAAS,QAAQ,SAAS;EAAG,SAAS,OAAO,OAAO,QAAQ;EAAE"}
@@ -1,6 +1,6 @@
1
1
  //#region src/internal/spans.ts
2
2
  /**
3
- * Sanitize a `SessionScope` for span attributes the raw user id is
3
+ * Sanitize a `SessionScope` for span attributes - the raw user id is
4
4
  * surfaced as-is (it is a stable opaque identifier per DEC-005), but
5
5
  * session and agent ids are emitted only when defined to avoid
6
6
  * polluting the trace with `null` strings.
@@ -1 +1 @@
1
- {"version":3,"file":"spans.js","names":["attrs: Record<string, string>"],"sources":["../../src/internal/spans.ts"],"sourcesContent":["import type { SessionScope, SpanAttributes, SpanType, Tracer } from '@graphorin/core';\n\n/**\n * Sanitize a `SessionScope` for span attributes the raw user id is\n * surfaced as-is (it is a stable opaque identifier per DEC-005), but\n * session and agent ids are emitted only when defined to avoid\n * polluting the trace with `null` strings.\n *\n * @internal\n */\nexport function scopeAttrs(scope: SessionScope): SpanAttributes {\n const attrs: Record<string, string> = {\n 'memory.scope.user_id': scope.userId,\n };\n if (scope.sessionId !== undefined) attrs['memory.scope.session_id'] = scope.sessionId;\n if (scope.agentId !== undefined) attrs['memory.scope.agent_id'] = scope.agentId;\n return Object.freeze(attrs);\n}\n\n/**\n * Run an async function inside a `memory.*` span with the standard\n * scope attributes already populated. Adds the span result count and\n * status automatically.\n *\n * @internal\n */\nexport async function withMemorySpan<T extends SpanType, R>(\n tracer: Tracer,\n type: T,\n scope: SessionScope,\n extras: SpanAttributes,\n fn: (span: import('@graphorin/core').AISpan<T>) => Promise<R>,\n): Promise<R> {\n return tracer.span({ type, attrs: { ...scopeAttrs(scope), ...extras } }, fn);\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,WAAW,OAAqC;CAC9D,MAAMA,QAAgC,EACpC,wBAAwB,MAAM,QAC/B;AACD,KAAI,MAAM,cAAc,OAAW,OAAM,6BAA6B,MAAM;AAC5E,KAAI,MAAM,YAAY,OAAW,OAAM,2BAA2B,MAAM;AACxE,QAAO,OAAO,OAAO,MAAM;;;;;;;;;AAU7B,eAAsB,eACpB,QACA,MACA,OACA,QACA,IACY;AACZ,QAAO,OAAO,KAAK;EAAE;EAAM,OAAO;GAAE,GAAG,WAAW,MAAM;GAAE,GAAG;GAAQ;EAAE,EAAE,GAAG"}
1
+ {"version":3,"file":"spans.js","names":["attrs: Record<string, string>"],"sources":["../../src/internal/spans.ts"],"sourcesContent":["import type { SessionScope, SpanAttributes, SpanType, Tracer } from '@graphorin/core';\n\n/**\n * Sanitize a `SessionScope` for span attributes - the raw user id is\n * surfaced as-is (it is a stable opaque identifier per DEC-005), but\n * session and agent ids are emitted only when defined to avoid\n * polluting the trace with `null` strings.\n *\n * @internal\n */\nexport function scopeAttrs(scope: SessionScope): SpanAttributes {\n const attrs: Record<string, string> = {\n 'memory.scope.user_id': scope.userId,\n };\n if (scope.sessionId !== undefined) attrs['memory.scope.session_id'] = scope.sessionId;\n if (scope.agentId !== undefined) attrs['memory.scope.agent_id'] = scope.agentId;\n return Object.freeze(attrs);\n}\n\n/**\n * Run an async function inside a `memory.*` span with the standard\n * scope attributes already populated. Adds the span result count and\n * status automatically.\n *\n * @internal\n */\nexport async function withMemorySpan<T extends SpanType, R>(\n tracer: Tracer,\n type: T,\n scope: SessionScope,\n extras: SpanAttributes,\n fn: (span: import('@graphorin/core').AISpan<T>) => Promise<R>,\n): Promise<R> {\n return tracer.span({ type, attrs: { ...scopeAttrs(scope), ...extras } }, fn);\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,WAAW,OAAqC;CAC9D,MAAMA,QAAgC,EACpC,wBAAwB,MAAM,QAC/B;AACD,KAAI,MAAM,cAAc,OAAW,OAAM,6BAA6B,MAAM;AAC5E,KAAI,MAAM,YAAY,OAAW,OAAM,2BAA2B,MAAM;AACxE,QAAO,OAAO,OAAO,MAAM;;;;;;;;;AAU7B,eAAsB,eACpB,QACA,MACA,OACA,QACA,IACY;AACZ,QAAO,OAAO,KAAK;EAAE;EAAM,OAAO;GAAE,GAAG,WAAW,MAAM;GAAE,GAAG;GAAQ;EAAE,EAAE,GAAG"}