@indexnetwork/protocol 3.0.0 → 3.1.0-rc.248.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/intent/intent.indexer.d.ts +3 -3
- package/dist/intent/intent.reconciler.d.ts +6 -6
- package/dist/intent/intent.tools.d.ts.map +1 -1
- package/dist/intent/intent.tools.js +9 -3
- package/dist/intent/intent.tools.js.map +1 -1
- package/dist/network/indexer/indexer.graph.d.ts +22 -11
- package/dist/network/indexer/indexer.graph.d.ts.map +1 -1
- package/dist/network/indexer/indexer.graph.js +47 -44
- package/dist/network/indexer/indexer.graph.js.map +1 -1
- package/dist/network/indexer/indexer.state.d.ts +3 -3
- package/dist/opportunity/opportunity.evaluator.d.ts +27 -9
- package/dist/opportunity/opportunity.evaluator.d.ts.map +1 -1
- package/dist/opportunity/opportunity.evaluator.js +9 -1
- package/dist/opportunity/opportunity.evaluator.js.map +1 -1
- package/dist/opportunity/opportunity.evidence.d.ts +22 -0
- package/dist/opportunity/opportunity.evidence.d.ts.map +1 -0
- package/dist/opportunity/opportunity.evidence.js +72 -0
- package/dist/opportunity/opportunity.evidence.js.map +1 -0
- package/dist/opportunity/opportunity.graph.d.ts +8 -7
- package/dist/opportunity/opportunity.graph.d.ts.map +1 -1
- package/dist/opportunity/opportunity.graph.js +74 -28
- package/dist/opportunity/opportunity.graph.js.map +1 -1
- package/dist/opportunity/opportunity.state.d.ts +10 -2
- package/dist/opportunity/opportunity.state.d.ts.map +1 -1
- package/dist/opportunity/opportunity.state.js.map +1 -1
- package/dist/premise/premise.graph.d.ts +14 -2
- package/dist/premise/premise.graph.d.ts.map +1 -1
- package/dist/premise/premise.graph.js +49 -20
- package/dist/premise/premise.graph.js.map +1 -1
- package/dist/premise/premise.indexer.d.ts +2 -2
- package/dist/premise/premise.state.d.ts +2 -0
- package/dist/premise/premise.state.d.ts.map +1 -1
- package/dist/premise/premise.state.js +8 -0
- package/dist/premise/premise.state.js.map +1 -1
- package/dist/shared/assignment/network-assignment.policy.d.ts +59 -0
- package/dist/shared/assignment/network-assignment.policy.d.ts.map +1 -0
- package/dist/shared/assignment/network-assignment.policy.js +101 -0
- package/dist/shared/assignment/network-assignment.policy.js.map +1 -0
- package/dist/shared/hyde/hyde.graph.d.ts +6 -6
- package/dist/shared/hyde/hyde.state.d.ts +2 -2
- package/dist/shared/interfaces/database.interface.d.ts +31 -17
- package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/database.interface.js.map +1 -1
- package/dist/shared/schemas/network-assignment.schema.d.ts +135 -0
- package/dist/shared/schemas/network-assignment.schema.d.ts.map +1 -0
- package/dist/shared/schemas/network-assignment.schema.js +55 -0
- package/dist/shared/schemas/network-assignment.schema.js.map +1 -0
- package/dist/shared/schemas/question.schema.d.ts +2 -2
- package/package.json +1 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { StateGraph, START, END } from "@langchain/langgraph";
|
|
2
|
+
import { buildNetworkAssignmentDecision, } from "../../shared/assignment/network-assignment.policy.js";
|
|
2
3
|
import { protocolLogger } from "../../shared/observability/protocol.logger.js";
|
|
3
4
|
import { timed } from "../../shared/observability/performance.js";
|
|
4
5
|
import { requestContext } from "../../shared/observability/request-context.js";
|
|
5
6
|
import { renderNetworkContext } from "../../shared/network/metadata.renderer.js";
|
|
6
7
|
import { IntentNetworkGraphState, } from "./indexer.state.js";
|
|
7
8
|
const logger = protocolLogger("IntentNetworkGraphFactory");
|
|
8
|
-
const QUALIFICATION_THRESHOLD = 0.7;
|
|
9
9
|
/**
|
|
10
10
|
* Factory class to build and compile the Intent Index Graph.
|
|
11
11
|
*
|
|
@@ -62,7 +62,15 @@ export class IntentNetworkGraphFactory {
|
|
|
62
62
|
}
|
|
63
63
|
// Direct assignment (skip evaluation)
|
|
64
64
|
if (state.skipEvaluation) {
|
|
65
|
-
|
|
65
|
+
const decision = buildNetworkAssignmentDecision({
|
|
66
|
+
resourceType: "intent",
|
|
67
|
+
mode: "manual_override",
|
|
68
|
+
scope: "network",
|
|
69
|
+
evaluator: "intent-network-graph",
|
|
70
|
+
source: "manual-index-assignment",
|
|
71
|
+
createdAt: new Date().toISOString(),
|
|
72
|
+
});
|
|
73
|
+
await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);
|
|
66
74
|
return {
|
|
67
75
|
agentTimings: agentTimingsAccum,
|
|
68
76
|
assignmentResult: { networkId, assigned: true, success: true },
|
|
@@ -74,23 +82,33 @@ export class IntentNetworkGraphFactory {
|
|
|
74
82
|
if (!intentForIndexing) {
|
|
75
83
|
return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: "Intent not found for networking." } };
|
|
76
84
|
}
|
|
77
|
-
const indexContext = await this.database.
|
|
85
|
+
const indexContext = await this.database.getNetworkAssignmentContext(networkId, intentForIndexing.userId);
|
|
78
86
|
if (!indexContext) {
|
|
79
|
-
// No prompts or not eligible - auto-assign
|
|
80
|
-
await this.database.assignIntentToNetwork(intentId, networkId, 1.0);
|
|
81
87
|
return {
|
|
82
88
|
agentTimings: agentTimingsAccum,
|
|
83
|
-
assignmentResult: { networkId, assigned:
|
|
84
|
-
mutationResult: { success:
|
|
89
|
+
assignmentResult: { networkId, assigned: false, success: false },
|
|
90
|
+
mutationResult: { success: false, error: "Network assignment context not found." },
|
|
85
91
|
};
|
|
86
92
|
}
|
|
87
|
-
const
|
|
93
|
+
const indexPrompt = indexContext.indexPrompt ?? null;
|
|
94
|
+
const memberPrompt = indexContext.memberPrompt ?? null;
|
|
95
|
+
const hasNoPrompts = !indexPrompt?.trim() && !memberPrompt?.trim();
|
|
88
96
|
if (hasNoPrompts) {
|
|
89
|
-
|
|
97
|
+
const decision = buildNetworkAssignmentDecision({
|
|
98
|
+
resourceType: "intent",
|
|
99
|
+
mode: "automatic",
|
|
100
|
+
scope: "network",
|
|
101
|
+
indexPrompt,
|
|
102
|
+
memberPrompt,
|
|
103
|
+
evaluator: "intent-indexer",
|
|
104
|
+
source: "intent-network-graph",
|
|
105
|
+
createdAt: new Date().toISOString(),
|
|
106
|
+
});
|
|
107
|
+
await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);
|
|
90
108
|
return {
|
|
91
109
|
agentTimings: agentTimingsAccum,
|
|
92
110
|
assignmentResult: { networkId, assigned: true, success: true },
|
|
93
|
-
mutationResult: { success: true, message: "Intent assigned to network (no prompts
|
|
111
|
+
mutationResult: { success: true, message: "Intent assigned to network (no prompts)." },
|
|
94
112
|
};
|
|
95
113
|
}
|
|
96
114
|
// Run IntentIndexer evaluation
|
|
@@ -112,7 +130,7 @@ export class IntentNetworkGraphFactory {
|
|
|
112
130
|
_traceEmitterIndexer?.({ type: "agent_start", name: "intent-indexer" });
|
|
113
131
|
let result = null;
|
|
114
132
|
try {
|
|
115
|
-
result = await indexer.evaluate(intentForIndexing.payload,
|
|
133
|
+
result = await indexer.evaluate(intentForIndexing.payload, indexPrompt, memberPrompt, sourceName, renderedContext);
|
|
116
134
|
}
|
|
117
135
|
finally {
|
|
118
136
|
const _indexerMs = Date.now() - _indexerStart;
|
|
@@ -128,51 +146,36 @@ export class IntentNetworkGraphFactory {
|
|
|
128
146
|
mutationResult: { success: false, error: "Evaluation returned no result." },
|
|
129
147
|
};
|
|
130
148
|
}
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
finalScore = indexScore;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
else if (mp) {
|
|
149
|
-
if (memberScore > QUALIFICATION_THRESHOLD) {
|
|
150
|
-
shouldAssign = true;
|
|
151
|
-
finalScore = memberScore;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
else {
|
|
155
|
-
shouldAssign = true;
|
|
156
|
-
finalScore = 1.0;
|
|
157
|
-
}
|
|
158
|
-
if (shouldAssign) {
|
|
159
|
-
await this.database.assignIntentToNetwork(intentId, networkId, finalScore);
|
|
149
|
+
const decision = buildNetworkAssignmentDecision({
|
|
150
|
+
resourceType: "intent",
|
|
151
|
+
mode: "automatic",
|
|
152
|
+
scope: "network",
|
|
153
|
+
indexPrompt,
|
|
154
|
+
memberPrompt,
|
|
155
|
+
rawScores: { indexScore: result.indexScore, memberScore: result.memberScore },
|
|
156
|
+
evaluator: "intent-indexer",
|
|
157
|
+
source: "intent-network-graph",
|
|
158
|
+
reason: result.reasoning,
|
|
159
|
+
createdAt: new Date().toISOString(),
|
|
160
|
+
});
|
|
161
|
+
if (decision.assigned) {
|
|
162
|
+
await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);
|
|
160
163
|
return {
|
|
161
164
|
agentTimings: agentTimingsAccum,
|
|
162
165
|
evaluation: result,
|
|
163
166
|
shouldAssign: true,
|
|
164
|
-
finalScore,
|
|
167
|
+
finalScore: decision.finalScore,
|
|
165
168
|
assignmentResult: { networkId, assigned: true, success: true },
|
|
166
|
-
mutationResult: { success: true, message: `Intent assigned to network (score: ${finalScore.toFixed(2)}).` },
|
|
169
|
+
mutationResult: { success: true, message: `Intent assigned to network (score: ${decision.finalScore.toFixed(2)}).` },
|
|
167
170
|
};
|
|
168
171
|
}
|
|
169
172
|
return {
|
|
170
173
|
agentTimings: agentTimingsAccum,
|
|
171
174
|
evaluation: result,
|
|
172
175
|
shouldAssign: false,
|
|
173
|
-
finalScore,
|
|
176
|
+
finalScore: decision.finalScore,
|
|
174
177
|
assignmentResult: { networkId, assigned: false, success: true },
|
|
175
|
-
mutationResult: { success: false, error: `Intent did not qualify for this network (score: ${finalScore.toFixed(2)}).` },
|
|
178
|
+
mutationResult: { success: false, error: `Intent did not qualify for this network (score: ${decision.finalScore.toF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,KAAK,EAAE,KAAK,EAAE,uCAAuC,EAAE,EAAE,CAAC;gBAChG,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,8BAA8B;QAE9B,MAAM,WAAW,GAAG,CAAC,KAA2C,EAAU,EAAE;YAC1E,QAAQ,KAAK,CAAC,aAAa,EAAE,CAAC;gBAC5B,KAAK,QAAQ,CAAC,CAAC,OAAO,QAAQ,CAAC;gBAC/B,KAAK,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC;gBAC3B,KAAK,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC;gBACjC,OAAO,CAAC,CAAC,OAAO,MAAM,CAAC;YACzB,CAAC;QACH,CAAC,CAAC;QAEF,yBAAyB;QAEzB,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,uBAAuB,CAAC;aACrD,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC;aAC7B,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC;aACzB,OAAO,CAAC,UAAU,EAAE,YAAY,CAAC;aACjC,mBAAmB,CAAC,KAAK,EAAE,WAAW,EAAE;YACvC,MAAM,EAAE,QAAQ;YAChB,IAAI,EAAE,MAAM;YACZ,QAAQ,EAAE,UAAU;SACrB,CAAC;aACD,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;aACtB,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;aACpB,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;QAE5B,OAAO,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC5B,CAAC;CACF","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\n\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport type { IntentNetworkGraphDatabase } from \"../../shared/interfaces/database.interface.js\";\nimport { protocolLogger } from \"../../shared/observability/protocol.logger.js\";\nimport { timed } from \"../../shared/observability/performance.js\";\nimport { requestContext } from \"../../shared/observability/request-context.js\";\nimport type { DebugMetaAgent } from \"../../chat/chat-streaming.types.js\";\nimport { renderNetworkContext } from \"../../shared/network/metadata.renderer.js\";\n\nimport {\n IntentNetworkGraphState,\n type IntentForIndexing,\n type IndexMemberContext,\n type AssignmentResult,\n} from \"./indexer.state.js\";\n\nconst logger = protocolLogger(\"IntentNetworkGraphFactory\");\nconst QUALIFICATION_THRESHOLD = 0.7;\n\n/**\n * Factory class to build and compile the Intent Index Graph.\n *\n * Handles CRUD for the intent_indexes junction table:\n * - create: Assign an intent to an index (direct or evaluated via IntentIndexer agent)\n * - read: List intent-index links (by intentId or by networkId)\n * - delete: Unassign an intent from an index\n *\n * The evaluate-based assignment flow is migrated from the old Index Graph.\n */\nexport class IntentNetworkGraphFactory {\n constructor(\n private database: IntentNetworkGraphDatabase,\n private intentNetworker: IntentIndexer,\n ) {}\n\n public createGraph() {\n const indexer = this.intentNetworker;\n\n // --- NODE DEFINITIONS ---\n\n /**\n * Assign Node: Assign an intent to an index.\n * Two sub-paths:\n * - Direct assignment (skipEvaluation=true): assign immediately\n * - Evaluated assignment (skipEvaluation=false): load intent + index context, evaluate via IntentIndexer\n */\n const assignNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.assign\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Assign intent to index\", { userId: state.userId, intentId, networkId, skipEvaluation: state.skipEvaluation });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n if (!intentId || !networkId) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Both intentId and networkId are required.\" } };\n }\n\n try {\n // Validate ownership and membership\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Intent not found.\" } };\n }\n if (intent.userId !== state.userId) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"You can only add your own intents to a network.\" } };\n }\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"You are not a member of that network.\" } };\n }\n\n // Check if already assigned\n const alreadyAssigned = await this.database.isIntentAssignedToIndex(intentId, networkId);\n if (alreadyAssigned) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: true, message: \"That intent is already in this network.\" } };\n }\n\n // Direct assignment (skip evaluation)\n if (state.skipEvaluation) {\n await this.database.assignIntentToNetwork(intentId, networkId, 1.0);\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: \"Intent saved to the network.\" },\n };\n }\n\n // Evaluated assignment (migrated from old Index Graph)\n const intentForIndexing = await this.database.getIntentForIndexing(intentId);\n if (!intentForIndexing) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Intent not found for networking.\" } };\n }\n\n const indexContext = await this.database.getNetworkMemberContext(networkId, intentForIndexing.userId);\n if (!indexContext) {\n // No prompts or not eligible - auto-assign\n await this.database.assignIntentToNetwork(intentId, networkId, 1.0);\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: \"Intent assigned to network (auto-assign, no prompts).\" },\n };\n }\n\n const hasNoPrompts = !indexContext.indexPrompt?.trim() && !indexContext.memberPrompt?.trim();\n if (hasNoPrompts) {\n await this.database.assignIntentToNetwork(intentId, networkId, 1.0);\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: \"Intent assigned to network (no prompts, auto-assign).\" },\n };\n }\n\n // Run IntentIndexer evaluation\n const sourceName = intentForIndexing.sourceType\n ? `${intentForIndexing.sourceType}:${intentForIndexing.sourceId ?? \"\"}`\n : undefined;\n\n // Render network context (type, metadata) for the evaluator\n const network = await this.database.getNetwork(networkId);\n const renderedContext = network\n ? renderNetworkContext({\n type: network.type ?? 'community',\n title: network.title,\n prompt: network.prompt,\n metadata: network.metadata ?? {},\n })\n : null;\n\n const _traceEmitterIndexer = requestContext.getStore()?.traceEmitter;\n const _indexerStart = Date.now();\n _traceEmitterIndexer?.({ type: \"agent_start\", name: \"intent-indexer\" });\n let result: Awaited<ReturnType<typeof indexer.evaluate>> | null = null;\n try {\n result = await indexer.evaluate(\n intentForIndexing.payload,\n indexContext.indexPrompt,\n indexContext.memberPrompt,\n sourceName,\n renderedContext\n );\n } finally {\n const _indexerMs = Date.now() - _indexerStart;\n agentTimingsAccum.push({ name: 'intent.indexer', durationMs: _indexerMs });\n _traceEmitterIndexer?.({ type: \"agent_end\", name: \"intent-indexer\", durationMs: _indexerMs, summary: result ? `Scored: index=${result.indexScore.toFixed(2)}, member=${result.memberScore.toFixed(2)}` : \"intent-indexer failed\" });\n }\n\n if (!result) {\n return {\n agentTimings: agentTimingsAccum,\n evaluation: null,\n shouldAssign: false,\n finalScore: 0,\n mutationResult: { success: false, error: \"Evaluation returned no result.\" },\n };\n }\n\n const { indexScore, memberScore } = result;\n const ip = indexContext.indexPrompt?.trim();\n const mp = indexContext.memberPrompt?.trim();\n\n let shouldAssign = false;\n let finalScore = 0;\n\n if (ip && mp) {\n if (indexScore > QUALIFICATION_THRESHOLD && memberScore > QUALIFICATION_THRESHOLD) {\n shouldAssign = true;\n finalScore = indexScore * 0.6 + memberScore * 0.4;\n }\n } else if (ip) {\n if (indexScore > QUALIFICATION_THRESHOLD) {\n shouldAssign = true;\n finalScore = indexScore;\n }\n } else if (mp) {\n if (memberScore > QUALIFICATION_THRESHOLD) {\n shouldAssign = true;\n finalScore = memberScore;\n }\n } else {\n shouldAssign = true;\n finalScore = 1.0;\n }\n\n if (shouldAssign) {\n await this.database.assignIntentToNetwork(intentId, networkId, finalScore);\n return {\n agentTimings: agentTimingsAccum,\n evaluation: result,\n shouldAssign: true,\n finalScore,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: `Intent assigned to network (score: ${finalScore.toFixed(2)}).` },\n };\n }\n\n return {\n agentTimings: agentTimingsAccum,\n evaluation: result,\n shouldAssign: false,\n finalScore,\n assignmentResult: { networkId, assigned: false, success: true } as AssignmentResult,\n mutationResult: { success: false, error: `Intent did not qualify for this network (score: ${finalScore.toFixed(2)}).` },\n };\n } catch (err) {\n logger.error(\"Assign failed\", { error: err });\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Failed to assign intent to network.\" } };\n }\n });\n };\n\n /**\n * Read Node: Query intent-index relationships.\n * - By intentId only: list all indexes the intent is in (owner only)\n * - By networkId only: list intents in the index (member only)\n * - By both intentId and networkId: check if specific link exists (owner only)\n */\n const readNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.read\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Read intent-index links\", { userId: state.userId, intentId, networkId, queryUserId: state.queryUserId });\n\n try {\n // By both: check if specific intent-index link exists\n if (intentId && networkId) {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { readResult: { links: [], count: 0, mode: \"check_link\" }, error: \"Intent not found.\" };\n }\n if (intent.userId !== state.userId) {\n return { readResult: { links: [], count: 0, mode: \"check_link\" }, error: \"You can only check links for your own intents.\" };\n }\n const isLinked = await this.database.isIntentAssignedToIndex(intentId, networkId);\n return {\n readResult: {\n links: isLinked ? [{ intentId, networkId }] : [],\n count: isLinked ? 1 : 0,\n mode: \"check_link\",\n note: isLinked ? \"Intent is linked to this network.\" : \"Intent is not linked to this network.\",\n },\n };\n }\n\n // By intent only: list all indexes for this intent\n if (intentId) {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { readResult: { links: [], count: 0, mode: \"networks_for_intent\" }, error: \"Intent not found.\" };\n }\n if (intent.userId !== state.userId) {\n return { readResult: { links: [], count: 0, mode: \"networks_for_intent\" }, error: \"You can only list networks for your own intents.\" };\n }\n const networkIds = await this.database.getNetworkIdsForIntent(intentId);\n return {\n readResult: {\n links: networkIds.map((id) => ({ intentId, networkId: id })),\n count: networkIds.length,\n mode: \"networks_for_intent\",\n note: \"To show network titles, use read_networks.\",\n },\n };\n }\n\n // By index: list intents in the index\n if (!networkId) {\n return {\n readResult: { links: [], count: 0, mode: \"unknown\" },\n error: \"Provide networkId or intentId.\",\n };\n }\n\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return {\n readResult: { links: [], count: 0, mode: \"intents_in_network\" },\n error: \"Network not found or you are not a member.\",\n };\n }\n\n // All intents or filtered by user\n if (!state.queryUserId) {\n const intents = await this.database.getNetworkIntentsForMember(networkId, state.userId, { limit: 50, offset: 0 });\n return {\n readResult: {\n links: intents.map((i) => ({\n intentId: i.id,\n networkId,\n intentTitle: i.payload,\n userId: i.userId,\n userName: i.userName,\n createdAt: i.createdAt,\n relevancyScore: i.relevancyScore,\n })),\n count: intents.length,\n mode: \"intents_in_network\",\n note: \"To show network title and full intent details, use read_networks and read_intents.\",\n },\n };\n }\n\n // Specific user's intents\n const intents = await this.database.getIntentsInIndexForMember(state.queryUserId, networkId);\n return {\n readResult: {\n links: intents.map((i) => ({\n intentId: i.id,\n networkId,\n intentTitle: i.payload,\n createdAt: i.createdAt,\n relevancyScore: i.relevancyScore,\n })),\n count: intents.length,\n mode: \"intents_in_network\",\n note: \"To show network title and full intent details, use read_networks and read_intents.\",\n },\n };\n } catch (err) {\n logger.error(\"Read intent-index failed\", { error: err });\n return { error: \"Failed to fetch intent-network links.\" };\n }\n });\n };\n\n /**\n * Unassign Node: Remove an intent from an index.\n */\n const unassignNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.unassign\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Unassign intent from index\", { userId: state.userId, intentId, networkId });\n\n if (!intentId || !networkId) {\n return { mutationResult: { success: false, error: \"Both intentId and networkId are required.\" } };\n }\n\n try {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { mutationResult: { success: false, error: \"Intent not found.\" } };\n }\n if (intent.userId !== state.userId) {\n return { mutationResult: { success: false, error: \"You can only remove your own intents from a network.\" } };\n }\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return { mutationResult: { success: false, error: \"You are not a member of that network.\" } };\n }\n\n const assigned = await this.database.isIntentAssignedToIndex(intentId, networkId);\n if (!assigned) {\n return { mutationResult: { success: true, message: \"That intent is not in this network.\" } };\n }\n\n await this.database.unassignIntentFromIndex(intentId, networkId);\n return { mutationResult: { success: true, message: \"Intent removed from the index.\" } };\n } catch (err) {\n logger.error(\"Unassign failed\", { error: err });\n return { mutationResult: { success: false, error: \"Failed to remove intent from network.\" } };\n }\n });\n };\n\n // --- CONDITIONAL ROUTING ---\n\n const routeByMode = (state: typeof IntentNetworkGraphState.State): string => {\n switch (state.operationMode) {\n case 'create': return 'assign';\n case 'read': return 'read';\n case 'delete': return 'unassign';\n default: return 'read';\n }\n };\n\n // --- GRAPH ASSEMBLY ---\n\n const workflow = new StateGraph(IntentNetworkGraphState)\n .addNode(\"assign\", assignNode)\n .addNode(\"read\", readNode)\n .addNode(\"unassign\", unassignNode)\n .addConditionalEdges(START, routeByMode, {\n assign: \"assign\",\n read: \"read\",\n unassign: \"unassign\",\n })\n .addEdge(\"assign\", END)\n .addEdge(\"read\", END)\n .addEdge(\"unassign\", END);\n\n return workflow.compile();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"indexer.graph.js","sourceRoot":"/","sources":["network/indexer/indexer.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAG9D,OAAO,EACL,8BAA8B,GAC/B,MAAM,sDAAsD,CAAC;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C;QAEF,8BAA8B;QAE9B,MAAM,WAAW,GAAG,CAAC,KAA2C,EAAU,EAAE;YAC1E,QAAQ,KAAK,CAAC,aAAa,EAAE,CAAC;gBAC5B,KAAK,QAAQ,CAAC,CAAC,OAAO,QAAQ,CAAC;gBAC/B,KAAK,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC;gBAC3B,KAAK,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC;gBACjC,OAAO,CAAC,CAAC,OAAO,MAAM,CAAC;YACzB,CAAC;QACH,CAAC,CAAC;QAEF,yBAAyB;QAEzB,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,uBAAuB,CAAC;aACrD,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC;aAC7B,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC;aACzB,OAAO,CAAC,UAAU,EAAE,YAAY,CAAC;aACjC,mBAAmB,CAAC,KAAK,EAAE,WAAW,EAAE;YACvC,MAAM,EAAE,QAAQ;YAChB,IAAI,EAAE,MAAM;YACZ,QAAQ,EAAE,UAAU;SACrB,CAAC;aACD,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;aACtB,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;aACpB,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;QAE5B,OAAO,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC5B,CAAC;CACF","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\n\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport {\n buildNetworkAssignmentDecision,\n} from \"../../shared/assignment/network-assignment.policy.js\";\nimport type { IntentNetworkGraphDatabase } from \"../../shared/interfaces/database.interface.js\";\nimport { protocolLogger } from \"../../shared/observability/protocol.logger.js\";\nimport { timed } from \"../../shared/observability/performance.js\";\nimport { requestContext } from \"../../shared/observability/request-context.js\";\nimport type { DebugMetaAgent } from \"../../chat/chat-streaming.types.js\";\nimport { renderNetworkContext } from \"../../shared/network/metadata.renderer.js\";\n\nimport {\n IntentNetworkGraphState,\n type IntentForIndexing,\n type IndexMemberContext,\n type AssignmentResult,\n} from \"./indexer.state.js\";\n\nconst logger = protocolLogger(\"IntentNetworkGraphFactory\");\n\n/**\n * Factory class to build and compile the Intent Index Graph.\n *\n * Handles CRUD for the intent_indexes junction table:\n * - create: Assign an intent to an index (direct or evaluated via IntentIndexer agent)\n * - read: List intent-index links (by intentId or by networkId)\n * - delete: Unassign an intent from an index\n *\n * The evaluate-based assignment flow is migrated from the old Index Graph.\n */\nexport class IntentNetworkGraphFactory {\n constructor(\n private database: IntentNetworkGraphDatabase,\n private intentNetworker: IntentIndexer,\n ) {}\n\n public createGraph() {\n const indexer = this.intentNetworker;\n\n // --- NODE DEFINITIONS ---\n\n /**\n * Assign Node: Assign an intent to an index.\n * Two sub-paths:\n * - Direct assignment (skipEvaluation=true): assign immediately\n * - Evaluated assignment (skipEvaluation=false): load intent + index context, evaluate via IntentIndexer\n */\n const assignNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.assign\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Assign intent to index\", { userId: state.userId, intentId, networkId, skipEvaluation: state.skipEvaluation });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n if (!intentId || !networkId) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Both intentId and networkId are required.\" } };\n }\n\n try {\n // Validate ownership and membership\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Intent not found.\" } };\n }\n if (intent.userId !== state.userId) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"You can only add your own intents to a network.\" } };\n }\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"You are not a member of that network.\" } };\n }\n\n // Check if already assigned\n const alreadyAssigned = await this.database.isIntentAssignedToIndex(intentId, networkId);\n if (alreadyAssigned) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: true, message: \"That intent is already in this network.\" } };\n }\n\n // Direct assignment (skip evaluation)\n if (state.skipEvaluation) {\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"intent\",\n mode: \"manual_override\",\n scope: \"network\",\n evaluator: \"intent-network-graph\",\n source: \"manual-index-assignment\",\n createdAt: new Date().toISOString(),\n });\n await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: \"Intent saved to the network.\" },\n };\n }\n\n // Evaluated assignment (migrated from old Index Graph)\n const intentForIndexing = await this.database.getIntentForIndexing(intentId);\n if (!intentForIndexing) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Intent not found for networking.\" } };\n }\n\n const indexContext = await this.database.getNetworkAssignmentContext(networkId, intentForIndexing.userId);\n if (!indexContext) {\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: false, success: false } as AssignmentResult,\n mutationResult: { success: false, error: \"Network assignment context not found.\" },\n };\n }\n const indexPrompt = indexContext.indexPrompt ?? null;\n const memberPrompt = indexContext.memberPrompt ?? null;\n const hasNoPrompts = !indexPrompt?.trim() && !memberPrompt?.trim();\n if (hasNoPrompts) {\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"intent\",\n mode: \"automatic\",\n scope: \"network\",\n indexPrompt,\n memberPrompt,\n evaluator: \"intent-indexer\",\n source: \"intent-network-graph\",\n createdAt: new Date().toISOString(),\n });\n await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: \"Intent assigned to network (no prompts).\" },\n };\n }\n\n // Run IntentIndexer evaluation\n const sourceName = intentForIndexing.sourceType\n ? `${intentForIndexing.sourceType}:${intentForIndexing.sourceId ?? \"\"}`\n : undefined;\n\n // Render network context (type, metadata) for the evaluator\n const network = await this.database.getNetwork(networkId);\n const renderedContext = network\n ? renderNetworkContext({\n type: network.type ?? 'community',\n title: network.title,\n prompt: network.prompt,\n metadata: network.metadata ?? {},\n })\n : null;\n\n const _traceEmitterIndexer = requestContext.getStore()?.traceEmitter;\n const _indexerStart = Date.now();\n _traceEmitterIndexer?.({ type: \"agent_start\", name: \"intent-indexer\" });\n let result: Awaited<ReturnType<typeof indexer.evaluate>> | null = null;\n try {\n result = await indexer.evaluate(\n intentForIndexing.payload,\n indexPrompt,\n memberPrompt,\n sourceName,\n renderedContext\n );\n } finally {\n const _indexerMs = Date.now() - _indexerStart;\n agentTimingsAccum.push({ name: 'intent.indexer', durationMs: _indexerMs });\n _traceEmitterIndexer?.({ type: \"agent_end\", name: \"intent-indexer\", durationMs: _indexerMs, summary: result ? `Scored: index=${result.indexScore.toFixed(2)}, member=${result.memberScore.toFixed(2)}` : \"intent-indexer failed\" });\n }\n\n if (!result) {\n return {\n agentTimings: agentTimingsAccum,\n evaluation: null,\n shouldAssign: false,\n finalScore: 0,\n mutationResult: { success: false, error: \"Evaluation returned no result.\" },\n };\n }\n\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"intent\",\n mode: \"automatic\",\n scope: \"network\",\n indexPrompt,\n memberPrompt,\n rawScores: { indexScore: result.indexScore, memberScore: result.memberScore },\n evaluator: \"intent-indexer\",\n source: \"intent-network-graph\",\n reason: result.reasoning,\n createdAt: new Date().toISOString(),\n });\n\n if (decision.assigned) {\n await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);\n return {\n agentTimings: agentTimingsAccum,\n evaluation: result,\n shouldAssign: true,\n finalScore: decision.finalScore,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: `Intent assigned to network (score: ${decision.finalScore.toFixed(2)}).` },\n };\n }\n\n return {\n agentTimings: agentTimingsAccum,\n evaluation: result,\n shouldAssign: false,\n finalScore: decision.finalScore,\n assignmentResult: { networkId, assigned: false, success: true } as AssignmentResult,\n mutationResult: { success: false, error: `Intent did not qualify for this network (score: ${decision.finalScore.toFixed(2)}).` },\n };\n } catch (err) {\n logger.error(\"Assign failed\", { error: err });\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Failed to assign intent to network.\" } };\n }\n });\n };\n\n /**\n * Read Node: Query intent-index relationships.\n * - By intentId only: list all indexes the intent is in (owner only)\n * - By networkId only: list intents in the index (member only)\n * - By both intentId and networkId: check if specific link exists (owner only)\n */\n const readNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.read\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Read intent-index links\", { userId: state.userId, intentId, networkId, queryUserId: state.queryUserId });\n\n try {\n // By both: check if specific intent-index link exists\n if (intentId && networkId) {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { readResult: { links: [], count: 0, mode: \"check_link\" }, error: \"Intent not found.\" };\n }\n if (intent.userId !== state.userId) {\n return { readResult: { links: [], count: 0, mode: \"check_link\" }, error: \"You can only check links for your own intents.\" };\n }\n const isLinked = await this.database.isIntentAssignedToIndex(intentId, networkId);\n return {\n readResult: {\n links: isLinked ? [{ intentId, networkId }] : [],\n count: isLinked ? 1 : 0,\n mode: \"check_link\",\n note: isLinked ? \"Intent is linked to this network.\" : \"Intent is not linked to this network.\",\n },\n };\n }\n\n // By intent only: list all indexes for this intent\n if (intentId) {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { readResult: { links: [], count: 0, mode: \"networks_for_intent\" }, error: \"Intent not found.\" };\n }\n if (intent.userId !== state.userId) {\n return { readResult: { links: [], count: 0, mode: \"networks_for_intent\" }, error: \"You can only list networks for your own intents.\" };\n }\n const networkIds = await this.database.getNetworkIdsForIntent(intentId);\n return {\n readResult: {\n links: networkIds.map((id) => ({ intentId, networkId: id })),\n count: networkIds.length,\n mode: \"networks_for_intent\",\n note: \"To show network titles, use read_networks.\",\n },\n };\n }\n\n // By index: list intents in the index\n if (!networkId) {\n return {\n readResult: { links: [], count: 0, mode: \"unknown\" },\n error: \"Provide networkId or intentId.\",\n };\n }\n\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return {\n readResult: { links: [], count: 0, mode: \"intents_in_network\" },\n error: \"Network not found or you are not a member.\",\n };\n }\n\n // All intents or filtered by user\n if (!state.queryUserId) {\n const intents = await this.database.getNetworkIntentsForMember(networkId, state.userId, { limit: 50, offset: 0 });\n return {\n readResult: {\n links: intents.map((i) => ({\n intentId: i.id,\n networkId,\n intentTitle: i.payload,\n userId: i.userId,\n userName: i.userName,\n createdAt: i.createdAt,\n relevancyScore: i.relevancyScore,\n })),\n count: intents.length,\n mode: \"intents_in_network\",\n note: \"To show network title and full intent details, use read_networks and read_intents.\",\n },\n };\n }\n\n // Specific user's intents\n const intents = await this.database.getIntentsInIndexForMember(state.queryUserId, networkId);\n return {\n readResult: {\n links: intents.map((i) => ({\n intentId: i.id,\n networkId,\n intentTitle: i.payload,\n createdAt: i.createdAt,\n relevancyScore: i.relevancyScore,\n })),\n count: intents.length,\n mode: \"intents_in_network\",\n note: \"To show network title and full intent details, use read_networks and read_intents.\",\n },\n };\n } catch (err) {\n logger.error(\"Read intent-index failed\", { error: err });\n return { error: \"Failed to fetch intent-network links.\" };\n }\n });\n };\n\n /**\n * Unassign Node: Remove an intent from an index.\n */\n const unassignNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.unassign\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Unassign intent from index\", { userId: state.userId, intentId, networkId });\n\n if (!intentId || !networkId) {\n return { mutationResult: { success: false, error: \"Both intentId and networkId are required.\" } };\n }\n\n try {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { mutationResult: { success: false, error: \"Intent not found.\" } };\n }\n if (intent.userId !== state.userId) {\n return { mutationResult: { success: false, error: \"You can only remove your own intents from a network.\" } };\n }\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return { mutationResult: { success: false, error: \"You are not a member of that network.\" } };\n }\n\n const assigned = await this.database.isIntentAssignedToIndex(intentId, networkId);\n if (!assigned) {\n return { mutationResult: { success: true, message: \"That intent is not in this network.\" } };\n }\n\n await this.database.unassignIntentFromIndex(intentId, networkId);\n return { mutationResult: { success: true, message: \"Intent removed from the index.\" } };\n } catch (err) {\n logger.error(\"Unassign failed\", { error: err });\n return { mutationResult: { success: false, error: \"Failed to remove intent from network.\" } };\n }\n });\n };\n\n // --- CONDITIONAL ROUTING ---\n\n const routeByMode = (state: typeof IntentNetworkGraphState.State): string => {\n switch (state.operationMode) {\n case 'create': return 'assign';\n case 'read': return 'read';\n case 'delete': return 'unassign';\n default: return 'read';\n }\n };\n\n // --- GRAPH ASSEMBLY ---\n\n const workflow = new StateGraph(IntentNetworkGraphState)\n .addNode(\"assign\", assignNode)\n .addNode(\"read\", readNode)\n .addNode(\"unassign\", unassignNode)\n .addConditionalEdges(START, routeByMode, {\n assign: \"assign\",\n read: \"read\",\n unassign: \"unassign\",\n })\n .addEdge(\"assign\", END)\n .addEdge(\"read\", END)\n .addEdge(\"unassign\", END);\n\n return workflow.compile();\n }\n}\n"]}
|
|
@@ -65,17 +65,17 @@ export declare const IntentNetworkGraphState: import("@langchain/langgraph").Ann
|
|
|
65
65
|
indexContext: import("@langchain/langgraph").BaseChannel<IndexMemberContext | null, IndexMemberContext | import("@langchain/langgraph").OverwriteValue<IndexMemberContext | null> | null, unknown>;
|
|
66
66
|
/** LLM evaluation result. Null if skipped. */
|
|
67
67
|
evaluation: import("@langchain/langgraph").BaseChannel<{
|
|
68
|
-
reasoning: string;
|
|
69
68
|
indexScore: number;
|
|
70
69
|
memberScore: number;
|
|
71
|
-
} | null, {
|
|
72
70
|
reasoning: string;
|
|
71
|
+
} | null, {
|
|
73
72
|
indexScore: number;
|
|
74
73
|
memberScore: number;
|
|
75
|
-
} | import("@langchain/langgraph").OverwriteValue<{
|
|
76
74
|
reasoning: string;
|
|
75
|
+
} | import("@langchain/langgraph").OverwriteValue<{
|
|
77
76
|
indexScore: number;
|
|
78
77
|
memberScore: number;
|
|
78
|
+
reasoning: string;
|
|
79
79
|
} | null> | null, unknown>;
|
|
80
80
|
/** Final decision: should intent be in this index? */
|
|
81
81
|
shouldAssign: import("@langchain/langgraph").BaseChannel<boolean | undefined, boolean | import("@langchain/langgraph").OverwriteValue<boolean | undefined> | undefined, unknown>;
|
|
@@ -2,6 +2,7 @@ import type { Runnable } from "@langchain/core/runnables";
|
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import type { Lens } from "../shared/hyde/lens.inferrer.js";
|
|
4
4
|
import type { OpportunityStatus } from "../shared/interfaces/database.interface.js";
|
|
5
|
+
import type { OpportunityEvidence } from '../shared/schemas/network-assignment.schema.js';
|
|
5
6
|
declare const OpportunitySchema: z.ZodObject<{
|
|
6
7
|
reasoning: z.ZodString;
|
|
7
8
|
score: z.ZodNumber;
|
|
@@ -9,15 +10,15 @@ declare const OpportunitySchema: z.ZodObject<{
|
|
|
9
10
|
sourceId: z.ZodString;
|
|
10
11
|
candidateId: z.ZodString;
|
|
11
12
|
}, "strip", z.ZodTypeAny, {
|
|
13
|
+
score: number;
|
|
12
14
|
sourceId: string;
|
|
13
15
|
reasoning: string;
|
|
14
|
-
score: number;
|
|
15
16
|
valencyRole: "Agent" | "Patient" | "Peer";
|
|
16
17
|
candidateId: string;
|
|
17
18
|
}, {
|
|
19
|
+
score: number;
|
|
18
20
|
sourceId: string;
|
|
19
21
|
reasoning: string;
|
|
20
|
-
score: number;
|
|
21
22
|
valencyRole: "Agent" | "Patient" | "Peer";
|
|
22
23
|
candidateId: string;
|
|
23
24
|
}>;
|
|
@@ -37,8 +38,10 @@ export interface EvaluatorEntity {
|
|
|
37
38
|
summary?: string;
|
|
38
39
|
}>;
|
|
39
40
|
networkId: string;
|
|
41
|
+
evidenceKey?: string;
|
|
40
42
|
ragScore?: number;
|
|
41
43
|
matchedVia?: string;
|
|
44
|
+
evidence?: OpportunityEvidence[];
|
|
42
45
|
}
|
|
43
46
|
export interface EvaluatorInput {
|
|
44
47
|
/** The user who triggered discovery (for context, not special treatment). */
|
|
@@ -62,14 +65,17 @@ declare const ActorSchema: z.ZodObject<{
|
|
|
62
65
|
userId: z.ZodString;
|
|
63
66
|
role: z.ZodEnum<["agent", "patient", "peer"]>;
|
|
64
67
|
intentId: z.ZodNullable<z.ZodString>;
|
|
68
|
+
evidenceKey: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
65
69
|
}, "strip", z.ZodTypeAny, {
|
|
66
70
|
userId: string;
|
|
67
71
|
role: "agent" | "patient" | "peer";
|
|
68
72
|
intentId: string | null;
|
|
73
|
+
evidenceKey?: string | null | undefined;
|
|
69
74
|
}, {
|
|
70
75
|
userId: string;
|
|
71
76
|
role: "agent" | "patient" | "peer";
|
|
72
77
|
intentId: string | null;
|
|
78
|
+
evidenceKey?: string | null | undefined;
|
|
73
79
|
}>;
|
|
74
80
|
declare const OpportunityWithActorsSchema: z.ZodObject<{
|
|
75
81
|
reasoning: z.ZodString;
|
|
@@ -78,30 +84,35 @@ declare const OpportunityWithActorsSchema: z.ZodObject<{
|
|
|
78
84
|
userId: z.ZodString;
|
|
79
85
|
role: z.ZodEnum<["agent", "patient", "peer"]>;
|
|
80
86
|
intentId: z.ZodNullable<z.ZodString>;
|
|
87
|
+
evidenceKey: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
81
88
|
}, "strip", z.ZodTypeAny, {
|
|
82
89
|
userId: string;
|
|
83
90
|
role: "agent" | "patient" | "peer";
|
|
84
91
|
intentId: string | null;
|
|
92
|
+
evidenceKey?: string | null | undefined;
|
|
85
93
|
}, {
|
|
86
94
|
userId: string;
|
|
87
95
|
role: "agent" | "patient" | "peer";
|
|
88
96
|
intentId: string | null;
|
|
97
|
+
evidenceKey?: string | null | undefined;
|
|
89
98
|
}>, "many">;
|
|
90
99
|
}, "strip", z.ZodTypeAny, {
|
|
91
|
-
reasoning: string;
|
|
92
100
|
score: number;
|
|
101
|
+
reasoning: string;
|
|
93
102
|
actors: {
|
|
94
103
|
userId: string;
|
|
95
104
|
role: "agent" | "patient" | "peer";
|
|
96
105
|
intentId: string | null;
|
|
106
|
+
evidenceKey?: string | null | undefined;
|
|
97
107
|
}[];
|
|
98
108
|
}, {
|
|
99
|
-
reasoning: string;
|
|
100
109
|
score: number;
|
|
110
|
+
reasoning: string;
|
|
101
111
|
actors: {
|
|
102
112
|
userId: string;
|
|
103
113
|
role: "agent" | "patient" | "peer";
|
|
104
114
|
intentId: string | null;
|
|
115
|
+
evidenceKey?: string | null | undefined;
|
|
105
116
|
}[];
|
|
106
117
|
}>;
|
|
107
118
|
declare const entityBundleResponseFormat: z.ZodObject<{
|
|
@@ -112,50 +123,57 @@ declare const entityBundleResponseFormat: z.ZodObject<{
|
|
|
112
123
|
userId: z.ZodString;
|
|
113
124
|
role: z.ZodEnum<["agent", "patient", "peer"]>;
|
|
114
125
|
intentId: z.ZodNullable<z.ZodString>;
|
|
126
|
+
evidenceKey: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
115
127
|
}, "strip", z.ZodTypeAny, {
|
|
116
128
|
userId: string;
|
|
117
129
|
role: "agent" | "patient" | "peer";
|
|
118
130
|
intentId: string | null;
|
|
131
|
+
evidenceKey?: string | null | undefined;
|
|
119
132
|
}, {
|
|
120
133
|
userId: string;
|
|
121
134
|
role: "agent" | "patient" | "peer";
|
|
122
135
|
intentId: string | null;
|
|
136
|
+
evidenceKey?: string | null | undefined;
|
|
123
137
|
}>, "many">;
|
|
124
138
|
}, "strip", z.ZodTypeAny, {
|
|
125
|
-
reasoning: string;
|
|
126
139
|
score: number;
|
|
140
|
+
reasoning: string;
|
|
127
141
|
actors: {
|
|
128
142
|
userId: string;
|
|
129
143
|
role: "agent" | "patient" | "peer";
|
|
130
144
|
intentId: string | null;
|
|
145
|
+
evidenceKey?: string | null | undefined;
|
|
131
146
|
}[];
|
|
132
147
|
}, {
|
|
133
|
-
reasoning: string;
|
|
134
148
|
score: number;
|
|
149
|
+
reasoning: string;
|
|
135
150
|
actors: {
|
|
136
151
|
userId: string;
|
|
137
152
|
role: "agent" | "patient" | "peer";
|
|
138
153
|
intentId: string | null;
|
|
154
|
+
evidenceKey?: string | null | undefined;
|
|
139
155
|
}[];
|
|
140
156
|
}>, "many">;
|
|
141
157
|
}, "strip", z.ZodTypeAny, {
|
|
142
158
|
opportunities: {
|
|
143
|
-
reasoning: string;
|
|
144
159
|
score: number;
|
|
160
|
+
reasoning: string;
|
|
145
161
|
actors: {
|
|
146
162
|
userId: string;
|
|
147
163
|
role: "agent" | "patient" | "peer";
|
|
148
164
|
intentId: string | null;
|
|
165
|
+
evidenceKey?: string | null | undefined;
|
|
149
166
|
}[];
|
|
150
167
|
}[];
|
|
151
168
|
}, {
|
|
152
169
|
opportunities: {
|
|
153
|
-
reasoning: string;
|
|
154
170
|
score: number;
|
|
171
|
+
reasoning: string;
|
|
155
172
|
actors: {
|
|
156
173
|
userId: string;
|
|
157
174
|
role: "agent" | "patient" | "peer";
|
|
158
175
|
intentId: string | null;
|
|
176
|
+
evidenceKey?: string | null | undefined;
|
|
159
177
|
}[];
|
|
160
178
|
}[];
|
|
161
179
|
}>;
|
|
@@ -244,9 +262,9 @@ export declare class OpportunityEvaluator {
|
|
|
244
262
|
minScore?: number | undefined;
|
|
245
263
|
candidatesJson?: string | undefined;
|
|
246
264
|
}, {
|
|
265
|
+
score: number;
|
|
247
266
|
sourceId: string;
|
|
248
267
|
reasoning: string;
|
|
249
|
-
score: number;
|
|
250
268
|
valencyRole: "Agent" | "Patient" | "Peer";
|
|
251
269
|
candidateId: string;
|
|
252
270
|
}[], unknown, "opportunity_evaluator">;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"opportunity.evaluator.d.ts","sourceRoot":"/","sources":["opportunity/opportunity.evaluator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAG1D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;
|
|
1
|
+
{"version":3,"file":"opportunity.evaluator.d.ts","sourceRoot":"/","sources":["opportunity/opportunity.evaluator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAG1D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;AAKpF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gDAAgD,CAAC;AA0J1F,QAAA,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;EAMrB,CAAC;AAQH,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE;QACP,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;QACrB,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;IACF,OA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E,MAAM,EAC5B,UAAU,EAAE,gBAAgB,EAAE,EAC9B,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,WAAW,EAAE,CAAC;IAgCzB;;OAEG;YACW,YAAY;IAgD1B;;OAEG;IAEU,kBAAkB,CAC7B,KAAK,EAAE,cAAc,EACrB,OAAO,GAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,CAAA;KAAO,GACvD,OAAO,CAAC,8BAA8B,EAAE,CAAC;IAuI5C;;;;OAIG;WACW,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCrB"}
|
|
@@ -15,6 +15,7 @@ import { Timed } from "../shared/observability/performance.js";
|
|
|
15
15
|
import { stripUuids } from "./opportunity.presentation.js";
|
|
16
16
|
import { createModel } from "../shared/agent/model.config.js";
|
|
17
17
|
import { invokeWithAbortSignal } from "../shared/agent/model-signal.js";
|
|
18
|
+
import { renderOpportunityEvidenceForPrompt } from './opportunity.evidence.js';
|
|
18
19
|
const logger = protocolLogger("OpportunityEvaluator");
|
|
19
20
|
const model = createModel("opportunityEvaluator");
|
|
20
21
|
// ──────────────────────────────────────────────────────────────
|
|
@@ -83,9 +84,11 @@ Input:
|
|
|
83
84
|
- DISCOVERER: The user ID who triggered discovery (for context; they may or may not be in the entity list).
|
|
84
85
|
- ENTITIES: A set of entities. Each entity has:
|
|
85
86
|
- userId, networkId (the index through which they were found)
|
|
87
|
+
- evidenceKey (stable key for the matched resource when available)
|
|
86
88
|
- profile: name, bio, location, interests, skills, context
|
|
87
89
|
- intents (optional): list of { intentId, payload, summary } — some entities are profile-only, some have intents
|
|
88
90
|
- ragScore, matchedVia (how they were found)
|
|
91
|
+
- evidence (typed retrieval evidence: discovery kind, network, score, lens, source/candidate ids)
|
|
89
92
|
- EXISTING OPPORTUNITIES: Context of matches already made (for deduplication).
|
|
90
93
|
|
|
91
94
|
BEFORE SCORING — determine role satisfiability:
|
|
@@ -121,6 +124,7 @@ Output:
|
|
|
121
124
|
- userId
|
|
122
125
|
- role: "agent" (can do something for others), "patient" (needs something from others), "peer" (symmetric collaboration)
|
|
123
126
|
- intentId (optional): if the match is intent-driven, the specific intent ID for that user
|
|
127
|
+
- evidenceKey (optional): copy the entity evidenceKey when the actor is driven by a specific listed entity
|
|
124
128
|
|
|
125
129
|
VISIBILITY (role controls who sees the opportunity when):
|
|
126
130
|
- agent: Last to see — after the patient has committed to reaching out.
|
|
@@ -170,6 +174,7 @@ const ActorSchema = z.object({
|
|
|
170
174
|
userId: z.string(),
|
|
171
175
|
role: z.enum(['agent', 'patient', 'peer']),
|
|
172
176
|
intentId: z.string().nullable().describe('If the match is intent-driven, the specific intent ID; null otherwise'),
|
|
177
|
+
evidenceKey: z.string().nullable().optional().describe('Stable evidence key for the matched entity; null if unknown'),
|
|
173
178
|
});
|
|
174
179
|
const OpportunityWithActorsSchema = z.object({
|
|
175
180
|
reasoning: z.string(),
|
|
@@ -352,9 +357,12 @@ CRITICAL SCORING RULES FOR DISCOVERY REQUESTS:
|
|
|
352
357
|
return `
|
|
353
358
|
USER: ${e.userId}
|
|
354
359
|
INDEX: ${e.networkId}
|
|
360
|
+
EVIDENCE KEY: ${e.evidenceKey ?? '—'}
|
|
355
361
|
PROFILE: Name: ${displayName} | Bio: ${e.profile.bio ?? ''} | Location: ${e.profile.location ?? ''} | Interests: ${e.profile.interests?.join(', ') ?? ''} | Skills: ${e.profile.skills?.join(', ') ?? ''} | Context: ${e.profile.context ?? ''}${intentsPart}
|
|
356
362
|
RAG SCORE: ${e.ragScore ?? '—'}
|
|
357
|
-
MATCHED VIA: ${e.matchedVia ?? '—'}
|
|
363
|
+
MATCHED VIA: ${e.matchedVia ?? '—'}
|
|
364
|
+
EVIDENCE:
|
|
365
|
+
${renderOpportunityEvidenceForPrompt(e.evidence ?? [])}`;
|
|
358
366
|
}).join('\n');
|
|
359
367
|
const networkContextPart = input.networkContexts && Object.keys(input.networkContexts).length > 0
|
|
360
368
|
? `\n\nNETWORK CONTEXTS:\n${Object.entries(input.networkContexts).map(([nid, ctx]) => `[INDEX: ${nid}]\n${ctx}`).join('\n\n')}`
|