@indexnetwork/protocol 6.6.1-rc.387.1 → 6.6.3-rc.389.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/dist/opportunity/discriminator/discriminator.adjustments.js +1 -1
  3. package/dist/opportunity/discriminator/discriminator.adjustments.js.map +1 -1
  4. package/dist/opportunity/opportunity.enricher.d.ts +5 -0
  5. package/dist/opportunity/opportunity.enricher.d.ts.map +1 -1
  6. package/dist/opportunity/opportunity.enricher.js +17 -1
  7. package/dist/opportunity/opportunity.enricher.js.map +1 -1
  8. package/dist/opportunity/opportunity.graph.d.ts +109 -247
  9. package/dist/opportunity/opportunity.graph.d.ts.map +1 -1
  10. package/dist/opportunity/opportunity.graph.js +198 -4
  11. package/dist/opportunity/opportunity.graph.js.map +1 -1
  12. package/dist/opportunity/opportunity.persist.d.ts +14 -1
  13. package/dist/opportunity/opportunity.persist.d.ts.map +1 -1
  14. package/dist/opportunity/opportunity.persist.js +33 -4
  15. package/dist/opportunity/opportunity.persist.js.map +1 -1
  16. package/dist/opportunity/opportunity.safe-presentation.d.ts +1 -1
  17. package/dist/opportunity/opportunity.safe-presentation.js +1 -1
  18. package/dist/opportunity/opportunity.safe-presentation.js.map +1 -1
  19. package/dist/opportunity/opportunity.state.d.ts +17 -0
  20. package/dist/opportunity/opportunity.state.d.ts.map +1 -1
  21. package/dist/opportunity/opportunity.state.js +5 -0
  22. package/dist/opportunity/opportunity.state.js.map +1 -1
  23. package/dist/shared/interfaces/database.interface.d.ts +25 -2
  24. package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
  25. package/dist/shared/interfaces/database.interface.js.map +1 -1
  26. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -45,6 +45,7 @@ See [STABILITY.md](./STABILITY.md) for the public-contract and tier definitions.
45
45
  - Included protocol documentation files in the published package tarball so README links remain available to package consumers.
46
46
 
47
47
  ### Fixed
48
+ - Made owned-intent opportunity persistence trigger-aware: recent/lifecycle dedup now reuses only rows linked to the same trigger intent, cross-trigger rows remain independently visible, enrichment cannot absorb another trigger's row, and final persistence reports typed same-trigger/active-negotiation conflicts (IND-495).
48
49
  - Clamped intent-pinned `list_negotiations` results to the user's signal, added explicit signal/all scope metadata, and prevented stale cross-signal history from being presented as current negotiations (IND-483).
49
50
  - Routed continuation-created and recovered opportunities through the normal negotiation boundary, threaded each persisted attempt version into atomic negotiation-task claiming, protected active/input-required tasks from duplicate negotiation, compensated pre-task failures and timeouts to truthful draft/latent states, and refreshed continuation cards from current lifecycle state (IND-470).
50
51
  - Normalized opportunity actor intent IDs at evaluator, graph, and shared persistence boundaries so blank or null-like model sentinels are omitted, valid branded string IDs remain supported, enrichment cannot use or reintroduce malformed provenance, and legacy negotiation reads fail closed (IND-469).
@@ -13,7 +13,7 @@
13
13
  * dismissal-driven reversal removes them.
14
14
  * - `detail` carries the template chip text built from the user's OWN answer
15
15
  * ("Hands-on builders vs advisors: you chose Advisor") — never LLM
16
- * reasoning (opportunity-presentation-safety).
16
+ * reasoning (review-opportunity-presentation).
17
17
  */
18
18
  import { POOL_ADJUSTMENT_FACTOR_OTHER, POOL_ADJUSTMENT_FACTOR_UNKNOWN, POOL_ADJUSTMENT_FLOOR } from "./discriminator.env.js";
19
19
  /** Reads valid adjustments, optionally narrowed to one recipient + intent. */
@@ -1 +1 @@
1
- {"version":3,"file":"discriminator.adjustments.js","sourceRoot":"/","sources":["opportunity/discriminator/discriminator.adjustments.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,4BAA4B,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AA6B7H,8EAA8E;AAC9E,MAAM,UAAU,mBAAmB,CACjC,QAAoD,EACpD,UAAqC;IAErC,MAAM,GAAG,GAAG,QAAQ,EAAE,eAAe,CAAC;IACtC,IAAI,CAAC,KAAK,CAAC,O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pure functions, no I/O.\n *\n * When a user answers a pool_discovery question, every candidate the mining\n * pass assigned to a side gets a multiplicative adjustment written to\n * `opportunities.metadata.poolAdjustments`. The home feed (flag-gated) orders\n * by `confidence × Π factor`, floored so demoted candidates stay visible.\n *\n * Invariants:\n * - Deterministic and O(pool): no LLM at answer time — the applyPlan was\n * computed (and evidence-verified) at mining time.\n * - Reversible: entries are keyed by questionId; re-answering replaces them,\n * dismissal-driven reversal removes them.\n * - `detail` carries the template chip text built from the user's OWN answer\n * (\"Hands-on builders vs advisors: you chose Advisor\") — never LLM\n * reasoning (opportunity-presentation-safety).\n */\nimport { POOL_ADJUSTMENT_FACTOR_OTHER, POOL_ADJUSTMENT_FACTOR_UNKNOWN, POOL_ADJUSTMENT_FLOOR } from \"./discriminator.env.js\";\nimport type { QuestionPoolDiscriminator } from \"../../shared/schemas/question.schema.js\";\n\n/** Recipient and intent provenance that scopes one pool preference. */\nexport interface PoolAdjustmentProvenance {\n recipientUserId: string;\n intentId: string;\n}\n\n/** One applied adjustment on an opportunity (stored in metadata.poolAdjustments). */\nexport interface PoolAdjustment extends PoolAdjustmentProvenance {\n /** The answered question that produced this adjustment (reversal key). */\n questionId: string;\n /** Discriminator label, e.g. \"Hands-on builders vs advisors\". */\n label: string;\n /** Side this candidate was assigned to (or \"unknown\"). */\n side: string;\n /** Multiplicative factor: chosen 1.0, other 0.6, unknown 0.9. */\n factor: number;\n /** Template chip text from the user's own answer. Set on demotions only. */\n detail?: string;\n /** ISO-8601 apply timestamp. */\n appliedAt: string;\n /** Full intent fingerprint authoritative when this adjustment was created. */\n intentFingerprint?: string;\n /** Audit-only marker: stale adjustments remain stored but have no ranking effect. */\n stale?: true;\n}\n\n/** Reads valid adjustments, optionally narrowed to one recipient + intent. */\nexport function readPoolAdjustments(\n metadata: Record<string, unknown> | null | undefined,\n provenance?: PoolAdjustmentProvenance,\n): PoolAdjustment[] {\n const raw = metadata?.poolAdjustments;\n if (!Array.isArray(raw)) return [];\n return raw.filter((a): a is PoolAdjustment => {\n if (\n typeof a !== \"object\" || a === null ||\n typeof (a as PoolAdjustment).questionId !== \"string\" ||\n typeof (a as PoolAdjustment).recipientUserId !== \"string\" ||\n typeof (a as PoolAdjustment).intentId !== \"string\" ||\n typeof (a as PoolAdjustment).factor !== \"number\" ||\n ((a as PoolAdjustment).stale !== undefined && (a as PoolAdjustment).stale !== true)\n ) return false;\n return provenance === undefined || (\n (a as PoolAdjustment).recipientUserId === provenance.recipientUserId &&\n (a as PoolAdjustment).intentId === provenance.intentId\n );\n });\n}\n\n/** Reads valid, non-stale adjustments for ranking and presentation behavior. */\nexport function readActivePoolAdjustments(\n metadata: Record<string, unknown> | null | undefined,\n provenance?: PoolAdjustmentProvenance,\n): PoolAdjustment[] {\n return readPoolAdjustments(metadata, provenance).filter((adjustment) => adjustment.stale !== true);\n}\n\n/**\n * Cumulative adjustment multiplier for an opportunity, floored at\n * {@link POOL_ADJUSTMENT_FLOOR}. 1 when no scoped adjustments exist.\n */\nexport function poolAdjustmentMultiplier(\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): number {\n const adjustments = readActivePoolAdjustments(metadata, provenance);\n if (adjustments.length === 0) return 1;\n const product = adjustments.reduce((acc, a) => acc * (Number.isFinite(a.factor) && a.factor > 0 ? a.factor : 1), 1);\n return Math.max(POOL_ADJUSTMENT_FLOOR, product);\n}\n\n/** Adjusted confidence: `confidence × Π factor`, floored. */\nexport function adjustedConfidence(\n confidence: number,\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): number {\n return confidence * poolAdjustmentMultiplier(metadata, provenance);\n}\n\n/** Deterministic provenance signal stored alongside one adjustment. */\nexport interface PoolAdjustmentSignal extends PoolAdjustmentProvenance {\n type: \"pool_discriminator\";\n weight: 1 | -1 | 0;\n detail: string;\n questionId: string;\n}\n\n/** Pure helper input shared by Tier-0 answers and newborn stamping. */\nexport interface BuildPoolAdjustmentInput extends PoolAdjustmentProvenance {\n questionId: string;\n label: string;\n /** Verified side assignment, or null when the candidate is unassigned. */\n assignedSide: string | null;\n chosenSide: string;\n appliedAt: string;\n /** Full intent fingerprint authoritative when this adjustment was created. */\n intentFingerprint?: string;\n}\n\n/**\n * Build one P3-compatible adjustment and signal. This is the only place that\n * defines chosen/other/unknown factors, weights, and safe template details.\n */\nexport function buildPoolAdjustment(input: BuildPoolAdjustmentInput): {\n adjustment: PoolAdjustment;\n signal: PoolAdjustmentSignal;\n} {\n const isUnknown = input.assignedSide === null;\n const isChosen = !isUnknown && input.assignedSide === input.chosenSide;\n const factor = isUnknown ? POOL_ADJUSTMENT_FACTOR_UNKNOWN : isChosen ? 1 : POOL_ADJUSTMENT_FACTOR_OTHER;\n const weight = isUnknown ? 0 : isChosen ? 1 : -1;\n const side = input.assignedSide ?? \"unknown\";\n return {\n adjustment: {\n questionId: input.questionId,\n recipientUserId: input.recipientUserId,\n intentId: input.intentId,\n label: input.label,\n side,\n factor,\n ...(!isChosen && !isUnknown ? { detail: `${input.label}: you chose ${input.chosenSide}` } : {}),\n appliedAt: input.appliedAt,\n ...(input.intentFingerprint !== undefined ? { intentFingerprint: input.intentFingerprint } : {}),\n },\n signal: {\n type: \"pool_discriminator\",\n weight,\n recipientUserId: input.recipientUserId,\n intentId: input.intentId,\n detail: isUnknown ? `${input.label}: unassigned` : `${input.label}: ${input.chosenSide}`,\n questionId: input.questionId,\n },\n };\n}\n\n/** Plan entry: what to write on one opportunity for one answer. */\nexport interface PoolAdjustmentPlanEntry {\n opportunityId: string;\n adjustment: PoolAdjustment;\n signal: PoolAdjustmentSignal;\n}\n\n/**\n * Computes the write plan for one answered discriminator. Pure: the caller\n * loads/patches rows. \"Both matter\" (or any label not in `sides`) yields an\n * empty plan — no preference, no adjustments.\n *\n * @param discriminator The asked discriminator (from detection.pool).\n * @param chosenSide The selected option label (chip label = side label).\n * @param questionId Reversal key.\n * @param recipientUserId User whose answer produced the preference.\n * @param intentId Intent whose candidate pool was ranked.\n * @param now ISO-8601 timestamp.\n * @param intentFingerprint Full intent fingerprint authoritative at apply time.\n */\nexport function planPoolAdjustments(\n discriminator: QuestionPoolDiscriminator,\n chosenSide: string,\n questionId: string,\n recipientUserId: string,\n intentId: string,\n now: string,\n intentFingerprint?: string,\n): PoolAdjustmentPlanEntry[] {\n // Chip labels are word-capped side labels; match on the capped prefix too.\n const matchesSide = (side: string): boolean =>\n side === chosenSide || side.startsWith(chosenSide) || chosenSide.startsWith(side);\n const chosen = discriminator.sides.find(matchesSide);\n if (!chosen) return []; // \"Both matter\" or unrecognized option → no adjustments.\n\n const plan: PoolAdjustmentPlanEntry[] = [];\n for (const a of discriminator.assignments) {\n plan.push({\n opportunityId: a.opportunityId,\n ...buildPoolAdjustment({\n questionId,\n recipientUserId,\n intentId,\n label: discriminator.label,\n assignedSide: a.side,\n chosenSide: chosen,\n appliedAt: now,\n ...(intentFingerprint !== undefined ? { intentFingerprint } : {}),\n }),\n });\n }\n return plan;\n}\n\n/**\n * Merges one adjustment into an opportunity's existing metadata, replacing\n * only the entry for the same question + recipient + intent provenance.\n * Returns the NEW metadata object (caller persists it wholesale).\n */\nexport function mergePoolAdjustment(\n metadata: Record<string, unknown> | null | undefined,\n adjustment: PoolAdjustment,\n): Record<string, unknown> {\n const existing = readPoolAdjustments(metadata).filter((a) => !(\n a.questionId === adjustment.questionId &&\n a.recipientUserId === adjustment.recipientUserId &&\n a.intentId === adjustment.intentId\n ));\n return { ...(metadata ?? {}), poolAdjustments: [...existing, adjustment] };\n}\n\n/** Latest scoped user-explainable demotion detail for card presentation. */\nexport function latestPoolDemotionDetail(\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): string | undefined {\n return [...readActivePoolAdjustments(metadata, provenance)]\n .reverse()\n .find((adjustment) => adjustment.factor < 1 && typeof adjustment.detail === 'string' && adjustment.detail.length > 0)\n ?.detail;\n}\n"]}
1
+ {"version":3,"file":"discriminator.adjustments.js","sourceRoot":"/","sources":["opportunity/discrimin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AAQ,EAAE,UAAU,CAAC,CAAC;SACxD,OAAO,EAAE;SACT,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,UAAU,CAAC,MAAM,KAAK,QAAQ,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;QACrH,EAAE,MAAM,CAAC;AACb,CAAC","sourcesContent":["/**\n * Pool-adjustment domain logic (IND-419) — pure functions, no I/O.\n *\n * When a user answers a pool_discovery question, every candidate the mining\n * pass assigned to a side gets a multiplicative adjustment written to\n * `opportunities.metadata.poolAdjustments`. The home feed (flag-gated) orders\n * by `confidence × Π factor`, floored so demoted candidates stay visible.\n *\n * Invariants:\n * - Deterministic and O(pool): no LLM at answer time — the applyPlan was\n * computed (and evidence-verified) at mining time.\n * - Reversible: entries are keyed by questionId; re-answering replaces them,\n * dismissal-driven reversal removes them.\n * - `detail` carries the template chip text built from the user's OWN answer\n * (\"Hands-on builders vs advisors: you chose Advisor\") — never LLM\n * reasoning (review-opportunity-presentation).\n */\nimport { POOL_ADJUSTMENT_FACTOR_OTHER, POOL_ADJUSTMENT_FACTOR_UNKNOWN, POOL_ADJUSTMENT_FLOOR } from \"./discriminator.env.js\";\nimport type { QuestionPoolDiscriminator } from \"../../shared/schemas/question.schema.js\";\n\n/** Recipient and intent provenance that scopes one pool preference. */\nexport interface PoolAdjustmentProvenance {\n recipientUserId: string;\n intentId: string;\n}\n\n/** One applied adjustment on an opportunity (stored in metadata.poolAdjustments). */\nexport interface PoolAdjustment extends PoolAdjustmentProvenance {\n /** The answered question that produced this adjustment (reversal key). */\n questionId: string;\n /** Discriminator label, e.g. \"Hands-on builders vs advisors\". */\n label: string;\n /** Side this candidate was assigned to (or \"unknown\"). */\n side: string;\n /** Multiplicative factor: chosen 1.0, other 0.6, unknown 0.9. */\n factor: number;\n /** Template chip text from the user's own answer. Set on demotions only. */\n detail?: string;\n /** ISO-8601 apply timestamp. */\n appliedAt: string;\n /** Full intent fingerprint authoritative when this adjustment was created. */\n intentFingerprint?: string;\n /** Audit-only marker: stale adjustments remain stored but have no ranking effect. */\n stale?: true;\n}\n\n/** Reads valid adjustments, optionally narrowed to one recipient + intent. */\nexport function readPoolAdjustments(\n metadata: Record<string, unknown> | null | undefined,\n provenance?: PoolAdjustmentProvenance,\n): PoolAdjustment[] {\n const raw = metadata?.poolAdjustments;\n if (!Array.isArray(raw)) return [];\n return raw.filter((a): a is PoolAdjustment => {\n if (\n typeof a !== \"object\" || a === null ||\n typeof (a as PoolAdjustment).questionId !== \"string\" ||\n typeof (a as PoolAdjustment).recipientUserId !== \"string\" ||\n typeof (a as PoolAdjustment).intentId !== \"string\" ||\n typeof (a as PoolAdjustment).factor !== \"number\" ||\n ((a as PoolAdjustment).stale !== undefined && (a as PoolAdjustment).stale !== true)\n ) return false;\n return provenance === undefined || (\n (a as PoolAdjustment).recipientUserId === provenance.recipientUserId &&\n (a as PoolAdjustment).intentId === provenance.intentId\n );\n });\n}\n\n/** Reads valid, non-stale adjustments for ranking and presentation behavior. */\nexport function readActivePoolAdjustments(\n metadata: Record<string, unknown> | null | undefined,\n provenance?: PoolAdjustmentProvenance,\n): PoolAdjustment[] {\n return readPoolAdjustments(metadata, provenance).filter((adjustment) => adjustment.stale !== true);\n}\n\n/**\n * Cumulative adjustment multiplier for an opportunity, floored at\n * {@link POOL_ADJUSTMENT_FLOOR}. 1 when no scoped adjustments exist.\n */\nexport function poolAdjustmentMultiplier(\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): number {\n const adjustments = readActivePoolAdjustments(metadata, provenance);\n if (adjustments.length === 0) return 1;\n const product = adjustments.reduce((acc, a) => acc * (Number.isFinite(a.factor) && a.factor > 0 ? a.factor : 1), 1);\n return Math.max(POOL_ADJUSTMENT_FLOOR, product);\n}\n\n/** Adjusted confidence: `confidence × Π factor`, floored. */\nexport function adjustedConfidence(\n confidence: number,\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): number {\n return confidence * poolAdjustmentMultiplier(metadata, provenance);\n}\n\n/** Deterministic provenance signal stored alongside one adjustment. */\nexport interface PoolAdjustmentSignal extends PoolAdjustmentProvenance {\n type: \"pool_discriminator\";\n weight: 1 | -1 | 0;\n detail: string;\n questionId: string;\n}\n\n/** Pure helper input shared by Tier-0 answers and newborn stamping. */\nexport interface BuildPoolAdjustmentInput extends PoolAdjustmentProvenance {\n questionId: string;\n label: string;\n /** Verified side assignment, or null when the candidate is unassigned. */\n assignedSide: string | null;\n chosenSide: string;\n appliedAt: string;\n /** Full intent fingerprint authoritative when this adjustment was created. */\n intentFingerprint?: string;\n}\n\n/**\n * Build one P3-compatible adjustment and signal. This is the only place that\n * defines chosen/other/unknown factors, weights, and safe template details.\n */\nexport function buildPoolAdjustment(input: BuildPoolAdjustmentInput): {\n adjustment: PoolAdjustment;\n signal: PoolAdjustmentSignal;\n} {\n const isUnknown = input.assignedSide === null;\n const isChosen = !isUnknown && input.assignedSide === input.chosenSide;\n const factor = isUnknown ? POOL_ADJUSTMENT_FACTOR_UNKNOWN : isChosen ? 1 : POOL_ADJUSTMENT_FACTOR_OTHER;\n const weight = isUnknown ? 0 : isChosen ? 1 : -1;\n const side = input.assignedSide ?? \"unknown\";\n return {\n adjustment: {\n questionId: input.questionId,\n recipientUserId: input.recipientUserId,\n intentId: input.intentId,\n label: input.label,\n side,\n factor,\n ...(!isChosen && !isUnknown ? { detail: `${input.label}: you chose ${input.chosenSide}` } : {}),\n appliedAt: input.appliedAt,\n ...(input.intentFingerprint !== undefined ? { intentFingerprint: input.intentFingerprint } : {}),\n },\n signal: {\n type: \"pool_discriminator\",\n weight,\n recipientUserId: input.recipientUserId,\n intentId: input.intentId,\n detail: isUnknown ? `${input.label}: unassigned` : `${input.label}: ${input.chosenSide}`,\n questionId: input.questionId,\n },\n };\n}\n\n/** Plan entry: what to write on one opportunity for one answer. */\nexport interface PoolAdjustmentPlanEntry {\n opportunityId: string;\n adjustment: PoolAdjustment;\n signal: PoolAdjustmentSignal;\n}\n\n/**\n * Computes the write plan for one answered discriminator. Pure: the caller\n * loads/patches rows. \"Both matter\" (or any label not in `sides`) yields an\n * empty plan — no preference, no adjustments.\n *\n * @param discriminator The asked discriminator (from detection.pool).\n * @param chosenSide The selected option label (chip label = side label).\n * @param questionId Reversal key.\n * @param recipientUserId User whose answer produced the preference.\n * @param intentId Intent whose candidate pool was ranked.\n * @param now ISO-8601 timestamp.\n * @param intentFingerprint Full intent fingerprint authoritative at apply time.\n */\nexport function planPoolAdjustments(\n discriminator: QuestionPoolDiscriminator,\n chosenSide: string,\n questionId: string,\n recipientUserId: string,\n intentId: string,\n now: string,\n intentFingerprint?: string,\n): PoolAdjustmentPlanEntry[] {\n // Chip labels are word-capped side labels; match on the capped prefix too.\n const matchesSide = (side: string): boolean =>\n side === chosenSide || side.startsWith(chosenSide) || chosenSide.startsWith(side);\n const chosen = discriminator.sides.find(matchesSide);\n if (!chosen) return []; // \"Both matter\" or unrecognized option → no adjustments.\n\n const plan: PoolAdjustmentPlanEntry[] = [];\n for (const a of discriminator.assignments) {\n plan.push({\n opportunityId: a.opportunityId,\n ...buildPoolAdjustment({\n questionId,\n recipientUserId,\n intentId,\n label: discriminator.label,\n assignedSide: a.side,\n chosenSide: chosen,\n appliedAt: now,\n ...(intentFingerprint !== undefined ? { intentFingerprint } : {}),\n }),\n });\n }\n return plan;\n}\n\n/**\n * Merges one adjustment into an opportunity's existing metadata, replacing\n * only the entry for the same question + recipient + intent provenance.\n * Returns the NEW metadata object (caller persists it wholesale).\n */\nexport function mergePoolAdjustment(\n metadata: Record<string, unknown> | null | undefined,\n adjustment: PoolAdjustment,\n): Record<string, unknown> {\n const existing = readPoolAdjustments(metadata).filter((a) => !(\n a.questionId === adjustment.questionId &&\n a.recipientUserId === adjustment.recipientUserId &&\n a.intentId === adjustment.intentId\n ));\n return { ...(metadata ?? {}), poolAdjustments: [...existing, adjustment] };\n}\n\n/** Latest scoped user-explainable demotion detail for card presentation. */\nexport function latestPoolDemotionDetail(\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): string | undefined {\n return [...readActivePoolAdjustments(metadata, provenance)]\n .reverse()\n .find((adjustment) => adjustment.factor < 1 && typeof adjustment.detail === 'string' && adjustment.detail.length > 0)\n ?.detail;\n}\n"]}
@@ -45,6 +45,11 @@ export type EnrichOrCreateOptions = {
45
45
  * Pass an empty array `[]` to consider all statuses.
46
46
  */
47
47
  excludeStatuses?: OpportunityStatus[];
48
+ /** Restrict merge/expiration candidates to the authoritative owned intent. */
49
+ ownedIntentScope?: {
50
+ triggerIntentId: string;
51
+ ownerUserId: string;
52
+ };
48
53
  };
49
54
  /**
50
55
  * Enrich or create: find overlapping opportunities, filter by semantic relatedness
@@ -1 +1 @@
1
- {"version":3,"file":"opportunity.enricher.d.ts","sourceRoot":"/","sources":["opportunity/opportunity.enricher.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,WAAW,EAAkE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;AAExL,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4CAA4C,CAAC;AAS3E;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,iCAAiC,EAAE,iBAAiB,EAA2C,CAAC;AAE7G,MAAM,MAAM,gBAAgB,GAAG;IAC7B,yBAAyB,CACvB,QAAQ,EAAE,MAAM,EAAE,EAClB,OAAO,CAAC,EAAE;QAAE,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,iBAAiB,EAAE,CAAC;QAAC,eAAe,CAAC,EAAE,iBAAiB,EAAE,CAAA;KAAE,GAChH,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;CAC3B,CAAC;AAEF,MAAM,MAAM,gBAAgB,GACxB;IAAE,QAAQ,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,qBAAqB,C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AA;CAAE,GAChD;IAAE,QAAQ,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,qBAAqB,CAAC;IAAC,UAAU,EAAE,MAAM,EAAE,CAAC;IAAC,cAAc,EAAE,iBAAiB,CAAA;CAAE,CAAC;AAE7G,MAAM,MAAM,qBAAqB,GAAG;IAClC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;OAIG;IACH,eAAe,CAAC,EAAE,iBAAiB,EAAE,CAAC;IACtC,8EAA8E;IAC9E,gBAAgB,CAAC,EAAE;QAAE,eAAe,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;CACrE,CAAC;AA0JF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,gBAAgB,EAC1B,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,qBAAqB,EAC9B,OAAO,CAAC,EAAE,qBAAqB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAiH3B"}
@@ -79,6 +79,11 @@ function getNonIntroducerUserIds(data) {
79
79
  /**
80
80
  * Extract intent IDs from actors.
81
81
  */
82
+ function belongsToOwnedIntent(opportunity, scope) {
83
+ if (opportunity.detection.triggeredBy === scope.triggerIntentId)
84
+ return true;
85
+ return opportunity.actors.some((actor) => actor.userId === scope.ownerUserId && actor.intent === scope.triggerIntentId);
86
+ }
82
87
  function getIntentIdsFromActors(actors) {
83
88
  const ids = new Set();
84
89
  for (const a of actors) {
@@ -178,7 +183,18 @@ export async function enrichOrCreate(database, embedder, newData, options) {
178
183
  return { enriched: false, data: newData };
179
184
  }
180
185
  const excludeStatuses = options?.excludeStatuses ?? DEFAULT_ENRICHER_EXCLUDE_STATUSES;
181
- const overlapping = await database.findOpportunitiesByActors(actorUserIds, { excludeStatuses });
186
+ const pairOverlaps = await database.findOpportunitiesByActors(actorUserIds, { excludeStatuses });
187
+ const ownedIntentScope = options?.ownedIntentScope;
188
+ const overlapping = ownedIntentScope
189
+ ? pairOverlaps.filter((opportunity) => belongsToOwnedIntent(opportunity, ownedIntentScope))
190
+ : pairOverlaps;
191
+ if (ownedIntentScope && pairOverlaps.length > overlapping.length) {
192
+ logger.info('Excluded cross-trigger overlaps from owned-intent enrichment', {
193
+ triggerIntentId: ownedIntentScope.triggerIntentId,
194
+ pairOverlapCount: pairOverlaps.length,
195
+ sameTriggerOverlapCount: overlapping.length,
196
+ });
197
+ }
182
198
  if (overlapping.length === 0) {
183
199
  return { enriched: false, data: newData };
184
200
  }
@@ -1 +1 @@
1
- {"version":3,"file":"opportunity.enricher.js","sourceRoot":"/","sources":["opportunity/opportunity.enricher.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAGvE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAErD,MAAM,4BAA4B,GAAG,GAAG,CAAC;AACzC,MAAM,kCAAkC,GAAG,EAAE,CAAC;AAE9C;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAwB,CAAC,UAAU,EAAE,aAAa,EAAE,SAAS,CAAC,CAAC;AAuB7G;;GAEG;AACH,SAAS,gBAAgB,CAAC,CAAW,EAAE,CAAW;IAChD,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,CAAC,CAAC;IACtD,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QAClC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAA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AC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9C,MAAM,gBAAgB,GACpB,OAAO,oBAAoB,CAAC,UAAU,KAAK,QAAQ;QACjD,CAAC,CAAC,MAAM,CAAC,oBAAoB,CAAC,UAAU,CAAC;QACzC,CAAC,CAAC,oBAAoB,CAAC,UAAU,CAAC;IAEtC,MAAM,YAAY,GAA0B;QAC1C,GAAG,OAAO;QACV,SAAS,EAAE;YACT,GAAG,OAAO,CAAC,SAAS;YACpB,MAAM,EAAE,YAAY;YACpB,YAAY;SACb;QACD,MAAM,EAAE,YAAY;QACpB,cAAc,EAAE,oBAAoB;QACpC,UAAU,EAAE,gBAAgB;KAC7B,CAAC;IAEF,MAAM,cAAc,GAAG,qBAAqB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAE3F,MAAM,CAAC,OAAO,CAAC,sBAAsB,EAAE;QACrC,YAAY;QACZ,UAAU,EAAE,YAAY,CAAC,MAAM;KAChC,CAAC,CAAC;IAEH,OAAO;QACL,QAAQ,EAAE,IAAI;QACd,IAAI,EAAE,YAAY;QAClB,UAAU,EAAE,YAAY;QACxB,cAAc;KACf,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Opportunity enricher: when creating an opportunity, find overlapping existing\n * opportunities (by non-introducer actor userId), check semantic relatedness, and\n * optionally merge into a single enriched opportunity and expire the old one(s).\n */\n\nimport type { CreateOpportunityData, Opportunity, OpportunityActor, OpportunityInterpretation, OpportunitySignal, OpportunityStatus } from '../shared/interfaces/database.interface.js';\nimport { getAbortSignalConfig } from '../shared/agent/model-signal.js';\nimport type { Embedder } from '../shared/interfaces/embedder.interface.js';\nimport type { Id } from '../shared/interfaces/database.interface.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('OpportunityEnricher');\n\nconst DEFAULT_SIMILARITY_THRESHOLD = 0.7;\nconst MIN_REASONING_LENGTH_FOR_EMBEDDING = 10;\n\n/**\n * Statuses excluded from the merge-candidate pool by default.\n *\n * - 'accepted': the pair already connected — do NOT fold a new discovery into\n * the historical opp. IND-237 surfaces the existing conversation separately.\n * - 'negotiating': a negotiation is in-flight for this pair; rolling a new\n * candidate into it would blur the outcome of the active turn. Wait for the\n * negotiation to finalize (→ draft/pending/rejected/stalled) first, then\n * enrichment can pick it up on the next pass.\n * - 'expired': already superseded by a later enriched opportunity. Without this\n * exclusion, each enrichment cycle re-merges previously-expired enriched\n * opportunities, compounding their actor arrays into 100+ entries.\n *\n * Exported for callers that want to extend rather than replace the default.\n */\nexport const DEFAULT_ENRICHER_EXCLUDE_STATUSES: OpportunityStatus[] = ['accepted', 'negotiating', 'expired'];\n\nexport type EnricherDatabase = {\n findOpportunitiesByActors(\n actorIds: string[],\n options?: { includeIntroducers?: boolean; statuses?: OpportunityStatus[]; excludeStatuses?: OpportunityStatus[] }\n ): Promise<Opportunity[]>;\n};\n\nexport type EnrichmentResult =\n | { enriched: false; data: CreateOpportunityData }\n | { enriched: true; data: CreateOpportunityData; expiredIds: string[]; resolvedStatus: OpportunityStatus };\n\nexport type EnrichOrCreateOptions = {\n similarityThreshold?: number;\n /**\n * Statuses to exclude from the merge-candidate pool. Defaults to\n * {@link DEFAULT_ENRICHER_EXCLUDE_STATUSES} (`['accepted', 'negotiating']`).\n * Pass an empty array `[]` to consider all statuses.\n */\n excludeStatuses?: OpportunityStatus[];\n};\n\n/**\n * Cosine similarity between two vectors (0–1).\n */\nfunction cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length === 0) return 0;\n let dot = 0;\n let normA = 0;\n let normB = 0;\n for (let i = 0; i < a.length; i++) {\n dot += a[i] * b[i];\n normA += a[i] * a[i];\n normB += b[i] * b[i];\n }\n const denom = Math.sqrt(normA) * Math.sqrt(normB);\n if (denom === 0) return 0;\n const sim = dot / denom;\n return Math.max(0, Math.min(1, sim));\n}\n\n/**\n * Resolve enriched opportunity status from related opportunities' statuses and the incoming status.\n * Priority: accepted > pending > rejected > stalled > draft (only when incoming is draft) > latent.\n * The incoming status is included so we do not wrongly downgrade when the new opportunity has a higher-priority status.\n * When incoming is 'draft' (e.g. from in-chat discovery), we preserve draft so the opportunity stays chat-only and\n * does not appear on the home view (home excludes draft).\n * When incoming is NOT draft (e.g. 'latent' from the background broker), existing draft status does NOT contaminate\n * the result — the broker-created opportunity retains its own status and can appear on the home view.\n */\nfunction resolveEnrichedStatus(relatedStatuses: string[], incomingStatus?: string): OpportunityStatus {\n const statuses = incomingStatus ? [...relatedStatuses, incomingStatus] : relatedStatuses;\n if (statuses.includes('accepted')) return 'accepted';\n if (statuses.includes('pending')) return 'pending';\n if (statuses.includes('rejected')) return 'rejected';\n if (statuses.includes('stalled')) return 'stalled';\n if (incomingStatus === 'draft') return 'draft';\n return 'latent';\n}\n\n/**\n * Extract non-introducer actor userIds from create data.\n */\nfunction getNonIntroducerUserIds(data: CreateOpportunityData): Id<'users'>[] {\n const ids = data.actors\n .filter((a) => a.role !== 'introducer')\n .map((a) => a.userId);\n return [...new Set(ids)];\n}\n\n/**\n * Extract intent IDs from actors.\n */\nfunction getIntentIdsFromActors(actors: OpportunityActor[]): Set<string> {\n const ids = new Set<string>();\n for (const a of actors) {\n if (a.intent) ids.add(a.intent);\n }\n return ids;\n}\n\n/**\n * Check if two opportunities share at least one intent ID.\n */\nfunction shareIntentIds(\n newData: CreateOpportunityData,\n existing: Opportunity\n): boolean {\n const newIntents = getIntentIdsFromActors(newData.actors);\n const existingIntents = getIntentIdsFromActors(existing.actors);\n for (const id of newIntents) {\n if (existingIntents.has(id)) return true;\n }\n return false;\n}\n\n/**\n * Merge actors from new data and existing opportunities: union by (networkId, userId, intent),\n * preserving all unique introducers and preferring newer role on conflict.\n */\nfunction mergeActors(\n newData: CreateOpportunityData,\n existingList: Opportunity[]\n): OpportunityActor[] {\n const key = (a: OpportunityActor) =>\n `${a.networkId}:${a.userId}:${a.intent ?? ''}`;\n const map = new Map<string, OpportunityActor>();\n\n // Add all from existing first (older)\n for (const opp of existingList) {\n for (const a of opp.actors) {\n map.set(key(a), a);\n }\n }\n // Add/overwrite with new (newer wins for same key, e.g. role)\n for (const a of newData.actors) {\n map.set(key(a), a);\n }\n\n return [...map.values()];\n}\n\n/**\n * Merge interpretation: single reasoning (new data only), max confidence, merged signals.\n * We use only the new opportunity's reasoning to avoid repetitive concatenation when\n * multiple overlapping opportunities share the same or similar text (e.g. same pair\n * across indexes), which previously produced long duplicated paragraphs in chat cards.\n */\nfunction mergeInterpretation(\n newData: CreateOpportunityData,\n existingList: Opportunity[]\n): OpportunityInterpretation {\n const reasoning = newData.interpretation.reasoning;\n\n let maxConf =\n typeof newData.interpretation.confidence === 'number'\n ? newData.interpretation.confidence\n : parseFloat(String(newData.interpretation.confidence ?? 0));\n for (const o of existingList) {\n const c = o.interpretation?.confidence;\n const cNum = typeof c === 'number' ? c : parseFloat(String(c ?? 0));\n if (cNum > maxConf) maxConf = cNum;\n }\n const confidence = maxConf;\n\n const signals: OpportunitySignal[] = [\n ...(newData.interpretation.signals ?? []),\n ...existingList.flatMap((o) => o.interpretation?.signals ?? []),\n ];\n const seen = new Set<string>();\n const dedupedSignals = signals.filter((s) => {\n const k = `${s.type}:${s.detail ?? ''}`;\n if (seen.has(k)) return false;\n seen.add(k);\n return true;\n });\n\n return {\n category: newData.interpretation.category,\n reasoning,\n confidence: typeof confidence === 'string' ? parseFloat(confidence) : confidence,\n signals: dedupedSignals.length > 0 ? dedupedSignals : newData.interpretation.signals,\n };\n}\n\n/**\n * Enrich or create: find overlapping opportunities, filter by semantic relatedness\n * using a two-phase approach, merge actors and interpretation into a single\n * CreateOpportunityData, and return the data plus IDs to expire. If no related\n * overlap, return original data unchanged.\n *\n * Phase 1 — Intent check (free, no API call):\n * Shared intent IDs mean the same declared user goal drove both opportunities.\n * This is rare because the IntentReconciler already deduplicates intents per-user\n * upstream, but when it fires it is definitive.\n *\n * Phase 2 — Batched embedding similarity (one API call for all remaining):\n * For opportunities without shared intents, embed all reasoning texts in a single\n * batch call and compare cosine similarity. Cross-user intent comparison (e.g.\n * Alice's \"find ML co-founder\" vs Bob's \"join ML startup\") is implicitly handled\n * here since reasoning text synthesizes both users' intents.\n */\nexport async function enrichOrCreate(\n database: EnricherDatabase,\n embedder: Embedder,\n newData: CreateOpportunityData,\n options?: EnrichOrCreateOptions\n): Promise<EnrichmentResult> {\n const actorUserIds = getNonIntroducerUserIds(newData);\n if (actorUserIds.length === 0) {\n return { enriched: false, data: newData };\n }\n\n const excludeStatuses = options?.excludeStatuses ?? DEFAULT_ENRICHER_EXCLUDE_STATUSES;\n const overlapping = await database.findOpportunitiesByActors(actorUserIds, { excludeStatuses });\n if (overlapping.length === 0) {\n return { enriched: false, data: newData };\n }\n\n const threshold = options?.similarityThreshold ?? DEFAULT_SIMILARITY_THRESHOLD;\n\n // Phase 1: Intent-based relatedness (free, strongest signal)\n const related: Opportunity[] = [];\n const remaining: Opportunity[] = [];\n for (const opp of overlapping) {\n if (shareIntentIds(newData, opp)) {\n related.push(opp);\n } else {\n remaining.push(opp);\n }\n }\n\n // Phase 2: Batched embedding similarity (one API call for all remaining)\n if (remaining.length > 0) {\n const newReasoning = (newData.interpretation?.reasoning ?? '').trim();\n\n // Only embed opps where both reasonings are long enough\n const embeddable: Opportunity[] = [];\n for (const opp of remaining) {\n const existingReasoning = (opp.interpretation?.reasoning ?? '').trim();\n if (\n newReasoning.length >= MIN_REASONING_LENGTH_FOR_EMBEDDING &&\n existingReasoning.length >= MIN_REASONING_LENGTH_FOR_EMBEDDING\n ) {\n embeddable.push(opp);\n }\n // Short reasoning + no shared intents (Phase 1 missed) → not related\n }\n\n if (embeddable.length > 0) {\n try {\n const textsToEmbed = [\n newReasoning,\n ...embeddable.map((o) => (o.interpretation?.reasoning ?? '').trim()),\n ];\n const vectors = (await embedder.generate(textsToEmbed, undefined, getAbortSignalConfig())) as number[][];\n const newVec = vectors[0];\n if (newVec?.length) {\n for (let i = 0; i < embeddable.length; i++) {\n const existingVec = vectors[i + 1];\n if (existingVec?.length && cosineSimilarity(newVec, existingVec) >= threshold) {\n related.push(embeddable[i]);\n }\n }\n }\n } catch (e) {\n logger.warn('Embedding check failed; intent-matched opportunities already captured', { error: e });\n // Phase 1 matches are preserved; remaining opps without shared intents are not related\n }\n }\n }\n\n if (related.length === 0) {\n return { enriched: false, data: newData };\n }\n\n const mergedActors = mergeActors(newData, related);\n const mergedInterpretation = mergeInterpretation(newData, related);\n const enrichedFrom = related.map((o) => o.id);\n const mergedConfidence =\n typeof mergedInterpretation.confidence === 'number'\n ? String(mergedInterpretation.confidence)\n : mergedInterpretation.confidence;\n\n const enrichedData: CreateOpportunityData = {\n ...newData,\n detection: {\n ...newData.detection,\n source: 'enrichment',\n enrichedFrom,\n },\n actors: mergedActors,\n interpretation: mergedInterpretation,\n confidence: mergedConfidence,\n };\n\n const resolvedStatus = resolveEnrichedStatus(related.map((o) => o.status), newData.status);\n\n logger.verbose('Enriched opportunity', {\n enrichedFrom,\n actorCount: mergedActors.length,\n });\n\n return {\n enriched: true,\n data: enrichedData,\n expiredIds: enrichedFrom,\n resolvedStatus,\n };\n}\n"]}
1
+ {"version":3,"file":"opportunity.enricher.js","sourceRoot":"/","sources":["opportunity/opportunity.enricher.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAGvE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAErD,MAAM,4BAA4B,GAAG,GAAG,CAAC;AACzC,MAAM,kCAAkC,GAAG,EAAE,CAAC;AAE9C;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAwB,CAAC,UAAU,EAAE,aAAa,EAAE,SAAS,CAAC,CAA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AC;IACnE,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9C,MAAM,gBAAgB,GACpB,OAAO,oBAAoB,CAAC,UAAU,KAAK,QAAQ;QACjD,CAAC,CAAC,MAAM,CAAC,oBAAoB,CAAC,UAAU,CAAC;QACzC,CAAC,CAAC,oBAAoB,CAAC,UAAU,CAAC;IAEtC,MAAM,YAAY,GAA0B;QAC1C,GAAG,OAAO;QACV,SAAS,EAAE;YACT,GAAG,OAAO,CAAC,SAAS;YACpB,MAAM,EAAE,YAAY;YACpB,YAAY;SACb;QACD,MAAM,EAAE,YAAY;QACpB,cAAc,EAAE,oBAAoB;QACpC,UAAU,EAAE,gBAAgB;KAC7B,CAAC;IAEF,MAAM,cAAc,GAAG,qBAAqB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAE3F,MAAM,CAAC,OAAO,CAAC,sBAAsB,EAAE;QACrC,YAAY;QACZ,UAAU,EAAE,YAAY,CAAC,MAAM;KAChC,CAAC,CAAC;IAEH,OAAO;QACL,QAAQ,EAAE,IAAI;QACd,IAAI,EAAE,YAAY;QAClB,UAAU,EAAE,YAAY;QACxB,cAAc;KACf,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Opportunity enricher: when creating an opportunity, find overlapping existing\n * opportunities (by non-introducer actor userId), check semantic relatedness, and\n * optionally merge into a single enriched opportunity and expire the old one(s).\n */\n\nimport type { CreateOpportunityData, Opportunity, OpportunityActor, OpportunityInterpretation, OpportunitySignal, OpportunityStatus } from '../shared/interfaces/database.interface.js';\nimport { getAbortSignalConfig } from '../shared/agent/model-signal.js';\nimport type { Embedder } from '../shared/interfaces/embedder.interface.js';\nimport type { Id } from '../shared/interfaces/database.interface.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('OpportunityEnricher');\n\nconst DEFAULT_SIMILARITY_THRESHOLD = 0.7;\nconst MIN_REASONING_LENGTH_FOR_EMBEDDING = 10;\n\n/**\n * Statuses excluded from the merge-candidate pool by default.\n *\n * - 'accepted': the pair already connected — do NOT fold a new discovery into\n * the historical opp. IND-237 surfaces the existing conversation separately.\n * - 'negotiating': a negotiation is in-flight for this pair; rolling a new\n * candidate into it would blur the outcome of the active turn. Wait for the\n * negotiation to finalize (→ draft/pending/rejected/stalled) first, then\n * enrichment can pick it up on the next pass.\n * - 'expired': already superseded by a later enriched opportunity. Without this\n * exclusion, each enrichment cycle re-merges previously-expired enriched\n * opportunities, compounding their actor arrays into 100+ entries.\n *\n * Exported for callers that want to extend rather than replace the default.\n */\nexport const DEFAULT_ENRICHER_EXCLUDE_STATUSES: OpportunityStatus[] = ['accepted', 'negotiating', 'expired'];\n\nexport type EnricherDatabase = {\n findOpportunitiesByActors(\n actorIds: string[],\n options?: { includeIntroducers?: boolean; statuses?: OpportunityStatus[]; excludeStatuses?: OpportunityStatus[] }\n ): Promise<Opportunity[]>;\n};\n\nexport type EnrichmentResult =\n | { enriched: false; data: CreateOpportunityData }\n | { enriched: true; data: CreateOpportunityData; expiredIds: string[]; resolvedStatus: OpportunityStatus };\n\nexport type EnrichOrCreateOptions = {\n similarityThreshold?: number;\n /**\n * Statuses to exclude from the merge-candidate pool. Defaults to\n * {@link DEFAULT_ENRICHER_EXCLUDE_STATUSES} (`['accepted', 'negotiating']`).\n * Pass an empty array `[]` to consider all statuses.\n */\n excludeStatuses?: OpportunityStatus[];\n /** Restrict merge/expiration candidates to the authoritative owned intent. */\n ownedIntentScope?: { triggerIntentId: string; ownerUserId: string };\n};\n\n/**\n * Cosine similarity between two vectors (0–1).\n */\nfunction cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length === 0) return 0;\n let dot = 0;\n let normA = 0;\n let normB = 0;\n for (let i = 0; i < a.length; i++) {\n dot += a[i] * b[i];\n normA += a[i] * a[i];\n normB += b[i] * b[i];\n }\n const denom = Math.sqrt(normA) * Math.sqrt(normB);\n if (denom === 0) return 0;\n const sim = dot / denom;\n return Math.max(0, Math.min(1, sim));\n}\n\n/**\n * Resolve enriched opportunity status from related opportunities' statuses and the incoming status.\n * Priority: accepted > pending > rejected > stalled > draft (only when incoming is draft) > latent.\n * The incoming status is included so we do not wrongly downgrade when the new opportunity has a higher-priority status.\n * When incoming is 'draft' (e.g. from in-chat discovery), we preserve draft so the opportunity stays chat-only and\n * does not appear on the home view (home excludes draft).\n * When incoming is NOT draft (e.g. 'latent' from the background broker), existing draft status does NOT contaminate\n * the result — the broker-created opportunity retains its own status and can appear on the home view.\n */\nfunction resolveEnrichedStatus(relatedStatuses: string[], incomingStatus?: string): OpportunityStatus {\n const statuses = incomingStatus ? [...relatedStatuses, incomingStatus] : relatedStatuses;\n if (statuses.includes('accepted')) return 'accepted';\n if (statuses.includes('pending')) return 'pending';\n if (statuses.includes('rejected')) return 'rejected';\n if (statuses.includes('stalled')) return 'stalled';\n if (incomingStatus === 'draft') return 'draft';\n return 'latent';\n}\n\n/**\n * Extract non-introducer actor userIds from create data.\n */\nfunction getNonIntroducerUserIds(data: CreateOpportunityData): Id<'users'>[] {\n const ids = data.actors\n .filter((a) => a.role !== 'introducer')\n .map((a) => a.userId);\n return [...new Set(ids)];\n}\n\n/**\n * Extract intent IDs from actors.\n */\nfunction belongsToOwnedIntent(\n opportunity: Opportunity,\n scope: { triggerIntentId: string; ownerUserId: string },\n): boolean {\n if (opportunity.detection.triggeredBy === scope.triggerIntentId) return true;\n return opportunity.actors.some((actor) =>\n actor.userId === scope.ownerUserId && actor.intent === scope.triggerIntentId);\n}\n\nfunction getIntentIdsFromActors(actors: OpportunityActor[]): Set<string> {\n const ids = new Set<string>();\n for (const a of actors) {\n if (a.intent) ids.add(a.intent);\n }\n return ids;\n}\n\n/**\n * Check if two opportunities share at least one intent ID.\n */\nfunction shareIntentIds(\n newData: CreateOpportunityData,\n existing: Opportunity\n): boolean {\n const newIntents = getIntentIdsFromActors(newData.actors);\n const existingIntents = getIntentIdsFromActors(existing.actors);\n for (const id of newIntents) {\n if (existingIntents.has(id)) return true;\n }\n return false;\n}\n\n/**\n * Merge actors from new data and existing opportunities: union by (networkId, userId, intent),\n * preserving all unique introducers and preferring newer role on conflict.\n */\nfunction mergeActors(\n newData: CreateOpportunityData,\n existingList: Opportunity[]\n): OpportunityActor[] {\n const key = (a: OpportunityActor) =>\n `${a.networkId}:${a.userId}:${a.intent ?? ''}`;\n const map = new Map<string, OpportunityActor>();\n\n // Add all from existing first (older)\n for (const opp of existingList) {\n for (const a of opp.actors) {\n map.set(key(a), a);\n }\n }\n // Add/overwrite with new (newer wins for same key, e.g. role)\n for (const a of newData.actors) {\n map.set(key(a), a);\n }\n\n return [...map.values()];\n}\n\n/**\n * Merge interpretation: single reasoning (new data only), max confidence, merged signals.\n * We use only the new opportunity's reasoning to avoid repetitive concatenation when\n * multiple overlapping opportunities share the same or similar text (e.g. same pair\n * across indexes), which previously produced long duplicated paragraphs in chat cards.\n */\nfunction mergeInterpretation(\n newData: CreateOpportunityData,\n existingList: Opportunity[]\n): OpportunityInterpretation {\n const reasoning = newData.interpretation.reasoning;\n\n let maxConf =\n typeof newData.interpretation.confidence === 'number'\n ? newData.interpretation.confidence\n : parseFloat(String(newData.interpretation.confidence ?? 0));\n for (const o of existingList) {\n const c = o.interpretation?.confidence;\n const cNum = typeof c === 'number' ? c : parseFloat(String(c ?? 0));\n if (cNum > maxConf) maxConf = cNum;\n }\n const confidence = maxConf;\n\n const signals: OpportunitySignal[] = [\n ...(newData.interpretation.signals ?? []),\n ...existingList.flatMap((o) => o.interpretation?.signals ?? []),\n ];\n const seen = new Set<string>();\n const dedupedSignals = signals.filter((s) => {\n const k = `${s.type}:${s.detail ?? ''}`;\n if (seen.has(k)) return false;\n seen.add(k);\n return true;\n });\n\n return {\n category: newData.interpretation.category,\n reasoning,\n confidence: typeof confidence === 'string' ? parseFloat(confidence) : confidence,\n signals: dedupedSignals.length > 0 ? dedupedSignals : newData.interpretation.signals,\n };\n}\n\n/**\n * Enrich or create: find overlapping opportunities, filter by semantic relatedness\n * using a two-phase approach, merge actors and interpretation into a single\n * CreateOpportunityData, and return the data plus IDs to expire. If no related\n * overlap, return original data unchanged.\n *\n * Phase 1 — Intent check (free, no API call):\n * Shared intent IDs mean the same declared user goal drove both opportunities.\n * This is rare because the IntentReconciler already deduplicates intents per-user\n * upstream, but when it fires it is definitive.\n *\n * Phase 2 — Batched embedding similarity (one API call for all remaining):\n * For opportunities without shared intents, embed all reasoning texts in a single\n * batch call and compare cosine similarity. Cross-user intent comparison (e.g.\n * Alice's \"find ML co-founder\" vs Bob's \"join ML startup\") is implicitly handled\n * here since reasoning text synthesizes both users' intents.\n */\nexport async function enrichOrCreate(\n database: EnricherDatabase,\n embedder: Embedder,\n newData: CreateOpportunityData,\n options?: EnrichOrCreateOptions\n): Promise<EnrichmentResult> {\n const actorUserIds = getNonIntroducerUserIds(newData);\n if (actorUserIds.length === 0) {\n return { enriched: false, data: newData };\n }\n\n const excludeStatuses = options?.excludeStatuses ?? DEFAULT_ENRICHER_EXCLUDE_STATUSES;\n const pairOverlaps = await database.findOpportunitiesByActors(actorUserIds, { excludeStatuses });\n const ownedIntentScope = options?.ownedIntentScope;\n const overlapping = ownedIntentScope\n ? pairOverlaps.filter((opportunity) => belongsToOwnedIntent(opportunity, ownedIntentScope))\n : pairOverlaps;\n if (ownedIntentScope && pairOverlaps.length > overlapping.length) {\n logger.info('Excluded cross-trigger overlaps from owned-intent enrichment', {\n triggerIntentId: ownedIntentScope.triggerIntentId,\n pairOverlapCount: pairOverlaps.length,\n sameTriggerOverlapCount: overlapping.length,\n });\n }\n if (overlapping.length === 0) {\n return { enriched: false, data: newData };\n }\n\n const threshold = options?.similarityThreshold ?? DEFAULT_SIMILARITY_THRESHOLD;\n\n // Phase 1: Intent-based relatedness (free, strongest signal)\n const related: Opportunity[] = [];\n const remaining: Opportunity[] = [];\n for (const opp of overlapping) {\n if (shareIntentIds(newData, opp)) {\n related.push(opp);\n } else {\n remaining.push(opp);\n }\n }\n\n // Phase 2: Batched embedding similarity (one API call for all remaining)\n if (remaining.length > 0) {\n const newReasoning = (newData.interpretation?.reasoning ?? '').trim();\n\n // Only embed opps where both reasonings are long enough\n const embeddable: Opportunity[] = [];\n for (const opp of remaining) {\n const existingReasoning = (opp.interpretation?.reasoning ?? '').trim();\n if (\n newReasoning.length >= MIN_REASONING_LENGTH_FOR_EMBEDDING &&\n existingReasoning.length >= MIN_REASONING_LENGTH_FOR_EMBEDDING\n ) {\n embeddable.push(opp);\n }\n // Short reasoning + no shared intents (Phase 1 missed) → not related\n }\n\n if (embeddable.length > 0) {\n try {\n const textsToEmbed = [\n newReasoning,\n ...embeddable.map((o) => (o.interpretation?.reasoning ?? '').trim()),\n ];\n const vectors = (await embedder.generate(textsToEmbed, undefined, getAbortSignalConfig())) as number[][];\n const newVec = vectors[0];\n if (newVec?.length) {\n for (let i = 0; i < embeddable.length; i++) {\n const existingVec = vectors[i + 1];\n if (existingVec?.length && cosineSimilarity(newVec, existingVec) >= threshold) {\n related.push(embeddable[i]);\n }\n }\n }\n } catch (e) {\n logger.warn('Embedding check failed; intent-matched opportunities already captured', { error: e });\n // Phase 1 matches are preserved; remaining opps without shared intents are not related\n }\n }\n }\n\n if (related.length === 0) {\n return { enriched: false, data: newData };\n }\n\n const mergedActors = mergeActors(newData, related);\n const mergedInterpretation = mergeInterpretation(newData, related);\n const enrichedFrom = related.map((o) => o.id);\n const mergedConfidence =\n typeof mergedInterpretation.confidence === 'number'\n ? String(mergedInterpretation.confidence)\n : mergedInterpretation.confidence;\n\n const enrichedData: CreateOpportunityData = {\n ...newData,\n detection: {\n ...newData.detection,\n source: 'enrichment',\n enrichedFrom,\n },\n actors: mergedActors,\n interpretation: mergedInterpretation,\n confidence: mergedConfidence,\n };\n\n const resolvedStatus = resolveEnrichedStatus(related.map((o) => o.status), newData.status);\n\n logger.verbose('Enriched opportunity', {\n enrichedFrom,\n actorCount: mergedActors.length,\n });\n\n return {\n enriched: true,\n data: enrichedData,\n expiredIds: enrichedFrom,\n resolvedStatus,\n };\n}\n"]}