@indexnetwork/protocol 3.7.0-rc.277.1 → 3.7.1-rc.278.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/agent/agent.tools.js +1 -1
- package/dist/agent/agent.tools.js.map +1 -1
- package/dist/chat/chat.agent.d.ts +6 -6
- package/dist/chat/chat.agent.d.ts.map +1 -1
- package/dist/chat/chat.agent.js +9 -9
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/chat/chat.graph.d.ts.map +1 -1
- package/dist/chat/chat.graph.js +3 -12
- package/dist/chat/chat.graph.js.map +1 -1
- package/dist/chat/chat.interrupt.classifier.d.ts.map +1 -1
- package/dist/chat/chat.interrupt.classifier.js +1 -3
- package/dist/chat/chat.interrupt.classifier.js.map +1 -1
- package/dist/chat/chat.suggester.js.map +1 -1
- package/dist/context/context.generator.d.ts +2 -0
- package/dist/context/context.generator.d.ts.map +1 -1
- package/dist/context/context.generator.js +8 -6
- package/dist/context/context.generator.js.map +1 -1
- package/dist/intent/intent.clarifier.d.ts +2 -0
- package/dist/intent/intent.clarifier.d.ts.map +1 -1
- package/dist/intent/intent.clarifier.js +9 -23
- package/dist/intent/intent.clarifier.js.map +1 -1
- package/dist/intent/intent.graph.d.ts.map +1 -1
- package/dist/intent/intent.graph.js +29 -26
- package/dist/intent/intent.graph.js.map +1 -1
- package/dist/intent/intent.tools.d.ts.map +1 -1
- package/dist/intent/intent.tools.js +18 -48
- package/dist/intent/intent.tools.js.map +1 -1
- package/dist/maintenance/maintenance.graph.d.ts.map +1 -1
- package/dist/maintenance/maintenance.graph.js +1 -2
- package/dist/maintenance/maintenance.graph.js.map +1 -1
- package/dist/mcp/mcp.server.d.ts.map +1 -1
- package/dist/mcp/mcp.server.js +2 -4
- package/dist/mcp/mcp.server.js.map +1 -1
- package/dist/negotiation/negotiation.graph.d.ts.map +1 -1
- package/dist/negotiation/negotiation.graph.js +13 -20
- package/dist/negotiation/negotiation.graph.js.map +1 -1
- package/dist/negotiation/negotiation.tools.d.ts.map +1 -1
- package/dist/negotiation/negotiation.tools.js +12 -12
- package/dist/negotiation/negotiation.tools.js.map +1 -1
- package/dist/network/indexer/indexer.graph.d.ts +9 -9
- package/dist/network/indexer/indexer.graph.d.ts.map +1 -1
- package/dist/network/indexer/indexer.graph.js.map +1 -1
- package/dist/network/network.graph.d.ts.map +1 -1
- package/dist/network/network.graph.js +19 -25
- package/dist/network/network.graph.js.map +1 -1
- package/dist/opportunity/feed/feed.categorizer.d.ts.map +1 -1
- package/dist/opportunity/feed/feed.categorizer.js +15 -20
- package/dist/opportunity/feed/feed.categorizer.js.map +1 -1
- package/dist/opportunity/feed/feed.graph.d.ts.map +1 -1
- package/dist/opportunity/feed/feed.graph.js +8 -10
- package/dist/opportunity/feed/feed.graph.js.map +1 -1
- package/dist/opportunity/opportunity.introducer.d.ts.map +1 -1
- package/dist/opportunity/opportunity.introducer.js +1 -2
- package/dist/opportunity/opportunity.introducer.js.map +1 -1
- package/dist/opportunity/opportunity.tools.d.ts.map +1 -1
- package/dist/opportunity/opportunity.tools.js +3 -2
- package/dist/opportunity/opportunity.tools.js.map +1 -1
- package/dist/profile/profile.enricher.d.ts +5 -7
- package/dist/profile/profile.enricher.d.ts.map +1 -1
- package/dist/profile/profile.enricher.js +8 -10
- package/dist/profile/profile.enricher.js.map +1 -1
- package/dist/profile/profile.generator.d.ts.map +1 -1
- package/dist/profile/profile.generator.js +1 -2
- package/dist/profile/profile.generator.js.map +1 -1
- package/dist/profile/profile.tools.js +1 -1
- package/dist/profile/profile.tools.js.map +1 -1
- package/dist/questioner/questioner.presets.d.ts.map +1 -1
- package/dist/questioner/questioner.presets.js +24 -38
- package/dist/questioner/questioner.presets.js.map +1 -1
- package/dist/shared/agent/tool.factory.d.ts.map +1 -1
- package/dist/shared/agent/tool.factory.js +1 -2
- package/dist/shared/agent/tool.factory.js.map +1 -1
- package/dist/shared/agent/tool.runtime.d.ts.map +1 -1
- package/dist/shared/agent/tool.runtime.js +20 -13
- package/dist/shared/agent/tool.runtime.js.map +1 -1
- package/dist/shared/hyde/hyde.graph.d.ts.map +1 -1
- package/dist/shared/hyde/hyde.graph.js +3 -2
- package/dist/shared/hyde/hyde.graph.js.map +1 -1
- package/dist/shared/hyde/hyde.strategies.d.ts +2 -1
- package/dist/shared/hyde/hyde.strategies.d.ts.map +1 -1
- package/dist/shared/hyde/hyde.strategies.js.map +1 -1
- package/dist/shared/observability/trace.d.ts +3 -3
- package/dist/shared/observability/trace.d.ts.map +1 -1
- package/dist/shared/observability/trace.js +19 -33
- package/dist/shared/observability/trace.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
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,EAAE,8BAA8B,EAAE,MAAM,sDAAsD,CAAC;AAEtG,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAC/E,OAAO,EAAE,KAAK,EAAE,MAAM,2CAA2C,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAE/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EAAE,uBAAuB,EAA0E,MAAM,oBAAoB,CAAC;AAErI,MAAM,MAAM,GAAG,cAAc,CAAC,2BAA2B,CAAC,CAAC;AAE3D;;;;;;;;;GASG;AACH,MAAM,OAAO,yBAAyB;IACpC,YACU,QAAoC,EACpC,eAA8B;QAD9B,aAAQ,GAAR,QAAQ,CAA4B;QACpC,oBAAe,GAAf,eAAe,CAAe;IACrC,CAAC;IAEG,WAAW;QAChB,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,CAAC;QAErC,2BAA2B;QAE3B;;;;;WAKG;QACH,MAAM,UAAU,GAAG,KA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AAM,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 { buildNetworkAssignmentDecision } 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 { IntentNetworkGraphState, type IntentForIndexing, type IndexMemberContext, type AssignmentResult } 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"]}
|
|
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,EAAE,8BAA8B,EAAE,MAAM,sDAAsD,CAAC;AAEtG,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAC/E,OAAO,EAAE,KAAK,EAAE,MAAM,2CAA2C,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAE/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EAAE,uBAAuB,EAAyB,MAAM,oBAAoB,CAAC;AAEpF,MAAM,MAAM,GAAG,cAAc,CAAC,2BAA2B,CAAC,CAAC;AAE3D;;;;;;;;;GASG;AACH,MAAM,OAAO,yBAAyB;IACpC,YACU,QAAoC,EACpC,eAA8B;QAD9B,aAAQ,GAAR,QAAQ,CAA4B;QACpC,oBAAe,GAAf,eAAe,CAAe;IACrC,CAAC;IAEG,WAAW;QAChB,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,CAAC;QAErC,2BAA2B;QAE3B;;;;;WAKG;QACH,MAAM,UAAU,GAAG,K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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 { buildNetworkAssignmentDecision } 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 { IntentNetworkGraphState, type AssignmentResult } 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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network.graph.d.ts","sourceRoot":"/","sources":["network/network.graph.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAQlF;;;;;;;;;GASG;AACH,qBAAa,mBAAmB;IAClB,OAAO,CAAC,QAAQ;gBAAR,QAAQ,EAAE,oBAAoB;IAE3C,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"network.graph.d.ts","sourceRoot":"/","sources":["network/network.graph.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAQlF;;;;;;;;;GASG;AACH,qBAAa,mBAAmB;IAClB,OAAO,CAAC,QAAQ;gBAAR,QAAQ,EAAE,oBAAoB;IAE3C,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCAmCuD,CAAC;yBACrD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCADmD,CAAC;yBACrD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCADmD,CAAC;yBACrD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCADmD,CAAC;yBACrD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCADmD,CAAC;yBACrD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCADmD,CAAC;yBACrD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCADmD,CAAC;yBACrD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCADmD,CAAC;yBACrD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCADmD,CAAC;yBACrD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqOvB"}
|
|
@@ -25,6 +25,23 @@ export class NetworkGraphFactory {
|
|
|
25
25
|
const readNode = async (state) => {
|
|
26
26
|
return timed("NetworkGraph.read", async () => {
|
|
27
27
|
logger.verbose("Read indexes", { userId: state.userId, networkId: state.networkId, showAll: state.showAll });
|
|
28
|
+
// Shared projections for both the scoped and unscoped read paths.
|
|
29
|
+
const projectMembership = (m) => ({
|
|
30
|
+
networkId: m.networkId,
|
|
31
|
+
title: m.networkTitle,
|
|
32
|
+
prompt: m.indexPrompt,
|
|
33
|
+
autoAssign: m.autoAssign,
|
|
34
|
+
isPersonal: m.isPersonal,
|
|
35
|
+
joinedAt: m.joinedAt,
|
|
36
|
+
});
|
|
37
|
+
const projectOwned = (o) => ({
|
|
38
|
+
networkId: o.id,
|
|
39
|
+
title: o.title,
|
|
40
|
+
prompt: o.prompt,
|
|
41
|
+
memberCount: o.memberCount,
|
|
42
|
+
intentCount: o.intentCount,
|
|
43
|
+
joinPolicy: o.permissions.joinPolicy,
|
|
44
|
+
});
|
|
28
45
|
try {
|
|
29
46
|
const [allMemberships, ownedIndexes, publicIndexesResult] = await Promise.all([
|
|
30
47
|
this.database.getNetworkMemberships(state.userId),
|
|
@@ -52,22 +69,6 @@ export class NetworkGraphFactory {
|
|
|
52
69
|
},
|
|
53
70
|
};
|
|
54
71
|
}
|
|
55
|
-
const projectMembership = (m) => ({
|
|
56
|
-
networkId: m.networkId,
|
|
57
|
-
title: m.networkTitle,
|
|
58
|
-
prompt: m.indexPrompt,
|
|
59
|
-
autoAssign: m.autoAssign,
|
|
60
|
-
isPersonal: m.isPersonal,
|
|
61
|
-
joinedAt: m.joinedAt,
|
|
62
|
-
});
|
|
63
|
-
const projectOwned = (o) => ({
|
|
64
|
-
networkId: o.id,
|
|
65
|
-
title: o.title,
|
|
66
|
-
prompt: o.prompt,
|
|
67
|
-
memberCount: o.memberCount,
|
|
68
|
-
intentCount: o.intentCount,
|
|
69
|
-
joinPolicy: o.permissions.joinPolicy,
|
|
70
|
-
});
|
|
71
72
|
const scopedMembership = allMemberships.find((m) => m.networkId === networkId);
|
|
72
73
|
const personalMembership = scopedMembership?.isPersonal
|
|
73
74
|
? undefined
|
|
@@ -106,15 +107,8 @@ export class NetworkGraphFactory {
|
|
|
106
107
|
}));
|
|
107
108
|
return {
|
|
108
109
|
readResult: {
|
|
109
|
-
memberOf: allMemberships.map(
|
|
110
|
-
|
|
111
|
-
title: m.networkTitle,
|
|
112
|
-
prompt: m.indexPrompt,
|
|
113
|
-
autoAssign: m.autoAssign,
|
|
114
|
-
isPersonal: m.isPersonal,
|
|
115
|
-
joinedAt: m.joinedAt,
|
|
116
|
-
})),
|
|
117
|
-
owns: ownedIndexes.map((o) => ({ networkId: o.id, title: o.title, prompt: o.prompt, memberCount: o.memberCount, intentCount: o.intentCount, joinPolicy: o.permissions.joinPolicy })),
|
|
110
|
+
memberOf: allMemberships.map(projectMembership),
|
|
111
|
+
owns: ownedIndexes.map(projectOwned),
|
|
118
112
|
publicNetworks,
|
|
119
113
|
stats: { memberOfCount: allMemberships.length, ownsCount: ownedIndexes.length, publicNetworksCount: publicNetworks.length },
|
|
120
114
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network.graph.js","sourceRoot":"/","sources":["network/network.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAG9D,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAE/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAErD;;;;;;;;;GASG;AACH,MAAM,OAAO,mBAAmB;IAC9B,YAAoB,QAA8B;QAA9B,aAAQ,GAAR,QAAQ,CAAsB;IAAG,CAAC;IAE/C,WAAW;QAChB,2BAA2B;QAE3B;;WAEG;QACH,MAAM,QAAQ,GAAG,KAAK,EAAE,KAAqC,EAAE,EAAE;YAC/D,OAAO,KAAK,CAAC,mBAAmB,EAAE,KAAK,IAAI,EAAE;gBAC3C,MAAM,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,SAAS,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;gBAE7G,IAAI,CAAC;oBACH,MAAM,CAAC,cAAc,EAAE,YAAY,EAAE,mBAAmB,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;wBAC5E,IAAI,CAAC,QAAQ,CAAC,qBAAqB,CAAC,KAAK,CAAC,MAAM,CAAC;wBACjD,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,KA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,EAAE,GAAG,CAAC;aACpB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;aACtB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;aACtB,OAAO,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;QAE9B,OAAO,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC5B,CAAC;CACF","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\n\nimport { NetworkGraphDatabase } from \"../shared/interfaces/database.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { timed } from \"../shared/observability/performance.js\";\n\nimport { NetworkGraphState } from \"./network.state.js\";\n\nconst logger = protocolLogger(\"NetworkGraphFactory\");\n\n/**\n * Factory class to build and compile the Index (CRUD) Graph.\n *\n * Handles create, read, update, and delete operations for indexes.\n * Membership and intent-index assignment operations are handled by\n * separate graphs (NetworkMembershipGraph and IntentNetworkGraph).\n *\n * Flow:\n * START → routerNode → {createNode | readNode | updateNode | deleteNode} → END\n */\nexport class NetworkGraphFactory {\n constructor(private database: NetworkGraphDatabase) {}\n\n public createGraph() {\n // --- NODE DEFINITIONS ---\n\n /**\n * Read Node: List indexes the user belongs to and owns.\n */\n const readNode = async (state: typeof NetworkGraphState.State) => {\n return timed(\"NetworkGraph.read\", async () => {\n logger.verbose(\"Read indexes\", { userId: state.userId, networkId: state.networkId, showAll: state.showAll });\n\n try {\n const [allMemberships, ownedIndexes, publicIndexesResult] = await Promise.all([\n this.database.getNetworkMemberships(state.userId),\n this.database.getOwnedIndexes(state.userId),\n this.database.getPublicIndexesNotJoined(state.userId),\n ]);\n\n // If index-scoped and not showAll, return just that index plus the\n // user's personal index (their contacts). The personal index is part\n // of every scope — `computeAgentIndexScope` keeps it reachable for\n // network-bound agents, and a user clicked into a community-scoped\n // chat still owns their contact list — so surfacing it here keeps\n // tools that operate on the personal index (add_contact, list_contacts,\n // import_*_contacts) discoverable. Other community memberships are\n // still hidden, and `publicNetworks` is omitted.\n const scopeToCurrentIndex = state.networkId && !state.showAll;\n if (scopeToCurrentIndex) {\n const networkId = state.networkId!;\n const isMember = await this.database.isNetworkMember(networkId, state.userId);\n if (!isMember) {\n return {\n readResult: {\n memberOf: [],\n owns: [],\n stats: { memberOfCount: 0, ownsCount: 0, scopeNote: \"Network not found or you are not a member.\" },\n },\n };\n }\n const projectMembership = (m: typeof allMemberships[number]) => ({\n networkId: m.networkId,\n title: m.networkTitle,\n prompt: m.indexPrompt,\n autoAssign: m.autoAssign,\n isPersonal: m.isPersonal,\n joinedAt: m.joinedAt,\n });\n const projectOwned = (o: typeof ownedIndexes[number]) => ({\n networkId: o.id,\n title: o.title,\n prompt: o.prompt,\n memberCount: o.memberCount,\n intentCount: o.intentCount,\n joinPolicy: o.permissions.joinPolicy,\n });\n const scopedMembership = allMemberships.find((m) => m.networkId === networkId);\n const personalMembership = scopedMembership?.isPersonal\n ? undefined\n : allMemberships.find((m) => m.isPersonal);\n const scopedOwned = ownedIndexes.find((o) => o.id === networkId);\n const personalOwned = personalMembership\n ? ownedIndexes.find((o) => o.id === personalMembership.networkId)\n : undefined;\n const memberOf = [\n ...(scopedMembership ? [projectMembership(scopedMembership)] : []),\n ...(personalMembership ? [projectMembership(personalMembership)] : []),\n ];\n const owns = [\n ...(scopedOwned ? [projectOwned(scopedOwned)] : []),\n ...(personalOwned ? [projectOwned(personalOwned)] : []),\n ];\n return {\n readResult: {\n memberOf,\n owns,\n stats: {\n memberOfCount: memberOf.length,\n ownsCount: owns.length,\n scopeNote: \"Showing current index and your personal index. Use showAll: true for all indexes.\",\n },\n },\n };\n }\n\n // Include public networks available to join\n const publicNetworks = publicIndexesResult.networks.map((idx) => ({\n networkId: idx.id,\n title: idx.title,\n prompt: idx.prompt,\n memberCount: idx.memberCount,\n owner: idx.owner,\n }));\n\n return {\n readResult: {\n memberOf: allMemberships.map((m) => ({\n networkId: m.networkId,\n title: m.networkTitle,\n prompt: m.indexPrompt,\n autoAssign: m.autoAssign,\n isPersonal: m.isPersonal,\n joinedAt: m.joinedAt,\n })),\n owns: ownedIndexes.map((o) => ({ networkId: o.id, title: o.title, prompt: o.prompt, memberCount: o.memberCount, intentCount: o.intentCount, joinPolicy: o.permissions.joinPolicy })),\n publicNetworks,\n stats: { memberOfCount: allMemberships.length, ownsCount: ownedIndexes.length, publicNetworksCount: publicNetworks.length },\n },\n };\n } catch (err) {\n logger.error(\"Read indexes failed\", { error: err });\n return { error: \"Failed to fetch network information.\" };\n }\n });\n };\n\n /**\n * Create Node: Create a new index and add user as owner.\n */\n const createNode = async (state: typeof NetworkGraphState.State) => {\n return timed(\"NetworkGraph.create\", async () => {\n logger.verbose(\"Create index\", { userId: state.userId, createInput: state.createInput });\n\n if (!state.createInput?.title?.trim()) {\n return { mutationResult: { success: false, error: \"Title is required.\" } };\n }\n\n let createdIndexId: string | undefined;\n try {\n const index = await this.database.createNetwork({\n title: state.createInput.title.trim(),\n prompt: state.createInput.prompt?.trim() || undefined,\n imageUrl: state.createInput.imageUrl ?? undefined,\n joinPolicy: state.createInput.joinPolicy,\n });\n createdIndexId = index.id;\n\n const added = await this.database.addMemberToNetwork(index.id, state.userId, 'owner');\n if (!added.success) {\n logger.error(\"addMemberToNetwork failed; cleaning up orphaned network\", { networkId: index.id });\n try { await this.database.softDeleteNetwork(index.id); } catch {}\n return { mutationResult: { success: false, error: \"Failed to set you as owner. Network was not created.\" } };\n }\n\n return {\n mutationResult: {\n success: true,\n networkId: index.id,\n title: index.title,\n message: `Network \"${index.title}\" created. You are the owner.`,\n },\n };\n } catch (err) {\n logger.error(\"Create index failed\", { error: err });\n if (createdIndexId) {\n try { await this.database.softDeleteNetwork(createdIndexId); } catch {}\n }\n return {\n mutationResult: {\n success: false,\n error: err instanceof Error ? err.message : \"Failed to create network.\",\n },\n };\n }\n });\n };\n\n /**\n * Update Node: Update index settings (owner only).\n */\n const updateNode = async (state: typeof NetworkGraphState.State) => {\n return timed(\"NetworkGraph.update\", async () => {\n const networkId = state.networkId;\n logger.verbose(\"Update index\", { userId: state.userId, networkId, updateInput: state.updateInput });\n\n if (!networkId) {\n return { mutationResult: { success: false, error: \"networkId is required for update.\" } };\n }\n\n try {\n const isOwner = await this.database.isIndexOwner(networkId, state.userId);\n if (!isOwner) {\n return { mutationResult: { success: false, error: \"You can only modify networks you own.\" } };\n }\n\n await this.database.updateIndexSettings(networkId, state.userId, state.updateInput ?? {});\n\n return {\n mutationResult: {\n success: true,\n networkId,\n message: \"Network settings updated.\",\n },\n };\n } catch (err) {\n logger.error(\"Update index failed\", { error: err });\n return { mutationResult: { success: false, error: \"Failed to update network.\" } };\n }\n });\n };\n\n /**\n * Delete Node: Soft-delete an index (owner only, sole member).\n */\n const deleteNode = async (state: typeof NetworkGraphState.State) => {\n return timed(\"NetworkGraph.delete\", async () => {\n const networkId = state.networkId;\n logger.verbose(\"Delete index\", { userId: state.userId, networkId });\n\n if (!networkId) {\n return { mutationResult: { success: false, error: \"networkId is required for delete.\" } };\n }\n\n try {\n const isOwner = await this.database.isIndexOwner(networkId, state.userId);\n if (!isOwner) {\n return { mutationResult: { success: false, error: \"You can only delete networks you own.\" } };\n }\n\n const count = await this.database.getNetworkMemberCount(networkId);\n if (count > 1) {\n return { mutationResult: { success: false, error: \"Cannot delete network with other members. Remove members first.\" } };\n }\n\n await this.database.softDeleteNetwork(networkId);\n\n return {\n mutationResult: {\n success: true,\n networkId,\n message: \"Network deleted.\",\n },\n };\n } catch (err) {\n logger.error(\"Delete index failed\", { error: err });\n return { mutationResult: { success: false, error: \"Failed to delete network.\" } };\n }\n });\n };\n\n // --- CONDITIONAL ROUTING ---\n\n const routeByMode = (state: typeof NetworkGraphState.State): string => {\n switch (state.operationMode) {\n case 'create': return 'create';\n case 'read': return 'read';\n case 'update': return 'update';\n case 'delete': return 'delete_idx';\n default: return 'read';\n }\n };\n\n // --- GRAPH ASSEMBLY ---\n\n const workflow = new StateGraph(NetworkGraphState)\n .addNode(\"read\", readNode)\n .addNode(\"create\", createNode)\n .addNode(\"update\", updateNode)\n .addNode(\"delete_idx\", deleteNode)\n .addConditionalEdges(START, routeByMode, {\n read: \"read\",\n create: \"create\",\n update: \"update\",\n delete_idx: \"delete_idx\",\n })\n .addEdge(\"read\", END)\n .addEdge(\"create\", END)\n .addEdge(\"update\", END)\n .addEdge(\"delete_idx\", END);\n\n return workflow.compile();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"network.graph.js","sourceRoot":"/","sources":["network/network.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAG9D,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAE/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAErD;;;;;;;;;GASG;AACH,MAAM,OAAO,mBAAmB;IAC9B,YAAoB,QAA8B;QAA9B,aAAQ,GAAR,QAAQ,CAAsB;IAAG,CAAC;IAE/C,WAAW;QAChB,2BAA2B;QAE3B;;WAEG;QACH,MAAM,QAAQ,GAAG,KAAK,EAAE,KAAqC,EAAE,EAAE;YAC/D,OAAO,KAAK,CAAC,mBAAmB,EAAE,KAAK,IAAI,EAAE;gBAC3C,MAAM,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,SAAS,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;gBAE7G,kEAAkE;gBAClE,MAAM,iBAAiB,GAAG,CAAC,CAA0E,EAAE,EAAE,CAAC,CAAC;oBACzG,SAAS,EAAE,CAAC,CAAC,SAAS;oBACtB,KAAK,EAAE,CAAC,CAAC,YAAY;oBACrB,MAAM,EAAE,CAAC,CAAC,WAAW;oBACrB,UAAU,EA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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,QAAQ,CAAC;gBAC/B,KAAK,QAAQ,CAAC,CAAC,OAAO,YAAY,CAAC;gBACnC,OAAO,CAAC,CAAC,OAAO,MAAM,CAAC;YACzB,CAAC;QACH,CAAC,CAAC;QAEF,yBAAyB;QAEzB,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,iBAAiB,CAAC;aAC/C,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC;aACzB,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC;aAC7B,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC;aAC7B,OAAO,CAAC,YAAY,EAAE,UAAU,CAAC;aACjC,mBAAmB,CAAC,KAAK,EAAE,WAAW,EAAE;YACvC,IAAI,EAAE,MAAM;YACZ,MAAM,EAAE,QAAQ;YAChB,MAAM,EAAE,QAAQ;YAChB,UAAU,EAAE,YAAY;SACzB,CAAC;aACD,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;aACpB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;aACtB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;aACtB,OAAO,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;QAE9B,OAAO,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC5B,CAAC;CACF","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\n\nimport { NetworkGraphDatabase } from \"../shared/interfaces/database.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { timed } from \"../shared/observability/performance.js\";\n\nimport { NetworkGraphState } from \"./network.state.js\";\n\nconst logger = protocolLogger(\"NetworkGraphFactory\");\n\n/**\n * Factory class to build and compile the Index (CRUD) Graph.\n *\n * Handles create, read, update, and delete operations for indexes.\n * Membership and intent-index assignment operations are handled by\n * separate graphs (NetworkMembershipGraph and IntentNetworkGraph).\n *\n * Flow:\n * START → routerNode → {createNode | readNode | updateNode | deleteNode} → END\n */\nexport class NetworkGraphFactory {\n constructor(private database: NetworkGraphDatabase) {}\n\n public createGraph() {\n // --- NODE DEFINITIONS ---\n\n /**\n * Read Node: List indexes the user belongs to and owns.\n */\n const readNode = async (state: typeof NetworkGraphState.State) => {\n return timed(\"NetworkGraph.read\", async () => {\n logger.verbose(\"Read indexes\", { userId: state.userId, networkId: state.networkId, showAll: state.showAll });\n\n // Shared projections for both the scoped and unscoped read paths.\n const projectMembership = (m: Awaited<ReturnType<typeof this.database.getNetworkMemberships>>[number]) => ({\n networkId: m.networkId,\n title: m.networkTitle,\n prompt: m.indexPrompt,\n autoAssign: m.autoAssign,\n isPersonal: m.isPersonal,\n joinedAt: m.joinedAt,\n });\n const projectOwned = (o: Awaited<ReturnType<typeof this.database.getOwnedIndexes>>[number]) => ({\n networkId: o.id,\n title: o.title,\n prompt: o.prompt,\n memberCount: o.memberCount,\n intentCount: o.intentCount,\n joinPolicy: o.permissions.joinPolicy,\n });\n\n try {\n const [allMemberships, ownedIndexes, publicIndexesResult] = await Promise.all([\n this.database.getNetworkMemberships(state.userId),\n this.database.getOwnedIndexes(state.userId),\n this.database.getPublicIndexesNotJoined(state.userId),\n ]);\n\n // If index-scoped and not showAll, return just that index plus the\n // user's personal index (their contacts). The personal index is part\n // of every scope — `computeAgentIndexScope` keeps it reachable for\n // network-bound agents, and a user clicked into a community-scoped\n // chat still owns their contact list — so surfacing it here keeps\n // tools that operate on the personal index (add_contact, list_contacts,\n // import_*_contacts) discoverable. Other community memberships are\n // still hidden, and `publicNetworks` is omitted.\n const scopeToCurrentIndex = state.networkId && !state.showAll;\n if (scopeToCurrentIndex) {\n const networkId = state.networkId!;\n const isMember = await this.database.isNetworkMember(networkId, state.userId);\n if (!isMember) {\n return {\n readResult: {\n memberOf: [],\n owns: [],\n stats: { memberOfCount: 0, ownsCount: 0, scopeNote: \"Network not found or you are not a member.\" },\n },\n };\n }\n const scopedMembership = allMemberships.find((m) => m.networkId === networkId);\n const personalMembership = scopedMembership?.isPersonal\n ? undefined\n : allMemberships.find((m) => m.isPersonal);\n const scopedOwned = ownedIndexes.find((o) => o.id === networkId);\n const personalOwned = personalMembership\n ? ownedIndexes.find((o) => o.id === personalMembership.networkId)\n : undefined;\n const memberOf = [\n ...(scopedMembership ? [projectMembership(scopedMembership)] : []),\n ...(personalMembership ? [projectMembership(personalMembership)] : []),\n ];\n const owns = [\n ...(scopedOwned ? [projectOwned(scopedOwned)] : []),\n ...(personalOwned ? [projectOwned(personalOwned)] : []),\n ];\n return {\n readResult: {\n memberOf,\n owns,\n stats: {\n memberOfCount: memberOf.length,\n ownsCount: owns.length,\n scopeNote: \"Showing current index and your personal index. Use showAll: true for all indexes.\",\n },\n },\n };\n }\n\n // Include public networks available to join\n const publicNetworks = publicIndexesResult.networks.map((idx) => ({\n networkId: idx.id,\n title: idx.title,\n prompt: idx.prompt,\n memberCount: idx.memberCount,\n owner: idx.owner,\n }));\n\n return {\n readResult: {\n memberOf: allMemberships.map(projectMembership),\n owns: ownedIndexes.map(projectOwned),\n publicNetworks,\n stats: { memberOfCount: allMemberships.length, ownsCount: ownedIndexes.length, publicNetworksCount: publicNetworks.length },\n },\n };\n } catch (err) {\n logger.error(\"Read indexes failed\", { error: err });\n return { error: \"Failed to fetch network information.\" };\n }\n });\n };\n\n /**\n * Create Node: Create a new index and add user as owner.\n */\n const createNode = async (state: typeof NetworkGraphState.State) => {\n return timed(\"NetworkGraph.create\", async () => {\n logger.verbose(\"Create index\", { userId: state.userId, createInput: state.createInput });\n\n if (!state.createInput?.title?.trim()) {\n return { mutationResult: { success: false, error: \"Title is required.\" } };\n }\n\n let createdIndexId: string | undefined;\n try {\n const index = await this.database.createNetwork({\n title: state.createInput.title.trim(),\n prompt: state.createInput.prompt?.trim() || undefined,\n imageUrl: state.createInput.imageUrl ?? undefined,\n joinPolicy: state.createInput.joinPolicy,\n });\n createdIndexId = index.id;\n\n const added = await this.database.addMemberToNetwork(index.id, state.userId, 'owner');\n if (!added.success) {\n logger.error(\"addMemberToNetwork failed; cleaning up orphaned network\", { networkId: index.id });\n try { await this.database.softDeleteNetwork(index.id); } catch {}\n return { mutationResult: { success: false, error: \"Failed to set you as owner. Network was not created.\" } };\n }\n\n return {\n mutationResult: {\n success: true,\n networkId: index.id,\n title: index.title,\n message: `Network \"${index.title}\" created. You are the owner.`,\n },\n };\n } catch (err) {\n logger.error(\"Create index failed\", { error: err });\n if (createdIndexId) {\n try { await this.database.softDeleteNetwork(createdIndexId); } catch {}\n }\n return {\n mutationResult: {\n success: false,\n error: err instanceof Error ? err.message : \"Failed to create network.\",\n },\n };\n }\n });\n };\n\n /**\n * Update Node: Update index settings (owner only).\n */\n const updateNode = async (state: typeof NetworkGraphState.State) => {\n return timed(\"NetworkGraph.update\", async () => {\n const networkId = state.networkId;\n logger.verbose(\"Update index\", { userId: state.userId, networkId, updateInput: state.updateInput });\n\n if (!networkId) {\n return { mutationResult: { success: false, error: \"networkId is required for update.\" } };\n }\n\n try {\n const isOwner = await this.database.isIndexOwner(networkId, state.userId);\n if (!isOwner) {\n return { mutationResult: { success: false, error: \"You can only modify networks you own.\" } };\n }\n\n await this.database.updateIndexSettings(networkId, state.userId, state.updateInput ?? {});\n\n return {\n mutationResult: {\n success: true,\n networkId,\n message: \"Network settings updated.\",\n },\n };\n } catch (err) {\n logger.error(\"Update index failed\", { error: err });\n return { mutationResult: { success: false, error: \"Failed to update network.\" } };\n }\n });\n };\n\n /**\n * Delete Node: Soft-delete an index (owner only, sole member).\n */\n const deleteNode = async (state: typeof NetworkGraphState.State) => {\n return timed(\"NetworkGraph.delete\", async () => {\n const networkId = state.networkId;\n logger.verbose(\"Delete index\", { userId: state.userId, networkId });\n\n if (!networkId) {\n return { mutationResult: { success: false, error: \"networkId is required for delete.\" } };\n }\n\n try {\n const isOwner = await this.database.isIndexOwner(networkId, state.userId);\n if (!isOwner) {\n return { mutationResult: { success: false, error: \"You can only delete networks you own.\" } };\n }\n\n const count = await this.database.getNetworkMemberCount(networkId);\n if (count > 1) {\n return { mutationResult: { success: false, error: \"Cannot delete network with other members. Remove members first.\" } };\n }\n\n await this.database.softDeleteNetwork(networkId);\n\n return {\n mutationResult: {\n success: true,\n networkId,\n message: \"Network deleted.\",\n },\n };\n } catch (err) {\n logger.error(\"Delete index failed\", { error: err });\n return { mutationResult: { success: false, error: \"Failed to delete network.\" } };\n }\n });\n };\n\n // --- CONDITIONAL ROUTING ---\n\n const routeByMode = (state: typeof NetworkGraphState.State): string => {\n switch (state.operationMode) {\n case 'create': return 'create';\n case 'read': return 'read';\n case 'update': return 'update';\n case 'delete': return 'delete_idx';\n default: return 'read';\n }\n };\n\n // --- GRAPH ASSEMBLY ---\n\n const workflow = new StateGraph(NetworkGraphState)\n .addNode(\"read\", readNode)\n .addNode(\"create\", createNode)\n .addNode(\"update\", updateNode)\n .addNode(\"delete_idx\", deleteNode)\n .addConditionalEdges(START, routeByMode, {\n read: \"read\",\n create: \"create\",\n update: \"update\",\n delete_idx: \"delete_idx\",\n })\n .addEdge(\"read\", END)\n .addEdge(\"create\", END)\n .addEdge(\"update\", END)\n .addEdge(\"delete_idx\", END);\n\n return workflow.compile();\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed.categorizer.d.ts","sourceRoot":"/","sources":["opportunity/feed/feed.categorizer.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAyB3D,MAAM,MAAM,oBAAoB,GAAG;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,EAAE,mBAAmB,EAAE,CAAC;CACjC,CAAC;
|
|
1
|
+
{"version":3,"file":"feed.categorizer.d.ts","sourceRoot":"/","sources":["opportunity/feed/feed.categorizer.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAyB3D,MAAM,MAAM,oBAAoB,GAAG;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,EAAE,mBAAmB,EAAE,CAAC;CACjC,CAAC;AAgFF,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,KAAK,CAAiD;;IAO9D;;OAEG;IAEG,UAAU,CAAC,KAAK,EAAE,oBAAoB,EAAE,GAAG,OAAO,CAAC,iBAAiB,CAAC;CAoD5E"}
|
|
@@ -35,6 +35,19 @@ const categorizationSchema = z.object({
|
|
|
35
35
|
});
|
|
36
36
|
const UNCATEGORIZED_SECTION_ID = 'uncategorized';
|
|
37
37
|
const UNCATEGORIZED_SECTION_TITLE = 'UNCATEGORIZED OPPORTUNITIES';
|
|
38
|
+
/** Single-section fallback grouping every card under one generic heading. */
|
|
39
|
+
function buildFallbackResult(cards) {
|
|
40
|
+
return {
|
|
41
|
+
sections: [
|
|
42
|
+
{
|
|
43
|
+
id: 'opportunities',
|
|
44
|
+
title: 'OPPORTUNITIES',
|
|
45
|
+
iconName: DEFAULT_HOME_SECTION_ICON,
|
|
46
|
+
itemIndices: cards.map((c) => c.index),
|
|
47
|
+
},
|
|
48
|
+
],
|
|
49
|
+
};
|
|
50
|
+
}
|
|
38
51
|
/**
|
|
39
52
|
* Build card summaries for the categorizer prompt.
|
|
40
53
|
*/
|
|
@@ -123,16 +136,7 @@ Rules:
|
|
|
123
136
|
const parsed = categorizationSchema.safeParse(result);
|
|
124
137
|
if (!parsed.success) {
|
|
125
138
|
logger.warn('HomeCategorizer parse failed', { error: parsed.error });
|
|
126
|
-
return
|
|
127
|
-
sections: [
|
|
128
|
-
{
|
|
129
|
-
id: 'opportunities',
|
|
130
|
-
title: 'OPPORTUNITIES',
|
|
131
|
-
iconName: DEFAULT_HOME_SECTION_ICON,
|
|
132
|
-
itemIndices: cards.map((c) => c.index),
|
|
133
|
-
},
|
|
134
|
-
],
|
|
135
|
-
};
|
|
139
|
+
return buildFallbackResult(cards);
|
|
136
140
|
}
|
|
137
141
|
const sections = parsed.data.sections.map((s) => ({
|
|
138
142
|
id: s.id,
|
|
@@ -147,16 +151,7 @@ Rules:
|
|
|
147
151
|
catch (e) {
|
|
148
152
|
const err = e instanceof Error ? { message: e.message, name: e.name } : String(e);
|
|
149
153
|
logger.error('HomeCategorizer categorize failed', { error: err });
|
|
150
|
-
return
|
|
151
|
-
sections: [
|
|
152
|
-
{
|
|
153
|
-
id: 'opportunities',
|
|
154
|
-
title: 'OPPORTUNITIES',
|
|
155
|
-
iconName: DEFAULT_HOME_SECTION_ICON,
|
|
156
|
-
itemIndices: cards.map((c) => c.index),
|
|
157
|
-
},
|
|
158
|
-
],
|
|
159
|
-
};
|
|
154
|
+
return buildFallbackResult(cards);
|
|
160
155
|
}
|
|
161
156
|
}
|
|
162
157
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed.categorizer.js","sourceRoot":"/","sources":["opportunity/feed/feed.categorizer.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;;;;;;;;;;AAGH,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO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B,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;YACjE,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,CAAC;QAC1C,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,MAAM,GAAG,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YAClF,MAAM,CAAC,KAAK,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;YAClE,OAAO;gBACL,QAAQ,EAAE;oBACR;wBACE,EAAE,EAAE,eAAe;wBACnB,KAAK,EAAE,eAAe;wBACtB,QAAQ,EAAE,yBAAyB;wBACnC,WAAW,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;qBACvC;iBACF;aACF,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AAtEO;IADL,KAAK,EAAE;;;;sDAsEP","sourcesContent":["/**\n * Home Categorizer Agent\n *\n * Takes a list of presenter-produced opportunity cards and returns dynamic sections\n * with CTA-style titles and Lucide icon names. Used by the home graph after\n * generateCardText.\n */\n\nimport type { ChatOpenAI } from \"@langchain/openai\";\nimport { HumanMessage, SystemMessage } from '@langchain/core/messages';\nimport { z } from 'zod';\n\nimport type { HomeSectionProposal } from './feed.state.js';\nimport { getIconNamesForPrompt, DEFAULT_HOME_SECTION_ICON } from '../../shared/ui/lucide.icon-catalog.js';\nimport { protocolLogger } from '../../shared/observability/protocol.logger.js';\nimport { Timed } from \"../../shared/observability/performance.js\";\nimport { createModel } from \"../../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger('HomeCategorizer');\n\nconst categorizationSchema = z.object({\n sections: z.array(\n z.object({\n id: z.string().describe('Short kebab-case id for the section'),\n title: z\n .string()\n .describe(\n 'Call-to-action style section heading (e.g. REACH OUT NOW, YOUR MOVE, CONNECTIONS WAITING FOR YOU)'\n ),\n subtitle: z.string().nullable().describe('Optional one-line description; use null if none'),\n iconName: z.string().describe('Lucide icon name in kebab-case from the allowed list'),\n itemIndices: z.array(z.number()).describe('Indices of cards in this section (0-based)'),\n })\n ),\n});\n\nexport type CategorizerInputItem = {\n index: number;\n headline?: string;\n mainText: string;\n name: string;\n viewerRole?: string;\n opportunityStatus?: string;\n};\n\nexport type CategorizerResult = {\n sections: HomeSectionProposal[];\n};\n\nconst UNCATEGORIZED_SECTION_ID = 'uncategorized';\nconst UNCATEGORIZED_SECTION_TITLE = 'UNCATEGORIZED OPPORTUNITIES';\n\n/**\n * Build card summaries for the categorizer prompt.\n */\nfunction buildCardSummaries(cards: CategorizerInputItem[]): string {\n return cards\n .map((c) => {\n const role = c.viewerRole ?? 'party';\n const status = c.opportunityStatus ?? 'pending';\n return `[${c.index}] role=${role}; status=${status}; ${c.headline ?? c.mainText.slice(0, 60)}... (${c.name})`;\n })\n .join('\\n');\n}\n\nfunction reconcileSections(sections: HomeSectionProposal[], maxIndex: number): HomeSectionProposal[] {\n const assigned = new Set<number>();\n\n const normalizedSections = sections.map((section) => {\n const uniqueIndices = Array.from(\n new Set(section.itemIndices.filter((index) => index >= 0 && index <= maxIndex))\n ).sort((a, b) => a - b);\n\n for (const index of uniqueIndices) {\n assigned.add(index);\n }\n\n return {\n ...section,\n itemIndices: uniqueIndices,\n };\n });\n\n const missingIndices: number[] = [];\n for (let index = 0; index <= maxIndex; index += 1) {\n if (!assigned.has(index)) {\n missingIndices.push(index);\n }\n }\n\n if (missingIndices.length === 0) {\n return normalizedSections;\n }\n\n const fallbackSection = normalizedSections.find((section) => section.id === UNCATEGORIZED_SECTION_ID);\n if (fallbackSection) {\n fallbackSection.itemIndices = Array.from(\n new Set([...fallbackSection.itemIndices, ...missingIndices])\n ).sort((a, b) => a - b);\n return normalizedSections;\n }\n\n return [\n ...normalizedSections,\n {\n id: UNCATEGORIZED_SECTION_ID,\n title: UNCATEGORIZED_SECTION_TITLE,\n iconName: DEFAULT_HOME_SECTION_ICON,\n itemIndices: missingIndices,\n },\n ];\n}\n\nexport class HomeCategorizerAgent {\n private model: ReturnType<ChatOpenAI['withStructuredOutput']>;\n\n constructor() {\n const llm = createModel(\"homeCategorizer\");\n this.model = llm.withStructuredOutput(categorizationSchema, { name: 'home_sections' });\n }\n\n /**\n * Categorize presenter-produced cards into 1–5 sections with CTA-style titles and icons.\n */\n @Timed()\n async categorize(cards: CategorizerInputItem[]): Promise<CategorizerResult> {\n if (cards.length === 0) {\n return { sections: [] };\n }\n const iconList = getIconNamesForPrompt();\n const cardSummaries = buildCardSummaries(cards);\n const maxIndex = cards.length - 1;\n\n const systemPrompt = `You are organizing connection opportunities into dynamic sections for a user's home feed.\n\nGiven a list of opportunity cards (each with index, headline/summary, and name), group them into 1–5 sections.\n\nEach section must have:\n- id: short kebab-case identifier (e.g. waiting-for-action, your-perspective, connector)\n- title: CALL-TO-ACTION style section heading in uppercase. Write as an action or invitation, not a neutral label. Examples: REACH OUT NOW, YOUR MOVE, CONNECTIONS WAITING FOR YOU, INTROS READY TO SEND, PEOPLE YOU SHOULD MEET\n- subtitle: optional one-line description\n- iconName: exactly ONE icon from this list (use the name as-is): ${iconList}\n- itemIndices: array of card indices that belong in this section (each index 0 to ${maxIndex} at most once)\n\nRules:\n- Use only icon names from the list above.\n- Every card index must appear in exactly one section.\n- Section titles must read as calls-to-action or invitations, not passive labels.\n- If a card has role=introducer and status=pending, prioritize grouping those cards under a connector curation section with a CTA title like \"YOU'RE THE CONNECTOR THEY NEED\", \"MAKE THE INTRO\", or \"DECIDE IF IT'S A GOOD MATCH\".`;\n\n const userContent = `Cards to categorize:\\n${cardSummaries}\\n\\nOutput sections with id, title (CTA-style), subtitle (optional), iconName, and itemIndices.`;\n\n try {\n const result = await invokeWithAbortSignal(this.model, [\n new SystemMessage(systemPrompt),\n new HumanMessage(userContent),\n ]);\n const parsed = categorizationSchema.safeParse(result);\n if (!parsed.success) {\n logger.warn('HomeCategorizer parse failed', { error: parsed.error });\n return {\n sections: [\n {\n id: 'opportunities',\n title: 'OPPORTUNITIES',\n iconName: DEFAULT_HOME_SECTION_ICON,\n itemIndices: cards.map((c) => c.index),\n },\n ],\n };\n }\n const sections: HomeSectionProposal[] = parsed.data.sections.map((s) => ({\n id: s.id,\n title: s.title,\n subtitle: s.subtitle ?? undefined,\n iconName: s.iconName,\n itemIndices: s.itemIndices.filter((i) => i >= 0 && i <= maxIndex),\n }));\n const reconciledSections = reconcileSections(sections, maxIndex);\n return { sections: reconciledSections };\n } catch (e) {\n const err = e instanceof Error ? { message: e.message, name: e.name } : String(e);\n logger.error('HomeCategorizer categorize failed', { error: err });\n return {\n sections: [\n {\n id: 'opportunities',\n title: 'OPPORTUNITIES',\n iconName: DEFAULT_HOME_SECTION_ICON,\n itemIndices: cards.map((c) => c.index),\n },\n ],\n };\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"feed.categorizer.js","sourceRoot":"/","sources":["opportunity/feed/feed.categorizer.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;;;;;;;;;;AAGH,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,qBAAqB,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AAC1G,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAC/E,OAAO,EAAE,KAAK,EAAE,MAAM,2CAA2C,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAE3E,MAAM,MAAM,GAAG,cAAc,CAAC,iBAAiB,CAAC,CAAC;AAEjD,MAA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C,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YAClF,MAAM,CAAC,KAAK,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;YAClE,OAAO,mBAAmB,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;IACH,CAAC;CACF;AApDO;IADL,KAAK,EAAE;;;;sDAoDP","sourcesContent":["/**\n * Home Categorizer Agent\n *\n * Takes a list of presenter-produced opportunity cards and returns dynamic sections\n * with CTA-style titles and Lucide icon names. Used by the home graph after\n * generateCardText.\n */\n\nimport type { ChatOpenAI } from \"@langchain/openai\";\nimport { HumanMessage, SystemMessage } from '@langchain/core/messages';\nimport { z } from 'zod';\n\nimport type { HomeSectionProposal } from './feed.state.js';\nimport { getIconNamesForPrompt, DEFAULT_HOME_SECTION_ICON } from '../../shared/ui/lucide.icon-catalog.js';\nimport { protocolLogger } from '../../shared/observability/protocol.logger.js';\nimport { Timed } from \"../../shared/observability/performance.js\";\nimport { createModel } from \"../../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger('HomeCategorizer');\n\nconst categorizationSchema = z.object({\n sections: z.array(\n z.object({\n id: z.string().describe('Short kebab-case id for the section'),\n title: z\n .string()\n .describe(\n 'Call-to-action style section heading (e.g. REACH OUT NOW, YOUR MOVE, CONNECTIONS WAITING FOR YOU)'\n ),\n subtitle: z.string().nullable().describe('Optional one-line description; use null if none'),\n iconName: z.string().describe('Lucide icon name in kebab-case from the allowed list'),\n itemIndices: z.array(z.number()).describe('Indices of cards in this section (0-based)'),\n })\n ),\n});\n\nexport type CategorizerInputItem = {\n index: number;\n headline?: string;\n mainText: string;\n name: string;\n viewerRole?: string;\n opportunityStatus?: string;\n};\n\nexport type CategorizerResult = {\n sections: HomeSectionProposal[];\n};\n\nconst UNCATEGORIZED_SECTION_ID = 'uncategorized';\nconst UNCATEGORIZED_SECTION_TITLE = 'UNCATEGORIZED OPPORTUNITIES';\n\n/** Single-section fallback grouping every card under one generic heading. */\nfunction buildFallbackResult(cards: CategorizerInputItem[]): CategorizerResult {\n return {\n sections: [\n {\n id: 'opportunities',\n title: 'OPPORTUNITIES',\n iconName: DEFAULT_HOME_SECTION_ICON,\n itemIndices: cards.map((c) => c.index),\n },\n ],\n };\n}\n\n/**\n * Build card summaries for the categorizer prompt.\n */\nfunction buildCardSummaries(cards: CategorizerInputItem[]): string {\n return cards\n .map((c) => {\n const role = c.viewerRole ?? 'party';\n const status = c.opportunityStatus ?? 'pending';\n return `[${c.index}] role=${role}; status=${status}; ${c.headline ?? c.mainText.slice(0, 60)}... (${c.name})`;\n })\n .join('\\n');\n}\n\nfunction reconcileSections(sections: HomeSectionProposal[], maxIndex: number): HomeSectionProposal[] {\n const assigned = new Set<number>();\n\n const normalizedSections = sections.map((section) => {\n const uniqueIndices = Array.from(\n new Set(section.itemIndices.filter((index) => index >= 0 && index <= maxIndex))\n ).sort((a, b) => a - b);\n\n for (const index of uniqueIndices) {\n assigned.add(index);\n }\n\n return {\n ...section,\n itemIndices: uniqueIndices,\n };\n });\n\n const missingIndices: number[] = [];\n for (let index = 0; index <= maxIndex; index += 1) {\n if (!assigned.has(index)) {\n missingIndices.push(index);\n }\n }\n\n if (missingIndices.length === 0) {\n return normalizedSections;\n }\n\n const fallbackSection = normalizedSections.find((section) => section.id === UNCATEGORIZED_SECTION_ID);\n if (fallbackSection) {\n fallbackSection.itemIndices = Array.from(\n new Set([...fallbackSection.itemIndices, ...missingIndices])\n ).sort((a, b) => a - b);\n return normalizedSections;\n }\n\n return [\n ...normalizedSections,\n {\n id: UNCATEGORIZED_SECTION_ID,\n title: UNCATEGORIZED_SECTION_TITLE,\n iconName: DEFAULT_HOME_SECTION_ICON,\n itemIndices: missingIndices,\n },\n ];\n}\n\nexport class HomeCategorizerAgent {\n private model: ReturnType<ChatOpenAI['withStructuredOutput']>;\n\n constructor() {\n const llm = createModel(\"homeCategorizer\");\n this.model = llm.withStructuredOutput(categorizationSchema, { name: 'home_sections' });\n }\n\n /**\n * Categorize presenter-produced cards into 1–5 sections with CTA-style titles and icons.\n */\n @Timed()\n async categorize(cards: CategorizerInputItem[]): Promise<CategorizerResult> {\n if (cards.length === 0) {\n return { sections: [] };\n }\n const iconList = getIconNamesForPrompt();\n const cardSummaries = buildCardSummaries(cards);\n const maxIndex = cards.length - 1;\n\n const systemPrompt = `You are organizing connection opportunities into dynamic sections for a user's home feed.\n\nGiven a list of opportunity cards (each with index, headline/summary, and name), group them into 1–5 sections.\n\nEach section must have:\n- id: short kebab-case identifier (e.g. waiting-for-action, your-perspective, connector)\n- title: CALL-TO-ACTION style section heading in uppercase. Write as an action or invitation, not a neutral label. Examples: REACH OUT NOW, YOUR MOVE, CONNECTIONS WAITING FOR YOU, INTROS READY TO SEND, PEOPLE YOU SHOULD MEET\n- subtitle: optional one-line description\n- iconName: exactly ONE icon from this list (use the name as-is): ${iconList}\n- itemIndices: array of card indices that belong in this section (each index 0 to ${maxIndex} at most once)\n\nRules:\n- Use only icon names from the list above.\n- Every card index must appear in exactly one section.\n- Section titles must read as calls-to-action or invitations, not passive labels.\n- If a card has role=introducer and status=pending, prioritize grouping those cards under a connector curation section with a CTA title like \"YOU'RE THE CONNECTOR THEY NEED\", \"MAKE THE INTRO\", or \"DECIDE IF IT'S A GOOD MATCH\".`;\n\n const userContent = `Cards to categorize:\\n${cardSummaries}\\n\\nOutput sections with id, title (CTA-style), subtitle (optional), iconName, and itemIndices.`;\n\n try {\n const result = await invokeWithAbortSignal(this.model, [\n new SystemMessage(systemPrompt),\n new HumanMessage(userContent),\n ]);\n const parsed = categorizationSchema.safeParse(result);\n if (!parsed.success) {\n logger.warn('HomeCategorizer parse failed', { error: parsed.error });\n return buildFallbackResult(cards);\n }\n const sections: HomeSectionProposal[] = parsed.data.sections.map((s) => ({\n id: s.id,\n title: s.title,\n subtitle: s.subtitle ?? undefined,\n iconName: s.iconName,\n itemIndices: s.itemIndices.filter((i) => i >= 0 && i <= maxIndex),\n }));\n const reconciledSections = reconcileSections(sections, maxIndex);\n return { sections: reconciledSections };\n } catch (e) {\n const err = e instanceof Error ? { message: e.message, name: e.name } : String(e);\n logger.error('HomeCategorizer categorize failed', { error: err });\n return buildFallbackResult(cards);\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed.graph.d.ts","sourceRoot":"/","sources":["opportunity/feed/feed.graph.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,+CAA+C,CAAC;AAC1G,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4CAA4C,CAAC;AACnF,OAAO,EAAkB,KAAK,YAAY,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAwB,MAAM,iBAAiB,CAAC;AAOtI,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAOzE,8HAA8H;AAC9H,KAAK,WAAW,GAAG,iBAAiB,CAAC;AAErC,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,8GAA8G;IAC9G,QAAQ,CAAC,EAAE,iBAAiB,EAAE,CAAC;CAChC,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IAClC,QAAQ,EAAE,WAAW,EAAE,CAAC;IACxB,IAAI,EAAE;QAAE,kBAAkB,EAAE,MAAM,CAAC;QAAC,aAAa,EAAE,MAAM,CAAA;KAAE,CAAC;IAC5D,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,kFAAkF;AAClF,eAAO,MAAM,qBAAqB,EAAE,iBAAiB,EAA0B,CAAC;AAgBhF,0HAA0H;AAC1H,eAAO,MAAM,wBAAwB,EAAE,iBA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AC,KAAK;gBAApC,QAAQ,EAAE,WAAW,EAAU,KAAK,EAAE,gBAAgB;IAE1E,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgiBZ"}
|
|
@@ -42,6 +42,12 @@ const MAX_ITEMS_PER_SECTION = 20;
|
|
|
42
42
|
const PRESENTATION_CONCURRENCY = 50;
|
|
43
43
|
const MAX_REASONING_SNIPPET_LENGTH = 240;
|
|
44
44
|
const HOME_CACHE_TTL = 24 * 60 * 60; // 24 hours in seconds
|
|
45
|
+
/** Redis key for the categorizer cache, derived from the user and the ordered opportunity-id set. */
|
|
46
|
+
function buildCategorizerCacheKey(userId, cards) {
|
|
47
|
+
const oppIds = cards.map((c) => c.opportunityId).join(',');
|
|
48
|
+
const hash = createHash('sha256').update(oppIds).digest('hex').slice(0, 16);
|
|
49
|
+
return `home:categories:${userId}:${hash}`;
|
|
50
|
+
}
|
|
45
51
|
/**
|
|
46
52
|
* Strip leading narrator name from remark when the UI already prepends "Name: " to the chip.
|
|
47
53
|
* Avoids duplication like "Yankı Ekin Yüksel: Yankı Ekin Yüksel introduced you two..."
|
|
@@ -486,11 +492,7 @@ export class HomeGraphFactory {
|
|
|
486
492
|
return { categoryCacheHit: false };
|
|
487
493
|
}
|
|
488
494
|
try {
|
|
489
|
-
const
|
|
490
|
-
.map((c) => c.opportunityId)
|
|
491
|
-
.join(',');
|
|
492
|
-
const hash = createHash('sha256').update(oppIds).digest('hex').slice(0, 16);
|
|
493
|
-
const key = `home:categories:${state.userId}:${hash}`;
|
|
495
|
+
const key = buildCategorizerCacheKey(state.userId, state.cards);
|
|
494
496
|
const cached = await this.cache.get(key);
|
|
495
497
|
if (cached) {
|
|
496
498
|
logger.verbose('[HomeGraph:checkCategorizerCache] cache hit');
|
|
@@ -548,11 +550,7 @@ export class HomeGraphFactory {
|
|
|
548
550
|
return {};
|
|
549
551
|
}
|
|
550
552
|
try {
|
|
551
|
-
const
|
|
552
|
-
.map((c) => c.opportunityId)
|
|
553
|
-
.join(',');
|
|
554
|
-
const hash = createHash('sha256').update(oppIds).digest('hex').slice(0, 16);
|
|
555
|
-
const key = `home:categories:${state.userId}:${hash}`;
|
|
553
|
+
const key = buildCategorizerCacheKey(state.userId, state.cards);
|
|
556
554
|
await this.cache.set(key, state.sectionProposals, { ttl: HOME_CACHE_TTL });
|
|
557
555
|
logger.verbose('[HomeGraph:cacheCategorizerResults] cached', {
|
|
558
556
|
sectionCount: state.sectionProposals.length,
|