@indexnetwork/protocol 14.3.2-rc.477.1 → 17.0.0-rc.479.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/IMPLEMENTATION.md +50 -52
  3. package/STABILITY.md +3 -3
  4. package/dist/chat/chat.agent.js +2 -3
  5. package/dist/chat/chat.graph.d.ts +41 -1
  6. package/dist/chat/chat.graph.js +108 -127
  7. package/dist/chat/negotiator.persona.d.ts +1 -1
  8. package/dist/chat/negotiator.persona.js +1 -4
  9. package/dist/chat/negotiator.prompt.js +1 -2
  10. package/dist/chat/onboarding.persona.js +0 -1
  11. package/dist/chat/reporter.persona.js +0 -1
  12. package/dist/chat/signal.persona.js +0 -1
  13. package/dist/contacts/application/contact.tools.d.ts +6 -9
  14. package/dist/contacts/application/contact.tools.js +11 -92
  15. package/dist/contacts/application/index.d.ts +2 -14
  16. package/dist/contacts/application/index.js +2 -13
  17. package/dist/contacts/domain/contact.types.d.ts +0 -23
  18. package/dist/contacts/domain/index.d.ts +2 -6
  19. package/dist/contacts/index.d.ts +1 -1
  20. package/dist/contacts/index.js +1 -1
  21. package/dist/contacts/ports/contact.repository.port.d.ts +5 -12
  22. package/dist/contacts/ports/contact.repository.port.js +4 -6
  23. package/dist/contacts/ports/contact.tools.port.d.ts +1 -3
  24. package/dist/contacts/ports/contact.tools.port.js +1 -2
  25. package/dist/contacts/ports/index.d.ts +1 -1
  26. package/dist/contacts/ports/index.js +1 -1
  27. package/dist/discovery/hyde.frame.d.ts +4 -4
  28. package/dist/discovery/hyde.graph.d.ts +71 -12
  29. package/dist/discovery/hyde.graph.js +337 -335
  30. package/dist/discovery/lens.inferrer.d.ts +6 -6
  31. package/dist/enrichment/enrichment.graph.d.ts +127 -9
  32. package/dist/enrichment/enrichment.graph.js +633 -655
  33. package/dist/enrichment/enrichment.state.d.ts +1 -1
  34. package/dist/enrichment/enrichment.tools.context-read.d.ts +10 -0
  35. package/dist/enrichment/enrichment.tools.context-read.js +353 -0
  36. package/dist/enrichment/enrichment.tools.context-write.d.ts +9 -0
  37. package/dist/enrichment/enrichment.tools.context-write.js +417 -0
  38. package/dist/enrichment/enrichment.tools.d.ts +11 -1
  39. package/dist/enrichment/enrichment.tools.helpers.d.ts +139 -0
  40. package/dist/enrichment/enrichment.tools.helpers.js +234 -0
  41. package/dist/enrichment/enrichment.tools.js +16 -975
  42. package/dist/index.d.ts +27 -50
  43. package/dist/index.js +17 -28
  44. package/dist/intents/application/intent.graph.d.ts +71 -67
  45. package/dist/intents/application/intent.graph.execute.d.ts +59 -0
  46. package/dist/intents/application/intent.graph.execute.js +301 -0
  47. package/dist/intents/application/intent.graph.infer.d.ts +44 -0
  48. package/dist/intents/application/intent.graph.infer.js +97 -0
  49. package/dist/intents/application/intent.graph.js +96 -888
  50. package/dist/intents/application/intent.graph.reconcile.d.ts +71 -0
  51. package/dist/intents/application/intent.graph.reconcile.js +274 -0
  52. package/dist/intents/application/intent.graph.shared.d.ts +70 -0
  53. package/dist/intents/application/intent.graph.shared.js +153 -0
  54. package/dist/intents/domain/intent.state.d.ts +1 -1
  55. package/dist/maintenance/maintenance.graph.d.ts +66 -3
  56. package/dist/maintenance/maintenance.graph.js +155 -156
  57. package/dist/mcp/mcp.authorization-policy.d.ts +24 -28
  58. package/dist/mcp/mcp.authorization-policy.js +14 -34
  59. package/dist/mcp/mcp.server.d.ts +3 -3
  60. package/dist/mcp/mcp.server.js +14 -20
  61. package/dist/negotiations/application/negotiation.candidates.d.ts +83 -0
  62. package/dist/negotiations/application/negotiation.candidates.js +162 -0
  63. package/dist/negotiations/application/negotiation.graph.d.ts +91 -157
  64. package/dist/negotiations/application/negotiation.graph.finalize.d.ts +5 -0
  65. package/dist/negotiations/application/negotiation.graph.finalize.js +280 -0
  66. package/dist/negotiations/application/negotiation.graph.init.d.ts +54 -0
  67. package/dist/negotiations/application/negotiation.graph.init.js +227 -0
  68. package/dist/negotiations/application/negotiation.graph.js +69 -1388
  69. package/dist/negotiations/application/negotiation.graph.screen.d.ts +23 -0
  70. package/dist/negotiations/application/negotiation.graph.screen.js +108 -0
  71. package/dist/negotiations/application/negotiation.graph.shared.d.ts +75 -0
  72. package/dist/negotiations/application/negotiation.graph.shared.js +125 -0
  73. package/dist/negotiations/application/negotiation.graph.turn.d.ts +105 -0
  74. package/dist/negotiations/application/negotiation.graph.turn.js +484 -0
  75. package/dist/negotiations/domain/negotiation.state.d.ts +1 -1
  76. package/dist/negotiations/domain/negotiation.state.js +0 -1
  77. package/dist/networks/application/indexer.graph.d.ts +165 -7
  78. package/dist/networks/application/indexer.graph.js +339 -388
  79. package/dist/networks/application/indexer.state.d.ts +1 -1
  80. package/dist/networks/application/membership.graph.d.ts +83 -5
  81. package/dist/networks/application/membership.graph.js +177 -207
  82. package/dist/networks/application/network.graph.d.ts +148 -5
  83. package/dist/networks/application/network.graph.js +249 -278
  84. package/dist/networks/domain/membership.state.d.ts +1 -1
  85. package/dist/networks/domain/network.state.d.ts +1 -1
  86. package/dist/opportunities/application/delivery-card.cache.d.ts +1 -1
  87. package/dist/opportunities/application/delivery-card.cache.js +2 -2
  88. package/dist/opportunities/application/index.d.ts +2 -2
  89. package/dist/opportunities/application/index.js +2 -2
  90. package/dist/opportunities/application/opportunity.evaluator.js +1 -1
  91. package/dist/opportunities/application/opportunity.graph.d.ts +686 -473
  92. package/dist/opportunities/application/opportunity.graph.discovery-strategies.d.ts +109 -0
  93. package/dist/opportunities/application/opportunity.graph.discovery-strategies.js +451 -0
  94. package/dist/opportunities/application/opportunity.graph.discovery.d.ts +69 -0
  95. package/dist/opportunities/application/opportunity.graph.discovery.js +397 -0
  96. package/dist/opportunities/application/opportunity.graph.evaluation.d.ts +82 -0
  97. package/dist/opportunities/application/opportunity.graph.evaluation.js +608 -0
  98. package/dist/opportunities/application/opportunity.graph.js +120 -3690
  99. package/dist/opportunities/application/opportunity.graph.modes.d.ts +538 -0
  100. package/dist/opportunities/application/opportunity.graph.modes.js +538 -0
  101. package/dist/opportunities/application/opportunity.graph.negotiate.d.ts +109 -0
  102. package/dist/opportunities/application/opportunity.graph.negotiate.js +392 -0
  103. package/dist/opportunities/application/opportunity.graph.persist-node.d.ts +93 -0
  104. package/dist/opportunities/application/opportunity.graph.persist-node.js +765 -0
  105. package/dist/opportunities/application/opportunity.graph.prep.d.ts +150 -0
  106. package/dist/opportunities/application/opportunity.graph.prep.js +381 -0
  107. package/dist/opportunities/application/opportunity.graph.shared.d.ts +173 -0
  108. package/dist/opportunities/application/opportunity.graph.shared.js +199 -0
  109. package/dist/opportunities/application/opportunity.presentation.d.ts +399 -0
  110. package/dist/opportunities/application/{opportunity.presenter.js → opportunity.presentation.js} +735 -9
  111. package/dist/opportunities/application/opportunity.tools.cards.d.ts +152 -0
  112. package/dist/opportunities/application/opportunity.tools.cards.js +235 -0
  113. package/dist/opportunities/application/opportunity.tools.d.ts +8 -114
  114. package/dist/opportunities/application/opportunity.tools.js +28 -711
  115. package/dist/opportunities/application/opportunity.tools.list.d.ts +10 -0
  116. package/dist/opportunities/application/opportunity.tools.list.js +493 -0
  117. package/dist/opportunities/domain/index.d.ts +3 -3
  118. package/dist/opportunities/domain/index.js +3 -3
  119. package/dist/opportunities/domain/opportunity.state.d.ts +19 -19
  120. package/dist/opportunities/index.d.ts +6 -6
  121. package/dist/opportunities/index.js +4 -4
  122. package/dist/opportunities/ports/opportunity.tools.port.d.ts +1 -1
  123. package/dist/opportunities/radar/radar.graph.d.ts +57 -13
  124. package/dist/opportunities/radar/radar.graph.js +470 -471
  125. package/dist/premises/premise.graph.d.ts +88 -20
  126. package/dist/premises/premise.graph.js +207 -218
  127. package/dist/questions/domain/question.schema.d.ts +40 -40
  128. package/dist/shared/agent/tool.factory.js +0 -8
  129. package/dist/shared/agent/tool.helpers.d.ts +21 -45
  130. package/dist/shared/agent/tool.helpers.js +1 -2
  131. package/dist/shared/agent/tool.registry.d.ts +4 -3
  132. package/dist/shared/agent/tool.registry.js +2 -4
  133. package/dist/shared/agent/tool.runtime.js +0 -2
  134. package/dist/shared/agent/utility.tools.js +9 -13
  135. package/dist/shared/interfaces/database.capabilities.d.ts +100 -0
  136. package/dist/shared/interfaces/database.capabilities.js +7 -0
  137. package/dist/shared/interfaces/database.entities.d.ts +533 -0
  138. package/dist/shared/interfaces/database.entities.js +10 -0
  139. package/dist/shared/interfaces/database.identity-queries.d.ts +294 -0
  140. package/dist/shared/interfaces/database.identity-queries.js +4 -0
  141. package/dist/shared/interfaces/database.interface.d.ts +15 -2277
  142. package/dist/shared/interfaces/database.interface.js +8 -0
  143. package/dist/shared/interfaces/database.member-queries.d.ts +221 -0
  144. package/dist/shared/interfaces/database.member-queries.js +4 -0
  145. package/dist/shared/interfaces/database.negotiation.d.ts +305 -0
  146. package/dist/shared/interfaces/database.negotiation.js +26 -0
  147. package/dist/shared/interfaces/database.network-queries.d.ts +277 -0
  148. package/dist/shared/interfaces/database.network-queries.js +4 -0
  149. package/dist/shared/interfaces/database.opportunity-queries.d.ts +285 -0
  150. package/dist/shared/interfaces/database.opportunity-queries.js +4 -0
  151. package/dist/shared/interfaces/database.port.d.ts +322 -0
  152. package/dist/shared/interfaces/database.port.js +29 -0
  153. package/dist/shared/schemas/discovery-question.schema.d.ts +14 -14
  154. package/dist/shared/schemas/negotiation-digest.schema.d.ts +2 -2
  155. package/package.json +2 -15
  156. package/dist/contacts/application/contact.inviter.d.ts +0 -49
  157. package/dist/contacts/application/contact.inviter.js +0 -64
  158. package/dist/integrations/application/index.d.ts +0 -14
  159. package/dist/integrations/application/index.js +0 -14
  160. package/dist/integrations/application/integration.tools.d.ts +0 -27
  161. package/dist/integrations/application/integration.tools.js +0 -98
  162. package/dist/integrations/domain/index.d.ts +0 -16
  163. package/dist/integrations/domain/index.js +0 -1
  164. package/dist/integrations/domain/integration.types.d.ts +0 -51
  165. package/dist/integrations/domain/integration.types.js +0 -9
  166. package/dist/integrations/index.d.ts +0 -10
  167. package/dist/integrations/index.js +0 -8
  168. package/dist/integrations/ports/index.d.ts +0 -25
  169. package/dist/integrations/ports/index.js +0 -23
  170. package/dist/integrations/ports/integration.adapter.port.d.ts +0 -62
  171. package/dist/integrations/ports/integration.adapter.port.js +0 -15
  172. package/dist/integrations/ports/integration.importer.port.d.ts +0 -31
  173. package/dist/integrations/ports/integration.importer.port.js +0 -15
  174. package/dist/integrations/ports/integration.tools.port.d.ts +0 -25
  175. package/dist/integrations/ports/integration.tools.port.js +0 -18
  176. package/dist/opportunities/application/opportunity.card-presentation.d.ts +0 -44
  177. package/dist/opportunities/application/opportunity.card-presentation.js +0 -93
  178. package/dist/opportunities/application/opportunity.presenter.d.ts +0 -156
  179. package/dist/opportunities/domain/opportunity.presentation-cache.d.ts +0 -5
  180. package/dist/opportunities/domain/opportunity.presentation-cache.js +0 -11
  181. package/dist/opportunities/domain/opportunity.presentation.d.ts +0 -76
  182. package/dist/opportunities/domain/opportunity.presentation.js +0 -516
  183. package/dist/opportunities/domain/opportunity.safe-presentation.d.ts +0 -104
  184. package/dist/opportunities/domain/opportunity.safe-presentation.js +0 -102
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The individual retrieval strategies the discovery node runs, plus the merge
3
+ * that folds their results into one candidate set.
4
+ *
5
+ * These were nested functions inside the discovery closure, capturing the node's
6
+ * locals. They now take an explicit {@link DiscoveryStrategyContext} so each
7
+ * strategy reads on its own.
8
+ */
9
+ import type { Id } from '../../shared/interfaces/database.interface.js';
10
+ import type { CandidateMatch } from '../domain/opportunity.state.js';
11
+ import type { LensEmbedding } from '../../shared/interfaces/embedder.interface.js';
12
+ import { discoveryProfileSource } from '../discovery.env.js';
13
+ import { type OpportunityGraphDeps, type OpportunityState } from './opportunity.graph.shared.js';
14
+ /** Corpus gating passed through to the embedder on every HyDE search. */
15
+ export interface DiscoveryCorpusGating {
16
+ readonly intents: boolean;
17
+ readonly profile: boolean;
18
+ readonly profileCorpus: ReturnType<typeof discoveryProfileSource>;
19
+ }
20
+ /** Everything the strategies below need, resolved once by the discovery node. */
21
+ export interface DiscoveryStrategyContext {
22
+ state: OpportunityState;
23
+ deps: OpportunityGraphDeps;
24
+ discoveryUserId: string;
25
+ limitPerStrategy: number;
26
+ perIndexLimit: number;
27
+ corpusGating: DiscoveryCorpusGating;
28
+ intentResultsEnabled: boolean;
29
+ premiseResultsEnabled: boolean;
30
+ contextResultsEnabled: boolean;
31
+ }
32
+ /** Trace payload the query-HyDE path produces alongside its candidates. */
33
+ export interface QueryHydeDiscoveryResult {
34
+ candidates: CandidateMatch[];
35
+ lensInput: {
36
+ profileContext: string | undefined;
37
+ model: string;
38
+ };
39
+ hydeOutput: {
40
+ lenses: Array<{
41
+ label: string;
42
+ corpus: string;
43
+ }>;
44
+ hydeDocuments: Record<string, {
45
+ hydeText?: string;
46
+ }>;
47
+ };
48
+ }
49
+ /**
50
+ * Query-driven HyDE retrieval: generate hypothetical documents from the search
51
+ * text, then search every target network with the resulting lens embeddings.
52
+ */
53
+ export declare function runQueryHydeDiscovery(ctx: DiscoveryStrategyContext): Promise<QueryHydeDiscoveryResult | null>;
54
+ /** Map HyDE embeddings back onto their lens metadata. */
55
+ export declare function toLensEmbeddings(hydeEmbeddings: Record<string, number[]>, lenses: Array<{
56
+ label: string;
57
+ corpus: 'profiles' | 'intents' | 'premises';
58
+ }>): LensEmbedding[];
59
+ /**
60
+ * Turn embedder hits into candidates, honouring the match-type gates.
61
+ *
62
+ * Result filtering here is defense-in-depth: corpusGating already scopes the
63
+ * embedder's corpus searches, but adapters may still return other types.
64
+ */
65
+ export declare function collectHydeResults(results: Awaited<ReturnType<OpportunityGraphDeps['embedder']['searchWithHydeEmbeddings']>>, networkId: Id<'networks'>, ctx: Pick<DiscoveryStrategyContext, 'intentResultsEnabled' | 'premiseResultsEnabled' | 'contextResultsEnabled'>): CandidateMatch[];
66
+ /**
67
+ * Premise-to-premise discovery (path D).
68
+ * Searches for other users' premises similar to the discoverer's premises,
69
+ * scoped to target networks. Additive — merges into existing candidates.
70
+ */
71
+ export declare function runPremiseDiscovery(ctx: DiscoveryStrategyContext): Promise<CandidateMatch[]>;
72
+ /**
73
+ * Context-to-intent discovery: searches intents using context HyDE embeddings.
74
+ * When HyDE documents exist for a context, uses optimised hypothetical-document
75
+ * embeddings via searchWithHydeEmbeddings. Falls back to raw context embedding
76
+ * via searchIntentsByContextEmbedding when no HyDE docs are available.
77
+ */
78
+ export declare function runContextToIntentDiscovery(ctx: DiscoveryStrategyContext): Promise<CandidateMatch[]>;
79
+ /**
80
+ * Context-to-context discovery (lightweight profile mode only).
81
+ * Raw network-scoped context embeddings → candidate user_contexts.
82
+ * No HyDE: both sides are the same document type (synthesized
83
+ * 3–6 sentence paragraphs), so direct paragraph similarity is correct
84
+ * (same rationale as raw premise-to-premise).
85
+ */
86
+ export declare function runContextToContextDiscovery(ctx: DiscoveryStrategyContext): Promise<CandidateMatch[]>;
87
+ /**
88
+ * Run the three additive strategies concurrently, in the order the discovery
89
+ * node reports them: premise-to-premise, context-to-intent, context-to-context.
90
+ */
91
+ export declare function runAuxiliaryStrategies(ctx: DiscoveryStrategyContext): Promise<[CandidateMatch[], CandidateMatch[], CandidateMatch[]]>;
92
+ /**
93
+ * Merge candidates from multiple strategies. Deduplicates by userId + networkId + entityId,
94
+ * keeps the highest similarity, tracks which strategies found each candidate,
95
+ * and applies a multi-strategy boost (+0.05 per additional strategy, boost capped at 0.15,
96
+ * final similarity capped at 1.0).
97
+ */
98
+ export declare function mergeStrategyCandidates(...groups: CandidateMatch[][]): CandidateMatch[];
99
+ /** Per-lens candidate counts and mean similarity, for the discovery trace. */
100
+ export declare function computeLensStats(candidates: CandidateMatch[]): Record<string, {
101
+ count: number;
102
+ avgSimilarity: number;
103
+ }>;
104
+ /** One `strategy` trace line per auxiliary strategy that produced candidates. */
105
+ export declare function auxiliaryStrategyTraces(premiseCands: CandidateMatch[], contextCands: CandidateMatch[], contextSimCands: CandidateMatch[]): Array<{
106
+ node: string;
107
+ detail?: string;
108
+ data?: Record<string, unknown>;
109
+ }>;
@@ -0,0 +1,451 @@
1
+ /**
2
+ * The individual retrieval strategies the discovery node runs, plus the merge
3
+ * that folds their results into one candidate set.
4
+ *
5
+ * These were nested functions inside the discovery closure, capturing the node's
6
+ * locals. They now take an explicit {@link DiscoveryStrategyContext} so each
7
+ * strategy reads on its own.
8
+ */
9
+ import { getModelName } from '../../shared/agent/model.config.js';
10
+ import { selectHydeDocumentsForGeneration, getHydeGenerationMode } from '../../discovery/index.js';
11
+ import { mergeOpportunityEvidence, withCandidateEvidence, withMatchedStrategies } from '../domain/opportunity.evidence.js';
12
+ import { discoveryProfileMatchingEnabled, discoveryProfileSource, discoveryIntentMatchingEnabled } from '../discovery.env.js';
13
+ import { buildDiscovererContext, discoveryLog, getSourcePremiseDiscoveryLimit, PREMISE_MATCH_LIMIT_PER_SOURCE } from './opportunity.graph.shared.js';
14
+ /**
15
+ * Query-driven HyDE retrieval: generate hypothetical documents from the search
16
+ * text, then search every target network with the resulting lens embeddings.
17
+ */
18
+ export async function runQueryHydeDiscovery(ctx) {
19
+ const { state, deps, discoveryUserId, limitPerStrategy, perIndexLimit, corpusGating } = ctx;
20
+ const searchText = state.searchQuery?.trim() ?? '';
21
+ const lensInput = {
22
+ profileContext: buildDiscovererContext(state.sourceProfile, state.indexedIntents),
23
+ model: getModelName("lensInferrer"),
24
+ };
25
+ if (!searchText)
26
+ return null;
27
+ discoveryLog.verbose('runQueryHydeDiscovery start', { searchText: searchText.slice(0, 80) });
28
+ const hydeResult = await deps.hydeGenerator.invoke({
29
+ sourceType: 'query',
30
+ sourceText: searchText,
31
+ forceRegenerate: false,
32
+ profileContext: lensInput.profileContext,
33
+ });
34
+ const hydeEmbeddings = hydeResult.hydeEmbeddings;
35
+ const lenses = hydeResult.lenses ?? [];
36
+ const hydeOutput = {
37
+ lenses: lenses,
38
+ hydeDocuments: (hydeResult.hydeDocuments ?? {}),
39
+ };
40
+ const embeddingKeys = hydeEmbeddings ? Object.keys(hydeEmbeddings) : [];
41
+ discoveryLog.verbose('HyDE generator result', {
42
+ lensCount: embeddingKeys.length,
43
+ lenses: embeddingKeys,
44
+ });
45
+ if (!hydeEmbeddings || Object.keys(hydeEmbeddings).length === 0) {
46
+ return { candidates: [], lensInput, hydeOutput };
47
+ }
48
+ const lensEmbeddings = toLensEmbeddings(hydeEmbeddings, lenses);
49
+ const all = [];
50
+ await Promise.all(state.targetNetworks.map(async (targetIndex) => {
51
+ const results = await deps.embedder.searchWithHydeEmbeddings(lensEmbeddings, {
52
+ indexScope: [targetIndex.networkId],
53
+ excludeUserId: discoveryUserId,
54
+ limitPerStrategy,
55
+ limit: perIndexLimit,
56
+ minScore: deps.retrievalMinSimilarity,
57
+ corpusGating,
58
+ });
59
+ all.push(...collectHydeResults(results, targetIndex.networkId, ctx));
60
+ }));
61
+ const intentCount = all.filter((c) => c.candidateIntentId).length;
62
+ const premiseCount = all.filter((c) => c.candidatePremiseId).length;
63
+ discoveryLog.verbose('searchWithHydeEmbeddings raw results', {
64
+ total: all.length,
65
+ fromIntent: intentCount,
66
+ fromPremise: premiseCount,
67
+ fromContext: all.filter((c) => c.candidateContextId).length,
68
+ });
69
+ const byKey = new Map();
70
+ for (const c of all) {
71
+ // Dedup by candidateUserId + entity (intent or premise), NOT by indexId.
72
+ // Including indexId caused the same user to appear once per index they belong to.
73
+ const key = `${c.candidateUserId}:${entityKey(c)}`;
74
+ if (!byKey.has(key) || c.similarity > (byKey.get(key)?.similarity ?? 0)) {
75
+ byKey.set(key, c);
76
+ }
77
+ }
78
+ return { candidates: Array.from(byKey.values()), lensInput, hydeOutput };
79
+ }
80
+ /** `intent:`/`premise:`/`context:` discriminator used by the dedup keys. */
81
+ function entityKey(c) {
82
+ return c.candidateIntentId
83
+ ? `intent:${c.candidateIntentId}`
84
+ : c.candidatePremiseId
85
+ ? `premise:${c.candidatePremiseId}`
86
+ : `context:${c.candidateContextId}`;
87
+ }
88
+ /** Map HyDE embeddings back onto their lens metadata. */
89
+ export function toLensEmbeddings(hydeEmbeddings, lenses) {
90
+ const lensMap = new Map(lenses.map(l => [l.label, l]));
91
+ const lensEmbeddings = [];
92
+ for (const [label, emb] of Object.entries(hydeEmbeddings)) {
93
+ if (emb?.length) {
94
+ const lens = lensMap.get(label);
95
+ lensEmbeddings.push({ lens: label, corpus: lens?.corpus ?? 'profiles', embedding: emb });
96
+ }
97
+ }
98
+ return lensEmbeddings;
99
+ }
100
+ /**
101
+ * Turn embedder hits into candidates, honouring the match-type gates.
102
+ *
103
+ * Result filtering here is defense-in-depth: corpusGating already scopes the
104
+ * embedder's corpus searches, but adapters may still return other types.
105
+ */
106
+ export function collectHydeResults(results, networkId, ctx) {
107
+ const collected = [];
108
+ if (ctx.intentResultsEnabled)
109
+ for (const r of results.filter((x) => x.type === 'intent')) {
110
+ collected.push(withCandidateEvidence({
111
+ candidateUserId: r.userId,
112
+ candidateIntentId: r.id,
113
+ networkId,
114
+ similarity: r.score,
115
+ lens: r.matchedVia,
116
+ candidatePayload: '',
117
+ candidateSummary: undefined,
118
+ discoverySource: 'query',
119
+ }));
120
+ }
121
+ if (ctx.premiseResultsEnabled)
122
+ for (const r of results.filter((x) => x.type === 'premise')) {
123
+ collected.push(withCandidateEvidence({
124
+ candidateUserId: r.userId,
125
+ candidatePremiseId: r.id,
126
+ networkId,
127
+ similarity: r.score,
128
+ lens: r.matchedVia,
129
+ candidatePayload: '',
130
+ candidateSummary: undefined,
131
+ discoverySource: 'query',
132
+ }));
133
+ }
134
+ if (ctx.contextResultsEnabled)
135
+ for (const r of results.filter((x) => x.type === 'user_context')) {
136
+ collected.push(withCandidateEvidence({
137
+ candidateUserId: r.userId,
138
+ candidateContextId: r.id,
139
+ networkId,
140
+ similarity: r.score,
141
+ lens: r.matchedVia,
142
+ candidatePayload: r.text ?? '',
143
+ candidateSummary: undefined,
144
+ discoverySource: 'query',
145
+ }));
146
+ }
147
+ return collected;
148
+ }
149
+ /**
150
+ * Premise-to-premise discovery (path D).
151
+ * Searches for other users' premises similar to the discoverer's premises,
152
+ * scoped to target networks. Additive — merges into existing candidates.
153
+ */
154
+ export async function runPremiseDiscovery(ctx) {
155
+ const { state, deps, discoveryUserId } = ctx;
156
+ const targetNetworkIds = state.targetNetworks.map(t => t.networkId);
157
+ if (targetNetworkIds.length === 0)
158
+ return [];
159
+ if (!discoveryProfileMatchingEnabled() || discoveryProfileSource() === 'user_context') {
160
+ discoveryLog.verbose('runPremiseDiscovery disabled by DISCOVERY_ALLOWED_TYPES/DISCOVERY_PROFILE_SOURCE');
161
+ return [];
162
+ }
163
+ const sourceLimit = getSourcePremiseDiscoveryLimit();
164
+ if (sourceLimit === 0) {
165
+ discoveryLog.verbose('runPremiseDiscovery disabled by DISCOVERY_SOURCE_PREMISE_LIMIT=0');
166
+ return [];
167
+ }
168
+ const sourcePremisesFromDb = deps.database.getPremisesForUserInNetworks
169
+ ? await deps.database.getPremisesForUserInNetworks(discoveryUserId, targetNetworkIds, 'ACTIVE', sourceLimit)
170
+ : await deps.database.getPremisesForUser(discoveryUserId, 'ACTIVE');
171
+ const sourcePremises = (sourcePremisesFromDb.length > 0
172
+ ? sourcePremisesFromDb
173
+ .filter(p => Array.isArray(p.embedding) && p.embedding.length > 0)
174
+ .slice(0, sourceLimit)
175
+ .map(p => ({ premiseId: p.id, embedding: p.embedding }))
176
+ : (state.sourcePremises ?? []).slice(0, sourceLimit));
177
+ if (sourcePremises.length === 0)
178
+ return [];
179
+ discoveryLog.verbose('runPremiseDiscovery start', {
180
+ premiseCount: sourcePremises.length,
181
+ sourceLimit,
182
+ targetNetworks: targetNetworkIds.length,
183
+ batched: !!deps.database.searchPremisesBySimilarityBatch,
184
+ });
185
+ const rawResults = deps.database.searchPremisesBySimilarityBatch
186
+ ? await deps.database.searchPremisesBySimilarityBatch({
187
+ sources: sourcePremises,
188
+ networkIds: targetNetworkIds,
189
+ excludeUserId: discoveryUserId,
190
+ limitPerSource: PREMISE_MATCH_LIMIT_PER_SOURCE,
191
+ minScore: deps.retrievalMinSimilarity,
192
+ })
193
+ : (await Promise.all(sourcePremises.map(async (sp) => {
194
+ const results = await deps.database.searchPremisesBySimilarity({
195
+ embedding: sp.embedding,
196
+ networkIds: targetNetworkIds,
197
+ excludeUserId: discoveryUserId,
198
+ limit: PREMISE_MATCH_LIMIT_PER_SOURCE,
199
+ minScore: deps.retrievalMinSimilarity,
200
+ });
201
+ return results.map((r) => ({ ...r, sourcePremiseId: sp.premiseId }));
202
+ }))).flat();
203
+ const premiseCandidates = [];
204
+ for (const r of rawResults) {
205
+ premiseCandidates.push(withCandidateEvidence({
206
+ candidateUserId: r.userId,
207
+ sourcePremiseId: r.sourcePremiseId,
208
+ candidatePremiseId: r.premiseId,
209
+ networkId: r.networkId,
210
+ similarity: typeof r.similarity === 'number' ? r.similarity : parseFloat(String(r.similarity)),
211
+ lens: 'premise_match',
212
+ candidatePayload: r.assertionText ?? '',
213
+ discoverySource: 'premise-similarity',
214
+ }));
215
+ }
216
+ // Dedup by userId + premiseId + networkId (a premise can appear in multiple networks)
217
+ const deduped = dedupeBestBy(premiseCandidates, (c) => `${c.candidateUserId}:${c.candidatePremiseId ?? 'none'}:${c.networkId}`);
218
+ discoveryLog.verbose('runPremiseDiscovery complete', {
219
+ sourcePremiseCount: sourcePremises.length,
220
+ rawCount: premiseCandidates.length,
221
+ dedupedCount: deduped.length,
222
+ });
223
+ return deduped;
224
+ }
225
+ /**
226
+ * Context-to-intent discovery: searches intents using context HyDE embeddings.
227
+ * When HyDE documents exist for a context, uses optimised hypothetical-document
228
+ * embeddings via searchWithHydeEmbeddings. Falls back to raw context embedding
229
+ * via searchIntentsByContextEmbedding when no HyDE docs are available.
230
+ */
231
+ export async function runContextToIntentDiscovery(ctx) {
232
+ const { state, deps, discoveryUserId, limitPerStrategy, corpusGating } = ctx;
233
+ if (!state.sourceContexts?.length)
234
+ return [];
235
+ const contextToIntentEnabled = process.env.DISCOVERY_CONTEXT_TO_INTENT !== '0';
236
+ if (!contextToIntentEnabled)
237
+ return [];
238
+ if (!discoveryProfileMatchingEnabled() || discoveryProfileSource() !== 'user_context' || !discoveryIntentMatchingEnabled())
239
+ return [];
240
+ const targetNetworkIds = state.targetNetworks.map(t => t.networkId);
241
+ if (targetNetworkIds.length === 0)
242
+ return [];
243
+ discoveryLog.verbose('runContextToIntentDiscovery start', {
244
+ contextCount: state.sourceContexts.length,
245
+ targetNetworks: targetNetworkIds.length,
246
+ });
247
+ const contextCandidates = [];
248
+ for (const context of state.sourceContexts.filter(c => targetNetworkIds.includes(c.networkId))) {
249
+ // Attempt HyDE-enhanced search first
250
+ const persistedHydeDocs = await deps.database.getHydeDocumentsForSource('context', context.contextId);
251
+ const hydeDocs = selectHydeDocumentsForGeneration(persistedHydeDocs, getHydeGenerationMode(), context.text);
252
+ const lensEmbeddings = hydeDocs
253
+ .filter(d => d.hydeEmbedding?.length > 0)
254
+ .map(d => ({
255
+ lens: d.strategy,
256
+ corpus: (d.targetCorpus === 'intents' ? 'intents' : d.targetCorpus === 'premises' ? 'premises' : 'intents'),
257
+ embedding: d.hydeEmbedding,
258
+ }));
259
+ if (lensEmbeddings.length > 0) {
260
+ // HyDE-enhanced search: same path as query HyDE, scoped to this context's network
261
+ const results = await deps.embedder.searchWithHydeEmbeddings(lensEmbeddings, {
262
+ indexScope: [context.networkId],
263
+ excludeUserId: discoveryUserId,
264
+ limitPerStrategy: limitPerStrategy,
265
+ limit: 20,
266
+ minScore: deps.retrievalMinSimilarity,
267
+ corpusGating,
268
+ });
269
+ for (const r of results.filter(r => r.type === 'intent')) {
270
+ contextCandidates.push(withCandidateEvidence({
271
+ candidateUserId: r.userId,
272
+ candidateIntentId: r.id,
273
+ sourceContextId: context.contextId,
274
+ networkId: context.networkId,
275
+ similarity: r.score,
276
+ lens: r.matchedVia,
277
+ candidatePayload: '',
278
+ candidateSummary: undefined,
279
+ discoverySource: 'context-to-intent',
280
+ }));
281
+ }
282
+ }
283
+ else {
284
+ // Fallback: raw context embedding search (no HyDE docs yet)
285
+ const results = await deps.database.searchIntentsByContextEmbedding({
286
+ embedding: context.embedding,
287
+ networkIds: [context.networkId],
288
+ excludeUserId: discoveryUserId,
289
+ limit: 20,
290
+ minScore: deps.retrievalMinSimilarity,
291
+ });
292
+ for (const r of results) {
293
+ contextCandidates.push(withCandidateEvidence({
294
+ candidateUserId: r.userId,
295
+ candidateIntentId: r.intentId,
296
+ sourceContextId: context.contextId,
297
+ networkId: r.networkId,
298
+ similarity: typeof r.similarity === 'number' ? r.similarity : parseFloat(String(r.similarity)),
299
+ lens: 'context_match',
300
+ candidatePayload: r.payload ?? '',
301
+ candidateSummary: r.summary ?? undefined,
302
+ discoverySource: 'context-to-intent',
303
+ }));
304
+ }
305
+ }
306
+ }
307
+ const deduped = dedupeBestBy(contextCandidates, (c) => `${c.candidateUserId}:${c.candidateIntentId ?? 'none'}:${c.networkId}`);
308
+ discoveryLog.verbose('runContextToIntentDiscovery complete', {
309
+ rawCount: contextCandidates.length,
310
+ dedupedCount: deduped.length,
311
+ });
312
+ return deduped;
313
+ }
314
+ /**
315
+ * Context-to-context discovery (lightweight profile mode only).
316
+ * Raw network-scoped context embeddings → candidate user_contexts.
317
+ * No HyDE: both sides are the same document type (synthesized
318
+ * 3–6 sentence paragraphs), so direct paragraph similarity is correct
319
+ * (same rationale as raw premise-to-premise).
320
+ */
321
+ export async function runContextToContextDiscovery(ctx) {
322
+ const { state, deps, discoveryUserId, contextResultsEnabled } = ctx;
323
+ if (!contextResultsEnabled)
324
+ return [];
325
+ if (!state.sourceContexts?.length)
326
+ return [];
327
+ if (typeof deps.database.searchUserContextsBySimilarity !== 'function')
328
+ return [];
329
+ const targetNetworkIds = state.targetNetworks.map(t => t.networkId);
330
+ if (targetNetworkIds.length === 0)
331
+ return [];
332
+ const contextCandidates = [];
333
+ for (const context of state.sourceContexts.filter(c => targetNetworkIds.includes(c.networkId))) {
334
+ const results = await deps.database.searchUserContextsBySimilarity({
335
+ embedding: context.embedding,
336
+ networkIds: [context.networkId],
337
+ excludeUserId: discoveryUserId,
338
+ limit: 20,
339
+ minScore: deps.retrievalMinSimilarity,
340
+ });
341
+ for (const r of results) {
342
+ contextCandidates.push(withCandidateEvidence({
343
+ candidateUserId: r.userId,
344
+ candidateContextId: r.contextId,
345
+ sourceContextId: context.contextId,
346
+ networkId: r.networkId,
347
+ similarity: typeof r.similarity === 'number' ? r.similarity : parseFloat(String(r.similarity)),
348
+ lens: 'context_match',
349
+ candidatePayload: r.text ?? '',
350
+ discoverySource: 'context-similarity',
351
+ }));
352
+ }
353
+ }
354
+ // Dedup by userId + contextId + networkId (mirror premise dedup)
355
+ const deduped = dedupeBestBy(contextCandidates, (c) => `${c.candidateUserId}:${c.candidateContextId ?? 'none'}:${c.networkId}`);
356
+ discoveryLog.verbose('runContextToContextDiscovery complete', {
357
+ rawCount: contextCandidates.length,
358
+ dedupedCount: deduped.length,
359
+ });
360
+ return deduped;
361
+ }
362
+ /** Keep the highest-similarity candidate per composite key. */
363
+ function dedupeBestBy(candidates, keyOf) {
364
+ const byKey = new Map();
365
+ for (const c of candidates) {
366
+ const key = keyOf(c);
367
+ if (!byKey.has(key) || c.similarity > (byKey.get(key)?.similarity ?? 0)) {
368
+ byKey.set(key, c);
369
+ }
370
+ }
371
+ return Array.from(byKey.values());
372
+ }
373
+ /**
374
+ * Run the three additive strategies concurrently, in the order the discovery
375
+ * node reports them: premise-to-premise, context-to-intent, context-to-context.
376
+ */
377
+ export function runAuxiliaryStrategies(ctx) {
378
+ return Promise.all([
379
+ runPremiseDiscovery(ctx),
380
+ runContextToIntentDiscovery(ctx),
381
+ runContextToContextDiscovery(ctx),
382
+ ]);
383
+ }
384
+ /**
385
+ * Merge candidates from multiple strategies. Deduplicates by userId + networkId + entityId,
386
+ * keeps the highest similarity, tracks which strategies found each candidate,
387
+ * and applies a multi-strategy boost (+0.05 per additional strategy, boost capped at 0.15,
388
+ * final similarity capped at 1.0).
389
+ */
390
+ export function mergeStrategyCandidates(...groups) {
391
+ const merged = new Map();
392
+ for (const group of groups) {
393
+ for (const c of group) {
394
+ const entityId = c.candidateIntentId ?? c.candidatePremiseId ?? c.candidateContextId ?? 'none';
395
+ const key = `${c.candidateUserId}:${c.networkId}:${entityId}`;
396
+ const existing = merged.get(key);
397
+ if (!existing) {
398
+ merged.set(key, { ...c, _strategies: new Set([c.discoverySource ?? 'unknown']) });
399
+ }
400
+ else {
401
+ existing._strategies.add(c.discoverySource ?? 'unknown');
402
+ const mergedEvidence = mergeOpportunityEvidence(existing.evidence, c.evidence);
403
+ if (c.similarity > existing.similarity) {
404
+ Object.assign(existing, { ...c, evidence: mergedEvidence });
405
+ }
406
+ else {
407
+ existing.evidence = mergedEvidence;
408
+ }
409
+ }
410
+ }
411
+ }
412
+ return Array.from(merged.values()).map(({ _strategies, ...c }) => {
413
+ const matchedStrategies = Array.from(_strategies);
414
+ const boost = Math.min((_strategies.size - 1) * 0.05, 0.15);
415
+ return {
416
+ ...c,
417
+ similarity: Math.min(c.similarity + boost, 1.0),
418
+ matchedStrategies,
419
+ evidence: withMatchedStrategies(mergeOpportunityEvidence(c.evidence), matchedStrategies),
420
+ };
421
+ });
422
+ }
423
+ /** Per-lens candidate counts and mean similarity, for the discovery trace. */
424
+ export function computeLensStats(candidates) {
425
+ const lensStats = {};
426
+ for (const c of candidates) {
427
+ const s = c.lens || 'unknown';
428
+ if (!lensStats[s])
429
+ lensStats[s] = { count: 0, avgSimilarity: 0 };
430
+ lensStats[s].count++;
431
+ lensStats[s].avgSimilarity += c.similarity;
432
+ }
433
+ for (const s of Object.values(lensStats)) {
434
+ s.avgSimilarity = s.count > 0 ? Math.round((s.avgSimilarity / s.count) * 1000) / 1000 : 0;
435
+ }
436
+ return lensStats;
437
+ }
438
+ /** One `strategy` trace line per auxiliary strategy that produced candidates. */
439
+ export function auxiliaryStrategyTraces(premiseCands, contextCands, contextSimCands) {
440
+ const entries = [];
441
+ if (premiseCands.length > 0) {
442
+ entries.push({ node: "strategy", detail: `premise-to-premise → ${premiseCands.length} candidate(s)` });
443
+ }
444
+ if (contextCands.length > 0) {
445
+ entries.push({ node: "strategy", detail: `context-to-intent → ${contextCands.length} candidate(s)` });
446
+ }
447
+ if (contextSimCands.length > 0) {
448
+ entries.push({ node: "strategy", detail: `context-to-context → ${contextSimCands.length} candidate(s)` });
449
+ }
450
+ return entries;
451
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Discovery pipeline, stage 3: candidate retrieval.
3
+ *
4
+ * Three shapes share this node — a direct-connection fast path, a
5
+ * context-sourced path, and the intent/query HyDE path. The retrieval
6
+ * strategies themselves live in `opportunity.graph.discovery-strategies.ts`.
7
+ */
8
+ import type { Id } from '../../shared/interfaces/database.interface.js';
9
+ import type { CandidateMatch } from '../domain/opportunity.state.js';
10
+ import { type OpportunityGraphDeps, type OpportunityState } from './opportunity.graph.shared.js';
11
+ /** Trace entries accumulate in the order the frontend renders them. */
12
+ type TraceEntry = {
13
+ node: string;
14
+ detail?: string;
15
+ data?: Record<string, unknown>;
16
+ };
17
+ /**
18
+ * Node 3: Discovery
19
+ * Generates HyDE embeddings and performs semantic search.
20
+ */
21
+ export declare function discoveryNode(state: OpportunityState, deps: OpportunityGraphDeps): Promise<{
22
+ candidates: never[];
23
+ trace: {
24
+ node: string;
25
+ detail: string;
26
+ data: {
27
+ targetUserId: Id<"users">;
28
+ };
29
+ }[];
30
+ } | {
31
+ candidates: CandidateMatch[];
32
+ trace: {
33
+ node: string;
34
+ detail: string;
35
+ data: {
36
+ targetUserId: Id<"users">;
37
+ candidateCount: number;
38
+ sharedIndexes: number;
39
+ durationMs: number;
40
+ };
41
+ }[];
42
+ } | {
43
+ candidates: CandidateMatch[];
44
+ trace: TraceEntry[];
45
+ } | {
46
+ candidates: CandidateMatch[];
47
+ trace: {
48
+ node: string;
49
+ detail: string;
50
+ }[];
51
+ hydeEmbeddings?: undefined;
52
+ } | {
53
+ candidates: never[];
54
+ error?: undefined;
55
+ trace?: undefined;
56
+ } | {
57
+ candidates: never[];
58
+ error: string;
59
+ trace: {
60
+ node: string;
61
+ detail: string;
62
+ data: {
63
+ error: string;
64
+ };
65
+ }[];
66
+ }>;
67
+ /** Trace summary for {@link discoveryNode}. */
68
+ export declare function discoveryTraceSummary(result: unknown): string | undefined;
69
+ export {};