@indexnetwork/protocol 4.0.0-rc.289.1 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/chat/chat.prompt.js +21 -21
  2. package/dist/chat/chat.prompt.js.map +1 -1
  3. package/dist/chat/chat.prompt.modules.js +8 -8
  4. package/dist/chat/chat.prompt.modules.js.map +1 -1
  5. package/dist/contact/contact.tools.js +3 -3
  6. package/dist/contact/contact.tools.js.map +1 -1
  7. package/dist/enrichment/enrichment.graph.js +1 -1
  8. package/dist/enrichment/enrichment.graph.js.map +1 -1
  9. package/dist/enrichment/enrichment.tools.js +47 -47
  10. package/dist/enrichment/enrichment.tools.js.map +1 -1
  11. package/dist/intent/intent.graph.d.ts.map +1 -1
  12. package/dist/intent/intent.graph.js +7 -6
  13. package/dist/intent/intent.graph.js.map +1 -1
  14. package/dist/intent/intent.tools.js +2 -2
  15. package/dist/intent/intent.tools.js.map +1 -1
  16. package/dist/mcp/mcp.server.d.ts +1 -1
  17. package/dist/mcp/mcp.server.d.ts.map +1 -1
  18. package/dist/mcp/mcp.server.js +12 -4
  19. package/dist/mcp/mcp.server.js.map +1 -1
  20. package/dist/negotiation/negotiation.tools.js +1 -1
  21. package/dist/negotiation/negotiation.tools.js.map +1 -1
  22. package/dist/network/network.tools.js +2 -2
  23. package/dist/network/network.tools.js.map +1 -1
  24. package/dist/opportunity/opportunity.graph.d.ts +8 -8
  25. package/dist/opportunity/opportunity.graph.js +7 -7
  26. package/dist/opportunity/opportunity.graph.js.map +1 -1
  27. package/dist/opportunity/opportunity.state.d.ts +2 -2
  28. package/dist/opportunity/opportunity.state.d.ts.map +1 -1
  29. package/dist/opportunity/opportunity.state.js +1 -1
  30. package/dist/opportunity/opportunity.state.js.map +1 -1
  31. package/dist/opportunity/opportunity.tools.js +8 -8
  32. package/dist/opportunity/opportunity.tools.js.map +1 -1
  33. package/dist/shared/agent/tool.registry.d.ts.map +1 -1
  34. package/dist/shared/agent/tool.registry.js +26 -0
  35. package/dist/shared/agent/tool.registry.js.map +1 -1
  36. package/dist/shared/agent/tool.runtime.d.ts.map +1 -1
  37. package/dist/shared/agent/tool.runtime.js +6 -0
  38. package/dist/shared/agent/tool.runtime.js.map +1 -1
  39. package/dist/shared/agent/utility.tools.js +5 -5
  40. package/dist/shared/agent/utility.tools.js.map +1 -1
  41. package/dist/shared/interfaces/database.interface.d.ts +2 -2
  42. package/dist/shared/interfaces/database.interface.js.map +1 -1
  43. package/dist/shared/interfaces/enrichment-run.interface.d.ts +1 -1
  44. package/dist/shared/interfaces/enrichment-run.interface.d.ts.map +1 -1
  45. package/dist/shared/interfaces/enrichment-run.interface.js.map +1 -1
  46. package/package.json +1 -1
@@ -12,7 +12,7 @@ const logger = protocolLogger("IntentGraphFactory");
12
12
  const MAX_PERMISSIBLE_ENTROPY = 0.75;
13
13
  const MIN_CLEAR_INTENT_SCORE = 40;
14
14
  const GENERIC_JOB_PHRASE = /\b(?:a|any|some)\s+job\b/i;
15
- const inferRoleFromProfileText = (text) => {
15
+ const inferRoleFromContextText = (text) => {
16
16
  const normalized = text.toLowerCase();
17
17
  if (/\b(engineer|developer)\b/.test(normalized))
18
18
  return "software engineering";
@@ -30,14 +30,15 @@ const inferRoleFromProfileText = (text) => {
30
30
  };
31
31
  /**
32
32
  * Derive a job-role qualifier from the user's global user_context paragraph
33
- * (profile-replacing identity text). Role is inferred from the free text; the
34
- * old structured skills/interests extraction is gone with the profile fields.
33
+ * (the identity text that replaced the legacy profile projection). Role is
34
+ * inferred from the free text; the old structured skills/interests extraction
35
+ * is gone with the removed profile fields.
35
36
  */
36
37
  const buildJobQualifierFromContext = (contextText) => {
37
- const roleHint = inferRoleFromProfileText(contextText ?? "");
38
+ const roleHint = inferRoleFromContextText(contextText ?? "");
38
39
  return roleHint ? `${roleHint} role` : null;
39
40
  };
40
- const enrichVagueIntentWithProfile = (description, userContext) => {
41
+ const enrichVagueIntentWithContext = (description, userContext) => {
41
42
  const trimmed = description?.trim();
42
43
  if (!trimmed)
43
44
  return description;
@@ -211,7 +212,7 @@ export class IntentGraphFactory {
211
212
  // Role-hint enrichment for vague job intents reads the global
212
213
  // user_context paragraph instead of the structured profile fields.
213
214
  const roleHintContext = (await this.database.getUserContext(state.userId, null))?.text ?? '';
214
- const enrichedDescription = enrichVagueIntentWithProfile(description, roleHintContext);
215
+ const enrichedDescription = enrichVagueIntentWithContext(description, roleHintContext);
215
216
  if (enrichedDescription !== description) {
216
217
  logger.verbose("Enriched vague intent using profile context", {
217
218
  before: description,
@@ -1 +1 @@
1
- {"version":3,"file":"intent.graph.js","sourceRoot":"/","sources":["intent/intent.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAmC,MAAM,mBAAmB,CAAC;AACtF,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAGvE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAI5E,MAAM,MAAM,GAAG,cAAc,CAAC,oBAAoB,CAAC,CAAC;AACpD,MAAM,uBAAuB,GAAG,IAAI,CAAC;AACrC,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAClC,MAAM,kBAAkB,GAAG,2BAA2B,CAAC;AAEvD,MAAM,wBAAwB,GAAG,CAAC,IAAY,EAAiB,EAAE;IAC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,CAAC,MAAM,EAAE,cAAc,EAAE;YAC3C,KAAK,EAAE,OAAO;YACd,SAAS,EAAE,WAAW;YACtB,UAAU,EAAE,YAAY;YACxB,OAAO,EAAE,GAAG;SACb,CAAC;YAEF,gCAAgC;aAC/B,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;YAEtB,uEAAuE;aACtE,mBAAmB,CAAC,WAAW,EAAE,qBAAqB,EAAE;YACvD,YAAY,EAAE,cAAc;YAC5B,UAAU,EAAE,YAAY;YACxB,OAAO,EAAE,GAAG;SACb,CAAC;YAEF,kFAAkF;aACjF,mBAAmB,CAAC,cAAc,EAAE,CAAC,KAAoC,EAAE,EAAE;YAC5E,IAAI,KAAK,CAAC,aAAa,KAAK,SAAS,EAAE,CAAC;gBACtC,MAAM,CAAC,OAAO,CAAC,qEAAqE,CAAC,CAAC;gBACtF,OAAO,SAAS,CAAC;YACnB,CAAC;YACD,OAAO,YAAY,CAAC;QACtB,CAAC,EAAE;YACD,UAAU,EAAE,YAAY;YACxB,OAAO,EAAE,GAAG;SACb,CAAC;YAEF,yCAAyC;aACxC,OAAO,CAAC,YAAY,EAAE,UAAU,CAAC;YAElC,6BAA6B;aAC5B,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\";\nimport { IntentGraphState, VerifiedIntent, ExecutionResult } from \"./intent.state.js\";\nimport { ExplicitIntentInferrer } from \"./intent.inferrer.js\";\nimport { SemanticVerifier } from \"./intent.verifier.js\";\nimport { DEFAULT_SPECIFICITY_WARNING } from \"./intent.specificity.js\";\nimport { IntentReconciler } from \"./intent.reconciler.js\";\nimport { IntentGraphDatabase } from \"../shared/interfaces/database.interface.js\";\nimport { getAbortSignalConfig } from \"../shared/agent/model-signal.js\";\nimport type { EmbeddingGenerator } from \"../shared/interfaces/embedder.interface.js\";\nimport type { IntentGraphQueue } from \"../shared/interfaces/queue.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 type { QuestionerEnqueueFn } from \"../questioner/questioner.types.js\";\n\nconst logger = protocolLogger(\"IntentGraphFactory\");\nconst MAX_PERMISSIBLE_ENTROPY = 0.75;\nconst MIN_CLEAR_INTENT_SCORE = 40;\nconst GENERIC_JOB_PHRASE = /\\b(?:a|any|some)\\s+job\\b/i;\n\nconst inferRoleFromProfileText = (text: string): string | null => {\n const normalized = text.toLowerCase();\n if (/\\b(engineer|developer)\\b/.test(normalized)) return \"software engineering\";\n if (/\\b(designer|ux|ui)\\b/.test(normalized)) return \"product design\";\n if (/\\b(marketing|marketer|growth)\\b/.test(normalized)) return \"marketing\";\n if (/\\b(product manager|product)\\b/.test(normalized)) return \"product management\";\n if (/\\b(data scientist|machine learning|ml|ai)\\b/.test(normalized)) return \"AI/ML\";\n if (/\\b(sales|account executive|business development)\\b/.test(normalized)) return \"sales\";\n return null;\n};\n\n/**\n * Derive a job-role qualifier from the user's global user_context paragraph\n * (profile-replacing identity text). Role is inferred from the free text; the\n * old structured skills/interests extraction is gone with the profile fields.\n */\nconst buildJobQualifierFromContext = (contextText: string): string | null => {\n const roleHint = inferRoleFromProfileText(contextText ?? \"\");\n return roleHint ? `${roleHint} role` : null;\n};\n\nconst enrichVagueIntentWithProfile = (description: string, userContext: string): string => {\n const trimmed = description?.trim();\n if (!trimmed) return description;\n\n const isGenericJobRequest =\n GENERIC_JOB_PHRASE.test(trimmed) ||\n /\\b(?:find|get|look(?:ing)?\\s+for|want)\\s+(?:to\\s+)?(?:find\\s+)?job\\b/i.test(trimmed);\n if (!isGenericJobRequest) return description;\n\n const qualifier = buildJobQualifierFromContext(userContext);\n if (!qualifier) return description;\n\n const enriched = trimmed\n .replace(/\\ba job\\b/i, `a ${qualifier}`)\n .replace(/\\bjob\\b/i, `${qualifier}`)\n .replace(/\\s{2,}/g, \" \")\n .trim();\n\n return enriched.length > 0 ? enriched : description;\n};\n\nconst isVague = (description: string, entropy: number, clarity: number): boolean => {\n if (GENERIC_JOB_PHRASE.test(description)) return true;\n if (entropy > MAX_PERMISSIBLE_ENTROPY) return true;\n if (clarity < MIN_CLEAR_INTENT_SCORE) return true;\n return false;\n};\n\nconst getSpecificityWarning = (verdict: { specificity_warning?: string | null }): string => {\n const warning = verdict.specificity_warning?.trim();\n return warning && warning.length > 0 ? warning : DEFAULT_SPECIFICITY_WARNING;\n};\n\nconst toSpeechActType = (classification?: string): \"COMMISSIVE\" | \"DIRECTIVE\" | null => {\n if (classification === \"COMMISSIVE\" || classification === \"DIRECTIVE\") return classification;\n return null;\n};\n\n/**\n * Factory class to build and compile the Intent Processing Graph.\n */\nexport class IntentGraphFactory {\n constructor(\n private database: IntentGraphDatabase,\n private embedder?: EmbeddingGenerator,\n private intentQueue?: IntentGraphQueue,\n private questionerEnqueue?: QuestionerEnqueueFn,\n ) { }\n\n public createGraph() {\n // Instantiate Agents (Nodes)\n const inferrer = new ExplicitIntentInferrer();\n const verifier = new SemanticVerifier();\n const reconciler = new IntentReconciler();\n\n // --- NODE DEFINITIONS ---\n\n /**\n * Node 0: Prep\n * Always fetches ALL of the user's active intents from the DB via getActiveIntents(userId).\n * This ensures reconciliation can detect duplicates and modifications globally,\n * regardless of index scope.\n */\n const prepNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.prep\", async () => {\n logger.verbose(\"Starting preparation phase\", {\n operationMode: state.operationMode,\n hasContent: !!state.inputContent,\n targetIntentIds: state.targetIntentIds,\n networkId: state.networkId,\n });\n\n // Gate: write operations require an existing profile\n if (state.operationMode !== 'read') {\n const profile = await this.database.getProfile(state.userId);\n if (!profile) {\n const msg = \"You need to create a profile before creating intents. Please set up your profile first.\";\n logger.error(\"Prep failed: no profile for user\", { userId: state.userId });\n return { error: msg };\n }\n }\n\n const activeIntents = await this.database.getActiveIntents(state.userId);\n const formattedActiveIntents = activeIntents\n .map(i => `ID: ${i.id}, Description: ${i.payload}, Summary: ${i.summary || 'N/A'}`)\n .join('\\n') || \"No active intents.\";\n\n logger.verbose(\"Fetched active intents\", {\n count: activeIntents.length,\n operationMode: state.operationMode\n });\n\n return {\n activeIntents: formattedActiveIntents,\n trace: [{\n node: \"prep\",\n detail: `Fetched ${activeIntents.length} active intent(s)`,\n }],\n };\n });\n };\n\n /**\n * Node 1: Inference\n * Extracts intents from raw content.\n * Phase 4: Uses operation mode to control behavior and determine if node should execute.\n * Phase 5: Passes conversation context for anaphoric resolution.\n */\n const inferenceNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.inference\", async () => {\n logger.verbose(\"Starting inference\", {\n operationMode: state.operationMode,\n hasContent: !!state.inputContent,\n contentPreview: state.inputContent?.substring(0, 50),\n hasConversationContext: !!state.conversationContext,\n conversationMessagesCount: state.conversationContext?.length || 0\n });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Phase 4: Control profile fallback based on operation mode\n // Only allow for create operations without explicit content\n const allowProfileFallback = state.operationMode === 'create' && !state.inputContent;\n\n // Cast operationMode: 'read' and 'propose' map to 'create' for the inferrer\n // (inference node is never called in read mode; propose behaves like create for inference)\n const inferrerMode = (state.operationMode === 'read' || state.operationMode === 'propose') ? 'create' : state.operationMode;\n const _traceEmitterInferrer = requestContext.getStore()?.traceEmitter;\n const inferrerStart = Date.now();\n _traceEmitterInferrer?.({ type: \"agent_start\", name: \"intent-inferrer\" });\n const result = await inferrer.invoke(\n state.inputContent || null,\n state.userProfile,\n {\n allowProfileFallback,\n operationMode: inferrerMode,\n conversationContext: state.conversationContext // Phase 5: Pass conversation history\n }\n );\n agentTimingsAccum.push({ name: 'intent.inferrer', durationMs: Date.now() - inferrerStart });\n _traceEmitterInferrer?.({ type: \"agent_end\", name: \"intent-inferrer\", durationMs: Date.now() - inferrerStart, summary: result.intents.length > 0 ? `Extracted ${result.intents.length} intent(s)` : \"intent-inferrer completed\" });\n\n logger.verbose(\"Inference complete\", {\n inferredCount: result.intents.length,\n operationMode: state.operationMode\n });\n\n const descriptions = result.intents.map(i => i.description).slice(0, 3);\n const truncated = result.intents.length > 3 ? `... +${result.intents.length - 3} more` : \"\";\n\n return {\n inferredIntents: result.intents,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"inference\",\n detail: result.intents.length === 0\n ? \"No intents extracted\"\n : `Extracted ${result.intents.length}: ${descriptions.map(d => `\"${d.slice(0, 50)}${d.length > 50 ? '...' : ''}\"`).join(\", \")}${truncated}`,\n }],\n };\n });\n };\n\n /**\n * Node 2: Verification (Map-Reduce / Parallel)\n * Verifies each inferred intent in parallel.\n * Phase 4: Can be skipped for delete operations and updates with no new intents.\n */\n const verificationNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.verification\", async () => {\n const intents = state.inferredIntents;\n\n logger.verbose(\"Starting verification\", {\n operationMode: state.operationMode,\n intentCount: intents.length\n });\n\n if (intents.length === 0) {\n logger.verbose(\"No intents to verify\");\n return { verifiedIntents: [], agentTimings: [] };\n }\n\n logger.verbose(`Verifying ${intents.length} intents in parallel...`);\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Parallel Execution\n const verificationResults = await Promise.all(\n intents.map(async (intent): Promise<VerifiedIntent | null> => {\n try {\n let description = intent.description;\n const _traceEmitterVerifier = requestContext.getStore()?.traceEmitter;\n const verifierStart1 = Date.now();\n _traceEmitterVerifier?.({ type: \"agent_start\", name: \"intent-verifier\" });\n let verdict = await verifier.invoke(description, state.userProfile);\n agentTimingsAccum.push({ name: 'intent.verifier', durationMs: Date.now() - verifierStart1 });\n _traceEmitterVerifier?.({ type: \"agent_end\", name: \"intent-verifier\", durationMs: Date.now() - verifierStart1, summary: `Verified: ${verdict.classification}` });\n\n if (isVague(description, verdict.semantic_entropy, verdict.felicity_scores.clarity)) {\n // Role-hint enrichment for vague job intents reads the global\n // user_context paragraph instead of the structured profile fields.\n const roleHintContext = (await this.database.getUserContext(state.userId, null))?.text ?? '';\n const enrichedDescription = enrichVagueIntentWithProfile(description, roleHintContext);\n if (enrichedDescription !== description) {\n logger.verbose(\"Enriched vague intent using profile context\", {\n before: description,\n after: enrichedDescription,\n });\n const _traceEmitterVerifier2 = requestContext.getStore()?.traceEmitter;\n const verifierStart2 = Date.now();\n _traceEmitterVerifier2?.({ type: \"agent_start\", name: \"intent-verifier\" });\n const enrichedVerdict = await verifier.invoke(enrichedDescription, state.userProfile);\n agentTimingsAccum.push({ name: 'intent.verifier', durationMs: Date.now() - verifierStart2 });\n _traceEmitterVerifier2?.({ type: \"agent_end\", name: \"intent-verifier\", durationMs: Date.now() - verifierStart2, summary: `Verified (enriched): ${enrichedVerdict.classification}` });\n const becameClear =\n enrichedVerdict.semantic_entropy < verdict.semantic_entropy ||\n enrichedVerdict.felicity_scores.clarity > verdict.felicity_scores.clarity;\n if (becameClear) {\n description = enrichedDescription;\n verdict = enrichedVerdict;\n }\n }\n }\n\n // Filter Logic: Must be a Commissive, Directive, or Declaration\n const VALID_TYPES = ['COMMISSIVE', 'DIRECTIVE', 'DECLARATION'];\n if (!VALID_TYPES.includes(verdict.classification)) {\n logger.warn(`Dropping intent: \"${description}\" (Type: ${verdict.classification})`);\n return null;\n }\n\n if (isVague(description, verdict.semantic_entropy, verdict.felicity_scores.clarity)) {\n logger.warn(`Dropping vague intent after verification: \"${description}\"`, {\n entropy: verdict.semantic_entropy,\n clarity: verdict.felicity_scores.clarity,\n });\n return null;\n }\n\n if (state.operationMode !== 'propose' && verdict.referential_breadth === 'broad') {\n logger.warn(`Dropping broad attributive intent before persistence: \"${description}\"`, {\n referentialBreadth: verdict.referential_breadth,\n missingSelectionalConstraints: verdict.missing_selectional_constraints,\n warning: getSpecificityWarning(verdict),\n });\n return null;\n }\n\n // Calculate Score\n const score = Math.min(\n verdict.felicity_scores.authority,\n verdict.felicity_scores.sincerity,\n verdict.felicity_scores.clarity\n );\n\n // Return enriched intent\n return {\n ...intent,\n description,\n verification: verdict,\n score\n };\n } catch (e) {\n logger.error(`Error verifying intent: ${intent.description}`, { error: e });\n return null;\n }\n })\n );\n\n // Filter out nulls\n const verified = verificationResults.filter((i): i is VerifiedIntent => i !== null);\n logger.verbose(`Verification complete`, {\n passed: verified.length,\n total: intents.length,\n operationMode: state.operationMode\n });\n\n // Build trace entries with Felicity scores for each verified intent\n const traceEntries = verified.map(v => {\n const fs = v.verification?.felicity_scores;\n const entropy = v.verification?.semantic_entropy;\n const classification = v.verification?.classification;\n const referentialBreadth = v.verification?.referential_breadth;\n return {\n node: \"verification\",\n detail: `\"${v.description.slice(0, 40)}${v.description.length > 40 ? '...' : ''}\" → ${classification}${referentialBreadth ? ` (${referentialBreadth} referential breadth)` : ''}`,\n data: fs ? {\n clarity: fs.clarity,\n authority: fs.authority,\n sincerity: fs.sincerity,\n entropy: entropy != null ? Math.round(entropy * 100) / 100 : undefined,\n referentialBreadth,\n missingSelectionalConstraints: v.verification?.missing_selectional_constraints,\n specificityWarning: v.verification?.specificity_warning ?? undefined,\n classification,\n score: v.score,\n } : undefined,\n };\n });\n\n // Add summary trace if some intents were filtered out\n const dropped = intents.length - verified.length;\n if (dropped > 0) {\n traceEntries.unshift({\n node: \"verification\",\n detail: `Verified ${verified.length}/${intents.length} (${dropped} filtered as invalid)`,\n data: undefined,\n });\n } else if (verified.length > 0) {\n traceEntries.unshift({\n node: \"verification\",\n detail: `Verified ${verified.length} intent(s)`,\n data: undefined,\n });\n }\n\n return { verifiedIntents: verified, agentTimings: agentTimingsAccum, trace: traceEntries };\n });\n };\n\n /**\n * Node 3: Reconciliation\n * Decides on final actions (Create, Update, Expire).\n * Phase 4: Handles delete operations directly without LLM reconciliation.\n */\n const reconciliationNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.reconciliation\", async () => {\n logger.verbose(\"Starting reconciliation\", {\n operationMode: state.operationMode,\n verifiedIntentCount: state.verifiedIntents.length,\n targetIntentIds: state.targetIntentIds\n });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Phase 4: Handle delete operations directly\n if (state.operationMode === 'delete') {\n if (!state.targetIntentIds || state.targetIntentIds.length === 0) {\n logger.warn(\"Delete mode with no target IDs\");\n return {\n actions: [],\n agentTimings: agentTimingsAccum,\n trace: [{ node: \"reconciler\", detail: \"Delete mode with no target IDs\" }],\n };\n }\n\n logger.verbose(\"Delete mode - generating expire actions\", {\n targetIds: state.targetIntentIds\n });\n\n const actions = state.targetIntentIds.map(id => ({\n type: 'expire' as const,\n id,\n reasoning: 'User requested deletion'\n }));\n\n return {\n actions,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"reconciler\",\n detail: `Actions: expire=${actions.length}`,\n }],\n };\n }\n\n // Standard reconciliation for create/update operations\n const candidates = state.verifiedIntents;\n if (candidates.length === 0) {\n logger.verbose(\"No verified intents to reconcile\");\n return {\n actions: [],\n agentTimings: agentTimingsAccum,\n trace: [{ node: \"reconciler\", detail: \"No intents to reconcile\" }],\n };\n }\n\n // Format candidates for the Reconciler Prompt\n const formattedCandidates = candidates.map(c =>\n `- [${c.type.toUpperCase()}] \"${c.description}\" (Confidence: ${c.confidence}, Score: ${c.score})\\n` +\n ` Reasoning: ${c.reasoning}\\n` +\n ` Verification: ${c.verification?.classification} (Flags: ${c.verification?.flags.join(', ') || 'None'})`\n ).join('\\n');\n\n logger.verbose(\"Invoking reconciler agent\", {\n candidateCount: candidates.length,\n operationMode: state.operationMode\n });\n\n const _traceEmitterReconciler = requestContext.getStore()?.traceEmitter;\n const reconcilerStart = Date.now();\n _traceEmitterReconciler?.({ type: \"agent_start\", name: \"intent-reconciler\" });\n const result = await reconciler.invoke(formattedCandidates, state.activeIntents);\n agentTimingsAccum.push({ name: 'intent.reconciler', durationMs: Date.now() - reconcilerStart });\n _traceEmitterReconciler?.({ type: \"agent_end\", name: \"intent-reconciler\", durationMs: Date.now() - reconcilerStart, summary: `Reconciled ${result.actions.length} action(s)` });\n\n logger.verbose(\"Reconciliation complete\", {\n actionCount: result.actions.length,\n operationMode: state.operationMode\n });\n\n // Count actions by type\n const counts = { create: 0, update: 0, expire: 0 };\n for (const a of result.actions) {\n if (a.type in counts) counts[a.type as keyof typeof counts]++;\n }\n\n return {\n actions: result.actions,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"reconciler\",\n detail: `Actions: create=${counts.create}, update=${counts.update}, expire=${counts.expire}`,\n }],\n };\n });\n };\n\n /** Strip URLs and \"More details at [url]\" from intent payloads before persisting. */\n const sanitizePayload = (payload: string): string => {\n if (!payload || typeof payload !== \"string\") return payload;\n const out = payload\n .replace(/\\s*More details at\\s*:?\\s*https?:\\/\\/[^\\s\"'<>)\\]]+/gi, \"\")\n .replace(/\\s*See\\s+https?:\\/\\/[^\\s\"'<>)\\]]+\\s+for\\s+more[^.]*\\.?/gi, \"\")\n .replace(/https?:\\/\\/[^\\s\"'<>)\\]]+/g, \"\")\n .replace(/\\s{2,}/g, \" \")\n .trim();\n return out.replace(/[.,;]\\s*$/, \"\").trim() || payload;\n };\n\n /**\n * Generate a flat embedding for an intent payload, swallowing failures so\n * persistence can continue without an embedding. `intentId` is logging-only\n * (present for updates, absent for creates).\n */\n const generateIntentEmbedding = async (\n sanitizedPayload: string,\n intentId?: string,\n ): Promise<number[] | undefined> => {\n if (!this.embedder) return undefined;\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n const flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for intent\", {\n ...(intentId ? { intentId } : {}),\n dimensions: flatEmbedding?.length,\n });\n return flatEmbedding;\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent (continuing without)\", {\n ...(intentId ? { intentId } : {}),\n error: embErr,\n });\n return undefined;\n }\n };\n\n /**\n * Node 4: Executor\n * Executes reconciler actions against the database.\n */\n const executorNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.executor\", async () => {\n const actions = state.actions;\n if (!actions || actions.length === 0) {\n return { executionResults: [] };\n }\n\n logger.verbose(`Executing ${actions.length} actions...`);\n const results: ExecutionResult[] = [];\n const verifiedIntentByPayload = new Map<string, VerifiedIntent>();\n for (const verifiedIntent of state.verifiedIntents) {\n verifiedIntentByPayload.set(verifiedIntent.description, verifiedIntent);\n verifiedIntentByPayload.set(sanitizePayload(verifiedIntent.description), verifiedIntent);\n }\n\n for (const action of actions) {\n const actionType = action.type.toLowerCase() as 'create' | 'update' | 'expire';\n try {\n if (actionType === 'create') {\n const createAction = action as {\n payload: string;\n score: number | null;\n semanticEntropy?: number | null;\n referentialAnchor?: string | null;\n intentMode?: 'REFERENTIAL' | 'ATTRIBUTIVE' | null;\n };\n const sanitizedPayload = sanitizePayload(createAction.payload);\n const matchedVerifiedIntent =\n verifiedIntentByPayload.get(createAction.payload) ||\n verifiedIntentByPayload.get(sanitizedPayload);\n\n // Generate embedding for the intent payload\n const flatEmbedding = await generateIntentEmbedding(sanitizedPayload);\n\n const created = await this.database.createIntent({\n userId: state.userId,\n payload: sanitizedPayload,\n confidence: createAction.score ? createAction.score / 100 : 1.0,\n inferenceType: 'explicit',\n sourceType: 'discovery_form',\n embedding: flatEmbedding,\n semanticEntropy:\n createAction.semanticEntropy ??\n matchedVerifiedIntent?.verification?.semantic_entropy ??\n null,\n referentialAnchor:\n createAction.referentialAnchor ??\n matchedVerifiedIntent?.verification?.referential_anchor ??\n null,\n felicityAuthority: matchedVerifiedIntent?.verification?.felicity_scores.authority ?? null,\n felicitySincerity: matchedVerifiedIntent?.verification?.felicity_scores.sincerity ?? null,\n felicityClarity: matchedVerifiedIntent?.verification?.felicity_scores.clarity ?? null,\n intentMode: createAction.intentMode ?? null,\n speechActType: toSpeechActType(matchedVerifiedIntent?.verification?.classification),\n });\n\n results.push({ actionType: 'create', success: true, intentId: created.id, payload: sanitizedPayload });\n logger.verbose(`Created intent: ${created.id}`);\n\n this.intentQueue?.addGenerateHydeJob({\n intentId: created.id,\n userId: state.userId,\n ...(state.networkId ? { networkScopeId: state.networkId } : {}),\n }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE job', { intentId: created.id, error: err })\n );\n\n if (this.questionerEnqueue) {\n const userContext = (await this.database.getUserContext(state.userId, null))?.text ?? '';\n this.questionerEnqueue({\n mode: 'intent',\n userId: state.userId,\n sourceType: 'intent',\n sourceId: created.id,\n context: {\n intentId: created.id,\n payload: sanitizedPayload,\n userContext,\n },\n }).catch((err) =>\n logger.error('Failed to enqueue intent question generation', { intentId: created.id, error: err })\n );\n }\n\n } else if (actionType === 'update') {\n const updateAction = action as {\n id: string;\n payload: string;\n intentMode?: 'REFERENTIAL' | 'ATTRIBUTIVE' | null;\n };\n const sanitizedPayload = sanitizePayload(updateAction.payload);\n const matchedVerifiedIntent =\n verifiedIntentByPayload.get(updateAction.payload) ||\n verifiedIntentByPayload.get(sanitizedPayload);\n\n // Regenerate embedding for the updated payload\n const flatEmbedding = await generateIntentEmbedding(sanitizedPayload, updateAction.id);\n\n const updated = await this.database.updateIntent(updateAction.id, {\n payload: sanitizedPayload,\n embedding: flatEmbedding,\n semanticEntropy:\n matchedVerifiedIntent?.verification?.semantic_entropy ??\n null,\n referentialAnchor:\n matchedVerifiedIntent?.verification?.referential_anchor ??\n null,\n felicityAuthority: matchedVerifiedIntent?.verification?.felicity_scores.authority ?? null,\n felicitySincerity: matchedVerifiedIntent?.verification?.felicity_scores.sincerity ?? null,\n felicityClarity: matchedVerifiedIntent?.verification?.felicity_scores.clarity ?? null,\n intentMode: updateAction.intentMode ?? null,\n speechActType: toSpeechActType(matchedVerifiedIntent?.verification?.classification),\n });\n results.push({\n actionType: 'update',\n success: !!updated,\n intentId: updateAction.id,\n payload: sanitizedPayload,\n error: updated ? undefined : 'Intent not found'\n });\n logger.verbose(`Updated intent: ${updateAction.id}`);\n if (updated) {\n this.intentQueue?.addGenerateHydeJob({\n intentId: updateAction.id,\n userId: state.userId,\n ...(state.networkId ? { networkScopeId: state.networkId } : {}),\n }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE job', { intentId: updateAction.id, error: err })\n );\n }\n\n } else if (actionType === 'expire') {\n const expireAction = action as { id: string };\n const result = await this.database.archiveIntent(expireAction.id);\n results.push({\n actionType: 'expire',\n success: result.success,\n intentId: expireAction.id,\n error: result.error\n });\n logger.verbose(`Archived intent: ${expireAction.id}`);\n if (result.success) {\n this.intentQueue?.addDeleteHydeJob({ intentId: expireAction.id }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE delete job', { intentId: expireAction.id, error: err })\n );\n }\n }\n } catch (error) {\n logger.error(`Failed to execute ${action.type}:`, { error });\n results.push({\n actionType,\n success: false,\n intentId: 'id' in action ? action.id : undefined,\n error: error instanceof Error ? error.message : 'Unknown error'\n });\n }\n }\n\n return { executionResults: results };\n });\n };\n\n // --- QUERY NODE (Read Mode) ---\n\n /**\n * Node: Query\n * Fast-path read node — fetches intents from DB based on scope.\n * Handles: global user intents, index-scoped (all or filtered by user).\n * No LLM calls; no inference/verification/reconciliation.\n */\n const queryNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.query\", async () => {\n logger.verbose(\"Starting query (read mode)\", {\n userId: state.userId,\n networkId: state.networkId,\n queryUserId: state.queryUserId,\n allUserIntents: state.allUserIntents,\n });\n\n try {\n // Scope-aware default: caller's intents across all reachable indexes.\n // Triggered when the tool layer passed indexScope and did not pick a\n // specific networkId or queryUserId — i.e. \"my intents\" in a chat\n // where the agent's reach is more than one index.\n if (\n !state.queryUserId &&\n !state.networkId &&\n state.indexScope &&\n state.indexScope.length > 0\n ) {\n const intents = await this.database.getActiveIntentsAcrossIndexes(\n state.userId,\n state.indexScope,\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"You don't have any active intents yet. Share what you're looking for.\",\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n })),\n },\n };\n }\n\n // When allUserIntents is true, ignore index scope and return all\n const effectiveIndexId = state.allUserIntents ? undefined : state.networkId;\n\n if (effectiveIndexId) {\n // Verify membership\n const isMember = await this.database.isNetworkMember(effectiveIndexId, state.userId);\n if (!isMember) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"Index not found or you are not a member.\",\n },\n };\n }\n\n // Index-scoped read\n if (!state.queryUserId) {\n // All intents in the index (any member can see)\n const intents = await this.database.getNetworkIntentsForMember(\n effectiveIndexId,\n state.userId,\n { limit: 50, offset: 0 }\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"No intents in this index yet.\",\n networkId: effectiveIndexId,\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n networkId: effectiveIndexId,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n userId: i.userId,\n userName: i.userName,\n })),\n },\n };\n }\n\n // Specific user's intents in the index\n const effectiveUserId = state.queryUserId;\n const intents = await this.database.getIntentsInIndexForMember(\n effectiveUserId,\n effectiveIndexId\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message:\n effectiveUserId === state.userId\n ? \"You don't have any intents in this index yet.\"\n : \"No intents for that user in this index.\",\n networkId: effectiveIndexId,\n },\n };\n }\n const user = await this.database.getUser(effectiveUserId);\n const userName = user?.name ?? null;\n return {\n readResult: {\n count: intents.length,\n networkId: effectiveIndexId,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n userId: effectiveUserId,\n userName,\n })),\n },\n };\n }\n\n // Global (no index scope): return user's own active intents\n const intents = await this.database.getActiveIntents(state.userId);\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message:\n \"You don't have any active intents yet. Share what you're looking for.\",\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n })),\n },\n };\n } catch (err) {\n logger.error(\"Query node failed\", { error: err });\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"Failed to fetch intents. Please try again.\",\n },\n };\n }\n });\n };\n\n // --- CONDITIONAL ROUTING FUNCTIONS ---\n\n /**\n * After prep: read mode → query; otherwise decide inference vs reconciler by operation mode.\n */\n const afterPrepRoute = (state: typeof IntentGraphState.State): string => {\n if (state.error) {\n logger.warn('Prep failed with error, short-circuiting to END', { error: state.error });\n return '__end__';\n }\n if (state.operationMode === 'read') {\n logger.verbose('Read mode - routing to query (fast path)');\n return 'query';\n }\n return shouldRunInference(state);\n };\n \n /**\n * Determines if inference should run based on operation mode.\n * Delete operations skip inference entirely and go straight to reconciliation.\n */\n const shouldRunInference = (state: typeof IntentGraphState.State): string => {\n if (state.operationMode === 'delete') {\n logger.verbose('Delete mode - skipping inference, routing to reconciliation');\n return 'reconciler';\n }\n \n logger.verbose('Running inference', {\n operationMode: state.operationMode\n });\n return 'inference';\n };\n \n /**\n * Determines if verification should run based on operation mode and inferred intents.\n * Skips verification for:\n * - Operations with no inferred intents\n * - Can be extended to skip for update operations with no new intents\n */\n const shouldRunVerification = (state: typeof IntentGraphState.State): string => {\n if (state.inferredIntents.length === 0) {\n if (state.operationMode === 'propose') {\n logger.verbose('Propose mode with no inferred intents - exiting early');\n return '__end__';\n }\n logger.verbose('No intents to verify - skipping verification, routing to reconciliation');\n return 'reconciler';\n }\n \n if (state.operationMode === 'update') {\n logger.verbose('Update mode with new intents - running verification');\n return 'verification';\n }\n \n if (state.operationMode === 'create') {\n logger.verbose('Create mode - running verification');\n return 'verification';\n }\n \n // Default to verification for safety\n logger.verbose('Default routing to verification');\n return 'verification';\n };\n\n // --- GRAPH ASSEMBLY WITH CONDITIONAL EDGES (PHASE 4) ---\n\n const workflow = new StateGraph(IntentGraphState)\n .addNode(\"prep\", prepNode)\n .addNode(\"query\", queryNode)\n .addNode(\"inference\", inferenceNode)\n .addNode(\"verification\", verificationNode)\n .addNode(\"reconciler\", reconciliationNode)\n .addNode(\"executor\", executorNode)\n\n // Flow paths:\n // - READ: prep → query → END (fast path, no LLM calls)\n // - CREATE: prep → inference → verification → reconciler → executor → END\n // - UPDATE: prep → inference → reconciliation → executor → END (skips verification if no new intents)\n // - DELETE: prep → reconciliation → executor → END (skips inference and verification)\n // - PROPOSE: prep → inference → verification → END (no reconciliation/execution, no DB writes)\n .addEdge(START, \"prep\")\n \n // After prep: read mode → query; else inference or reconciler\n .addConditionalEdges(\"prep\", afterPrepRoute, {\n query: \"query\",\n inference: \"inference\",\n reconciler: \"reconciler\",\n __end__: END,\n })\n\n // Query (read mode) always ends\n .addEdge(\"query\", END)\n \n // After inference: decide if we need verification (skip if no intents)\n .addConditionalEdges(\"inference\", shouldRunVerification, {\n verification: \"verification\",\n reconciler: \"reconciler\",\n __end__: END,\n })\n \n // After verification: propose mode exits early; others continue to reconciliation\n .addConditionalEdges(\"verification\", (state: typeof IntentGraphState.State) => {\n if (state.operationMode === 'propose') {\n logger.verbose('Propose mode - stopping after verification, skipping reconciliation');\n return '__end__';\n }\n return 'reconciler';\n }, {\n reconciler: \"reconciler\",\n __end__: END,\n })\n \n // Reconciliation always goes to executor\n .addEdge(\"reconciler\", \"executor\")\n \n // Executor is always the end\n .addEdge(\"executor\", END);\n\n return workflow.compile();\n }\n}\n"]}
1
+ {"version":3,"file":"intent.graph.js","sourceRoot":"/","sources":["intent/intent.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAmC,MAAM,mBAAmB,CAAC;AACtF,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,2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UAAU,CAAC;YAElC,6BAA6B;aAC5B,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\";\nimport { IntentGraphState, VerifiedIntent, ExecutionResult } from \"./intent.state.js\";\nimport { ExplicitIntentInferrer } from \"./intent.inferrer.js\";\nimport { SemanticVerifier } from \"./intent.verifier.js\";\nimport { DEFAULT_SPECIFICITY_WARNING } from \"./intent.specificity.js\";\nimport { IntentReconciler } from \"./intent.reconciler.js\";\nimport { IntentGraphDatabase } from \"../shared/interfaces/database.interface.js\";\nimport { getAbortSignalConfig } from \"../shared/agent/model-signal.js\";\nimport type { EmbeddingGenerator } from \"../shared/interfaces/embedder.interface.js\";\nimport type { IntentGraphQueue } from \"../shared/interfaces/queue.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 type { QuestionerEnqueueFn } from \"../questioner/questioner.types.js\";\n\nconst logger = protocolLogger(\"IntentGraphFactory\");\nconst MAX_PERMISSIBLE_ENTROPY = 0.75;\nconst MIN_CLEAR_INTENT_SCORE = 40;\nconst GENERIC_JOB_PHRASE = /\\b(?:a|any|some)\\s+job\\b/i;\n\nconst inferRoleFromContextText = (text: string): string | null => {\n const normalized = text.toLowerCase();\n if (/\\b(engineer|developer)\\b/.test(normalized)) return \"software engineering\";\n if (/\\b(designer|ux|ui)\\b/.test(normalized)) return \"product design\";\n if (/\\b(marketing|marketer|growth)\\b/.test(normalized)) return \"marketing\";\n if (/\\b(product manager|product)\\b/.test(normalized)) return \"product management\";\n if (/\\b(data scientist|machine learning|ml|ai)\\b/.test(normalized)) return \"AI/ML\";\n if (/\\b(sales|account executive|business development)\\b/.test(normalized)) return \"sales\";\n return null;\n};\n\n/**\n * Derive a job-role qualifier from the user's global user_context paragraph\n * (the identity text that replaced the legacy profile projection). Role is\n * inferred from the free text; the old structured skills/interests extraction\n * is gone with the removed profile fields.\n */\nconst buildJobQualifierFromContext = (contextText: string): string | null => {\n const roleHint = inferRoleFromContextText(contextText ?? \"\");\n return roleHint ? `${roleHint} role` : null;\n};\n\nconst enrichVagueIntentWithContext = (description: string, userContext: string): string => {\n const trimmed = description?.trim();\n if (!trimmed) return description;\n\n const isGenericJobRequest =\n GENERIC_JOB_PHRASE.test(trimmed) ||\n /\\b(?:find|get|look(?:ing)?\\s+for|want)\\s+(?:to\\s+)?(?:find\\s+)?job\\b/i.test(trimmed);\n if (!isGenericJobRequest) return description;\n\n const qualifier = buildJobQualifierFromContext(userContext);\n if (!qualifier) return description;\n\n const enriched = trimmed\n .replace(/\\ba job\\b/i, `a ${qualifier}`)\n .replace(/\\bjob\\b/i, `${qualifier}`)\n .replace(/\\s{2,}/g, \" \")\n .trim();\n\n return enriched.length > 0 ? enriched : description;\n};\n\nconst isVague = (description: string, entropy: number, clarity: number): boolean => {\n if (GENERIC_JOB_PHRASE.test(description)) return true;\n if (entropy > MAX_PERMISSIBLE_ENTROPY) return true;\n if (clarity < MIN_CLEAR_INTENT_SCORE) return true;\n return false;\n};\n\nconst getSpecificityWarning = (verdict: { specificity_warning?: string | null }): string => {\n const warning = verdict.specificity_warning?.trim();\n return warning && warning.length > 0 ? warning : DEFAULT_SPECIFICITY_WARNING;\n};\n\nconst toSpeechActType = (classification?: string): \"COMMISSIVE\" | \"DIRECTIVE\" | null => {\n if (classification === \"COMMISSIVE\" || classification === \"DIRECTIVE\") return classification;\n return null;\n};\n\n/**\n * Factory class to build and compile the Intent Processing Graph.\n */\nexport class IntentGraphFactory {\n constructor(\n private database: IntentGraphDatabase,\n private embedder?: EmbeddingGenerator,\n private intentQueue?: IntentGraphQueue,\n private questionerEnqueue?: QuestionerEnqueueFn,\n ) { }\n\n public createGraph() {\n // Instantiate Agents (Nodes)\n const inferrer = new ExplicitIntentInferrer();\n const verifier = new SemanticVerifier();\n const reconciler = new IntentReconciler();\n\n // --- NODE DEFINITIONS ---\n\n /**\n * Node 0: Prep\n * Always fetches ALL of the user's active intents from the DB via getActiveIntents(userId).\n * This ensures reconciliation can detect duplicates and modifications globally,\n * regardless of index scope.\n */\n const prepNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.prep\", async () => {\n logger.verbose(\"Starting preparation phase\", {\n operationMode: state.operationMode,\n hasContent: !!state.inputContent,\n targetIntentIds: state.targetIntentIds,\n networkId: state.networkId,\n });\n\n // Gate: write operations require an existing profile\n if (state.operationMode !== 'read') {\n const profile = await this.database.getProfile(state.userId);\n if (!profile) {\n const msg = \"You need to create a profile before creating intents. Please set up your profile first.\";\n logger.error(\"Prep failed: no profile for user\", { userId: state.userId });\n return { error: msg };\n }\n }\n\n const activeIntents = await this.database.getActiveIntents(state.userId);\n const formattedActiveIntents = activeIntents\n .map(i => `ID: ${i.id}, Description: ${i.payload}, Summary: ${i.summary || 'N/A'}`)\n .join('\\n') || \"No active intents.\";\n\n logger.verbose(\"Fetched active intents\", {\n count: activeIntents.length,\n operationMode: state.operationMode\n });\n\n return {\n activeIntents: formattedActiveIntents,\n trace: [{\n node: \"prep\",\n detail: `Fetched ${activeIntents.length} active intent(s)`,\n }],\n };\n });\n };\n\n /**\n * Node 1: Inference\n * Extracts intents from raw content.\n * Phase 4: Uses operation mode to control behavior and determine if node should execute.\n * Phase 5: Passes conversation context for anaphoric resolution.\n */\n const inferenceNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.inference\", async () => {\n logger.verbose(\"Starting inference\", {\n operationMode: state.operationMode,\n hasContent: !!state.inputContent,\n contentPreview: state.inputContent?.substring(0, 50),\n hasConversationContext: !!state.conversationContext,\n conversationMessagesCount: state.conversationContext?.length || 0\n });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Phase 4: Control profile fallback based on operation mode\n // Only allow for create operations without explicit content\n const allowProfileFallback = state.operationMode === 'create' && !state.inputContent;\n\n // Cast operationMode: 'read' and 'propose' map to 'create' for the inferrer\n // (inference node is never called in read mode; propose behaves like create for inference)\n const inferrerMode = (state.operationMode === 'read' || state.operationMode === 'propose') ? 'create' : state.operationMode;\n const _traceEmitterInferrer = requestContext.getStore()?.traceEmitter;\n const inferrerStart = Date.now();\n _traceEmitterInferrer?.({ type: \"agent_start\", name: \"intent-inferrer\" });\n const result = await inferrer.invoke(\n state.inputContent || null,\n state.userProfile,\n {\n allowProfileFallback,\n operationMode: inferrerMode,\n conversationContext: state.conversationContext // Phase 5: Pass conversation history\n }\n );\n agentTimingsAccum.push({ name: 'intent.inferrer', durationMs: Date.now() - inferrerStart });\n _traceEmitterInferrer?.({ type: \"agent_end\", name: \"intent-inferrer\", durationMs: Date.now() - inferrerStart, summary: result.intents.length > 0 ? `Extracted ${result.intents.length} intent(s)` : \"intent-inferrer completed\" });\n\n logger.verbose(\"Inference complete\", {\n inferredCount: result.intents.length,\n operationMode: state.operationMode\n });\n\n const descriptions = result.intents.map(i => i.description).slice(0, 3);\n const truncated = result.intents.length > 3 ? `... +${result.intents.length - 3} more` : \"\";\n\n return {\n inferredIntents: result.intents,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"inference\",\n detail: result.intents.length === 0\n ? \"No intents extracted\"\n : `Extracted ${result.intents.length}: ${descriptions.map(d => `\"${d.slice(0, 50)}${d.length > 50 ? '...' : ''}\"`).join(\", \")}${truncated}`,\n }],\n };\n });\n };\n\n /**\n * Node 2: Verification (Map-Reduce / Parallel)\n * Verifies each inferred intent in parallel.\n * Phase 4: Can be skipped for delete operations and updates with no new intents.\n */\n const verificationNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.verification\", async () => {\n const intents = state.inferredIntents;\n\n logger.verbose(\"Starting verification\", {\n operationMode: state.operationMode,\n intentCount: intents.length\n });\n\n if (intents.length === 0) {\n logger.verbose(\"No intents to verify\");\n return { verifiedIntents: [], agentTimings: [] };\n }\n\n logger.verbose(`Verifying ${intents.length} intents in parallel...`);\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Parallel Execution\n const verificationResults = await Promise.all(\n intents.map(async (intent): Promise<VerifiedIntent | null> => {\n try {\n let description = intent.description;\n const _traceEmitterVerifier = requestContext.getStore()?.traceEmitter;\n const verifierStart1 = Date.now();\n _traceEmitterVerifier?.({ type: \"agent_start\", name: \"intent-verifier\" });\n let verdict = await verifier.invoke(description, state.userProfile);\n agentTimingsAccum.push({ name: 'intent.verifier', durationMs: Date.now() - verifierStart1 });\n _traceEmitterVerifier?.({ type: \"agent_end\", name: \"intent-verifier\", durationMs: Date.now() - verifierStart1, summary: `Verified: ${verdict.classification}` });\n\n if (isVague(description, verdict.semantic_entropy, verdict.felicity_scores.clarity)) {\n // Role-hint enrichment for vague job intents reads the global\n // user_context paragraph instead of the structured profile fields.\n const roleHintContext = (await this.database.getUserContext(state.userId, null))?.text ?? '';\n const enrichedDescription = enrichVagueIntentWithContext(description, roleHintContext);\n if (enrichedDescription !== description) {\n logger.verbose(\"Enriched vague intent using profile context\", {\n before: description,\n after: enrichedDescription,\n });\n const _traceEmitterVerifier2 = requestContext.getStore()?.traceEmitter;\n const verifierStart2 = Date.now();\n _traceEmitterVerifier2?.({ type: \"agent_start\", name: \"intent-verifier\" });\n const enrichedVerdict = await verifier.invoke(enrichedDescription, state.userProfile);\n agentTimingsAccum.push({ name: 'intent.verifier', durationMs: Date.now() - verifierStart2 });\n _traceEmitterVerifier2?.({ type: \"agent_end\", name: \"intent-verifier\", durationMs: Date.now() - verifierStart2, summary: `Verified (enriched): ${enrichedVerdict.classification}` });\n const becameClear =\n enrichedVerdict.semantic_entropy < verdict.semantic_entropy ||\n enrichedVerdict.felicity_scores.clarity > verdict.felicity_scores.clarity;\n if (becameClear) {\n description = enrichedDescription;\n verdict = enrichedVerdict;\n }\n }\n }\n\n // Filter Logic: Must be a Commissive, Directive, or Declaration\n const VALID_TYPES = ['COMMISSIVE', 'DIRECTIVE', 'DECLARATION'];\n if (!VALID_TYPES.includes(verdict.classification)) {\n logger.warn(`Dropping intent: \"${description}\" (Type: ${verdict.classification})`);\n return null;\n }\n\n if (isVague(description, verdict.semantic_entropy, verdict.felicity_scores.clarity)) {\n logger.warn(`Dropping vague intent after verification: \"${description}\"`, {\n entropy: verdict.semantic_entropy,\n clarity: verdict.felicity_scores.clarity,\n });\n return null;\n }\n\n if (state.operationMode !== 'propose' && verdict.referential_breadth === 'broad') {\n logger.warn(`Dropping broad attributive intent before persistence: \"${description}\"`, {\n referentialBreadth: verdict.referential_breadth,\n missingSelectionalConstraints: verdict.missing_selectional_constraints,\n warning: getSpecificityWarning(verdict),\n });\n return null;\n }\n\n // Calculate Score\n const score = Math.min(\n verdict.felicity_scores.authority,\n verdict.felicity_scores.sincerity,\n verdict.felicity_scores.clarity\n );\n\n // Return enriched intent\n return {\n ...intent,\n description,\n verification: verdict,\n score\n };\n } catch (e) {\n logger.error(`Error verifying intent: ${intent.description}`, { error: e });\n return null;\n }\n })\n );\n\n // Filter out nulls\n const verified = verificationResults.filter((i): i is VerifiedIntent => i !== null);\n logger.verbose(`Verification complete`, {\n passed: verified.length,\n total: intents.length,\n operationMode: state.operationMode\n });\n\n // Build trace entries with Felicity scores for each verified intent\n const traceEntries = verified.map(v => {\n const fs = v.verification?.felicity_scores;\n const entropy = v.verification?.semantic_entropy;\n const classification = v.verification?.classification;\n const referentialBreadth = v.verification?.referential_breadth;\n return {\n node: \"verification\",\n detail: `\"${v.description.slice(0, 40)}${v.description.length > 40 ? '...' : ''}\" → ${classification}${referentialBreadth ? ` (${referentialBreadth} referential breadth)` : ''}`,\n data: fs ? {\n clarity: fs.clarity,\n authority: fs.authority,\n sincerity: fs.sincerity,\n entropy: entropy != null ? Math.round(entropy * 100) / 100 : undefined,\n referentialBreadth,\n missingSelectionalConstraints: v.verification?.missing_selectional_constraints,\n specificityWarning: v.verification?.specificity_warning ?? undefined,\n classification,\n score: v.score,\n } : undefined,\n };\n });\n\n // Add summary trace if some intents were filtered out\n const dropped = intents.length - verified.length;\n if (dropped > 0) {\n traceEntries.unshift({\n node: \"verification\",\n detail: `Verified ${verified.length}/${intents.length} (${dropped} filtered as invalid)`,\n data: undefined,\n });\n } else if (verified.length > 0) {\n traceEntries.unshift({\n node: \"verification\",\n detail: `Verified ${verified.length} intent(s)`,\n data: undefined,\n });\n }\n\n return { verifiedIntents: verified, agentTimings: agentTimingsAccum, trace: traceEntries };\n });\n };\n\n /**\n * Node 3: Reconciliation\n * Decides on final actions (Create, Update, Expire).\n * Phase 4: Handles delete operations directly without LLM reconciliation.\n */\n const reconciliationNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.reconciliation\", async () => {\n logger.verbose(\"Starting reconciliation\", {\n operationMode: state.operationMode,\n verifiedIntentCount: state.verifiedIntents.length,\n targetIntentIds: state.targetIntentIds\n });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Phase 4: Handle delete operations directly\n if (state.operationMode === 'delete') {\n if (!state.targetIntentIds || state.targetIntentIds.length === 0) {\n logger.warn(\"Delete mode with no target IDs\");\n return {\n actions: [],\n agentTimings: agentTimingsAccum,\n trace: [{ node: \"reconciler\", detail: \"Delete mode with no target IDs\" }],\n };\n }\n\n logger.verbose(\"Delete mode - generating expire actions\", {\n targetIds: state.targetIntentIds\n });\n\n const actions = state.targetIntentIds.map(id => ({\n type: 'expire' as const,\n id,\n reasoning: 'User requested deletion'\n }));\n\n return {\n actions,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"reconciler\",\n detail: `Actions: expire=${actions.length}`,\n }],\n };\n }\n\n // Standard reconciliation for create/update operations\n const candidates = state.verifiedIntents;\n if (candidates.length === 0) {\n logger.verbose(\"No verified intents to reconcile\");\n return {\n actions: [],\n agentTimings: agentTimingsAccum,\n trace: [{ node: \"reconciler\", detail: \"No intents to reconcile\" }],\n };\n }\n\n // Format candidates for the Reconciler Prompt\n const formattedCandidates = candidates.map(c =>\n `- [${c.type.toUpperCase()}] \"${c.description}\" (Confidence: ${c.confidence}, Score: ${c.score})\\n` +\n ` Reasoning: ${c.reasoning}\\n` +\n ` Verification: ${c.verification?.classification} (Flags: ${c.verification?.flags.join(', ') || 'None'})`\n ).join('\\n');\n\n logger.verbose(\"Invoking reconciler agent\", {\n candidateCount: candidates.length,\n operationMode: state.operationMode\n });\n\n const _traceEmitterReconciler = requestContext.getStore()?.traceEmitter;\n const reconcilerStart = Date.now();\n _traceEmitterReconciler?.({ type: \"agent_start\", name: \"intent-reconciler\" });\n const result = await reconciler.invoke(formattedCandidates, state.activeIntents);\n agentTimingsAccum.push({ name: 'intent.reconciler', durationMs: Date.now() - reconcilerStart });\n _traceEmitterReconciler?.({ type: \"agent_end\", name: \"intent-reconciler\", durationMs: Date.now() - reconcilerStart, summary: `Reconciled ${result.actions.length} action(s)` });\n\n logger.verbose(\"Reconciliation complete\", {\n actionCount: result.actions.length,\n operationMode: state.operationMode\n });\n\n // Count actions by type\n const counts = { create: 0, update: 0, expire: 0 };\n for (const a of result.actions) {\n if (a.type in counts) counts[a.type as keyof typeof counts]++;\n }\n\n return {\n actions: result.actions,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"reconciler\",\n detail: `Actions: create=${counts.create}, update=${counts.update}, expire=${counts.expire}`,\n }],\n };\n });\n };\n\n /** Strip URLs and \"More details at [url]\" from intent payloads before persisting. */\n const sanitizePayload = (payload: string): string => {\n if (!payload || typeof payload !== \"string\") return payload;\n const out = payload\n .replace(/\\s*More details at\\s*:?\\s*https?:\\/\\/[^\\s\"'<>)\\]]+/gi, \"\")\n .replace(/\\s*See\\s+https?:\\/\\/[^\\s\"'<>)\\]]+\\s+for\\s+more[^.]*\\.?/gi, \"\")\n .replace(/https?:\\/\\/[^\\s\"'<>)\\]]+/g, \"\")\n .replace(/\\s{2,}/g, \" \")\n .trim();\n return out.replace(/[.,;]\\s*$/, \"\").trim() || payload;\n };\n\n /**\n * Generate a flat embedding for an intent payload, swallowing failures so\n * persistence can continue without an embedding. `intentId` is logging-only\n * (present for updates, absent for creates).\n */\n const generateIntentEmbedding = async (\n sanitizedPayload: string,\n intentId?: string,\n ): Promise<number[] | undefined> => {\n if (!this.embedder) return undefined;\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n const flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for intent\", {\n ...(intentId ? { intentId } : {}),\n dimensions: flatEmbedding?.length,\n });\n return flatEmbedding;\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent (continuing without)\", {\n ...(intentId ? { intentId } : {}),\n error: embErr,\n });\n return undefined;\n }\n };\n\n /**\n * Node 4: Executor\n * Executes reconciler actions against the database.\n */\n const executorNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.executor\", async () => {\n const actions = state.actions;\n if (!actions || actions.length === 0) {\n return { executionResults: [] };\n }\n\n logger.verbose(`Executing ${actions.length} actions...`);\n const results: ExecutionResult[] = [];\n const verifiedIntentByPayload = new Map<string, VerifiedIntent>();\n for (const verifiedIntent of state.verifiedIntents) {\n verifiedIntentByPayload.set(verifiedIntent.description, verifiedIntent);\n verifiedIntentByPayload.set(sanitizePayload(verifiedIntent.description), verifiedIntent);\n }\n\n for (const action of actions) {\n const actionType = action.type.toLowerCase() as 'create' | 'update' | 'expire';\n try {\n if (actionType === 'create') {\n const createAction = action as {\n payload: string;\n score: number | null;\n semanticEntropy?: number | null;\n referentialAnchor?: string | null;\n intentMode?: 'REFERENTIAL' | 'ATTRIBUTIVE' | null;\n };\n const sanitizedPayload = sanitizePayload(createAction.payload);\n const matchedVerifiedIntent =\n verifiedIntentByPayload.get(createAction.payload) ||\n verifiedIntentByPayload.get(sanitizedPayload);\n\n // Generate embedding for the intent payload\n const flatEmbedding = await generateIntentEmbedding(sanitizedPayload);\n\n const created = await this.database.createIntent({\n userId: state.userId,\n payload: sanitizedPayload,\n confidence: createAction.score ? createAction.score / 100 : 1.0,\n inferenceType: 'explicit',\n sourceType: 'discovery_form',\n embedding: flatEmbedding,\n semanticEntropy:\n createAction.semanticEntropy ??\n matchedVerifiedIntent?.verification?.semantic_entropy ??\n null,\n referentialAnchor:\n createAction.referentialAnchor ??\n matchedVerifiedIntent?.verification?.referential_anchor ??\n null,\n felicityAuthority: matchedVerifiedIntent?.verification?.felicity_scores.authority ?? null,\n felicitySincerity: matchedVerifiedIntent?.verification?.felicity_scores.sincerity ?? null,\n felicityClarity: matchedVerifiedIntent?.verification?.felicity_scores.clarity ?? null,\n intentMode: createAction.intentMode ?? null,\n speechActType: toSpeechActType(matchedVerifiedIntent?.verification?.classification),\n });\n\n results.push({ actionType: 'create', success: true, intentId: created.id, payload: sanitizedPayload });\n logger.verbose(`Created intent: ${created.id}`);\n\n this.intentQueue?.addGenerateHydeJob({\n intentId: created.id,\n userId: state.userId,\n ...(state.networkId ? { networkScopeId: state.networkId } : {}),\n }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE job', { intentId: created.id, error: err })\n );\n\n if (this.questionerEnqueue) {\n const userContext = (await this.database.getUserContext(state.userId, null))?.text ?? '';\n this.questionerEnqueue({\n mode: 'intent',\n userId: state.userId,\n sourceType: 'intent',\n sourceId: created.id,\n context: {\n intentId: created.id,\n payload: sanitizedPayload,\n userContext,\n },\n }).catch((err) =>\n logger.error('Failed to enqueue intent question generation', { intentId: created.id, error: err })\n );\n }\n\n } else if (actionType === 'update') {\n const updateAction = action as {\n id: string;\n payload: string;\n intentMode?: 'REFERENTIAL' | 'ATTRIBUTIVE' | null;\n };\n const sanitizedPayload = sanitizePayload(updateAction.payload);\n const matchedVerifiedIntent =\n verifiedIntentByPayload.get(updateAction.payload) ||\n verifiedIntentByPayload.get(sanitizedPayload);\n\n // Regenerate embedding for the updated payload\n const flatEmbedding = await generateIntentEmbedding(sanitizedPayload, updateAction.id);\n\n const updated = await this.database.updateIntent(updateAction.id, {\n payload: sanitizedPayload,\n embedding: flatEmbedding,\n semanticEntropy:\n matchedVerifiedIntent?.verification?.semantic_entropy ??\n null,\n referentialAnchor:\n matchedVerifiedIntent?.verification?.referential_anchor ??\n null,\n felicityAuthority: matchedVerifiedIntent?.verification?.felicity_scores.authority ?? null,\n felicitySincerity: matchedVerifiedIntent?.verification?.felicity_scores.sincerity ?? null,\n felicityClarity: matchedVerifiedIntent?.verification?.felicity_scores.clarity ?? null,\n intentMode: updateAction.intentMode ?? null,\n speechActType: toSpeechActType(matchedVerifiedIntent?.verification?.classification),\n });\n results.push({\n actionType: 'update',\n success: !!updated,\n intentId: updateAction.id,\n payload: sanitizedPayload,\n error: updated ? undefined : 'Intent not found'\n });\n logger.verbose(`Updated intent: ${updateAction.id}`);\n if (updated) {\n this.intentQueue?.addGenerateHydeJob({\n intentId: updateAction.id,\n userId: state.userId,\n ...(state.networkId ? { networkScopeId: state.networkId } : {}),\n }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE job', { intentId: updateAction.id, error: err })\n );\n }\n\n } else if (actionType === 'expire') {\n const expireAction = action as { id: string };\n const result = await this.database.archiveIntent(expireAction.id);\n results.push({\n actionType: 'expire',\n success: result.success,\n intentId: expireAction.id,\n error: result.error\n });\n logger.verbose(`Archived intent: ${expireAction.id}`);\n if (result.success) {\n this.intentQueue?.addDeleteHydeJob({ intentId: expireAction.id }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE delete job', { intentId: expireAction.id, error: err })\n );\n }\n }\n } catch (error) {\n logger.error(`Failed to execute ${action.type}:`, { error });\n results.push({\n actionType,\n success: false,\n intentId: 'id' in action ? action.id : undefined,\n error: error instanceof Error ? error.message : 'Unknown error'\n });\n }\n }\n\n return { executionResults: results };\n });\n };\n\n // --- QUERY NODE (Read Mode) ---\n\n /**\n * Node: Query\n * Fast-path read node — fetches intents from DB based on scope.\n * Handles: global user intents, index-scoped (all or filtered by user).\n * No LLM calls; no inference/verification/reconciliation.\n */\n const queryNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.query\", async () => {\n logger.verbose(\"Starting query (read mode)\", {\n userId: state.userId,\n networkId: state.networkId,\n queryUserId: state.queryUserId,\n allUserIntents: state.allUserIntents,\n });\n\n try {\n // Scope-aware default: caller's intents across all reachable indexes.\n // Triggered when the tool layer passed indexScope and did not pick a\n // specific networkId or queryUserId — i.e. \"my intents\" in a chat\n // where the agent's reach is more than one index.\n if (\n !state.queryUserId &&\n !state.networkId &&\n state.indexScope &&\n state.indexScope.length > 0\n ) {\n const intents = await this.database.getActiveIntentsAcrossIndexes(\n state.userId,\n state.indexScope,\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"You don't have any active intents yet. Share what you're looking for.\",\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n })),\n },\n };\n }\n\n // When allUserIntents is true, ignore index scope and return all\n const effectiveIndexId = state.allUserIntents ? undefined : state.networkId;\n\n if (effectiveIndexId) {\n // Verify membership\n const isMember = await this.database.isNetworkMember(effectiveIndexId, state.userId);\n if (!isMember) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"Index not found or you are not a member.\",\n },\n };\n }\n\n // Index-scoped read\n if (!state.queryUserId) {\n // All intents in the index (any member can see)\n const intents = await this.database.getNetworkIntentsForMember(\n effectiveIndexId,\n state.userId,\n { limit: 50, offset: 0 }\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"No intents in this index yet.\",\n networkId: effectiveIndexId,\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n networkId: effectiveIndexId,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n userId: i.userId,\n userName: i.userName,\n })),\n },\n };\n }\n\n // Specific user's intents in the index\n const effectiveUserId = state.queryUserId;\n const intents = await this.database.getIntentsInIndexForMember(\n effectiveUserId,\n effectiveIndexId\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message:\n effectiveUserId === state.userId\n ? \"You don't have any intents in this index yet.\"\n : \"No intents for that user in this index.\",\n networkId: effectiveIndexId,\n },\n };\n }\n const user = await this.database.getUser(effectiveUserId);\n const userName = user?.name ?? null;\n return {\n readResult: {\n count: intents.length,\n networkId: effectiveIndexId,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n userId: effectiveUserId,\n userName,\n })),\n },\n };\n }\n\n // Global (no index scope): return user's own active intents\n const intents = await this.database.getActiveIntents(state.userId);\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message:\n \"You don't have any active intents yet. Share what you're looking for.\",\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n })),\n },\n };\n } catch (err) {\n logger.error(\"Query node failed\", { error: err });\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"Failed to fetch intents. Please try again.\",\n },\n };\n }\n });\n };\n\n // --- CONDITIONAL ROUTING FUNCTIONS ---\n\n /**\n * After prep: read mode → query; otherwise decide inference vs reconciler by operation mode.\n */\n const afterPrepRoute = (state: typeof IntentGraphState.State): string => {\n if (state.error) {\n logger.warn('Prep failed with error, short-circuiting to END', { error: state.error });\n return '__end__';\n }\n if (state.operationMode === 'read') {\n logger.verbose('Read mode - routing to query (fast path)');\n return 'query';\n }\n return shouldRunInference(state);\n };\n \n /**\n * Determines if inference should run based on operation mode.\n * Delete operations skip inference entirely and go straight to reconciliation.\n */\n const shouldRunInference = (state: typeof IntentGraphState.State): string => {\n if (state.operationMode === 'delete') {\n logger.verbose('Delete mode - skipping inference, routing to reconciliation');\n return 'reconciler';\n }\n \n logger.verbose('Running inference', {\n operationMode: state.operationMode\n });\n return 'inference';\n };\n \n /**\n * Determines if verification should run based on operation mode and inferred intents.\n * Skips verification for:\n * - Operations with no inferred intents\n * - Can be extended to skip for update operations with no new intents\n */\n const shouldRunVerification = (state: typeof IntentGraphState.State): string => {\n if (state.inferredIntents.length === 0) {\n if (state.operationMode === 'propose') {\n logger.verbose('Propose mode with no inferred intents - exiting early');\n return '__end__';\n }\n logger.verbose('No intents to verify - skipping verification, routing to reconciliation');\n return 'reconciler';\n }\n \n if (state.operationMode === 'update') {\n logger.verbose('Update mode with new intents - running verification');\n return 'verification';\n }\n \n if (state.operationMode === 'create') {\n logger.verbose('Create mode - running verification');\n return 'verification';\n }\n \n // Default to verification for safety\n logger.verbose('Default routing to verification');\n return 'verification';\n };\n\n // --- GRAPH ASSEMBLY WITH CONDITIONAL EDGES (PHASE 4) ---\n\n const workflow = new StateGraph(IntentGraphState)\n .addNode(\"prep\", prepNode)\n .addNode(\"query\", queryNode)\n .addNode(\"inference\", inferenceNode)\n .addNode(\"verification\", verificationNode)\n .addNode(\"reconciler\", reconciliationNode)\n .addNode(\"executor\", executorNode)\n\n // Flow paths:\n // - READ: prep → query → END (fast path, no LLM calls)\n // - CREATE: prep → inference → verification → reconciler → executor → END\n // - UPDATE: prep → inference → reconciliation → executor → END (skips verification if no new intents)\n // - DELETE: prep → reconciliation → executor → END (skips inference and verification)\n // - PROPOSE: prep → inference → verification → END (no reconciliation/execution, no DB writes)\n .addEdge(START, \"prep\")\n \n // After prep: read mode → query; else inference or reconciler\n .addConditionalEdges(\"prep\", afterPrepRoute, {\n query: \"query\",\n inference: \"inference\",\n reconciler: \"reconciler\",\n __end__: END,\n })\n\n // Query (read mode) always ends\n .addEdge(\"query\", END)\n \n // After inference: decide if we need verification (skip if no intents)\n .addConditionalEdges(\"inference\", shouldRunVerification, {\n verification: \"verification\",\n reconciler: \"reconciler\",\n __end__: END,\n })\n \n // After verification: propose mode exits early; others continue to reconciliation\n .addConditionalEdges(\"verification\", (state: typeof IntentGraphState.State) => {\n if (state.operationMode === 'propose') {\n logger.verbose('Propose mode - stopping after verification, skipping reconciliation');\n return '__end__';\n }\n return 'reconciler';\n }, {\n reconciler: \"reconciler\",\n __end__: END,\n })\n \n // Reconciliation always goes to executor\n .addEdge(\"reconciler\", \"executor\")\n \n // Executor is always the end\n .addEdge(\"executor\", END);\n\n return workflow.compile();\n }\n}\n"]}
@@ -189,14 +189,14 @@ export function createIntentTools(defineTool, deps) {
189
189
  "or wait for background processing to find matches.\n\n" +
190
190
  "**Specificity gate.** Before calling this tool, judge whether the description is concrete enough to be " +
191
191
  "useful for matching. If the user says \"find a job\", \"meet people\", or \"learn something\", that's too " +
192
- "vague — FIRST call read_user_profiles() + read_intents() to understand their context, THEN propose a " +
192
+ "vague — FIRST call read_user_contexts() + read_intents() to understand their context, THEN propose a " +
193
193
  "refined version (\"Based on your background in X, did you mean 'Y'?\") and wait for confirmation before " +
194
194
  "calling create_intent. Specific asks (\"senior UX design role at a tech company in Berlin\") can go " +
195
195
  "directly to create_intent.\n\n" +
196
196
  "**URL handling.** If the user pastes a URL describing the intent (e.g. a job posting), call scrape_url " +
197
197
  "first with objective=\"Extract key details for an intent\", synthesize a conceptual description from the " +
198
198
  "content, then call create_intent with the synthesis. Exception: profile URLs (LinkedIn, GitHub, X) passed " +
199
- "to create_user_profile are handled by that tool directly — do not scrape first.",
199
+ "to create_user_context are handled by that tool directly — do not scrape first.",
200
200
  querySchema: z.object({
201
201
  description: z.string().describe("A clear, specific description of what the user is looking for. Should be concept-based, not a raw URL. If the user shared a URL, scrape it first with scrape_url and pass the synthesized content here. Vague descriptions will be rejected — include what kind, what for, and/or timeframe."),
202
202
  networkId: z.string().optional().describe("Index UUID to link the intent to upon creation. Defaults to the scoped index in index-scoped chats. Get index IDs from read_networks. If omitted, the system auto-assigns to relevant indexes based on their prompts."),