@indexnetwork/protocol 1.26.2 → 1.26.3-rc.223.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.
@@ -388,6 +388,9 @@ export declare class IntentGraphFactory {
388
388
  authority: number;
389
389
  sincerity: number;
390
390
  entropy: number | undefined;
391
+ referentialBreadth: "narrow" | "moderate" | "broad" | undefined;
392
+ missingSelectionalConstraints: ("location" | "role" | "outcome" | "timeframe" | "domain" | "concrete_need")[] | undefined;
393
+ specificityWarning: string | undefined;
391
394
  classification: "COMMISSIVE" | "DIRECTIVE" | "ASSERTIVE" | "EXPRESSIVE" | "DECLARATION" | "UNKNOWN" | undefined;
392
395
  score: number | undefined;
393
396
  } | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"intent.graph.d.ts","sourceRoot":"/","sources":["intent/intent.graph.ts"],"names":[],"mappings":"AACA,OAAO,EAAoB,cAAc,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAItF,OAAO,EAAE,mBAAmB,EAAE,MAAM,4CAA4C,CAAC;AAEjF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,4CAA4C,CAAC;AACrF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAIhF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAqG7E;;GAEG;AACH,qBAAa,kBAAkB;IAE3B,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,QAAQ,CAAC;IACjB,OAAO,CAAC,WAAW,CAAC;IACpB,OAAO,CAAC,iBAAiB,CAAC;gBAHlB,QAAQ,EAAE,mBAAmB,EAC7B,QAAQ,CAAC,EAAE,kBAAkB,YAAA,EAC7B,WAAW,CAAC,EAAE,gBAAgB,YAAA,EAC9B,iBAAiB,CAAC,EAAE,mBAAmB,YAAA;IAG1C,WAAW;;;;;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EI,CAAA;;;;;;;;;;;0BAFI,CAAR;4BAEI,CAAA;;;;;;;;;;CAizBH"}
@@ -2,6 +2,7 @@ import { StateGraph, START, END } from "@langchain/langgraph";
2
2
  import { IntentGraphState } from "./intent.state.js";
3
3
  import { ExplicitIntentInferrer } from "./intent.inferrer.js";
4
4
  import { SemanticVerifier } from "./intent.verifier.js";
5
+ import { DEFAULT_SPECIFICITY_WARNING } from "./intent.specificity.js";
5
6
  import { IntentReconciler } from "./intent.reconciler.js";
6
7
  import { getAbortSignalConfig } from "../shared/agent/model-signal.js";
7
8
  import { protocolLogger } from "../shared/observability/protocol.logger.js";
@@ -96,6 +97,10 @@ const isVague = (description, entropy, clarity) => {
96
97
  return true;
97
98
  return false;
98
99
  };
100
+ const getSpecificityWarning = (verdict) => {
101
+ const warning = verdict.specificity_warning?.trim();
102
+ return warning && warning.length > 0 ? warning : DEFAULT_SPECIFICITY_WARNING;
103
+ };
99
104
  const toSpeechActType = (classification) => {
100
105
  if (classification === "COMMISSIVE" || classification === "DIRECTIVE")
101
106
  return classification;
@@ -269,6 +274,14 @@ export class IntentGraphFactory {
269
274
  });
270
275
  return null;
271
276
  }
277
+ if (state.operationMode !== 'propose' && verdict.referential_breadth === 'broad') {
278
+ logger.warn(`Dropping broad attributive intent before persistence: "${description}"`, {
279
+ referentialBreadth: verdict.referential_breadth,
280
+ missingSelectionalConstraints: verdict.missing_selectional_constraints,
281
+ warning: getSpecificityWarning(verdict),
282
+ });
283
+ return null;
284
+ }
272
285
  // Calculate Score
273
286
  const score = Math.min(verdict.felicity_scores.authority, verdict.felicity_scores.sincerity, verdict.felicity_scores.clarity);
274
287
  // Return enriched intent
@@ -296,14 +309,18 @@ export class IntentGraphFactory {
296
309
  const fs = v.verification?.felicity_scores;
297
310
  const entropy = v.verification?.semantic_entropy;
298
311
  const classification = v.verification?.classification;
312
+ const referentialBreadth = v.verification?.referential_breadth;
299
313
  return {
300
314
  node: "verification",
301
- detail: `"${v.description.slice(0, 40)}${v.description.length > 40 ? '...' : ''}" → ${classification}`,
315
+ detail: `"${v.description.slice(0, 40)}${v.description.length > 40 ? '...' : ''}" → ${classification}${referentialBreadth ? ` (${referentialBreadth} referential breadth)` : ''}`,
302
316
  data: fs ? {
303
317
  clarity: fs.clarity,
304
318
  authority: fs.authority,
305
319
  sincerity: fs.sincerity,
306
320
  entropy: entropy != null ? Math.round(entropy * 100) / 100 : undefined,
321
+ referentialBreadth,
322
+ missingSelectionalConstraints: v.verification?.missing_selectional_constraints,
323
+ specificityWarning: v.verification?.specificity_warning ?? undefined,
307
324
  classification,
308
325
  score: v.score,
309
326
  } : undefined,
@@ -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,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;AAQvD,MAAM,YAAY,GAAG,CAAC,OAAe,EAAwB,EAAE;IAC7D,IAAI,CAAC,OAAO,IAAI,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AqB,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 { 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\ntype ParsedProfile = {\n identity?: { bio?: string; name?: string; location?: string };\n narrative?: { context?: string };\n attributes?: { skills?: string[]; interests?: string[] };\n};\n\nconst parseProfile = (profile: string): ParsedProfile | null => {\n if (!profile || !profile.trim()) return null;\n try {\n const parsed = JSON.parse(profile) as ParsedProfile;\n return parsed && typeof parsed === \"object\" ? parsed : null;\n } catch {\n return null;\n }\n};\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\nconst buildJobQualifierFromProfile = (profile: ParsedProfile | null): string | null => {\n if (!profile) return null;\n\n const skills = (profile.attributes?.skills ?? [])\n .filter((skill): skill is string => typeof skill === \"string\" && skill.trim().length > 0)\n .slice(0, 2);\n const interests = (profile.attributes?.interests ?? [])\n .filter((interest): interest is string => typeof interest === \"string\" && interest.trim().length > 0)\n .slice(0, 1);\n\n const profileText = [\n profile.identity?.bio,\n profile.narrative?.context,\n ]\n .filter((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n .join(\" \");\n const roleHint = inferRoleFromProfileText(profileText);\n\n if (skills.length > 0 && roleHint) {\n return `${skills.join(\" / \")} ${roleHint} role`;\n }\n if (skills.length > 0) {\n return `${skills.join(\" / \")} role`;\n }\n if (interests.length > 0 && roleHint) {\n return `${interests[0]} ${roleHint} role`;\n }\n if (roleHint) {\n return `${roleHint} role`;\n }\n return null;\n};\n\nconst enrichVagueIntentWithProfile = (description: string, profileContext: 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 profile = parseProfile(profileContext);\n const qualifier = buildJobQualifierFromProfile(profile);\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 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 const enrichedDescription = enrichVagueIntentWithProfile(description, state.userProfile);\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 // 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 return {\n node: \"verification\",\n detail: `\"${v.description.slice(0, 40)}${v.description.length > 40 ? '...' : ''}\" → ${classification}`,\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 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 let 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 * 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 let flatEmbedding: number[] | undefined;\n if (this.embedder) {\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for new intent\", { dimensions: flatEmbedding?.length });\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent (continuing without)\", { error: embErr });\n }\n }\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 parsed = parseProfile(state.userProfile);\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 userProfile: {\n name: parsed?.identity?.name,\n bio: parsed?.identity?.bio,\n skills: parsed?.attributes?.skills,\n interests: parsed?.attributes?.interests,\n },\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 let flatEmbedding: number[] | undefined;\n if (this.embedder) {\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for updated intent\", { intentId: updateAction.id, dimensions: flatEmbedding?.length });\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent update (continuing without)\", { error: embErr });\n }\n }\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,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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AAqB,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\ntype ParsedProfile = {\n identity?: { bio?: string; name?: string; location?: string };\n narrative?: { context?: string };\n attributes?: { skills?: string[]; interests?: string[] };\n};\n\nconst parseProfile = (profile: string): ParsedProfile | null => {\n if (!profile || !profile.trim()) return null;\n try {\n const parsed = JSON.parse(profile) as ParsedProfile;\n return parsed && typeof parsed === \"object\" ? parsed : null;\n } catch {\n return null;\n }\n};\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\nconst buildJobQualifierFromProfile = (profile: ParsedProfile | null): string | null => {\n if (!profile) return null;\n\n const skills = (profile.attributes?.skills ?? [])\n .filter((skill): skill is string => typeof skill === \"string\" && skill.trim().length > 0)\n .slice(0, 2);\n const interests = (profile.attributes?.interests ?? [])\n .filter((interest): interest is string => typeof interest === \"string\" && interest.trim().length > 0)\n .slice(0, 1);\n\n const profileText = [\n profile.identity?.bio,\n profile.narrative?.context,\n ]\n .filter((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n .join(\" \");\n const roleHint = inferRoleFromProfileText(profileText);\n\n if (skills.length > 0 && roleHint) {\n return `${skills.join(\" / \")} ${roleHint} role`;\n }\n if (skills.length > 0) {\n return `${skills.join(\" / \")} role`;\n }\n if (interests.length > 0 && roleHint) {\n return `${interests[0]} ${roleHint} role`;\n }\n if (roleHint) {\n return `${roleHint} role`;\n }\n return null;\n};\n\nconst enrichVagueIntentWithProfile = (description: string, profileContext: 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 profile = parseProfile(profileContext);\n const qualifier = buildJobQualifierFromProfile(profile);\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 const enrichedDescription = enrichVagueIntentWithProfile(description, state.userProfile);\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 let 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 * 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 let flatEmbedding: number[] | undefined;\n if (this.embedder) {\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for new intent\", { dimensions: flatEmbedding?.length });\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent (continuing without)\", { error: embErr });\n }\n }\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 parsed = parseProfile(state.userProfile);\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 userProfile: {\n name: parsed?.identity?.name,\n bio: parsed?.identity?.bio,\n skills: parsed?.attributes?.skills,\n interests: parsed?.attributes?.interests,\n },\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 let flatEmbedding: number[] | undefined;\n if (this.embedder) {\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for updated intent\", { intentId: updateAction.id, dimensions: flatEmbedding?.length });\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent update (continuing without)\", { error: embErr });\n }\n }\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"]}
@@ -0,0 +1,3 @@
1
+ /** Default user-facing warning for broad attributive intent proposals. */
2
+ export declare const DEFAULT_SPECIFICITY_WARNING = "This signal is broad and may produce many weak matches. Add a more concrete role, outcome, location, timeframe, domain, or specific need to get better recommendations.";
3
+ //# sourceMappingURL=intent.specificity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intent.specificity.d.ts","sourceRoot":"/","sources":["intent/intent.specificity.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,eAAO,MAAM,2BAA2B,4KAA4K,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** Default user-facing warning for broad attributive intent proposals. */
2
+ export const DEFAULT_SPECIFICITY_WARNING = "This signal is broad and may produce many weak matches. Add a more concrete role, outcome, location, timeframe, domain, or specific need to get better recommendations.";
3
+ //# sourceMappingURL=intent.specificity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intent.specificity.js","sourceRoot":"/","sources":["intent/intent.specificity.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,MAAM,CAAC,MAAM,2BAA2B,GAAG,yKAAyK,CAAC","sourcesContent":["/** Default user-facing warning for broad attributive intent proposals. */\nexport const DEFAULT_SPECIFICITY_WARNING = \"This signal is broad and may produce many weak matches. Add a more concrete role, outcome, location, timeframe, domain, or specific need to get better recommendations.\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"intent.tools.d.ts","sourceRoot":"/","sources":["intent/intent.tools.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AA4C5E,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,qDAmrBvE"}
1
+ {"version":3,"file":"intent.tools.d.ts","sourceRoot":"/","sources":["intent/intent.tools.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAqD5E,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,qDAysBvE"}
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { DEFAULT_SPECIFICITY_WARNING } from "./intent.specificity.js";
2
3
  import { protocolLogger } from "../shared/observability/protocol.logger.js";
3
4
  import { requestContext } from "../shared/observability/request-context.js";
4
5
  import { success, error, UUID_REGEX } from "../shared/agent/tool.helpers.js";
@@ -36,6 +37,13 @@ function buildApprovedProfileFallback(user) {
36
37
  attributes: { skills: [], interests: [] },
37
38
  });
38
39
  }
40
+ function isBroadAttributiveIntent(intent) {
41
+ return intent.verification?.referential_breadth === "broad";
42
+ }
43
+ function specificityWarningFor(intent) {
44
+ const warning = intent.verification?.specificity_warning?.trim();
45
+ return warning && warning.length > 0 ? warning : DEFAULT_SPECIFICITY_WARNING;
46
+ }
39
47
  export function createIntentTools(defineTool, deps) {
40
48
  const { graphs, userDb } = deps;
41
49
  // ─────────────────────────────────────────────────────────────────────────────
@@ -258,6 +266,14 @@ export function createIntentTools(defineTool, deps) {
258
266
  }
259
267
  // ── Auto-approve path (for MCP agents or explicit opt-in) ──
260
268
  if (shouldAutoApprove) {
269
+ const broadIntents = verified.filter(isBroadAttributiveIntent);
270
+ if (broadIntents.length > 0) {
271
+ const first = broadIntents[0];
272
+ const missing = first.verification?.missing_selectional_constraints ?? [];
273
+ const missingHint = missing.length > 0 ? ` Missing selectional constraints: ${missing.join(", ")}.` : "";
274
+ return error(`${specificityWarningFor(first)}${missingHint} ` +
275
+ `Please ask the user to clarify before creating this signal, or retry with a narrower description.`, debugSteps);
276
+ }
261
277
  const createdIntents = [];
262
278
  const createTimings = [];
263
279
  for (const v of verified) {
@@ -302,12 +318,17 @@ export function createIntentTools(defineTool, deps) {
302
318
  // Build intent_proposal code fences for each verified intent
303
319
  const proposalBlocks = verified.map((v) => {
304
320
  const proposalId = crypto.randomUUID();
321
+ const isBroad = isBroadAttributiveIntent(v);
305
322
  const data = {
306
323
  proposalId,
307
324
  description: v.description,
308
325
  ...(effectiveIndexId ? { networkId: effectiveIndexId } : {}),
309
326
  confidence: v.score != null ? Math.round(v.score * 100) / 100 : null,
310
327
  speechActType: v.verification?.classification ?? null,
328
+ semanticEntropy: v.verification?.semantic_entropy ?? null,
329
+ referentialBreadth: v.verification?.referential_breadth ?? null,
330
+ missingSelectionalConstraints: v.verification?.missing_selectional_constraints ?? [],
331
+ specificityWarning: isBroad ? specificityWarningFor(v) : v.verification?.specificity_warning ?? null,
311
332
  };
312
333
  return ("```intent_proposal\n" +
313
334
  sanitizeJsonForCodeFence(JSON.stringify(data)) +
@@ -386,6 +407,9 @@ export function createIntentTools(defineTool, deps) {
386
407
  if (result.executionResults?.some((r) => !r.success)) {
387
408
  return error("Failed to update intent.");
388
409
  }
410
+ if (!result.executionResults?.some((r) => r.success)) {
411
+ return error("Intent update was not applied. The new description may be too broad, too vague, or failed semantic verification. Please ask the user to clarify with a more concrete role, outcome, location, timeframe, domain, or specific need.");
412
+ }
389
413
  return success({
390
414
  message: "Intent updated.",
391
415
  intentId,
@@ -1 +1 @@
1
- {"version":3,"file":"intent.tools.js","sourceRoot":"/","sources":["intent/intent.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAE7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;GAGG;AACH,SAAS,wBAAwB,CAAC,IAAY;IAC5C,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;AACvC,CAAC;AAED,wHAAwH;AACxH,KAAK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,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,aAAa,CAAU,CAAC;AAClJ,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport type { ExecutionResult, VerifiedIntent } from \"./intent.state.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\nimport type { UserRecord } from \"../shared/interfaces/database.interface.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"ChatTools:Intent\");\n\n/**\n * Sanitize JSON string for use inside a markdown code fence (```). Escapes backticks\n * so embedded ``` cannot close the fence prematurely.\n */\nfunction sanitizeJsonForCodeFence(json: string): string {\n return json.replace(/`/g, \"\\\\u0060\");\n}\n\n/** When context is index-scoped, verifies the caller is still a member of that index. Returns error message or null. */\nasync function ensureScopedMembership(\n context: { networkId?: string; indexName?: string; userId: string },\n systemDb: ToolDeps['systemDb']\n): Promise<string | null> {\n if (!context.networkId) return null;\n const isMember = await systemDb.isNetworkMember(context.networkId, context.userId);\n if (!isMember) {\n return `This chat is scoped to ${context.indexName ?? 'this index'}. You are no longer a member of this community.`;\n }\n return null;\n}\n\nfunction buildApprovedProfileFallback(user: UserRecord | null | undefined): string {\n const bio = user?.intro?.trim();\n if (!user || !bio) return \"\";\n\n return JSON.stringify({\n userId: user.id,\n identity: {\n name: user.name ?? \"\",\n bio,\n location: user.location?.trim() ?? \"\",\n },\n narrative: { context: bio },\n attributes: { skills: [], interests: [] },\n });\n}\n\nexport function createIntentTools(defineTool: DefineTool, deps: ToolDeps) {\n const { graphs, userDb } = deps;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // INTENT CRUD\n // ─────────────────────────────────────────────────────────────────────────────\n\n const readIntents = defineTool({\n name: \"read_intents\",\n description:\n \"Retrieves intents (signals of interest/need, e.g. 'Looking for a React developer in Berlin'). \" +\n \"Intents are the core unit of discovery — they represent what users are seeking and drive semantic matching for opportunities.\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- No parameters: returns the **caller's own** active intents. In an index-scoped chat the result is clamped to the reachable indexes (the bound index plus the user's personal index). In an unscoped chat the result spans all of the user's active intents. There is no implicit default to the scoped index — to browse the bound community's intents, pass `networkId` explicitly.\\n\" +\n \"- With networkId: returns **all members'** intents in that index (community browse path). Add userId to filter to one member.\\n\" +\n \"- With userId in an index-scoped chat: reads that member's intents in the bound index. The target user must be a member of that index.\\n\" +\n \"- With userId in an unscoped chat: only works for the current user (cannot read another user's global intents without an index scope).\\n\\n\" +\n \"**Workflow:** To explore what members of an index are looking for, first call read_network_memberships(networkId) to list members, \" +\n \"then read_intents(networkId) to see all intents in that community. \" +\n \"Each intent includes: id, description (payload), summary, confidence (0-1), inferenceType (explicit/implicit), status, and linked indexes.\\n\\n\" +\n \"**Returns:** Paginated list of intents with count. Use the intent IDs in subsequent calls to update_intent, delete_intent, or create_intent_index.\",\n querySchema: z.object({\n networkId: z.string().optional().describe(\"Index UUID — filters intents to this index (community browse path: returns all members' intents). There is no implicit default in index-scoped chats; omit to get caller-owned intents across the reachable indexes, or pass the scoped index UUID to browse community members. Get index IDs from read_networks.\"),\n userId: z.string().optional().describe(\"User ID — filters to this user's intents. In an index-scoped chat, this reads that member's intents in the bound index (no networkId required). In an unscoped chat, only the current user is allowed without networkId; cross-user reads require an index scope. Omit for caller-owned intents.\"),\n limit: z.number().int().min(1).max(100).optional().describe(\"Page size (1-100). Defaults to returning all results if omitted.\"),\n page: z.number().int().min(1).optional().describe(\"Page number (1-based). Only used when limit is also provided.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n\n // Distinguish \"explicit network browse\" from \"implicit scope-aware read\"\n const explicitNetworkId = query.networkId?.trim();\n const explicitUserId = query.userId?.trim();\n\n // Validate explicit networkId format\n if (explicitNetworkId && !UUID_REGEX.test(explicitNetworkId)) {\n return error(\"Invalid network ID format.\");\n }\n\n // Strict scope enforcement: in a scoped chat, the only allowed explicit\n // networkId is context.networkId itself. The chat's focus is the bound\n // network; cross-network browse must happen in a separate (unscoped)\n // chat or a chat scoped to that other network.\n if (context.networkId && explicitNetworkId && explicitNetworkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only read intents from this community.`\n );\n }\n\n // Cross-user read in scoped chat: target user must be a member of the scoped index\n if (context.networkId && explicitUserId && explicitUserId !== context.userId) {\n const isInScopedIndex = await deps.systemDb.isNetworkMember(context.networkId, explicitUserId);\n if (!isInScopedIndex) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only read intents from members of this community.`\n );\n }\n }\n\n // Cross-user global read is disallowed without an index scope\n if (!explicitNetworkId && !context.networkId && explicitUserId && explicitUserId !== context.userId) {\n return error(\"Cannot read another user's global intents. Use networkId to scope to a shared network.\");\n }\n\n // Membership check for explicit cross-network reads in unscoped chats\n if (!context.networkId && explicitNetworkId) {\n const callerIsMember = await deps.systemDb.isNetworkMember(explicitNetworkId, context.userId);\n if (!callerIsMember) {\n return error(\"You can only read intents from indexes you are a member of.\");\n }\n }\n\n // ── Choose the read mode ──\n // 1. Explicit networkId (browse all members in that index) — pass networkId, optionally + queryUserId.\n // 2. Explicit userId in a scoped chat — read that user's intents in the bound network.\n // 3. Explicit userId in an unscoped chat — only self (cross-user rejected above); global \"my intents\".\n // 4. Implicit (no explicit network/user) in scoped chat — pass indexScope, no networkId.\n // 5. Implicit in unscoped chat — global getActiveIntents (caller's own).\n const graphInput: Record<string, unknown> = {\n userId: context.userId,\n userProfile: \"\",\n operationMode: 'read' as const,\n };\n\n if (explicitNetworkId) {\n graphInput.networkId = explicitNetworkId;\n if (explicitUserId) graphInput.queryUserId = explicitUserId;\n } else if (explicitUserId && context.networkId) {\n // Scoped chat + userId: implicit network is the chat's bound network.\n // Membership of the target user was verified above.\n graphInput.networkId = context.networkId;\n graphInput.queryUserId = explicitUserId;\n } else if (explicitUserId) {\n // Unscoped chat + userId: only allowed for self (others rejected above).\n graphInput.queryUserId = explicitUserId;\n graphInput.allUserIntents = true;\n } else if (context.indexScope && context.indexScope.length > 0 && context.networkId) {\n // Scoped chat, implicit read: caller-only across reachable indexes.\n graphInput.indexScope = context.indexScope;\n } else {\n // Unscoped, implicit read: caller's global intents.\n graphInput.allUserIntents = true;\n }\n\n const _readIntentGraphStart = Date.now();\n const _readIntentTraceEmitter = requestContext.getStore()?.traceEmitter;\n _readIntentTraceEmitter?.({ type: \"graph_start\", name: \"intent\" });\n const result = await invokeWithAbortSignal(graphs.intent, graphInput);\n const _readIntentGraphMs = Date.now() - _readIntentGraphStart;\n _readIntentTraceEmitter?.({ type: \"graph_end\", name: \"intent\", durationMs: _readIntentGraphMs });\n\n if (result.readResult) {\n if (result.readResult.count === 0 && result.readResult.message && /not a member|Network not found/i.test(result.readResult.message)) {\n return error(result.readResult.message);\n }\n\n const shouldPaginate = query.limit !== undefined || query.page !== undefined;\n if (shouldPaginate && Array.isArray(result.readResult.intents)) {\n const limit = query.limit ?? 20;\n const page = query.page ?? 1;\n const offset = (page - 1) * limit;\n const pagedIntents = result.readResult.intents.slice(offset, offset + limit);\n return success({\n ...result.readResult,\n count: pagedIntents.length,\n totalCount: result.readResult.intents.length,\n limit,\n page,\n totalPages: Math.ceil(result.readResult.intents.length / limit),\n intents: pagedIntents,\n _graphTimings: [{ name: 'intent', durationMs: _readIntentGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n\n return success({ ...result.readResult, _graphTimings: [{ name: 'intent', durationMs: _readIntentGraphMs, agents: result.agentTimings ?? [] }] });\n }\n return error(\"Failed to fetch intents.\");\n },\n });\n\n const createIntent = defineTool({\n name: \"create_intent\",\n description:\n \"Creates a new intent (signal of interest/need) for the authenticated user. Intents drive the discovery engine — once created, \" +\n \"the system automatically evaluates them against indexes the user belongs to, links them to relevant communities, and begins \" +\n \"searching for matching opportunities (complementary intents from other users).\\n\\n\" +\n \"**What to pass:** A clear, concept-based description of what the user is looking for (e.g. 'Looking for an AI/ML co-founder in Berlin', \" +\n \"'Need a designer for a mobile app project'). If the user provided a URL, scrape it with scrape_url first and synthesize the content into a description.\\n\\n\" +\n \"**What happens:** The system runs inference (extracting structured intents), verification (checking specificity and speech-act type), \" +\n \"and returns a proposal widget. The proposal is NOT yet persisted — the user must approve it first.\\n\\n\" +\n \"**Returns:** An intent_proposal code block that MUST be included verbatim in the response. The frontend renders it as an interactive \" +\n \"card the user can approve or skip. On approval, the intent is persisted, indexed, and discovery begins.\\n\\n\" +\n \"**Next steps after approval:** The intent is automatically linked to relevant indexes. Call discover_opportunities(searchQuery) to explicitly trigger discovery, \" +\n \"or wait for background processing to find matches.\\n\\n\" +\n \"**Specificity gate.** Before calling this tool, judge whether the description is concrete enough to be \" +\n \"useful for matching. If the user says \\\"find a job\\\", \\\"meet people\\\", or \\\"learn something\\\", that's too \" +\n \"vague — FIRST call read_user_profiles() + read_intents() to understand their context, THEN propose a \" +\n \"refined version (\\\"Based on your background in X, did you mean 'Y'?\\\") and wait for confirmation before \" +\n \"calling create_intent. Specific asks (\\\"senior UX design role at a tech company in Berlin\\\") can go \" +\n \"directly to create_intent.\\n\\n\" +\n \"**URL handling.** If the user pastes a URL describing the intent (e.g. a job posting), call scrape_url \" +\n \"first with objective=\\\"Extract key details for an intent\\\", synthesize a conceptual description from the \" +\n \"content, then call create_intent with the synthesis. Exception: profile URLs (LinkedIn, GitHub, X) passed \" +\n \"to create_user_profile are handled by that tool directly — do not scrape first.\",\n querySchema: z.object({\n 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.\"),\n 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.\"),\n autoApprove: z.boolean().optional().describe(\"When true, automatically persists all verified intents without returning proposal cards for manual approval. MCP agents SHOULD set this to true since there is no UI for card-based approval. Web chat agents should omit or set to false to get interactive proposal cards.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n if (!query.description?.trim()) {\n return error(\"Description is required.\");\n }\n\n // Strict scope enforcement\n if (context.networkId && query.networkId?.trim() && query.networkId.trim() !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only create intents in this community.`\n );\n }\n\n const effectiveIndexId = context.networkId || query.networkId?.trim() || undefined;\n\n // Fetch profile (the intent graph needs it for inference)\n const _profileGraphStart1 = Date.now();\n const _createIntentProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createIntentProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const profileResult = await invokeWithAbortSignal(graphs.profile, { userId: context.userId, operationMode: 'query' as const });\n const _profileGraphMs1 = Date.now() - _profileGraphStart1;\n _createIntentProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _profileGraphMs1 });\n const latestUser = profileResult.profile ? undefined : typeof userDb.getUser === \"function\" ? await userDb.getUser() : context.user;\n const approvedProfileFallback = profileResult.profile ? \"\" : buildApprovedProfileFallback(latestUser);\n const userProfile = profileResult.profile ? JSON.stringify(profileResult.profile) : approvedProfileFallback;\n\n // Run inference + verification only (propose mode — no DB persistence)\n const _intentGraphStart1 = Date.now();\n const _createIntentTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createIntentTraceEmitter?.({ type: \"graph_start\", name: \"intent\" });\n const result = await invokeWithAbortSignal(graphs.intent, {\n userId: context.userId,\n userProfile,\n inputContent: query.description,\n operationMode: 'propose' as const,\n ...(effectiveIndexId ? { networkId: effectiveIndexId } : {}),\n });\n const _intentGraphMs1 = Date.now() - _intentGraphStart1;\n _createIntentTraceEmitter?.({ type: \"graph_end\", name: \"intent\", durationMs: _intentGraphMs1 });\n logger.debug(\"Intent graph propose response\", { result });\n\n const verified = result.verifiedIntents || [];\n\n // MCP contexts have no interactive UI for proposal cards — default to auto-approve\n const shouldAutoApprove = query.autoApprove ?? context.isMcp ?? false;\n \n // Extract trace from graph and convert to debugSteps\n const trace = Array.isArray(result.trace) ? result.trace : [];\n const debugSteps = trace.map((t: { node: string; detail?: string; data?: Record<string, unknown> }) => ({\n step: t.node,\n detail: t.detail,\n ...(t.data ? { data: t.data } : {}),\n }));\n \n if (verified.length === 0) {\n // Build a descriptive rejection reason from the trace so the ReACT agent\n // can retry with a better description or ask the user for clarification.\n // When inference produces 0 intents, propose mode exits before verification\n // runs — so we check inference trace first.\n const verificationTrace = debugSteps.find((s: { step: string; detail?: string }) => s.step === \"verification\");\n\n if (!verificationTrace) {\n const inferenceHint =\n debugSteps.find((s: { step: string; detail?: string }) => s.step === \"inference\")?.detail\n ?? \"no intents extracted\";\n return error(\n `No actionable intent was extracted (${inferenceHint}). ` +\n `Please retry with a more specific goal (what kind, what for, and/or timeframe), ` +\n `or ask the user to clarify.`,\n debugSteps,\n );\n }\n\n const rejectionHint =\n verificationTrace.detail ?? \"all candidate intents were filtered as invalid or too vague\";\n return error(\n `Intent verification failed (${rejectionHint}). ` +\n `The description may be too vague or was classified as a statement rather than a goal. ` +\n `Either retry with a more specific description (e.g. include what kind, what for, or a timeframe) ` +\n `or ask the user to clarify what exactly they are looking for.`,\n debugSteps,\n );\n }\n\n // ── Auto-approve path (for MCP agents or explicit opt-in) ──\n if (shouldAutoApprove) {\n const createdIntents: Array<{ description: string; confidence: number | null; speechActType: string | null }> = [];\n const createTimings: Array<{ name: string; durationMs: number; agents: unknown[] }> = [];\n\n for (const v of verified as VerifiedIntent[]) {\n const _createGraphStart = Date.now();\n const _createTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createTraceEmitter?.({ type: \"graph_start\", name: \"intent\" });\n const createResult = await invokeWithAbortSignal(graphs.intent, {\n userId: context.userId,\n userProfile,\n inputContent: v.description,\n operationMode: 'create' as const,\n ...(effectiveIndexId ? { networkId: effectiveIndexId } : {}),\n });\n const _createGraphMs = Date.now() - _createGraphStart;\n _createTraceEmitter?.({ type: \"graph_end\", name: \"intent\", durationMs: _createGraphMs });\n\n createTimings.push({ name: 'intent-create', durationMs: _createGraphMs, agents: createResult.agentTimings ?? [] });\n\n const succeeded = createResult.executionResults?.some((r: ExecutionResult) => r.success);\n if (succeeded) {\n createdIntents.push({\n description: v.description,\n confidence: v.score != null ? Math.round(v.score * 100) / 100 : null,\n speechActType: v.verification?.classification ?? null,\n });\n }\n }\n\n return success({\n created: createdIntents.length > 0,\n count: createdIntents.length,\n intents: createdIntents,\n message: createdIntents.length > 0\n ? `Created ${createdIntents.length} intent${createdIntents.length > 1 ? 's' : ''} successfully. The system will automatically index them and begin searching for matching opportunities.`\n : 'Intent creation failed — the intents could not be persisted.',\n debugSteps,\n _graphTimings: [\n { name: 'profile', durationMs: _profileGraphMs1, agents: profileResult.agentTimings ?? [] },\n { name: 'intent-propose', durationMs: _intentGraphMs1, agents: result.agentTimings ?? [] },\n ...createTimings,\n ],\n });\n }\n\n // ── Proposal path (for web chat with interactive cards) ──\n // Build intent_proposal code fences for each verified intent\n const proposalBlocks = verified.map((v: VerifiedIntent) => {\n const proposalId = crypto.randomUUID();\n const data = {\n proposalId,\n description: v.description,\n ...(effectiveIndexId ? { networkId: effectiveIndexId } : {}),\n confidence: v.score != null ? Math.round(v.score * 100) / 100 : null,\n speechActType: v.verification?.classification ?? null,\n };\n return (\n \"```intent_proposal\\n\" +\n sanitizeJsonForCodeFence(JSON.stringify(data)) +\n \"\\n```\"\n );\n });\n\n const blocksText = proposalBlocks.join(\"\\n\\n\");\n\n return success({\n proposed: true,\n count: verified.length,\n message: `IMPORTANT: Include the following \\`\\`\\`intent_proposal code blocks EXACTLY as-is in your response (they render as interactive cards for the user to approve or skip):\\n\\n${blocksText}`,\n debugSteps,\n _graphTimings: [\n { name: 'profile', durationMs: _profileGraphMs1, agents: profileResult.agentTimings ?? [] },\n { name: 'intent', durationMs: _intentGraphMs1, agents: result.agentTimings ?? [] },\n ],\n });\n },\n });\n\n const updateIntent = defineTool({\n name: \"update_intent\",\n description:\n \"Updates an existing intent's description. After updating, the system re-processes the intent through inference and verification, \" +\n \"re-evaluates its index assignments, and triggers fresh opportunity discovery with the new description.\\n\\n\" +\n \"**When to use:** When the user wants to refine or change what they're looking for — e.g. narrowing scope, adding specificity, \" +\n \"or pivoting to a different need. Prefer updating over delete+create to preserve the intent's history and existing index links.\\n\\n\" +\n \"**Returns:** Updated `intentId` and `description`, plus a confirmation message. The intent's embeddings and index relevancy scores are recalculated automatically.\",\n querySchema: z.object({\n intentId: z.string().describe(\"The UUID of the intent to update. Get this from read_intents results.\"),\n description: z.string().describe(\"The updated description of what the user is looking for. Same guidelines as create_intent — should be clear and specific.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n const intentId = query.intentId?.trim() ?? \"\";\n if (!UUID_REGEX.test(intentId)) {\n return error(\"Invalid intent ID format.\");\n }\n\n // Ownership guard: caller must own the intent\n const intent = await deps.systemDb.getIntent(intentId);\n if (!intent || intent.userId !== context.userId) {\n return error(\"Intent not found or you can only update your own intents.\");\n }\n if (intent.archivedAt) {\n return error(\"This intent is archived and cannot be updated. Create a new intent instead.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, verify intent is linked to that index\n if (context.networkId) {\n const db = deps.userDb;\n const intentNetworks = await db.getNetworkIdsForIntent(intentId);\n if (!intentNetworks.includes(context.networkId)) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only update intents linked to this community.`\n );\n }\n }\n\n const _profileGraphStart2 = Date.now();\n const _updateIntentProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _updateIntentProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const profileResult = await invokeWithAbortSignal(graphs.profile, { userId: context.userId, operationMode: 'query' as const });\n const _profileGraphMs2 = Date.now() - _profileGraphStart2;\n _updateIntentProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _profileGraphMs2 });\n const latestUser = profileResult.profile ? undefined : typeof userDb.getUser === \"function\" ? await userDb.getUser() : context.user;\n const approvedProfileFallback = profileResult.profile ? \"\" : buildApprovedProfileFallback(latestUser);\n const userProfile = profileResult.profile ? JSON.stringify(profileResult.profile) : approvedProfileFallback;\n\n const _intentGraphStart2 = Date.now();\n const _updateIntentTraceEmitter = requestContext.getStore()?.traceEmitter;\n _updateIntentTraceEmitter?.({ type: \"graph_start\", name: \"intent\" });\n const result = await invokeWithAbortSignal(graphs.intent, {\n userId: context.userId,\n userProfile,\n operationMode: 'update' as const,\n inputContent: query.description,\n targetIntentIds: [intentId],\n ...(context.networkId && { networkId: context.networkId }),\n });\n const _intentGraphMs2 = Date.now() - _intentGraphStart2;\n _updateIntentTraceEmitter?.({ type: \"graph_end\", name: \"intent\", durationMs: _intentGraphMs2 });\n\n if (result.executionResults?.some((r: ExecutionResult) => !r.success)) {\n return error(\"Failed to update intent.\");\n }\n return success({\n message: \"Intent updated.\",\n intentId,\n description: query.description,\n _graphTimings: [\n { name: 'profile', durationMs: _profileGraphMs2, agents: profileResult.agentTimings ?? [] },\n { name: 'intent', durationMs: _intentGraphMs2, agents: result.agentTimings ?? [] },\n ],\n });\n },\n });\n\n const deleteIntent = defineTool({\n name: \"delete_intent\",\n description:\n \"Archives (soft-deletes) an intent, removing it from active discovery. The intent is not permanently deleted — it is marked as archived \" +\n \"and no longer participates in opportunity matching or index evaluation.\\n\\n\" +\n \"**When to use:** When the user's need has been fulfilled, is no longer relevant, or was created by mistake. \" +\n \"If the user wants to change the description instead, use update_intent to preserve history.\\n\\n\" +\n \"**Returns:** Confirmation that the intent was archived. Previously created opportunities from this intent remain but won't generate new ones.\",\n querySchema: z.object({\n intentId: z.string().describe(\"The UUID of the intent to archive. Get this from read_intents results.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n const intentId = query.intentId?.trim() ?? \"\";\n if (!UUID_REGEX.test(intentId)) {\n return error(\"Invalid intent ID format.\");\n }\n\n // Ownership guard: caller must own the intent\n const intent = await deps.systemDb.getIntent(intentId);\n if (!intent || intent.userId !== context.userId) {\n return error(\"Intent not found or you can only delete your own intents.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, verify intent is linked to that index\n if (context.networkId) {\n const db = deps.userDb;\n const intentNetworks = await db.getNetworkIdsForIntent(intentId);\n if (!intentNetworks.includes(context.networkId)) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only delete intents linked to this community.`\n );\n }\n }\n\n const _deleteIntentGraphStart = Date.now();\n const _deleteIntentTraceEmitter = requestContext.getStore()?.traceEmitter;\n _deleteIntentTraceEmitter?.({ type: \"graph_start\", name: \"intent\" });\n const result = await invokeWithAbortSignal(graphs.intent, {\n userId: context.userId,\n userProfile: \"\",\n operationMode: 'delete' as const,\n targetIntentIds: [intentId],\n ...(context.networkId && { networkId: context.networkId }),\n });\n const _deleteIntentGraphMs = Date.now() - _deleteIntentGraphStart;\n _deleteIntentTraceEmitter?.({ type: \"graph_end\", name: \"intent\", durationMs: _deleteIntentGraphMs });\n\n if (result.executionResults?.some((r: ExecutionResult) => !r.success)) {\n return error(\"Failed to delete intent.\");\n }\n return success({\n message: \"Intent archived successfully.\",\n _graphTimings: [{ name: 'intent', durationMs: _deleteIntentGraphMs, agents: result.agentTimings ?? [] }],\n });\n },\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // INTENT–INDEX JUNCTION (link / list / unlink)\n // ─────────────────────────────────────────────────────────────────────────────\n\n const createIntentIndex = defineTool({\n name: \"create_intent_index\",\n description:\n \"Manually links an intent to an index (community), making it visible to other members and eligible for opportunity discovery within that index. \" +\n \"Normally intents are auto-assigned to relevant indexes on creation, but use this to explicitly add an intent to an additional index.\\n\\n\" +\n \"**When to use:** When the user wants to share an existing intent with a specific community they belong to, \" +\n \"or when auto-assignment missed an index the user considers relevant.\\n\\n\" +\n \"**Returns:** Confirmation that the link was created. The intent will now appear in that index's intent list and participate in discovery within that community.\",\n querySchema: z.object({\n intentId: z.string().describe(\"The UUID of the intent to link. Get this from read_intents results.\"),\n networkId: z.string().optional().describe(\"The UUID of the index to link the intent to. Get this from read_networks. Defaults to the scoped index in index-scoped chats.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n const intentId = query.intentId?.trim() ?? \"\";\n const networkId = query.networkId?.trim() || context.networkId || \"\";\n if (!UUID_REGEX.test(intentId) || !UUID_REGEX.test(networkId)) {\n return error(\"Invalid ID format. Both must be UUIDs.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow linking to that index\n if (context.networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only link intents to this community.`\n );\n }\n\n const _createIntentIndexGraphStart = Date.now();\n const _createIntentIndexTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createIntentIndexTraceEmitter?.({ type: \"graph_start\", name: \"intent_network\" });\n const result = await invokeWithAbortSignal(graphs.intentIndex, {\n userId: context.userId,\n networkId,\n intentId,\n operationMode: 'create' as const,\n skipEvaluation: true,\n });\n const _createIntentIndexGraphMs = Date.now() - _createIntentIndexGraphStart;\n _createIntentIndexTraceEmitter?.({ type: \"graph_end\", name: \"intent_network\", durationMs: _createIntentIndexGraphMs });\n\n if (result.mutationResult) {\n if (result.mutationResult.success) {\n const alreadyExisted = result.mutationResult.message?.includes('already in this network') ?? false;\n return success({\n created: !alreadyExisted,\n message: result.mutationResult.message,\n _graphTimings: [{ name: 'intent_network', durationMs: _createIntentIndexGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(result.mutationResult.error || \"Failed to link intent to network.\");\n }\n return error(\"Failed to link intent to network.\");\n },\n });\n\n const readIntentIndexes = defineTool({\n name: \"read_intent_indexes\",\n description:\n \"Reads the many-to-many links between intents and indexes. Use this to understand which intents are shared in which communities, \" +\n \"and which indexes a specific intent belongs to.\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- With networkId: lists all intents linked to that index. Add userId to filter to one member's intents in that index.\\n\" +\n \"- With intentId + networkId: checks whether a specific intent is linked to a specific index.\\n\" +\n \"- intentId alone requires a networkId (the system won't reveal all indexes an intent is in).\\n\\n\" +\n \"**When to use:** To audit which intents are active in a community, verify an intent's index assignment before unlinking, \" +\n \"or check if a newly created intent was auto-assigned to the expected index.\\n\\n\" +\n \"**Returns:** List of intent-index links with relevancy scores (0-1, how well the intent fits the index's purpose).\",\n querySchema: z.object({\n intentId: z.string().optional().describe(\"Intent UUID — check if this specific intent is linked to the specified index. Must be combined with networkId.\"),\n networkId: z.string().optional().describe(\"Index UUID — list all intents linked to this index. Get this from read_networks. Defaults to scoped index in index-scoped chats.\"),\n userId: z.string().optional().describe(\"Filter results to this user's intents within the specified index. Omit to see all members' intents.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n const intentId = query.intentId?.trim() || undefined;\n let networkId = query.networkId?.trim() || context.networkId || undefined;\n const queryUserId = query.userId?.trim() || undefined;\n\n if (intentId && !UUID_REGEX.test(intentId)) {\n return error(\"Invalid intent ID format.\");\n }\n if (networkId && !UUID_REGEX.test(networkId)) {\n return error(\"Invalid network ID format.\");\n }\n if (!intentId && !networkId) {\n return error(\"Provide networkId or intentId.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow querying that index\n if (context.networkId && networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only read intent links from this community.`\n );\n }\n\n // When only intentId is provided, enforce scope - don't reveal all linked indexes\n if (intentId && !networkId) {\n if (context.networkId) {\n // When scoped, only check if intent is linked to the scoped index\n networkId = context.networkId;\n } else {\n // When unscoped, still don't reveal all indexes - require explicit networkId\n return error(\n \"Please provide a networkId to check if the intent is linked to a specific network. Listing all linked networks is not supported.\"\n );\n }\n }\n\n const _readIntentIndexGraphStart = Date.now();\n const _readIntentIndexTraceEmitter = requestContext.getStore()?.traceEmitter;\n _readIntentIndexTraceEmitter?.({ type: \"graph_start\", name: \"intent_network\" });\n const result = await invokeWithAbortSignal(graphs.intentIndex, {\n userId: context.userId,\n networkId,\n intentId,\n operationMode: 'read' as const,\n queryUserId,\n });\n const _readIntentIndexGraphMs = Date.now() - _readIntentIndexGraphStart;\n _readIntentIndexTraceEmitter?.({ type: \"graph_end\", name: \"intent_network\", durationMs: _readIntentIndexGraphMs });\n\n if (result.error) {\n return error(result.error);\n }\n if (result.readResult) {\n return success({ ...result.readResult, _graphTimings: [{ name: 'intent_network', durationMs: _readIntentIndexGraphMs, agents: result.agentTimings ?? [] }] });\n }\n return error(\"Failed to fetch intent-network links.\");\n },\n });\n\n const deleteIntentIndex = defineTool({\n name: \"delete_intent_index\",\n description:\n \"Removes the link between an intent and an index. The intent itself is NOT deleted — it just stops being visible in that community \" +\n \"and no longer participates in opportunity discovery within that index. The intent may still be linked to other indexes.\\n\\n\" +\n \"**When to use:** When the user wants to withdraw an intent from a specific community without archiving it entirely. \" +\n \"Use read_intent_indexes first to verify the link exists.\\n\\n\" +\n \"**Returns:** Confirmation that the link was removed. To fully remove an intent, use delete_intent instead.\",\n querySchema: z.object({\n intentId: z.string().describe(\"The UUID of the intent to unlink. Get this from read_intents or read_intent_indexes.\"),\n networkId: z.string().optional().describe(\"The UUID of the index to unlink from. Get this from read_networks. Defaults to the scoped index in index-scoped chats.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n const intentId = query.intentId?.trim() ?? \"\";\n const networkId = query.networkId?.trim() || context.networkId || \"\";\n if (!UUID_REGEX.test(intentId) || !UUID_REGEX.test(networkId)) {\n return error(\"Invalid ID format. Both must be UUIDs.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow unlinking from that index\n if (context.networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only unlink intents from this community.`\n );\n }\n\n const _deleteIntentIndexGraphStart = Date.now();\n const _deleteIntentIndexTraceEmitter = requestContext.getStore()?.traceEmitter;\n _deleteIntentIndexTraceEmitter?.({ type: \"graph_start\", name: \"intent_network\" });\n const result = await invokeWithAbortSignal(graphs.intentIndex, {\n userId: context.userId,\n networkId,\n intentId,\n operationMode: 'delete' as const,\n });\n const _deleteIntentIndexGraphMs = Date.now() - _deleteIntentIndexGraphStart;\n _deleteIntentIndexTraceEmitter?.({ type: \"graph_end\", name: \"intent_network\", durationMs: _deleteIntentIndexGraphMs });\n\n if (result.mutationResult) {\n if (result.mutationResult.success) {\n return success({\n deleted: true,\n message: result.mutationResult.message,\n _graphTimings: [{ name: 'intent_network', durationMs: _deleteIntentIndexGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(result.mutationResult.error || \"Failed to unlink.\");\n }\n return error(\"Failed to unlink intent from network.\");\n },\n });\n\n const searchIntents = defineTool({\n name: \"search_intents\",\n description:\n \"Text-searches the authenticated user's own active signals by description. Case-insensitive substring \" +\n \"match over the signal's payload and summary. Use when the user references a past signal they wrote \" +\n '(\"find my signal about React mentorship\") or wants to audit what they\\'ve posted.\\n\\n' +\n \"For discovery of OTHER users' signals that match a query, use discover_opportunities(searchQuery=...) \" +\n \"instead — that runs semantic matching across the user's networks.\\n\\n\" +\n \"**Returns:** `intents: [{ id, payload, summary, createdAt }]`, most recent first, up to `limit` (default 25).\",\n querySchema: z.object({\n query: z.string().min(1).describe(\"Text to match against payload and summary (case-insensitive).\"),\n limit: z\n .number()\n .int()\n .positive()\n .max(100)\n .optional()\n .describe(\"Maximum intents to return (default 25, max 100).\"),\n }),\n handler: async ({ context, query }) => {\n const rows = await userDb.searchOwnIntents(query.query, query.limit ?? 25);\n logger.verbose(\"search_intents\", { userId: context.userId, query: query.query, matched: rows.length });\n return success({ intents: rows });\n },\n });\n\n return [readIntents, createIntent, updateIntent, deleteIntent, createIntentIndex, readIntentIndexes, deleteIntentIndex, searchIntents] as const;\n}\n"]}
1
+ {"version":3,"file":"intent.tools.js","sourceRoot":"/","sources":["intent/intent.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAE7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;GAGG;AACH,SAAS,wBAAwB,CAAC,IAAY;IAC5C,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;AACvC,CAAC;AAED,wHAAwH;AACxH,KAAK,UAAU,sBAAsB,CACnC,OAAmE,EACnE,QAA8B;IAE9B,IAAI,CAAC,OAAO,CAAC,SAAS;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,eAAe,CAAC,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IACnF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,0BAA0B,OAAO,CAAC,SAAS,IAAI,YAAY,iDAAiD,CAAC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iBAAiB,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,aAAa,CAAU,CAAC;AAClJ,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport type { ExecutionResult, VerifiedIntent } from \"./intent.state.js\";\nimport { DEFAULT_SPECIFICITY_WARNING } from \"./intent.specificity.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\nimport type { UserRecord } from \"../shared/interfaces/database.interface.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"ChatTools:Intent\");\n\n/**\n * Sanitize JSON string for use inside a markdown code fence (```). Escapes backticks\n * so embedded ``` cannot close the fence prematurely.\n */\nfunction sanitizeJsonForCodeFence(json: string): string {\n return json.replace(/`/g, \"\\\\u0060\");\n}\n\n/** When context is index-scoped, verifies the caller is still a member of that index. Returns error message or null. */\nasync function ensureScopedMembership(\n context: { networkId?: string; indexName?: string; userId: string },\n systemDb: ToolDeps['systemDb']\n): Promise<string | null> {\n if (!context.networkId) return null;\n const isMember = await systemDb.isNetworkMember(context.networkId, context.userId);\n if (!isMember) {\n return `This chat is scoped to ${context.indexName ?? 'this index'}. You are no longer a member of this community.`;\n }\n return null;\n}\n\nfunction buildApprovedProfileFallback(user: UserRecord | null | undefined): string {\n const bio = user?.intro?.trim();\n if (!user || !bio) return \"\";\n\n return JSON.stringify({\n userId: user.id,\n identity: {\n name: user.name ?? \"\",\n bio,\n location: user.location?.trim() ?? \"\",\n },\n narrative: { context: bio },\n attributes: { skills: [], interests: [] },\n });\n}\n\nfunction isBroadAttributiveIntent(intent: VerifiedIntent): boolean {\n return intent.verification?.referential_breadth === \"broad\";\n}\n\nfunction specificityWarningFor(intent: VerifiedIntent): string {\n const warning = intent.verification?.specificity_warning?.trim();\n return warning && warning.length > 0 ? warning : DEFAULT_SPECIFICITY_WARNING;\n}\n\nexport function createIntentTools(defineTool: DefineTool, deps: ToolDeps) {\n const { graphs, userDb } = deps;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // INTENT CRUD\n // ─────────────────────────────────────────────────────────────────────────────\n\n const readIntents = defineTool({\n name: \"read_intents\",\n description:\n \"Retrieves intents (signals of interest/need, e.g. 'Looking for a React developer in Berlin'). \" +\n \"Intents are the core unit of discovery — they represent what users are seeking and drive semantic matching for opportunities.\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- No parameters: returns the **caller's own** active intents. In an index-scoped chat the result is clamped to the reachable indexes (the bound index plus the user's personal index). In an unscoped chat the result spans all of the user's active intents. There is no implicit default to the scoped index — to browse the bound community's intents, pass `networkId` explicitly.\\n\" +\n \"- With networkId: returns **all members'** intents in that index (community browse path). Add userId to filter to one member.\\n\" +\n \"- With userId in an index-scoped chat: reads that member's intents in the bound index. The target user must be a member of that index.\\n\" +\n \"- With userId in an unscoped chat: only works for the current user (cannot read another user's global intents without an index scope).\\n\\n\" +\n \"**Workflow:** To explore what members of an index are looking for, first call read_network_memberships(networkId) to list members, \" +\n \"then read_intents(networkId) to see all intents in that community. \" +\n \"Each intent includes: id, description (payload), summary, confidence (0-1), inferenceType (explicit/implicit), status, and linked indexes.\\n\\n\" +\n \"**Returns:** Paginated list of intents with count. Use the intent IDs in subsequent calls to update_intent, delete_intent, or create_intent_index.\",\n querySchema: z.object({\n networkId: z.string().optional().describe(\"Index UUID — filters intents to this index (community browse path: returns all members' intents). There is no implicit default in index-scoped chats; omit to get caller-owned intents across the reachable indexes, or pass the scoped index UUID to browse community members. Get index IDs from read_networks.\"),\n userId: z.string().optional().describe(\"User ID — filters to this user's intents. In an index-scoped chat, this reads that member's intents in the bound index (no networkId required). In an unscoped chat, only the current user is allowed without networkId; cross-user reads require an index scope. Omit for caller-owned intents.\"),\n limit: z.number().int().min(1).max(100).optional().describe(\"Page size (1-100). Defaults to returning all results if omitted.\"),\n page: z.number().int().min(1).optional().describe(\"Page number (1-based). Only used when limit is also provided.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n\n // Distinguish \"explicit network browse\" from \"implicit scope-aware read\"\n const explicitNetworkId = query.networkId?.trim();\n const explicitUserId = query.userId?.trim();\n\n // Validate explicit networkId format\n if (explicitNetworkId && !UUID_REGEX.test(explicitNetworkId)) {\n return error(\"Invalid network ID format.\");\n }\n\n // Strict scope enforcement: in a scoped chat, the only allowed explicit\n // networkId is context.networkId itself. The chat's focus is the bound\n // network; cross-network browse must happen in a separate (unscoped)\n // chat or a chat scoped to that other network.\n if (context.networkId && explicitNetworkId && explicitNetworkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only read intents from this community.`\n );\n }\n\n // Cross-user read in scoped chat: target user must be a member of the scoped index\n if (context.networkId && explicitUserId && explicitUserId !== context.userId) {\n const isInScopedIndex = await deps.systemDb.isNetworkMember(context.networkId, explicitUserId);\n if (!isInScopedIndex) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only read intents from members of this community.`\n );\n }\n }\n\n // Cross-user global read is disallowed without an index scope\n if (!explicitNetworkId && !context.networkId && explicitUserId && explicitUserId !== context.userId) {\n return error(\"Cannot read another user's global intents. Use networkId to scope to a shared network.\");\n }\n\n // Membership check for explicit cross-network reads in unscoped chats\n if (!context.networkId && explicitNetworkId) {\n const callerIsMember = await deps.systemDb.isNetworkMember(explicitNetworkId, context.userId);\n if (!callerIsMember) {\n return error(\"You can only read intents from indexes you are a member of.\");\n }\n }\n\n // ── Choose the read mode ──\n // 1. Explicit networkId (browse all members in that index) — pass networkId, optionally + queryUserId.\n // 2. Explicit userId in a scoped chat — read that user's intents in the bound network.\n // 3. Explicit userId in an unscoped chat — only self (cross-user rejected above); global \"my intents\".\n // 4. Implicit (no explicit network/user) in scoped chat — pass indexScope, no networkId.\n // 5. Implicit in unscoped chat — global getActiveIntents (caller's own).\n const graphInput: Record<string, unknown> = {\n userId: context.userId,\n userProfile: \"\",\n operationMode: 'read' as const,\n };\n\n if (explicitNetworkId) {\n graphInput.networkId = explicitNetworkId;\n if (explicitUserId) graphInput.queryUserId = explicitUserId;\n } else if (explicitUserId && context.networkId) {\n // Scoped chat + userId: implicit network is the chat's bound network.\n // Membership of the target user was verified above.\n graphInput.networkId = context.networkId;\n graphInput.queryUserId = explicitUserId;\n } else if (explicitUserId) {\n // Unscoped chat + userId: only allowed for self (others rejected above).\n graphInput.queryUserId = explicitUserId;\n graphInput.allUserIntents = true;\n } else if (context.indexScope && context.indexScope.length > 0 && context.networkId) {\n // Scoped chat, implicit read: caller-only across reachable indexes.\n graphInput.indexScope = context.indexScope;\n } else {\n // Unscoped, implicit read: caller's global intents.\n graphInput.allUserIntents = true;\n }\n\n const _readIntentGraphStart = Date.now();\n const _readIntentTraceEmitter = requestContext.getStore()?.traceEmitter;\n _readIntentTraceEmitter?.({ type: \"graph_start\", name: \"intent\" });\n const result = await invokeWithAbortSignal(graphs.intent, graphInput);\n const _readIntentGraphMs = Date.now() - _readIntentGraphStart;\n _readIntentTraceEmitter?.({ type: \"graph_end\", name: \"intent\", durationMs: _readIntentGraphMs });\n\n if (result.readResult) {\n if (result.readResult.count === 0 && result.readResult.message && /not a member|Network not found/i.test(result.readResult.message)) {\n return error(result.readResult.message);\n }\n\n const shouldPaginate = query.limit !== undefined || query.page !== undefined;\n if (shouldPaginate && Array.isArray(result.readResult.intents)) {\n const limit = query.limit ?? 20;\n const page = query.page ?? 1;\n const offset = (page - 1) * limit;\n const pagedIntents = result.readResult.intents.slice(offset, offset + limit);\n return success({\n ...result.readResult,\n count: pagedIntents.length,\n totalCount: result.readResult.intents.length,\n limit,\n page,\n totalPages: Math.ceil(result.readResult.intents.length / limit),\n intents: pagedIntents,\n _graphTimings: [{ name: 'intent', durationMs: _readIntentGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n\n return success({ ...result.readResult, _graphTimings: [{ name: 'intent', durationMs: _readIntentGraphMs, agents: result.agentTimings ?? [] }] });\n }\n return error(\"Failed to fetch intents.\");\n },\n });\n\n const createIntent = defineTool({\n name: \"create_intent\",\n description:\n \"Creates a new intent (signal of interest/need) for the authenticated user. Intents drive the discovery engine — once created, \" +\n \"the system automatically evaluates them against indexes the user belongs to, links them to relevant communities, and begins \" +\n \"searching for matching opportunities (complementary intents from other users).\\n\\n\" +\n \"**What to pass:** A clear, concept-based description of what the user is looking for (e.g. 'Looking for an AI/ML co-founder in Berlin', \" +\n \"'Need a designer for a mobile app project'). If the user provided a URL, scrape it with scrape_url first and synthesize the content into a description.\\n\\n\" +\n \"**What happens:** The system runs inference (extracting structured intents), verification (checking specificity and speech-act type), \" +\n \"and returns a proposal widget. The proposal is NOT yet persisted — the user must approve it first.\\n\\n\" +\n \"**Returns:** An intent_proposal code block that MUST be included verbatim in the response. The frontend renders it as an interactive \" +\n \"card the user can approve or skip. On approval, the intent is persisted, indexed, and discovery begins.\\n\\n\" +\n \"**Next steps after approval:** The intent is automatically linked to relevant indexes. Call discover_opportunities(searchQuery) to explicitly trigger discovery, \" +\n \"or wait for background processing to find matches.\\n\\n\" +\n \"**Specificity gate.** Before calling this tool, judge whether the description is concrete enough to be \" +\n \"useful for matching. If the user says \\\"find a job\\\", \\\"meet people\\\", or \\\"learn something\\\", that's too \" +\n \"vague — FIRST call read_user_profiles() + read_intents() to understand their context, THEN propose a \" +\n \"refined version (\\\"Based on your background in X, did you mean 'Y'?\\\") and wait for confirmation before \" +\n \"calling create_intent. Specific asks (\\\"senior UX design role at a tech company in Berlin\\\") can go \" +\n \"directly to create_intent.\\n\\n\" +\n \"**URL handling.** If the user pastes a URL describing the intent (e.g. a job posting), call scrape_url \" +\n \"first with objective=\\\"Extract key details for an intent\\\", synthesize a conceptual description from the \" +\n \"content, then call create_intent with the synthesis. Exception: profile URLs (LinkedIn, GitHub, X) passed \" +\n \"to create_user_profile are handled by that tool directly — do not scrape first.\",\n querySchema: z.object({\n 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.\"),\n 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.\"),\n autoApprove: z.boolean().optional().describe(\"When true, automatically persists all verified intents without returning proposal cards for manual approval. MCP agents SHOULD set this to true since there is no UI for card-based approval. Web chat agents should omit or set to false to get interactive proposal cards.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n if (!query.description?.trim()) {\n return error(\"Description is required.\");\n }\n\n // Strict scope enforcement\n if (context.networkId && query.networkId?.trim() && query.networkId.trim() !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only create intents in this community.`\n );\n }\n\n const effectiveIndexId = context.networkId || query.networkId?.trim() || undefined;\n\n // Fetch profile (the intent graph needs it for inference)\n const _profileGraphStart1 = Date.now();\n const _createIntentProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createIntentProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const profileResult = await invokeWithAbortSignal(graphs.profile, { userId: context.userId, operationMode: 'query' as const });\n const _profileGraphMs1 = Date.now() - _profileGraphStart1;\n _createIntentProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _profileGraphMs1 });\n const latestUser = profileResult.profile ? undefined : typeof userDb.getUser === \"function\" ? await userDb.getUser() : context.user;\n const approvedProfileFallback = profileResult.profile ? \"\" : buildApprovedProfileFallback(latestUser);\n const userProfile = profileResult.profile ? JSON.stringify(profileResult.profile) : approvedProfileFallback;\n\n // Run inference + verification only (propose mode — no DB persistence)\n const _intentGraphStart1 = Date.now();\n const _createIntentTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createIntentTraceEmitter?.({ type: \"graph_start\", name: \"intent\" });\n const result = await invokeWithAbortSignal(graphs.intent, {\n userId: context.userId,\n userProfile,\n inputContent: query.description,\n operationMode: 'propose' as const,\n ...(effectiveIndexId ? { networkId: effectiveIndexId } : {}),\n });\n const _intentGraphMs1 = Date.now() - _intentGraphStart1;\n _createIntentTraceEmitter?.({ type: \"graph_end\", name: \"intent\", durationMs: _intentGraphMs1 });\n logger.debug(\"Intent graph propose response\", { result });\n\n const verified = result.verifiedIntents || [];\n\n // MCP contexts have no interactive UI for proposal cards — default to auto-approve\n const shouldAutoApprove = query.autoApprove ?? context.isMcp ?? false;\n \n // Extract trace from graph and convert to debugSteps\n const trace = Array.isArray(result.trace) ? result.trace : [];\n const debugSteps = trace.map((t: { node: string; detail?: string; data?: Record<string, unknown> }) => ({\n step: t.node,\n detail: t.detail,\n ...(t.data ? { data: t.data } : {}),\n }));\n \n if (verified.length === 0) {\n // Build a descriptive rejection reason from the trace so the ReACT agent\n // can retry with a better description or ask the user for clarification.\n // When inference produces 0 intents, propose mode exits before verification\n // runs — so we check inference trace first.\n const verificationTrace = debugSteps.find((s: { step: string; detail?: string }) => s.step === \"verification\");\n\n if (!verificationTrace) {\n const inferenceHint =\n debugSteps.find((s: { step: string; detail?: string }) => s.step === \"inference\")?.detail\n ?? \"no intents extracted\";\n return error(\n `No actionable intent was extracted (${inferenceHint}). ` +\n `Please retry with a more specific goal (what kind, what for, and/or timeframe), ` +\n `or ask the user to clarify.`,\n debugSteps,\n );\n }\n\n const rejectionHint =\n verificationTrace.detail ?? \"all candidate intents were filtered as invalid or too vague\";\n return error(\n `Intent verification failed (${rejectionHint}). ` +\n `The description may be too vague or was classified as a statement rather than a goal. ` +\n `Either retry with a more specific description (e.g. include what kind, what for, or a timeframe) ` +\n `or ask the user to clarify what exactly they are looking for.`,\n debugSteps,\n );\n }\n\n // ── Auto-approve path (for MCP agents or explicit opt-in) ──\n if (shouldAutoApprove) {\n const broadIntents = (verified as VerifiedIntent[]).filter(isBroadAttributiveIntent);\n if (broadIntents.length > 0) {\n const first = broadIntents[0];\n const missing = first.verification?.missing_selectional_constraints ?? [];\n const missingHint = missing.length > 0 ? ` Missing selectional constraints: ${missing.join(\", \")}.` : \"\";\n return error(\n `${specificityWarningFor(first)}${missingHint} ` +\n `Please ask the user to clarify before creating this signal, or retry with a narrower description.`,\n debugSteps,\n );\n }\n\n const createdIntents: Array<{ description: string; confidence: number | null; speechActType: string | null }> = [];\n const createTimings: Array<{ name: string; durationMs: number; agents: unknown[] }> = [];\n\n for (const v of verified as VerifiedIntent[]) {\n const _createGraphStart = Date.now();\n const _createTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createTraceEmitter?.({ type: \"graph_start\", name: \"intent\" });\n const createResult = await invokeWithAbortSignal(graphs.intent, {\n userId: context.userId,\n userProfile,\n inputContent: v.description,\n operationMode: 'create' as const,\n ...(effectiveIndexId ? { networkId: effectiveIndexId } : {}),\n });\n const _createGraphMs = Date.now() - _createGraphStart;\n _createTraceEmitter?.({ type: \"graph_end\", name: \"intent\", durationMs: _createGraphMs });\n\n createTimings.push({ name: 'intent-create', durationMs: _createGraphMs, agents: createResult.agentTimings ?? [] });\n\n const succeeded = createResult.executionResults?.some((r: ExecutionResult) => r.success);\n if (succeeded) {\n createdIntents.push({\n description: v.description,\n confidence: v.score != null ? Math.round(v.score * 100) / 100 : null,\n speechActType: v.verification?.classification ?? null,\n });\n }\n }\n\n return success({\n created: createdIntents.length > 0,\n count: createdIntents.length,\n intents: createdIntents,\n message: createdIntents.length > 0\n ? `Created ${createdIntents.length} intent${createdIntents.length > 1 ? 's' : ''} successfully. The system will automatically index them and begin searching for matching opportunities.`\n : 'Intent creation failed — the intents could not be persisted.',\n debugSteps,\n _graphTimings: [\n { name: 'profile', durationMs: _profileGraphMs1, agents: profileResult.agentTimings ?? [] },\n { name: 'intent-propose', durationMs: _intentGraphMs1, agents: result.agentTimings ?? [] },\n ...createTimings,\n ],\n });\n }\n\n // ── Proposal path (for web chat with interactive cards) ──\n // Build intent_proposal code fences for each verified intent\n const proposalBlocks = verified.map((v: VerifiedIntent) => {\n const proposalId = crypto.randomUUID();\n const isBroad = isBroadAttributiveIntent(v);\n const data = {\n proposalId,\n description: v.description,\n ...(effectiveIndexId ? { networkId: effectiveIndexId } : {}),\n confidence: v.score != null ? Math.round(v.score * 100) / 100 : null,\n speechActType: v.verification?.classification ?? null,\n semanticEntropy: v.verification?.semantic_entropy ?? null,\n referentialBreadth: v.verification?.referential_breadth ?? null,\n missingSelectionalConstraints: v.verification?.missing_selectional_constraints ?? [],\n specificityWarning: isBroad ? specificityWarningFor(v) : v.verification?.specificity_warning ?? null,\n };\n return (\n \"```intent_proposal\\n\" +\n sanitizeJsonForCodeFence(JSON.stringify(data)) +\n \"\\n```\"\n );\n });\n\n const blocksText = proposalBlocks.join(\"\\n\\n\");\n\n return success({\n proposed: true,\n count: verified.length,\n message: `IMPORTANT: Include the following \\`\\`\\`intent_proposal code blocks EXACTLY as-is in your response (they render as interactive cards for the user to approve or skip):\\n\\n${blocksText}`,\n debugSteps,\n _graphTimings: [\n { name: 'profile', durationMs: _profileGraphMs1, agents: profileResult.agentTimings ?? [] },\n { name: 'intent', durationMs: _intentGraphMs1, agents: result.agentTimings ?? [] },\n ],\n });\n },\n });\n\n const updateIntent = defineTool({\n name: \"update_intent\",\n description:\n \"Updates an existing intent's description. After updating, the system re-processes the intent through inference and verification, \" +\n \"re-evaluates its index assignments, and triggers fresh opportunity discovery with the new description.\\n\\n\" +\n \"**When to use:** When the user wants to refine or change what they're looking for — e.g. narrowing scope, adding specificity, \" +\n \"or pivoting to a different need. Prefer updating over delete+create to preserve the intent's history and existing index links.\\n\\n\" +\n \"**Returns:** Updated `intentId` and `description`, plus a confirmation message. The intent's embeddings and index relevancy scores are recalculated automatically.\",\n querySchema: z.object({\n intentId: z.string().describe(\"The UUID of the intent to update. Get this from read_intents results.\"),\n description: z.string().describe(\"The updated description of what the user is looking for. Same guidelines as create_intent — should be clear and specific.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n const intentId = query.intentId?.trim() ?? \"\";\n if (!UUID_REGEX.test(intentId)) {\n return error(\"Invalid intent ID format.\");\n }\n\n // Ownership guard: caller must own the intent\n const intent = await deps.systemDb.getIntent(intentId);\n if (!intent || intent.userId !== context.userId) {\n return error(\"Intent not found or you can only update your own intents.\");\n }\n if (intent.archivedAt) {\n return error(\"This intent is archived and cannot be updated. Create a new intent instead.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, verify intent is linked to that index\n if (context.networkId) {\n const db = deps.userDb;\n const intentNetworks = await db.getNetworkIdsForIntent(intentId);\n if (!intentNetworks.includes(context.networkId)) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only update intents linked to this community.`\n );\n }\n }\n\n const _profileGraphStart2 = Date.now();\n const _updateIntentProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _updateIntentProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const profileResult = await invokeWithAbortSignal(graphs.profile, { userId: context.userId, operationMode: 'query' as const });\n const _profileGraphMs2 = Date.now() - _profileGraphStart2;\n _updateIntentProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _profileGraphMs2 });\n const latestUser = profileResult.profile ? undefined : typeof userDb.getUser === \"function\" ? await userDb.getUser() : context.user;\n const approvedProfileFallback = profileResult.profile ? \"\" : buildApprovedProfileFallback(latestUser);\n const userProfile = profileResult.profile ? JSON.stringify(profileResult.profile) : approvedProfileFallback;\n\n const _intentGraphStart2 = Date.now();\n const _updateIntentTraceEmitter = requestContext.getStore()?.traceEmitter;\n _updateIntentTraceEmitter?.({ type: \"graph_start\", name: \"intent\" });\n const result = await invokeWithAbortSignal(graphs.intent, {\n userId: context.userId,\n userProfile,\n operationMode: 'update' as const,\n inputContent: query.description,\n targetIntentIds: [intentId],\n ...(context.networkId && { networkId: context.networkId }),\n });\n const _intentGraphMs2 = Date.now() - _intentGraphStart2;\n _updateIntentTraceEmitter?.({ type: \"graph_end\", name: \"intent\", durationMs: _intentGraphMs2 });\n\n if (result.executionResults?.some((r: ExecutionResult) => !r.success)) {\n return error(\"Failed to update intent.\");\n }\n if (!result.executionResults?.some((r: ExecutionResult) => r.success)) {\n return error(\n \"Intent update was not applied. The new description may be too broad, too vague, or failed semantic verification. Please ask the user to clarify with a more concrete role, outcome, location, timeframe, domain, or specific need.\",\n );\n }\n return success({\n message: \"Intent updated.\",\n intentId,\n description: query.description,\n _graphTimings: [\n { name: 'profile', durationMs: _profileGraphMs2, agents: profileResult.agentTimings ?? [] },\n { name: 'intent', durationMs: _intentGraphMs2, agents: result.agentTimings ?? [] },\n ],\n });\n },\n });\n\n const deleteIntent = defineTool({\n name: \"delete_intent\",\n description:\n \"Archives (soft-deletes) an intent, removing it from active discovery. The intent is not permanently deleted — it is marked as archived \" +\n \"and no longer participates in opportunity matching or index evaluation.\\n\\n\" +\n \"**When to use:** When the user's need has been fulfilled, is no longer relevant, or was created by mistake. \" +\n \"If the user wants to change the description instead, use update_intent to preserve history.\\n\\n\" +\n \"**Returns:** Confirmation that the intent was archived. Previously created opportunities from this intent remain but won't generate new ones.\",\n querySchema: z.object({\n intentId: z.string().describe(\"The UUID of the intent to archive. Get this from read_intents results.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n const intentId = query.intentId?.trim() ?? \"\";\n if (!UUID_REGEX.test(intentId)) {\n return error(\"Invalid intent ID format.\");\n }\n\n // Ownership guard: caller must own the intent\n const intent = await deps.systemDb.getIntent(intentId);\n if (!intent || intent.userId !== context.userId) {\n return error(\"Intent not found or you can only delete your own intents.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, verify intent is linked to that index\n if (context.networkId) {\n const db = deps.userDb;\n const intentNetworks = await db.getNetworkIdsForIntent(intentId);\n if (!intentNetworks.includes(context.networkId)) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only delete intents linked to this community.`\n );\n }\n }\n\n const _deleteIntentGraphStart = Date.now();\n const _deleteIntentTraceEmitter = requestContext.getStore()?.traceEmitter;\n _deleteIntentTraceEmitter?.({ type: \"graph_start\", name: \"intent\" });\n const result = await invokeWithAbortSignal(graphs.intent, {\n userId: context.userId,\n userProfile: \"\",\n operationMode: 'delete' as const,\n targetIntentIds: [intentId],\n ...(context.networkId && { networkId: context.networkId }),\n });\n const _deleteIntentGraphMs = Date.now() - _deleteIntentGraphStart;\n _deleteIntentTraceEmitter?.({ type: \"graph_end\", name: \"intent\", durationMs: _deleteIntentGraphMs });\n\n if (result.executionResults?.some((r: ExecutionResult) => !r.success)) {\n return error(\"Failed to delete intent.\");\n }\n return success({\n message: \"Intent archived successfully.\",\n _graphTimings: [{ name: 'intent', durationMs: _deleteIntentGraphMs, agents: result.agentTimings ?? [] }],\n });\n },\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // INTENT–INDEX JUNCTION (link / list / unlink)\n // ─────────────────────────────────────────────────────────────────────────────\n\n const createIntentIndex = defineTool({\n name: \"create_intent_index\",\n description:\n \"Manually links an intent to an index (community), making it visible to other members and eligible for opportunity discovery within that index. \" +\n \"Normally intents are auto-assigned to relevant indexes on creation, but use this to explicitly add an intent to an additional index.\\n\\n\" +\n \"**When to use:** When the user wants to share an existing intent with a specific community they belong to, \" +\n \"or when auto-assignment missed an index the user considers relevant.\\n\\n\" +\n \"**Returns:** Confirmation that the link was created. The intent will now appear in that index's intent list and participate in discovery within that community.\",\n querySchema: z.object({\n intentId: z.string().describe(\"The UUID of the intent to link. Get this from read_intents results.\"),\n networkId: z.string().optional().describe(\"The UUID of the index to link the intent to. Get this from read_networks. Defaults to the scoped index in index-scoped chats.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n const intentId = query.intentId?.trim() ?? \"\";\n const networkId = query.networkId?.trim() || context.networkId || \"\";\n if (!UUID_REGEX.test(intentId) || !UUID_REGEX.test(networkId)) {\n return error(\"Invalid ID format. Both must be UUIDs.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow linking to that index\n if (context.networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only link intents to this community.`\n );\n }\n\n const _createIntentIndexGraphStart = Date.now();\n const _createIntentIndexTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createIntentIndexTraceEmitter?.({ type: \"graph_start\", name: \"intent_network\" });\n const result = await invokeWithAbortSignal(graphs.intentIndex, {\n userId: context.userId,\n networkId,\n intentId,\n operationMode: 'create' as const,\n skipEvaluation: true,\n });\n const _createIntentIndexGraphMs = Date.now() - _createIntentIndexGraphStart;\n _createIntentIndexTraceEmitter?.({ type: \"graph_end\", name: \"intent_network\", durationMs: _createIntentIndexGraphMs });\n\n if (result.mutationResult) {\n if (result.mutationResult.success) {\n const alreadyExisted = result.mutationResult.message?.includes('already in this network') ?? false;\n return success({\n created: !alreadyExisted,\n message: result.mutationResult.message,\n _graphTimings: [{ name: 'intent_network', durationMs: _createIntentIndexGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(result.mutationResult.error || \"Failed to link intent to network.\");\n }\n return error(\"Failed to link intent to network.\");\n },\n });\n\n const readIntentIndexes = defineTool({\n name: \"read_intent_indexes\",\n description:\n \"Reads the many-to-many links between intents and indexes. Use this to understand which intents are shared in which communities, \" +\n \"and which indexes a specific intent belongs to.\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- With networkId: lists all intents linked to that index. Add userId to filter to one member's intents in that index.\\n\" +\n \"- With intentId + networkId: checks whether a specific intent is linked to a specific index.\\n\" +\n \"- intentId alone requires a networkId (the system won't reveal all indexes an intent is in).\\n\\n\" +\n \"**When to use:** To audit which intents are active in a community, verify an intent's index assignment before unlinking, \" +\n \"or check if a newly created intent was auto-assigned to the expected index.\\n\\n\" +\n \"**Returns:** List of intent-index links with relevancy scores (0-1, how well the intent fits the index's purpose).\",\n querySchema: z.object({\n intentId: z.string().optional().describe(\"Intent UUID — check if this specific intent is linked to the specified index. Must be combined with networkId.\"),\n networkId: z.string().optional().describe(\"Index UUID — list all intents linked to this index. Get this from read_networks. Defaults to scoped index in index-scoped chats.\"),\n userId: z.string().optional().describe(\"Filter results to this user's intents within the specified index. Omit to see all members' intents.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n const intentId = query.intentId?.trim() || undefined;\n let networkId = query.networkId?.trim() || context.networkId || undefined;\n const queryUserId = query.userId?.trim() || undefined;\n\n if (intentId && !UUID_REGEX.test(intentId)) {\n return error(\"Invalid intent ID format.\");\n }\n if (networkId && !UUID_REGEX.test(networkId)) {\n return error(\"Invalid network ID format.\");\n }\n if (!intentId && !networkId) {\n return error(\"Provide networkId or intentId.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow querying that index\n if (context.networkId && networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only read intent links from this community.`\n );\n }\n\n // When only intentId is provided, enforce scope - don't reveal all linked indexes\n if (intentId && !networkId) {\n if (context.networkId) {\n // When scoped, only check if intent is linked to the scoped index\n networkId = context.networkId;\n } else {\n // When unscoped, still don't reveal all indexes - require explicit networkId\n return error(\n \"Please provide a networkId to check if the intent is linked to a specific network. Listing all linked networks is not supported.\"\n );\n }\n }\n\n const _readIntentIndexGraphStart = Date.now();\n const _readIntentIndexTraceEmitter = requestContext.getStore()?.traceEmitter;\n _readIntentIndexTraceEmitter?.({ type: \"graph_start\", name: \"intent_network\" });\n const result = await invokeWithAbortSignal(graphs.intentIndex, {\n userId: context.userId,\n networkId,\n intentId,\n operationMode: 'read' as const,\n queryUserId,\n });\n const _readIntentIndexGraphMs = Date.now() - _readIntentIndexGraphStart;\n _readIntentIndexTraceEmitter?.({ type: \"graph_end\", name: \"intent_network\", durationMs: _readIntentIndexGraphMs });\n\n if (result.error) {\n return error(result.error);\n }\n if (result.readResult) {\n return success({ ...result.readResult, _graphTimings: [{ name: 'intent_network', durationMs: _readIntentIndexGraphMs, agents: result.agentTimings ?? [] }] });\n }\n return error(\"Failed to fetch intent-network links.\");\n },\n });\n\n const deleteIntentIndex = defineTool({\n name: \"delete_intent_index\",\n description:\n \"Removes the link between an intent and an index. The intent itself is NOT deleted — it just stops being visible in that community \" +\n \"and no longer participates in opportunity discovery within that index. The intent may still be linked to other indexes.\\n\\n\" +\n \"**When to use:** When the user wants to withdraw an intent from a specific community without archiving it entirely. \" +\n \"Use read_intent_indexes first to verify the link exists.\\n\\n\" +\n \"**Returns:** Confirmation that the link was removed. To fully remove an intent, use delete_intent instead.\",\n querySchema: z.object({\n intentId: z.string().describe(\"The UUID of the intent to unlink. Get this from read_intents or read_intent_indexes.\"),\n networkId: z.string().optional().describe(\"The UUID of the index to unlink from. Get this from read_networks. Defaults to the scoped index in index-scoped chats.\"),\n }),\n handler: async ({ context, query }) => {\n const scopeErr = await ensureScopedMembership(context, deps.systemDb);\n if (scopeErr) return error(scopeErr);\n const intentId = query.intentId?.trim() ?? \"\";\n const networkId = query.networkId?.trim() || context.networkId || \"\";\n if (!UUID_REGEX.test(intentId) || !UUID_REGEX.test(networkId)) {\n return error(\"Invalid ID format. Both must be UUIDs.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow unlinking from that index\n if (context.networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only unlink intents from this community.`\n );\n }\n\n const _deleteIntentIndexGraphStart = Date.now();\n const _deleteIntentIndexTraceEmitter = requestContext.getStore()?.traceEmitter;\n _deleteIntentIndexTraceEmitter?.({ type: \"graph_start\", name: \"intent_network\" });\n const result = await invokeWithAbortSignal(graphs.intentIndex, {\n userId: context.userId,\n networkId,\n intentId,\n operationMode: 'delete' as const,\n });\n const _deleteIntentIndexGraphMs = Date.now() - _deleteIntentIndexGraphStart;\n _deleteIntentIndexTraceEmitter?.({ type: \"graph_end\", name: \"intent_network\", durationMs: _deleteIntentIndexGraphMs });\n\n if (result.mutationResult) {\n if (result.mutationResult.success) {\n return success({\n deleted: true,\n message: result.mutationResult.message,\n _graphTimings: [{ name: 'intent_network', durationMs: _deleteIntentIndexGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(result.mutationResult.error || \"Failed to unlink.\");\n }\n return error(\"Failed to unlink intent from network.\");\n },\n });\n\n const searchIntents = defineTool({\n name: \"search_intents\",\n description:\n \"Text-searches the authenticated user's own active signals by description. Case-insensitive substring \" +\n \"match over the signal's payload and summary. Use when the user references a past signal they wrote \" +\n '(\"find my signal about React mentorship\") or wants to audit what they\\'ve posted.\\n\\n' +\n \"For discovery of OTHER users' signals that match a query, use discover_opportunities(searchQuery=...) \" +\n \"instead — that runs semantic matching across the user's networks.\\n\\n\" +\n \"**Returns:** `intents: [{ id, payload, summary, createdAt }]`, most recent first, up to `limit` (default 25).\",\n querySchema: z.object({\n query: z.string().min(1).describe(\"Text to match against payload and summary (case-insensitive).\"),\n limit: z\n .number()\n .int()\n .positive()\n .max(100)\n .optional()\n .describe(\"Maximum intents to return (default 25, max 100).\"),\n }),\n handler: async ({ context, query }) => {\n const rows = await userDb.searchOwnIntents(query.query, query.limit ?? 25);\n logger.verbose(\"search_intents\", { userId: context.userId, query: query.query, matched: rows.length });\n return success({ intents: rows });\n },\n });\n\n return [readIntents, createIntent, updateIntent, deleteIntent, createIntentIndex, readIntentIndexes, deleteIntentIndex, searchIntents] as const;\n}\n"]}
@@ -1,4 +1,6 @@
1
1
  import { z } from "zod";
2
+ declare const referentialBreadthSchema: z.ZodEnum<["narrow", "moderate", "broad"]>;
3
+ declare const missingSelectionalConstraintSchema: z.ZodEnum<["role", "outcome", "location", "timeframe", "domain", "concrete_need"]>;
2
4
  declare const responseFormat: z.ZodObject<{
3
5
  reasoning: z.ZodString;
4
6
  classification: z.ZodEnum<["COMMISSIVE", "DIRECTIVE", "ASSERTIVE", "EXPRESSIVE", "DECLARATION", "UNKNOWN"]>;
@@ -17,6 +19,9 @@ declare const responseFormat: z.ZodObject<{
17
19
  }>;
18
20
  semantic_entropy: z.ZodNumber;
19
21
  referential_anchor: z.ZodNullable<z.ZodString>;
22
+ referential_breadth: z.ZodEnum<["narrow", "moderate", "broad"]>;
23
+ missing_selectional_constraints: z.ZodArray<z.ZodEnum<["role", "outcome", "location", "timeframe", "domain", "concrete_need"]>, "many">;
24
+ specificity_warning: z.ZodNullable<z.ZodString>;
20
25
  flags: z.ZodArray<z.ZodString, "many">;
21
26
  }, "strip", z.ZodTypeAny, {
22
27
  reasoning: string;
@@ -28,6 +33,9 @@ declare const responseFormat: z.ZodObject<{
28
33
  };
29
34
  semantic_entropy: number;
30
35
  referential_anchor: string | null;
36
+ referential_breadth: "narrow" | "moderate" | "broad";
37
+ missing_selectional_constraints: ("location" | "role" | "outcome" | "timeframe" | "domain" | "concrete_need")[];
38
+ specificity_warning: string | null;
31
39
  flags: string[];
32
40
  }, {
33
41
  reasoning: string;
@@ -39,8 +47,13 @@ declare const responseFormat: z.ZodObject<{
39
47
  };
40
48
  semantic_entropy: number;
41
49
  referential_anchor: string | null;
50
+ referential_breadth: "narrow" | "moderate" | "broad";
51
+ missing_selectional_constraints: ("location" | "role" | "outcome" | "timeframe" | "domain" | "concrete_need")[];
52
+ specificity_warning: string | null;
42
53
  flags: string[];
43
54
  }>;
55
+ export type ReferentialBreadth = z.infer<typeof referentialBreadthSchema>;
56
+ export type MissingSelectionalConstraint = z.infer<typeof missingSelectionalConstraintSchema>;
44
57
  export type SemanticVerifierOutput = z.infer<typeof responseFormat>;
45
58
  export declare class SemanticVerifier {
46
59
  private model;
@@ -60,6 +73,9 @@ export declare class SemanticVerifier {
60
73
  };
61
74
  semantic_entropy: number;
62
75
  referential_anchor: string | null;
76
+ referential_breadth: "narrow" | "moderate" | "broad";
77
+ missing_selectional_constraints: ("location" | "role" | "outcome" | "timeframe" | "domain" | "concrete_need")[];
78
+ specificity_warning: string | null;
63
79
  flags: string[];
64
80
  }>;
65
81
  /**
@@ -90,6 +106,9 @@ export declare class SemanticVerifier {
90
106
  };
91
107
  semantic_entropy: number;
92
108
  referential_anchor: string | null;
109
+ referential_breadth: "narrow" | "moderate" | "broad";
110
+ missing_selectional_constraints: ("location" | "role" | "outcome" | "timeframe" | "domain" | "concrete_need")[];
111
+ specificity_warning: string | null;
93
112
  flags: string[];
94
113
  }, unknown, "semantic_verifier">;
95
114
  }
@@ -1 +1 @@
1
- {"version":3,"file":"intent.verifier.d.ts","sourceRoot":"/","sources":["intent/intent.verifier.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAyIxB,QAAA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmClB,CAAC;AAMH,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AAMpE,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,KAAK,CAAM;;IAQnB;;;;OAIG;IAEU,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;;;;;;;;;;;;IA8BpD;;OAEG;WACW,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgBrB"}
1
+ {"version":3,"file":"intent.verifier.d.ts","sourceRoot":"/","sources":["intent/intent.verifier.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB,QAAA,MAAM,wBAAwB,4CAA0C,CAAC;AACzE,QAAA,MAAM,kCAAkC,oFAOtC,CAAC;AAwJH,QAAA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+ClB,CAAC;AAMH,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAC1E,MAAM,MAAM,4BAA4B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kCAAkC,CAAC,CAAC;AAC9F,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AAMpE,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,KAAK,CAAM;;IAQnB;;;;OAIG;IAEU,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;;;;;;;;;;;;;;;IA8BpD;;OAEG;WACW,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgBrB"}
@@ -15,6 +15,15 @@ import { Timed } from "../shared/observability/performance.js";
15
15
  import { createModel } from "../shared/agent/model.config.js";
16
16
  import { invokeWithAbortSignal } from "../shared/agent/model-signal.js";
17
17
  const logger = protocolLogger("SemanticVerifier");
18
+ const referentialBreadthSchema = z.enum(["narrow", "moderate", "broad"]);
19
+ const missingSelectionalConstraintSchema = z.enum([
20
+ "role",
21
+ "outcome",
22
+ "location",
23
+ "timeframe",
24
+ "domain",
25
+ "concrete_need",
26
+ ]);
18
27
  const model = createModel("intentVerifier");
19
28
  // ──────────────────────────────────────────────────────────────
20
29
  // 1. SYSTEM PROMPT
@@ -128,6 +137,26 @@ REFERENTIAL ANCHOR → referential_anchor field
128
137
  "I want to join Google" → "Google"
129
138
  "I want to join a startup" → null
130
139
 
140
+ REFERENTIAL BREADTH → referential_breadth field
141
+ Estimate the extension size of the open candidate class: how many people could plausibly satisfy the description.
142
+ This is NOT the same as semantic_entropy. Semantic entropy measures underspecification/constraint density;
143
+ referential breadth measures whether the attributive description narrows the satisfier class enough for discovery.
144
+
145
+ narrow → a small satisfier class due to concrete role/outcome/location/timeframe/specific need.
146
+ Example: "Find a robotics founder in Healdsburg this week to test my meditation hardware prototype"
147
+ moderate → a bounded professional/community class, but some constraints are still missing.
148
+ Example: "Meet AI safety researchers working on evals in London"
149
+ broad → a large satisfier class; many people could plausibly match even if topical constraints are present.
150
+ Example: "Meet creative people, builders, and makers interested in AI, meditation, and tech exploration"
151
+
152
+ MISSING SELECTIONAL CONSTRAINTS → missing_selectional_constraints field
153
+ Report the constraints whose absence keeps the candidate class too broad:
154
+ role, outcome, location, timeframe, domain, concrete_need.
155
+
156
+ SPECIFICITY WARNING → specificity_warning field
157
+ If referential_breadth is broad, provide a concise user-facing warning asking for a more concrete role,
158
+ outcome, location, timeframe, domain, or need. Otherwise output null.
159
+
131
160
  ═══════════════════════════════════════════════════
132
161
  STEP 3 — FLAGS
133
162
  ═══════════════════════════════════════════════════
@@ -137,6 +166,7 @@ Add flags when scores fall below threshold:
137
166
  sincerity < 70 → "WEAK_COMMITMENT"
138
167
  clarity < 50 → "VAGUE_INTENT"
139
168
  classification is ASSERTIVE or EXPRESSIVE → "NOISE"
169
+ referential_breadth is broad → "BROAD_ATTRIBUTIVE_REFERENCE"
140
170
  `;
141
171
  // ──────────────────────────────────────────────────────────────
142
172
  // 2. RESPONSE SCHEMA (Zod)
@@ -162,7 +192,10 @@ const responseFormat = z.object({
162
192
  }),
163
193
  semantic_entropy: z.number().min(0).max(1).describe("Constraint density: 0.0 = maximally specific (time + location + tech + quantifiers), 1.0 = completely unconstrained"),
164
194
  referential_anchor: z.string().nullable().describe("Named specific entity the utterance refers to (Donnellan referential), or null for attributive reference"),
165
- flags: z.array(z.string()).describe("Semantic violation tags: SKILL_MISMATCH (authority<70), WEAK_COMMITMENT (sincerity<70), VAGUE_INTENT (clarity<50), NOISE (ASSERTIVE or EXPRESSIVE)"),
195
+ referential_breadth: referentialBreadthSchema.describe("Extension size of the open candidate class: narrow, moderate, or broad. Distinct from semantic entropy."),
196
+ missing_selectional_constraints: z.array(missingSelectionalConstraintSchema).describe("Selectional constraints whose absence leaves the satisfier class too broad."),
197
+ specificity_warning: z.string().nullable().describe("Concise user-facing warning when referential_breadth is broad; otherwise null."),
198
+ flags: z.array(z.string()).describe("Semantic violation tags: SKILL_MISMATCH (authority<70), WEAK_COMMITMENT (sincerity<70), VAGUE_INTENT (clarity<50), NOISE (ASSERTIVE or EXPRESSIVE), BROAD_ATTRIBUTIVE_REFERENCE (referential_breadth=broad)"),
166
199
  });
167
200
  // ──────────────────────────────────────────────────────────────
168
201
  // 4. CLASS DEFINITION
@@ -1 +1 @@
1
- {"version":3,"file":"intent.verifier.js","sourceRoot":"/","sources":["intent/intent.verifier.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD,MAAM,KAAK,GAAG,WAAW,CAAC,gBAAgB,CAAC,CAAC;AAC5C,iEAAiE;AACjE,mBAAmB;AACnB,iEAAiE;AAEjE,MAAM,YAAY,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsHpB,CAAC;AAEF,iEAAiE;AACjE,2BAA2B;AAC3B,iEAAiE;AAEjE,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9B,6DAA6D;IAC7D,yEAAyE;IACzE,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,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BAC5D,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,0BAA0B,CAAC;aACzD,CAAC;SACH,CACF,CAAC;IACJ,CAAC;CACF;AAjDc;IADZ,KAAK,EAAE;;;;8CA6BP","sourcesContent":["import { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\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(\"SemanticVerifier\");\n\nconst model = createModel(\"intentVerifier\");\n// ──────────────────────────────────────────────────────────────\n// 1. SYSTEM PROMPT\n// ──────────────────────────────────────────────────────────────\n\nconst systemPrompt = `\nYou are the Semantic Verification Engine for the Index Network — an intent-driven discovery protocol.\n\nYour job: classify a user utterance using Searle's Speech Act Theory, then score its felicity conditions.\n\nAlways reason before classifying. Output reasoning first.\n\n═══════════════════════════════════════════════════\nSTEP 1 — CLASSIFY THE ILLOCUTIONARY ACT\n═══════════════════════════════════════════════════\n\nWork through this decision tree in order. Stop at the first matching branch.\n\nIF the utterance cancels, terminates, or declares a state change (e.g., \"I quit\", \"Project cancelled\", \"This position is closed\"):\n → DECLARATION\n\nELSE IF the utterance expresses a search, need, or request for another party — even without an explicit verb or first-person subject:\n → DIRECTIVE\n\n DIRECTIVE trigger patterns (any of these → DIRECTIVE):\n · \"Looking for [X]\" · \"Seeking [X]\"\n · \"In search of [X]\" · \"Need a [X]\"\n · \"Want to find [X]\" · \"Interested in connecting with [X]\"\n · \"Open to [X]\" · \"Hiring [X]\"\n · \"Would love to meet [X]\" · \"Anyone know [X]\"\n\n KEY RULE: A verbless gerundive like \"Looking for artists for collaboration\" IS a DIRECTIVE.\n The missing first-person subject (\"I am\") is routinely elided in natural intent language.\n The illocutionary force is a search directive aimed at the system, not an assertion about reality.\n\n DIRECTIVE positive examples:\n · \"Looking for artists for collaboration\" → DIRECTIVE (elided subject, search intent)\n · \"Seeking a technical co-founder in NYC\" → DIRECTIVE\n · \"Need a PyTorch expert for a 3-month contract\" → DIRECTIVE\n · \"Open to angel investment opportunities\" → DIRECTIVE\n · \"Anyone building in the DeSci space?\" → DIRECTIVE\n\n DIRECTIVE negative examples (do NOT classify these as DIRECTIVE):\n · \"AI is changing the creative industry\" → ASSERTIVE (states a belief, no search)\n · \"I built a collaboration platform\" → ASSERTIVE/COMMISSIVE (past action, no request)\n · \"Collaboration is important\" → ASSERTIVE (general belief)\n\nELSE IF the utterance commits the speaker to a future action:\n → COMMISSIVE\n\n COMMISSIVE positive examples:\n · \"I will deploy the contract by Friday\" → COMMISSIVE\n · \"I'm going to learn Rust this quarter\" → COMMISSIVE\n · \"I commit to mentoring two junior devs\" → COMMISSIVE\n\n COMMISSIVE negative examples (do NOT classify these as COMMISSIVE):\n · \"I could probably look into it\" → too hedged; score sincerity low instead\n · \"We should build something cool\" → vague, no personal commitment\n\nELSE IF the utterance states a fact, belief, or opinion with no implied request or commitment:\n → ASSERTIVE\n\n ASSERTIVE positive examples:\n · \"Rust is faster than C++\" → ASSERTIVE\n · \"I have 10 years of experience in ML\" → ASSERTIVE (profile statement, not a request)\n · \"The crypto market is volatile\" → ASSERTIVE\n\nELSE IF the utterance expresses a psychological state or social ritual:\n → EXPRESSIVE\n\n EXPRESSIVE examples: \"I'm so excited!\", \"Hello everyone\", \"Congrats to the team\"\n\nIf none of the above apply cleanly:\n → UNKNOWN\n\n═══════════════════════════════════════════════════\nSTEP 2 — SCORE THE FELICITY CONDITIONS (0–100)\n═══════════════════════════════════════════════════\n\nScore AFTER classification. Do not let scores influence the category decision.\n\nCLARITY (Essential Condition)\n How unambiguous and actionable is the utterance?\n 100 → \"Deploy the Solidity contract to Mainnet by March 15\"\n 60 → \"Looking for a developer\" (clear direction, vague spec)\n 20 → \"We should do something cool\"\n\nAUTHORITY (Preparatory Condition)\n Does the speaker's profile support this act?\n Compare stated skills/role against the action or search domain.\n 100 → Profile: Senior ML Engineer | Utterance: \"Seeking a research collaborator on transformers\"\n 20 → Profile: Junior Marketer | Utterance: \"I will rewrite the Rust compiler\"\n For DIRECTIVEs: authority = plausibility that this person would make this search.\n\nSINCERITY (Sincerity Condition)\n Does the linguistic form imply genuine commitment or genuine need?\n For COMMISSIVEs: check modality (will > going to > might > could).\n For DIRECTIVEs: check specificity of the search (specific need > vague wish).\n 100 → \"I need a Rails contractor starting next week, $150/hr, remote\"\n 40 → \"I could maybe try to find someone\"\n\nSEMANTIC ENTROPY (Constraint Density) → semantic_entropy field, range 0.0–1.0\n 0.0 = maximally constrained (time, location, tech stack, quantifiers all present)\n 1.0 = no constraints at all\n 0.0 example: \"Meet 50 senior React devs in SF by Friday\"\n 1.0 example: \"Network\"\n\nREFERENTIAL ANCHOR → referential_anchor field\n Does the utterance name a specific unique entity (Donnellan referential use)?\n If YES → output the entity name string.\n If NO (attributive reference to any member of a class) → output null.\n \"I want to join Google\" → \"Google\"\n \"I want to join a startup\" → null\n\n═══════════════════════════════════════════════════\nSTEP 3 — FLAGS\n═══════════════════════════════════════════════════\n\nAdd flags when scores fall below threshold:\n authority < 70 → \"SKILL_MISMATCH\"\n sincerity < 70 → \"WEAK_COMMITMENT\"\n clarity < 50 → \"VAGUE_INTENT\"\n classification is ASSERTIVE or EXPRESSIVE → \"NOISE\"\n`;\n\n// ──────────────────────────────────────────────────────────────\n// 2. RESPONSE SCHEMA (Zod)\n// ──────────────────────────────────────────────────────────────\n\nconst responseFormat = z.object({\n // reasoning comes first so the model commits to its analysis\n // before the classification token is generated (chain-of-thought anchor)\n reasoning: z.string().describe(\n \"Step-by-step analysis: (1) which decision-tree branch fired and why, \" +\n \"(2) key surface features of the utterance (trigger keywords, elided subject, modality), \" +\n \"(3) felicity condition assessment.\"\n ),\n\n classification: z.enum([\n \"COMMISSIVE\",\n \"DIRECTIVE\",\n \"ASSERTIVE\",\n \"EXPRESSIVE\",\n \"DECLARATION\",\n \"UNKNOWN\"\n ]).describe(\"Searle's Speech Act category — determined by the decision tree in STEP 1\"),\n\n felicity_scores: z.object({\n clarity: z.number().min(0).max(100).describe(\"Essential Condition: how unambiguous and actionable is the utterance (0–100)\"),\n authority: z.number().min(0).max(100).describe(\"Preparatory Condition: does the speaker's profile support this act (0–100)\"),\n sincerity: z.number().min(0).max(100).describe(\"Sincerity Condition: does the linguistic form imply genuine commitment or need (0–100)\"),\n }),\n\n semantic_entropy: z.number().min(0).max(1).describe(\n \"Constraint density: 0.0 = maximally specific (time + location + tech + quantifiers), 1.0 = completely unconstrained\"\n ),\n\n referential_anchor: z.string().nullable().describe(\n \"Named specific entity the utterance refers to (Donnellan referential), or null for attributive reference\"\n ),\n\n flags: z.array(z.string()).describe(\n \"Semantic violation tags: SKILL_MISMATCH (authority<70), WEAK_COMMITMENT (sincerity<70), VAGUE_INTENT (clarity<50), NOISE (ASSERTIVE or EXPRESSIVE)\"\n ),\n});\n\n// ──────────────────────────────────────────────────────────────\n// 3. TYPE DEFINITIONS\n// ──────────────────────────────────────────────────────────────\n\nexport type SemanticVerifierOutput = z.infer<typeof responseFormat>;\n\n// ──────────────────────────────────────────────────────────────\n// 4. CLASS DEFINITION\n// ──────────────────────────────────────────────────────────────\n\nexport class SemanticVerifier {\n private model: any;\n\n constructor() {\n this.model = model.withStructuredOutput(responseFormat, {\n name: \"semantic_verifier\"\n });\n }\n\n /**\n * Verifies the semantic validity of an intent.\n * @param content - The user's raw utterance.\n * @param context - The User Profile as a JSON string.\n */\n @Timed()\n public async invoke(content: string, context: string) {\n logger.verbose(`[SemanticVerifier.invoke] Verifying: \"${content.substring(0, 30)}...\"`);\n\n const prompt = `\n # User Profile (Context)\n ${context}\n\n # User Utterance (Content)\n \"${content}\"\n \n Verify the Felicity Conditions and Semantic Metrics for this utterance.\n `;\n\n const messages = [\n new SystemMessage(systemPrompt),\n new HumanMessage(prompt)\n ];\n\n try {\n const result = await invokeWithAbortSignal(this.model, messages);\n const output = responseFormat.parse(result);\n\n logger.verbose(`[SemanticVerifier.invoke] Verdict: ${output.classification} Entropy: ${output.semantic_entropy}`);\n return output;\n } catch (error) {\n logger.error(\"[SemanticVerifier] Error during invocation\", { error });\n throw error;\n }\n }\n\n /**\n * Factory method to expose the agent as a LangChain tool.\n */\n public static asTool() {\n return tool(\n async (args: { content: string; context: string }) => {\n const agent = new SemanticVerifier();\n return await agent.invoke(args.content, args.context);\n },\n {\n name: 'semantic_verifier',\n description: 'Verifies the semantic validity and felicity conditions of an intent.',\n schema: z.object({\n content: z.string().describe('The intent content to verify'),\n context: z.string().describe('The user profile context')\n })\n }\n );\n }\n}\n"]}
1
+ {"version":3,"file":"intent.verifier.js","sourceRoot":"/","sources":["intent/intent.verifier.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD,MAAM,wBAAwB,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;AACzE,MAAM,kCAAkC,GAAG,CAAC,CAAC,IAAI,CAAC;IAChD,MAAM;IACN,SAAS;IACT,UAAU;IACV,WAAW;IACX,QAAQ;IACR,eAAe;CAChB,CAAC,CAAC;AAEH,MAAM,KAAK,GAAG,WAAW,CAAC,gBAAgB,CA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AAO,CAAC,sCAAsC,MAAM,CAAC,cAAc,aAAa,MAAM,CAAC,gBAAgB,EAAE,CAAC,CAAC;YAClH,OAAO,MAAM,CAAC;QAChB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,KAAK,CAAC,4CAA4C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;YACtE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,MAAM;QAClB,OAAO,IAAI,CACT,KAAK,EAAE,IAA0C,EAAE,EAAE;YACnD,MAAM,KAAK,GAAG,IAAI,gBAAgB,EAAE,CAAC;YACrC,OAAO,MAAM,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACxD,CAAC,EACD;YACE,IAAI,EAAE,mBAAmB;YACzB,WAAW,EAAE,sEAAsE;YACnF,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC;gBACf,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,8BAA8B,CAAC;gBAC5D,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,0BAA0B,CAAC;aACzD,CAAC;SACH,CACF,CAAC;IACJ,CAAC;CACF;AAjDc;IADZ,KAAK,EAAE;;;;8CA6BP","sourcesContent":["import { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\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(\"SemanticVerifier\");\n\nconst referentialBreadthSchema = z.enum([\"narrow\", \"moderate\", \"broad\"]);\nconst missingSelectionalConstraintSchema = z.enum([\n \"role\",\n \"outcome\",\n \"location\",\n \"timeframe\",\n \"domain\",\n \"concrete_need\",\n]);\n\nconst model = createModel(\"intentVerifier\");\n// ──────────────────────────────────────────────────────────────\n// 1. SYSTEM PROMPT\n// ──────────────────────────────────────────────────────────────\n\nconst systemPrompt = `\nYou are the Semantic Verification Engine for the Index Network — an intent-driven discovery protocol.\n\nYour job: classify a user utterance using Searle's Speech Act Theory, then score its felicity conditions.\n\nAlways reason before classifying. Output reasoning first.\n\n═══════════════════════════════════════════════════\nSTEP 1 — CLASSIFY THE ILLOCUTIONARY ACT\n═══════════════════════════════════════════════════\n\nWork through this decision tree in order. Stop at the first matching branch.\n\nIF the utterance cancels, terminates, or declares a state change (e.g., \"I quit\", \"Project cancelled\", \"This position is closed\"):\n → DECLARATION\n\nELSE IF the utterance expresses a search, need, or request for another party — even without an explicit verb or first-person subject:\n → DIRECTIVE\n\n DIRECTIVE trigger patterns (any of these → DIRECTIVE):\n · \"Looking for [X]\" · \"Seeking [X]\"\n · \"In search of [X]\" · \"Need a [X]\"\n · \"Want to find [X]\" · \"Interested in connecting with [X]\"\n · \"Open to [X]\" · \"Hiring [X]\"\n · \"Would love to meet [X]\" · \"Anyone know [X]\"\n\n KEY RULE: A verbless gerundive like \"Looking for artists for collaboration\" IS a DIRECTIVE.\n The missing first-person subject (\"I am\") is routinely elided in natural intent language.\n The illocutionary force is a search directive aimed at the system, not an assertion about reality.\n\n DIRECTIVE positive examples:\n · \"Looking for artists for collaboration\" → DIRECTIVE (elided subject, search intent)\n · \"Seeking a technical co-founder in NYC\" → DIRECTIVE\n · \"Need a PyTorch expert for a 3-month contract\" → DIRECTIVE\n · \"Open to angel investment opportunities\" → DIRECTIVE\n · \"Anyone building in the DeSci space?\" → DIRECTIVE\n\n DIRECTIVE negative examples (do NOT classify these as DIRECTIVE):\n · \"AI is changing the creative industry\" → ASSERTIVE (states a belief, no search)\n · \"I built a collaboration platform\" → ASSERTIVE/COMMISSIVE (past action, no request)\n · \"Collaboration is important\" → ASSERTIVE (general belief)\n\nELSE IF the utterance commits the speaker to a future action:\n → COMMISSIVE\n\n COMMISSIVE positive examples:\n · \"I will deploy the contract by Friday\" → COMMISSIVE\n · \"I'm going to learn Rust this quarter\" → COMMISSIVE\n · \"I commit to mentoring two junior devs\" → COMMISSIVE\n\n COMMISSIVE negative examples (do NOT classify these as COMMISSIVE):\n · \"I could probably look into it\" → too hedged; score sincerity low instead\n · \"We should build something cool\" → vague, no personal commitment\n\nELSE IF the utterance states a fact, belief, or opinion with no implied request or commitment:\n → ASSERTIVE\n\n ASSERTIVE positive examples:\n · \"Rust is faster than C++\" → ASSERTIVE\n · \"I have 10 years of experience in ML\" → ASSERTIVE (profile statement, not a request)\n · \"The crypto market is volatile\" → ASSERTIVE\n\nELSE IF the utterance expresses a psychological state or social ritual:\n → EXPRESSIVE\n\n EXPRESSIVE examples: \"I'm so excited!\", \"Hello everyone\", \"Congrats to the team\"\n\nIf none of the above apply cleanly:\n → UNKNOWN\n\n═══════════════════════════════════════════════════\nSTEP 2 — SCORE THE FELICITY CONDITIONS (0–100)\n═══════════════════════════════════════════════════\n\nScore AFTER classification. Do not let scores influence the category decision.\n\nCLARITY (Essential Condition)\n How unambiguous and actionable is the utterance?\n 100 → \"Deploy the Solidity contract to Mainnet by March 15\"\n 60 → \"Looking for a developer\" (clear direction, vague spec)\n 20 → \"We should do something cool\"\n\nAUTHORITY (Preparatory Condition)\n Does the speaker's profile support this act?\n Compare stated skills/role against the action or search domain.\n 100 → Profile: Senior ML Engineer | Utterance: \"Seeking a research collaborator on transformers\"\n 20 → Profile: Junior Marketer | Utterance: \"I will rewrite the Rust compiler\"\n For DIRECTIVEs: authority = plausibility that this person would make this search.\n\nSINCERITY (Sincerity Condition)\n Does the linguistic form imply genuine commitment or genuine need?\n For COMMISSIVEs: check modality (will > going to > might > could).\n For DIRECTIVEs: check specificity of the search (specific need > vague wish).\n 100 → \"I need a Rails contractor starting next week, $150/hr, remote\"\n 40 → \"I could maybe try to find someone\"\n\nSEMANTIC ENTROPY (Constraint Density) → semantic_entropy field, range 0.0–1.0\n 0.0 = maximally constrained (time, location, tech stack, quantifiers all present)\n 1.0 = no constraints at all\n 0.0 example: \"Meet 50 senior React devs in SF by Friday\"\n 1.0 example: \"Network\"\n\nREFERENTIAL ANCHOR → referential_anchor field\n Does the utterance name a specific unique entity (Donnellan referential use)?\n If YES → output the entity name string.\n If NO (attributive reference to any member of a class) → output null.\n \"I want to join Google\" → \"Google\"\n \"I want to join a startup\" → null\n\nREFERENTIAL BREADTH → referential_breadth field\n Estimate the extension size of the open candidate class: how many people could plausibly satisfy the description.\n This is NOT the same as semantic_entropy. Semantic entropy measures underspecification/constraint density;\n referential breadth measures whether the attributive description narrows the satisfier class enough for discovery.\n\n narrow → a small satisfier class due to concrete role/outcome/location/timeframe/specific need.\n Example: \"Find a robotics founder in Healdsburg this week to test my meditation hardware prototype\"\n moderate → a bounded professional/community class, but some constraints are still missing.\n Example: \"Meet AI safety researchers working on evals in London\"\n broad → a large satisfier class; many people could plausibly match even if topical constraints are present.\n Example: \"Meet creative people, builders, and makers interested in AI, meditation, and tech exploration\"\n\nMISSING SELECTIONAL CONSTRAINTS → missing_selectional_constraints field\n Report the constraints whose absence keeps the candidate class too broad:\n role, outcome, location, timeframe, domain, concrete_need.\n\nSPECIFICITY WARNING → specificity_warning field\n If referential_breadth is broad, provide a concise user-facing warning asking for a more concrete role,\n outcome, location, timeframe, domain, or need. Otherwise output null.\n\n═══════════════════════════════════════════════════\nSTEP 3 — FLAGS\n═══════════════════════════════════════════════════\n\nAdd flags when scores fall below threshold:\n authority < 70 → \"SKILL_MISMATCH\"\n sincerity < 70 → \"WEAK_COMMITMENT\"\n clarity < 50 → \"VAGUE_INTENT\"\n classification is ASSERTIVE or EXPRESSIVE → \"NOISE\"\n referential_breadth is broad → \"BROAD_ATTRIBUTIVE_REFERENCE\"\n`;\n\n// ──────────────────────────────────────────────────────────────\n// 2. RESPONSE SCHEMA (Zod)\n// ──────────────────────────────────────────────────────────────\n\nconst responseFormat = z.object({\n // reasoning comes first so the model commits to its analysis\n // before the classification token is generated (chain-of-thought anchor)\n reasoning: z.string().describe(\n \"Step-by-step analysis: (1) which decision-tree branch fired and why, \" +\n \"(2) key surface features of the utterance (trigger keywords, elided subject, modality), \" +\n \"(3) felicity condition assessment.\"\n ),\n\n classification: z.enum([\n \"COMMISSIVE\",\n \"DIRECTIVE\",\n \"ASSERTIVE\",\n \"EXPRESSIVE\",\n \"DECLARATION\",\n \"UNKNOWN\"\n ]).describe(\"Searle's Speech Act category — determined by the decision tree in STEP 1\"),\n\n felicity_scores: z.object({\n clarity: z.number().min(0).max(100).describe(\"Essential Condition: how unambiguous and actionable is the utterance (0–100)\"),\n authority: z.number().min(0).max(100).describe(\"Preparatory Condition: does the speaker's profile support this act (0–100)\"),\n sincerity: z.number().min(0).max(100).describe(\"Sincerity Condition: does the linguistic form imply genuine commitment or need (0–100)\"),\n }),\n\n semantic_entropy: z.number().min(0).max(1).describe(\n \"Constraint density: 0.0 = maximally specific (time + location + tech + quantifiers), 1.0 = completely unconstrained\"\n ),\n\n referential_anchor: z.string().nullable().describe(\n \"Named specific entity the utterance refers to (Donnellan referential), or null for attributive reference\"\n ),\n\n referential_breadth: referentialBreadthSchema.describe(\n \"Extension size of the open candidate class: narrow, moderate, or broad. Distinct from semantic entropy.\"\n ),\n\n missing_selectional_constraints: z.array(missingSelectionalConstraintSchema).describe(\n \"Selectional constraints whose absence leaves the satisfier class too broad.\"\n ),\n\n specificity_warning: z.string().nullable().describe(\n \"Concise user-facing warning when referential_breadth is broad; otherwise null.\"\n ),\n\n flags: z.array(z.string()).describe(\n \"Semantic violation tags: SKILL_MISMATCH (authority<70), WEAK_COMMITMENT (sincerity<70), VAGUE_INTENT (clarity<50), NOISE (ASSERTIVE or EXPRESSIVE), BROAD_ATTRIBUTIVE_REFERENCE (referential_breadth=broad)\"\n ),\n});\n\n// ──────────────────────────────────────────────────────────────\n// 3. TYPE DEFINITIONS\n// ──────────────────────────────────────────────────────────────\n\nexport type ReferentialBreadth = z.infer<typeof referentialBreadthSchema>;\nexport type MissingSelectionalConstraint = z.infer<typeof missingSelectionalConstraintSchema>;\nexport type SemanticVerifierOutput = z.infer<typeof responseFormat>;\n\n// ──────────────────────────────────────────────────────────────\n// 4. CLASS DEFINITION\n// ──────────────────────────────────────────────────────────────\n\nexport class SemanticVerifier {\n private model: any;\n\n constructor() {\n this.model = model.withStructuredOutput(responseFormat, {\n name: \"semantic_verifier\"\n });\n }\n\n /**\n * Verifies the semantic validity of an intent.\n * @param content - The user's raw utterance.\n * @param context - The User Profile as a JSON string.\n */\n @Timed()\n public async invoke(content: string, context: string) {\n logger.verbose(`[SemanticVerifier.invoke] Verifying: \"${content.substring(0, 30)}...\"`);\n\n const prompt = `\n # User Profile (Context)\n ${context}\n\n # User Utterance (Content)\n \"${content}\"\n \n Verify the Felicity Conditions and Semantic Metrics for this utterance.\n `;\n\n const messages = [\n new SystemMessage(systemPrompt),\n new HumanMessage(prompt)\n ];\n\n try {\n const result = await invokeWithAbortSignal(this.model, messages);\n const output = responseFormat.parse(result);\n\n logger.verbose(`[SemanticVerifier.invoke] Verdict: ${output.classification} Entropy: ${output.semantic_entropy}`);\n return output;\n } catch (error) {\n logger.error(\"[SemanticVerifier] Error during invocation\", { error });\n throw error;\n }\n }\n\n /**\n * Factory method to expose the agent as a LangChain tool.\n */\n public static asTool() {\n return tool(\n async (args: { content: string; context: string }) => {\n const agent = new SemanticVerifier();\n return await agent.invoke(args.content, args.context);\n },\n {\n name: 'semantic_verifier',\n description: 'Verifies the semantic validity and felicity conditions of an intent.',\n schema: z.object({\n content: z.string().describe('The intent content to verify'),\n context: z.string().describe('The user profile context')\n })\n }\n );\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indexnetwork/protocol",
3
- "version": "1.26.2",
3
+ "version": "1.26.3-rc.223.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",