@indexnetwork/protocol 6.6.1-rc.387.1 → 6.6.2-rc.388.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/opportunity/discriminator/discriminator.adjustments.js +1 -1
- package/dist/opportunity/discriminator/discriminator.adjustments.js.map +1 -1
- package/dist/opportunity/opportunity.safe-presentation.d.ts +1 -1
- package/dist/opportunity/opportunity.safe-presentation.js +1 -1
- package/dist/opportunity/opportunity.safe-presentation.js.map +1 -1
- package/package.json +1 -1
|
@@ -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
|
|
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,OAAO,CAAC,GAAG,CAAC;QAAE,OAAO,EAAE,CAAC;IACnC,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAuB,EAAE;QAC3C,IAC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AI;gBACpB,UAAU,EAAE,MAAM;gBAClB,SAAS,EAAE,GAAG;gBACd,GAAG,CAAC,iBAAiB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,iBAAiB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAClE,CAAC;SACH,CAAC,CAAC;IACL,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CACjC,QAAoD,EACpD,UAA0B;IAE1B,MAAM,QAAQ,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAC5D,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC,UAAU;QACtC,CAAC,CAAC,eAAe,KAAK,UAAU,CAAC,eAAe;QAChD,CAAC,CAAC,QAAQ,KAAK,UAAU,CAAC,QAAQ,CACnC,CAAC,CAAC;IACH,OAAO,EAAE,GAAG,CAAC,QAAQ,IAAI,EAAE,CAAC,EAAE,eAAe,EAAE,CAAC,GAAG,QAAQ,EAAE,UAAU,CAAC,EAAE,CAAC;AAC7E,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,wBAAwB,CACtC,QAAoD,EACpD,UAAoC;IAEpC,OAAO,CAAC,GAAG,yBAAyB,CAAC,QAAQ,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 (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/discriminator/discriminator.adjustments.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,4BAA4B,EAAE,8BAA8B,EAAE,q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M,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"]}
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via
|
|
17
17
|
* `allowFallback`; they no longer choose (or forget) sanitization steps.
|
|
18
18
|
*
|
|
19
|
-
* See `.pi/skills/opportunity-presentation
|
|
19
|
+
* See `.pi/skills/review-opportunity-presentation/SKILL.md` for the review
|
|
20
20
|
* checklist this module exists to satisfy.
|
|
21
21
|
*/
|
|
22
22
|
/** Default max length for fallback summaries (matches presenter internal fallback). */
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via
|
|
17
17
|
* `allowFallback`; they no longer choose (or forget) sanitization steps.
|
|
18
18
|
*
|
|
19
|
-
* See `.pi/skills/opportunity-presentation
|
|
19
|
+
* See `.pi/skills/review-opportunity-presentation/SKILL.md` for the review
|
|
20
20
|
* checklist this module exists to satisfy.
|
|
21
21
|
*/
|
|
22
22
|
import { truncateAtBoundary, viewerCentricCardSummary } from "./opportunity.presentation.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"opportunity.safe-presentation.js","sourceRoot":"/","sources":["opportunity/opportunity.safe-presentation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAElF,uFAAuF;AACvF,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAE3C,+DAA+D;AAC/D,MAAM,CAAC,MAAM,2BAA2B,GAAG,yBAAyB,CAAC;AAErE,yFAAyF;AACzF,MAAM,CAAC,MAAM,yBAAyB,GAAG,wB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AAE,CAAC;QACpE,MAAM,OAAO,GAAG,iCAAiC,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC;QACjF,IAAI,OAAO,EAAE,CAAC;YACZ,OAAO;gBACL,QAAQ,EACN,iCAAiC,CAAC,SAAS,CAAC,QAAQ,CAAC;oBACrD,yBAAyB;gBAC3B,OAAO;gBACP,eAAe,EACb,iCAAiC,CAAC,SAAS,CAAC,eAAe,CAAC;oBAC5D,uBAAuB;gBACzB,UAAU,EAAE,KAAK;aAClB,CAAC;QACJ,CAAC;IACH,CAAC;IAED,IAAI,IAAI,CAAC,aAAa,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAE9C,MAAM,YAAY,GAChB,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,cAAc,EAAE,SAAS,IAAI,EAAE,CAAC;IAC/D,OAAO;QACL,QAAQ,EAAE,yBAAyB;QACnC,OAAO,EAAE,mBAAmB,CAAC,YAAY,EAAE,IAAI,CAAC;QAChD,eAAe,EAAE,uBAAuB;QACxC,UAAU,EAAE,IAAI;KACjB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared safe-presentation primitive for all user-facing opportunity surfaces.\n *\n * Historically every surface (home feed, list/discover cards, minimal chat\n * cards, notification emails/Telegram, chat context, delivery cards) invented\n * its own fallback chain for the case where genuine LLM presenter output is\n * unavailable — some sliced raw `interpretation.reasoning` with no\n * sanitization at all. This module is the single standard:\n *\n * raw reasoning\n * → whitespace-normalize\n * → viewer-centric rewrite (incl. UUID stripping + introducer-mention stripping)\n * → boundary-aware truncation\n * → per-surface empty-text default\n *\n * Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via\n * `allowFallback`; they no longer choose (or forget) sanitization steps.\n *\n * See `.pi/skills/opportunity-presentation
|
|
1
|
+
{"version":3,"file":"opportunity.safe-presentation.js","sourceRoot":"/","sources":["opportunity/opportunity.safe-presentation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,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AAS,EAAE,QAAQ,CAAC,CAAC;IAC1D,OAAO,SAAS,IAAI,SAAS,CAAC;AAChC,CAAC;AAuCD;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,yBAAyB,CACvC,MAA8B,EAC9B,OAAgC,EAAE;IAElC,MAAM,SAAS,GAAG,MAAM,CAAC,oBAAoB,CAAC;IAC9C,IAAI,SAAS,EAAE,mBAAmB,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE,CAAC;QACpE,MAAM,OAAO,GAAG,iCAAiC,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC;QACjF,IAAI,OAAO,EAAE,CAAC;YACZ,OAAO;gBACL,QAAQ,EACN,iCAAiC,CAAC,SAAS,CAAC,QAAQ,CAAC;oBACrD,yBAAyB;gBAC3B,OAAO;gBACP,eAAe,EACb,iCAAiC,CAAC,SAAS,CAAC,eAAe,CAAC;oBAC5D,uBAAuB;gBACzB,UAAU,EAAE,KAAK;aAClB,CAAC;QACJ,CAAC;IACH,CAAC;IAED,IAAI,IAAI,CAAC,aAAa,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAE9C,MAAM,YAAY,GAChB,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,cAAc,EAAE,SAAS,IAAI,EAAE,CAAC;IAC/D,OAAO;QACL,QAAQ,EAAE,yBAAyB;QACnC,OAAO,EAAE,mBAAmB,CAAC,YAAY,EAAE,IAAI,CAAC;QAChD,eAAe,EAAE,uBAAuB;QACxC,UAAU,EAAE,IAAI;KACjB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared safe-presentation primitive for all user-facing opportunity surfaces.\n *\n * Historically every surface (home feed, list/discover cards, minimal chat\n * cards, notification emails/Telegram, chat context, delivery cards) invented\n * its own fallback chain for the case where genuine LLM presenter output is\n * unavailable — some sliced raw `interpretation.reasoning` with no\n * sanitization at all. This module is the single standard:\n *\n * raw reasoning\n * → whitespace-normalize\n * → viewer-centric rewrite (incl. UUID stripping + introducer-mention stripping)\n * → boundary-aware truncation\n * → per-surface empty-text default\n *\n * Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via\n * `allowFallback`; they no longer choose (or forget) sanitization steps.\n *\n * See `.pi/skills/review-opportunity-presentation/SKILL.md` for the review\n * checklist this module exists to satisfy.\n */\n\nimport { truncateAtBoundary, viewerCentricCardSummary } from \"./opportunity.presentation.js\";\nimport { stripUnsupportedOpportunityClaims } from \"./opportunity.claim-safety.js\";\n\n/** Default max length for fallback summaries (matches presenter internal fallback). */\nexport const SAFE_FALLBACK_MAX_CHARS = 300;\n\n/** Default copy when no reasoning text is available at all. */\nexport const DEFAULT_EMPTY_FALLBACK_TEXT = \"A promising connection.\";\n\n/** Default headline for fallback presentations (matches presenter internal fallback). */\nexport const DEFAULT_FALLBACK_HEADLINE = \"A promising connection\";\n\n/** Default CTA for fallback presentations (matches presenter internal fallback). */\nexport const DEFAULT_FALLBACK_ACTION =\n \"Take a look and decide whether to reach out.\";\n\nexport interface SafeFallbackOptions {\n /** Display name of the counterpart shown on the card (enables viewer-centric rewrite). */\n counterpartName?: string;\n /** Display name of the viewer; sentences describing the viewer are skipped/rewritten to \"you\". */\n viewerName?: string;\n /** Introducer display name; introducer mentions are stripped from the summary body. */\n introducerName?: string | null;\n /** Max output length (boundary-aware). Default {@link SAFE_FALLBACK_MAX_CHARS}. */\n maxChars?: number;\n /** Copy returned when reasoning is empty/blank. Default {@link DEFAULT_EMPTY_FALLBACK_TEXT}. */\n emptyText?: string;\n}\n\n/**\n * Produce safe user-facing fallback copy from raw match reasoning.\n *\n * This is the ONE sanitization standard: UUID stripping, introducer-mention\n * stripping, and viewer-centric rewrite (via {@link viewerCentricCardSummary}),\n * followed by whitespace normalization and boundary-aware truncation (via\n * {@link truncateAtBoundary}). Never returns raw reasoning verbatim beyond\n * these guarantees, and never returns an empty string.\n *\n * @param rawReasoning - Raw `interpretation.reasoning` / `matchReason` text (may be null/undefined).\n * @param opts - Per-surface knobs (names for rewrite, max length, empty-text copy).\n */\nexport function safeFallbackSummary(\n rawReasoning: string | null | undefined,\n opts: SafeFallbackOptions = {},\n): string {\n const emptyText = opts.emptyText ?? DEFAULT_EMPTY_FALLBACK_TEXT;\n const maxChars = opts.maxChars ?? SAFE_FALLBACK_MAX_CHARS;\n\n const normalized = (rawReasoning ?? \"\").replace(/\\s+/g, \" \").trim();\n if (!normalized) return emptyText;\n const claimSafeInput = stripUnsupportedOpportunityClaims(normalized);\n if (!claimSafeInput) return emptyText;\n\n // viewerCentricCardSummary handles UUID stripping, introducer-mention\n // stripping, and the viewer-centric rewrite. Pass Infinity so truncation is\n // handled by boundary-aware logic below instead of a mid-word hard slice.\n const rewritten = viewerCentricCardSummary(\n claimSafeInput,\n opts.counterpartName ?? \"\",\n Number.POSITIVE_INFINITY,\n opts.viewerName,\n opts.introducerName ?? undefined,\n );\n\n // Claim validation intentionally runs after viewer-centric rewriting: rewrite\n // heuristics may select or join different source sentences, and the final\n // user-facing sentence set is what must be safe.\n const claimSafe = stripUnsupportedOpportunityClaims(rewritten);\n const truncated = truncateAtBoundary(claimSafe, maxChars);\n return truncated || emptyText;\n}\n\n/** Minimal presenter-output shape the primitive inspects (subset of HomeCardPresentationResult). */\nexport interface SafePresentationCandidate {\n headline?: string;\n personalizedSummary?: string;\n suggestedAction?: string;\n /** Set by OpportunityPresenter when its LLM call failed and it returned fallback-shaped copy. */\n isFallback?: boolean;\n}\n\n/** Opportunity-ish source object accepted by {@link getSafePresentationOrSkip}. */\nexport interface SafePresentationSource {\n /** Presenter output attached to the record, when available. */\n homeCardPresentation?: SafePresentationCandidate | null;\n /** Pre-truncated raw reasoning carried on discovery/list card data. */\n matchReason?: string | null;\n /** Full opportunity interpretation, when the caller holds the record. */\n interpretation?: { reasoning?: string | null } | null;\n}\n\nexport interface SafePresentationOptions extends SafeFallbackOptions {\n /**\n * Policy switch: when false, return null instead of fallback copy so the\n * surface can skip rendering entirely (e.g. scheduled digests where sending\n * degraded copy is worse than sending nothing). Default true.\n */\n allowFallback?: boolean;\n}\n\n/** Resolved safe presentation for a surface to render. */\nexport interface SafePresentation {\n headline: string;\n summary: string;\n suggestedAction: string;\n /** True when copy was derived from raw reasoning rather than genuine LLM presenter output. */\n isFallback: boolean;\n}\n\n/**\n * Resolve the safe user-facing presentation for an opportunity, or signal skip.\n *\n * Resolution order:\n * 1. Genuine presenter output (`homeCardPresentation` present, non-empty, and\n * NOT tagged `isFallback` by the presenter) — claim-validated before return.\n * 2. Otherwise, if `allowFallback` (default true): sanitized fallback copy\n * built from `matchReason` / `interpretation.reasoning` via\n * {@link safeFallbackSummary}.\n * 3. Otherwise `null` — the surface must skip this opportunity.\n *\n * Raw `interpretation.reasoning` / `matchReason` never reaches the caller\n * unsanitized through this function.\n */\nexport function getSafePresentationOrSkip(\n source: SafePresentationSource,\n opts: SafePresentationOptions = {},\n): SafePresentation | null {\n const candidate = source.homeCardPresentation;\n if (candidate?.personalizedSummary?.trim() && !candidate.isFallback) {\n const summary = stripUnsupportedOpportunityClaims(candidate.personalizedSummary);\n if (summary) {\n return {\n headline:\n stripUnsupportedOpportunityClaims(candidate.headline) ||\n DEFAULT_FALLBACK_HEADLINE,\n summary,\n suggestedAction:\n stripUnsupportedOpportunityClaims(candidate.suggestedAction) ||\n DEFAULT_FALLBACK_ACTION,\n isFallback: false,\n };\n }\n }\n\n if (opts.allowFallback === false) return null;\n\n const rawReasoning =\n source.matchReason ?? source.interpretation?.reasoning ?? \"\";\n return {\n headline: DEFAULT_FALLBACK_HEADLINE,\n summary: safeFallbackSummary(rawReasoning, opts),\n suggestedAction: DEFAULT_FALLBACK_ACTION,\n isFallback: true,\n };\n}\n"]}
|