@indexnetwork/protocol 5.0.0 → 5.2.0-rc.368.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 (71) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/dist/index.d.ts +8 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +5 -2
  5. package/dist/index.js.map +1 -1
  6. package/dist/negotiation/negotiation.summarizer.d.ts +1 -1
  7. package/dist/negotiation/negotiation.summarizer.d.ts.map +1 -1
  8. package/dist/negotiation/negotiation.summarizer.js.map +1 -1
  9. package/dist/opportunity/discovery-question.helper.d.ts +1 -1
  10. package/dist/opportunity/discovery-question.helper.d.ts.map +1 -1
  11. package/dist/opportunity/discovery-question.helper.js.map +1 -1
  12. package/dist/opportunity/discriminator/discriminator.miner.d.ts +3 -1
  13. package/dist/opportunity/discriminator/discriminator.miner.d.ts.map +1 -1
  14. package/dist/opportunity/discriminator/discriminator.miner.js +48 -18
  15. package/dist/opportunity/discriminator/discriminator.miner.js.map +1 -1
  16. package/dist/opportunity/negotiation-summary.builder.d.ts +1 -1
  17. package/dist/opportunity/negotiation-summary.builder.d.ts.map +1 -1
  18. package/dist/opportunity/negotiation-summary.builder.js.map +1 -1
  19. package/dist/opportunity/opportunity.discover.js.map +1 -1
  20. package/dist/opportunity/opportunity.graph.d.ts +323 -15
  21. package/dist/opportunity/opportunity.graph.d.ts.map +1 -1
  22. package/dist/opportunity/opportunity.state.d.ts +68 -2
  23. package/dist/opportunity/opportunity.state.d.ts.map +1 -1
  24. package/dist/opportunity/opportunity.state.js.map +1 -1
  25. package/dist/opportunity/outcome/outcome.env.d.ts +61 -0
  26. package/dist/opportunity/outcome/outcome.env.d.ts.map +1 -0
  27. package/dist/opportunity/outcome/outcome.env.js +64 -0
  28. package/dist/opportunity/outcome/outcome.env.js.map +1 -0
  29. package/dist/opportunity/outcome/outcome.hypotheses.d.ts +30 -0
  30. package/dist/opportunity/outcome/outcome.hypotheses.d.ts.map +1 -0
  31. package/dist/opportunity/outcome/outcome.hypotheses.js +118 -0
  32. package/dist/opportunity/outcome/outcome.hypotheses.js.map +1 -0
  33. package/dist/opportunity/outcome/outcome.shadow.d.ts +57 -0
  34. package/dist/opportunity/outcome/outcome.shadow.d.ts.map +1 -0
  35. package/dist/opportunity/outcome/outcome.shadow.js +88 -0
  36. package/dist/opportunity/outcome/outcome.shadow.js.map +1 -0
  37. package/dist/opportunity/outcome/outcome.types.d.ts +111 -0
  38. package/dist/opportunity/outcome/outcome.types.d.ts.map +1 -0
  39. package/dist/opportunity/outcome/outcome.types.js +27 -0
  40. package/dist/opportunity/outcome/outcome.types.js.map +1 -0
  41. package/dist/questioner/questioner.discovery.prompt.d.ts +9 -0
  42. package/dist/questioner/questioner.discovery.prompt.d.ts.map +1 -0
  43. package/dist/{opportunity/question.prompt.js → questioner/questioner.discovery.prompt.js} +6 -7
  44. package/dist/questioner/questioner.discovery.prompt.js.map +1 -0
  45. package/dist/questioner/questioner.presets.js +2 -2
  46. package/dist/questioner/questioner.presets.js.map +1 -1
  47. package/dist/questioner/questioner.types.d.ts +2 -2
  48. package/dist/questioner/questioner.types.d.ts.map +1 -1
  49. package/dist/questioner/questioner.types.js.map +1 -1
  50. package/dist/shared/agent/model.config.d.ts +0 -5
  51. package/dist/shared/agent/model.config.d.ts.map +1 -1
  52. package/dist/shared/agent/model.config.js +0 -1
  53. package/dist/shared/agent/model.config.js.map +1 -1
  54. package/dist/shared/interfaces/database.interface.d.ts +28 -2
  55. package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
  56. package/dist/shared/interfaces/database.interface.js.map +1 -1
  57. package/dist/shared/interfaces/negotiation-summary.interface.d.ts +1 -1
  58. package/dist/shared/interfaces/negotiation-summary.interface.d.ts.map +1 -1
  59. package/dist/shared/interfaces/negotiation-summary.interface.js.map +1 -1
  60. package/dist/shared/interfaces/question-generator.interface.d.ts +7 -5
  61. package/dist/shared/interfaces/question-generator.interface.d.ts.map +1 -1
  62. package/dist/shared/interfaces/question-generator.interface.js.map +1 -1
  63. package/dist/shared/schemas/discovery-question.schema.d.ts +2 -2
  64. package/package.json +1 -1
  65. package/dist/opportunity/question.generator.d.ts +0 -22
  66. package/dist/opportunity/question.generator.d.ts.map +0 -1
  67. package/dist/opportunity/question.generator.js +0 -147
  68. package/dist/opportunity/question.generator.js.map +0 -1
  69. package/dist/opportunity/question.prompt.d.ts +0 -102
  70. package/dist/opportunity/question.prompt.d.ts.map +0 -1
  71. package/dist/opportunity/question.prompt.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outcome.shadow.js","sourceRoot":"/","sources":["opportunity/outcome/outcome.shadow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAG/E,OAAO,EAAE,sBAAsB,EAAE,0BAA0B,EAAE,+BAA+B,EAAE,MAAM,kBAAkB,CAAC;AACvH,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAGhE,MAAM,MAAM,GAAG,cAAc,CAAC,uBAAuB,CAAC,CAAC;AAyBvD;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CAAC,QAA0B;IACnE,MAAM,KAAK,GAAG,IAAI,GAAG,EAA0B,CAAC;IAChD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,MAAM,QAAQ,GAAG,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QAC7C,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YACrC,SAAS;QACX,CAAC;QACD,MAAM,KAAK,GACT,OAAO,CAAC,UAAU,GAAG,QAAQ,CAAC,UAAU;YACxC,CAAC,OAAO,CAAC,UAAU,KAAK,QAAQ,CAAC,UAAU,IAAI,OAA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plicate related opportunities,\n * mine neutral axes over the deduplicated historical pool BLIND to outcome,\n * then join the owner-outcome labels and threshold the result.\n *\n * No persistence, no questions, no UI. The output is consumed only by aggregate\n * telemetry for human review.\n *\n * Pipeline:\n * 1. Dedup related opportunities: collapse examples sharing a dedup key to a\n * single representative (most recent), so a cluster of related opps can\n * neither dominate the miner nor inflate a side's independent support.\n * 2. Cap to the most recent OUTCOME_MAX_CANDIDATES for a bounded LLM pass.\n * 3. Build the miner pool — PoolCandidate carries id + publicContext + score\n * and, critically, NO outcome label. The miner is structurally blind.\n * 4. Mine neutral axes + assign candidates (evidence-verified).\n * 5. Join outcome labels (only now) and apply the k-support threshold.\n */\n\nimport { protocolLogger } from \"../../shared/observability/protocol.logger.js\";\nimport type { PoolDiscriminatorMiner } from \"../discriminator/discriminator.miner.js\";\nimport type { PoolCandidate } from \"../discriminator/discriminator.types.js\";\nimport { OUTCOME_MAX_CANDIDATES, OUTCOME_MIN_COMPARED_SIDES, OUTCOME_MIN_INDEPENDENT_SUPPORT } from \"./outcome.env.js\";\nimport { joinOutcomeHypotheses } from \"./outcome.hypotheses.js\";\nimport type { OutcomeExample, OutcomeLabel, OutcomeShadowResult } from \"./outcome.types.js\";\n\nconst logger = protocolLogger(\"OutcomeQuestionShadow\");\n\n/** Input for one Lens B shadow mining+join pass. */\nexport interface OutcomeShadowInput {\n /**\n * Intent payload (+ summary) text that owns this scope. Used only as miner\n * context; never mixed with outcome labels.\n */\n intentText: string;\n /**\n * Captured owner-outcome examples for exactly one recipient + intent +\n * fingerprint scope. Each carries a presentation-safe snapshot and a dedup\n * key; outcome labels live here but are withheld from the miner.\n */\n examples: OutcomeExample[];\n miner: Pick<PoolDiscriminatorMiner, \"mine\">;\n /** Override the independent-support threshold (defaults to k). */\n minIndependentSupport?: number;\n /** Override the minimum qualified sides. */\n minComparedSides?: number;\n /** Override the LLM candidate cap. */\n maxCandidates?: number;\n signal?: AbortSignal;\n}\n\n/**\n * Collapse related opportunities to independent examples: one representative\n * (most recent by occurredAt) per distinct dedup key. Deterministic — ties on\n * occurredAt fall back to opportunityId ordering.\n */\nexport function deduplicateOutcomeExamples(examples: OutcomeExample[]): OutcomeExample[] {\n const byKey = new Map<string, OutcomeExample>();\n for (const example of examples) {\n const existing = byKey.get(example.dedupKey);\n if (existing === undefined) {\n byKey.set(example.dedupKey, example);\n continue;\n }\n const newer =\n example.occurredAt > existing.occurredAt ||\n (example.occurredAt === existing.occurredAt && example.opportunityId > existing.opportunityId);\n if (newer) byKey.set(example.dedupKey, example);\n }\n return [...byKey.values()].sort(\n (a, b) => b.occurredAt.localeCompare(a.occurredAt) || a.opportunityId.localeCompare(b.opportunityId),\n );\n}\n\n/**\n * Run the Lens B shadow pipeline for one scope.\n *\n * Throws only when *mining* fails (callers are fire-and-forget and must catch).\n * A pool that is empty or below the compare floor after dedup returns an empty\n * result rather than throwing.\n */\nexport async function runOutcomeShadow(input: OutcomeShadowInput): Promise<OutcomeShadowResult> {\n const minSupport = input.minIndependentSupport ?? OUTCOME_MIN_INDEPENDENT_SUPPORT;\n const minSides = input.minComparedSides ?? OUTCOME_MIN_COMPARED_SIDES;\n const maxCandidates = input.maxCandidates ?? OUTCOME_MAX_CANDIDATES;\n\n // 1–2. Dedup related opportunities, then cap to a bounded, recent pool.\n const independent = deduplicateOutcomeExamples(input.examples).slice(0, maxCandidates);\n if (independent.length < minSupport * minSides) {\n return { poolSize: independent.length, eligibleCount: 0, hypotheses: [] };\n }\n\n // 3. Build the miner pool with RUN-LOCAL aliases (c0, c1, …) as candidate ids\n // — raw opportunity ids are never sent to the LLM. The alias→outcome map is\n // kept internally for the join. PoolCandidate deliberately excludes the\n // outcome label, so the miner cannot condition on which side was chosen.\n const aliased = independent.map((example, index) => ({ alias: `c${index}`, example }));\n const candidates: PoolCandidate[] = aliased.map(({ alias, example }) => ({\n id: alias,\n publicContext: example.publicContext,\n score: example.score ?? 1,\n }));\n\n // 4. Blind assignment (assignments come back keyed by the run-local alias).\n const mined = await input.miner.mine(\n { intentText: input.intentText, candidates },\n input.signal ? { signal: input.signal } : undefined,\n );\n if (mined.length === 0) {\n return { poolSize: independent.length, eligibleCount: 0, hypotheses: [] };\n }\n\n // 5. Join outcome labels (only now) by alias, and threshold.\n const examples = new Map<string, OutcomeLabel>(\n aliased.map(({ alias, example }) => [alias, example.label]),\n );\n const result = joinOutcomeHypotheses({\n discriminators: mined,\n examples,\n minIndependentSupport: minSupport,\n minComparedSides: minSides,\n });\n\n logger.debug(\"shadow join complete\", {\n poolSize: result.poolSize,\n eligibleCount: result.eligibleCount,\n });\n\n return result;\n}\n"]}
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Lens B outcome-question mining — shared types (IND-434).
3
+ *
4
+ * Lens B learns whether a user's OWN past explicit opportunity decisions
5
+ * (accept / reject) suggest a useful clarification question, WITHOUT treating
6
+ * mutable statuses, counterparty actions, or system transitions as
7
+ * preferences. It is the historical-outcome analogue of the live-pool Lens A
8
+ * discriminator (see ../discriminator/*).
9
+ *
10
+ * The two lenses share the neutral-axis mining machinery (PoolDiscriminatorMiner
11
+ * assigns candidates to axis sides from presentation-safe context only). Lens B
12
+ * adds the crucial privacy/correctness discipline on top:
13
+ *
14
+ * 1. Candidates are assigned to sides BLIND to their outcome label — the
15
+ * classifier never sees which side the user chose (the miner input carries
16
+ * no outcome field at all).
17
+ * 2. Outcome labels are joined only AFTER assignment.
18
+ * 3. Related opportunities are deduplicated (one independent example per
19
+ * distinct counterpart) before support is counted.
20
+ * 4. Every compared group (side) must clear the independent-support
21
+ * threshold k, so aggregate telemetry never exposes a small cell.
22
+ *
23
+ * P7 (shadow) uses these types for aggregate-telemetry output only: no
24
+ * questions, ranking, intent, premise, memory, newborn-stamp, or push writes.
25
+ */
26
+ import type { MinedDiscriminator } from "../discriminator/discriminator.types.js";
27
+ /**
28
+ * The only two explicit owner actions Lens B treats as preference labels.
29
+ * Non-action, delivery, expiry, timeout, merge, cascade, screening, and every
30
+ * counterparty/agent/system transition are deliberately excluded upstream.
31
+ */
32
+ export type OutcomeLabel = "accepted" | "rejected";
33
+ /**
34
+ * One captured owner-outcome example, as consumed by the mining orchestrator.
35
+ * Built from an append-only feedback event; carries only presentation-safe
36
+ * text plus join/dedup keys — never raw ids, vectors, or model reasoning.
37
+ */
38
+ export interface OutcomeExample {
39
+ /**
40
+ * Opportunity id — the join key between blind assignment and outcome label.
41
+ * Never emitted in telemetry.
42
+ */
43
+ opportunityId: string;
44
+ /** Presentation-safe candidate snapshot the miner assigns sides from. */
45
+ publicContext: string;
46
+ /** Explicit owner action. Joined AFTER assignment, never seen by the miner. */
47
+ label: OutcomeLabel;
48
+ /**
49
+ * Related-opportunity dedup key: a stable, non-reversible identifier of the
50
+ * counterpart (or opportunity when no counterpart). Two examples with the
51
+ * same key count as ONE independent example.
52
+ */
53
+ dedupKey: string;
54
+ /** Sort key for recency-based capping/representative selection (ISO-8601). */
55
+ occurredAt: string;
56
+ /** Optional confidence mass for score-weighted assignment; defaults to 1. */
57
+ score?: number;
58
+ }
59
+ /** Aggregate support for one discriminator side, after dedup + threshold. */
60
+ export interface OutcomeSideSupport {
61
+ /** Neutral side label carried verbatim from the miner. */
62
+ side: string;
63
+ /** Distinct independent (deduplicated) examples assigned to this side (≥ k). */
64
+ independentSupport: number;
65
+ /**
66
+ * Independent accepted examples ÷ independentSupport, rounded to 0.01. A
67
+ * rate, never a raw small-cell count.
68
+ */
69
+ acceptRate: number;
70
+ }
71
+ /** One eligible neutral hypothesis with aggregate-only stats. */
72
+ export interface OutcomeHypothesis {
73
+ /** Discriminator label, e.g. "Hands-on builders vs strategic advisors". */
74
+ label: string;
75
+ /** A neutral question the intent owner could answer to resolve the axis. */
76
+ questionSeed: string;
77
+ /** Only the qualified sides (each ≥ k independent examples). */
78
+ sides: OutcomeSideSupport[];
79
+ /** Evidence-verification rate carried from the miner (hallucination health). */
80
+ evidenceRate: number;
81
+ /** Minimum independentSupport across the qualified sides (≥ k). */
82
+ minIndependentSupport: number;
83
+ }
84
+ /** Result of one shadow mining pass (the aggregate telemetry payload shape). */
85
+ export interface OutcomeShadowResult {
86
+ /** Distinct independent examples considered after dedup + capping. */
87
+ poolSize: number;
88
+ /** Count of eligible hypotheses (meets k + ≥ minComparedSides qualified). */
89
+ eligibleCount: number;
90
+ /**
91
+ * Eligible hypotheses only, sorted deterministically. Aggregate stats only —
92
+ * no opportunity ids, no candidate text, no small-cell counts.
93
+ */
94
+ hypotheses: OutcomeHypothesis[];
95
+ }
96
+ /** Input to the pure outcome-join step (assignment already done, blind). */
97
+ export interface JoinOutcomeHypothesesInput {
98
+ /** Mined discriminators with verified side assignments (blind to outcome). */
99
+ discriminators: MinedDiscriminator[];
100
+ /**
101
+ * Outcome labels keyed by opportunity id. Each example is already
102
+ * independent (deduplicated by the orchestrator), so one entry = one
103
+ * independent example.
104
+ */
105
+ examples: Map<string, OutcomeLabel>;
106
+ /** Independent-support threshold per side. Defaults to k. */
107
+ minIndependentSupport?: number;
108
+ /** Minimum qualified sides. Defaults to the module constant. */
109
+ minComparedSides?: number;
110
+ }
111
+ //# sourceMappingURL=outcome.types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outcome.types.d.ts","sourceRoot":"/","sources":["opportunity/outcome/outcome.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAElF;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,UAAU,GAAG,UAAU,CAAC;AAEnD;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB,yEAAyE;IACzE,aAAa,EAAE,MAAM,CAAC;IACtB,+EAA+E;IAC/E,KAAK,EAAE,YAAY,CAAC;IACpB;;;;OAIG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,8EAA8E;IAC9E,UAAU,EAAE,MAAM,CAAC;IACnB,6EAA6E;IAC7E,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,6EAA6E;AAC7E,MAAM,WAAW,kBAAkB;IACjC,0DAA0D;IAC1D,IAAI,EAAE,MAAM,CAAC;IACb,gFAAgF;IAChF,kBAAkB,EAAE,MAAM,CAAC;IAC3B;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,iEAAiE;AACjE,MAAM,WAAW,iBAAiB;IAChC,2EAA2E;IAC3E,KAAK,EAAE,MAAM,CAAC;IACd,4EAA4E;IAC5E,YAAY,EAAE,MAAM,CAAC;IACrB,gEAAgE;IAChE,KAAK,EAAE,kBAAkB,EAAE,CAAC;IAC5B,gFAAgF;IAChF,YAAY,EAAE,MAAM,CAAC;IACrB,mEAAmE;IACnE,qBAAqB,EAAE,MAAM,CAAC;CAC/B;AAED,gFAAgF;AAChF,MAAM,WAAW,mBAAmB;IAClC,sEAAsE;IACtE,QAAQ,EAAE,MAAM,CAAC;IACjB,6EAA6E;IAC7E,aAAa,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,UAAU,EAAE,iBAAiB,EAAE,CAAC;CACjC;AAED,4EAA4E;AAC5E,MAAM,WAAW,0BAA0B;IACzC,8EAA8E;IAC9E,cAAc,EAAE,kBAAkB,EAAE,CAAC;IACrC;;;;OAIG;IACH,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IACpC,6DAA6D;IAC7D,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,gEAAgE;IAChE,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Lens B outcome-question mining — shared types (IND-434).
3
+ *
4
+ * Lens B learns whether a user's OWN past explicit opportunity decisions
5
+ * (accept / reject) suggest a useful clarification question, WITHOUT treating
6
+ * mutable statuses, counterparty actions, or system transitions as
7
+ * preferences. It is the historical-outcome analogue of the live-pool Lens A
8
+ * discriminator (see ../discriminator/*).
9
+ *
10
+ * The two lenses share the neutral-axis mining machinery (PoolDiscriminatorMiner
11
+ * assigns candidates to axis sides from presentation-safe context only). Lens B
12
+ * adds the crucial privacy/correctness discipline on top:
13
+ *
14
+ * 1. Candidates are assigned to sides BLIND to their outcome label — the
15
+ * classifier never sees which side the user chose (the miner input carries
16
+ * no outcome field at all).
17
+ * 2. Outcome labels are joined only AFTER assignment.
18
+ * 3. Related opportunities are deduplicated (one independent example per
19
+ * distinct counterpart) before support is counted.
20
+ * 4. Every compared group (side) must clear the independent-support
21
+ * threshold k, so aggregate telemetry never exposes a small cell.
22
+ *
23
+ * P7 (shadow) uses these types for aggregate-telemetry output only: no
24
+ * questions, ranking, intent, premise, memory, newborn-stamp, or push writes.
25
+ */
26
+ export {};
27
+ //# sourceMappingURL=outcome.types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outcome.types.js","sourceRoot":"/","sources":["opportunity/outcome/outcome.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG","sourcesContent":["/**\n * Lens B outcome-question mining — shared types (IND-434).\n *\n * Lens B learns whether a user's OWN past explicit opportunity decisions\n * (accept / reject) suggest a useful clarification question, WITHOUT treating\n * mutable statuses, counterparty actions, or system transitions as\n * preferences. It is the historical-outcome analogue of the live-pool Lens A\n * discriminator (see ../discriminator/*).\n *\n * The two lenses share the neutral-axis mining machinery (PoolDiscriminatorMiner\n * assigns candidates to axis sides from presentation-safe context only). Lens B\n * adds the crucial privacy/correctness discipline on top:\n *\n * 1. Candidates are assigned to sides BLIND to their outcome label — the\n * classifier never sees which side the user chose (the miner input carries\n * no outcome field at all).\n * 2. Outcome labels are joined only AFTER assignment.\n * 3. Related opportunities are deduplicated (one independent example per\n * distinct counterpart) before support is counted.\n * 4. Every compared group (side) must clear the independent-support\n * threshold k, so aggregate telemetry never exposes a small cell.\n *\n * P7 (shadow) uses these types for aggregate-telemetry output only: no\n * questions, ranking, intent, premise, memory, newborn-stamp, or push writes.\n */\n\nimport type { MinedDiscriminator } from \"../discriminator/discriminator.types.js\";\n\n/**\n * The only two explicit owner actions Lens B treats as preference labels.\n * Non-action, delivery, expiry, timeout, merge, cascade, screening, and every\n * counterparty/agent/system transition are deliberately excluded upstream.\n */\nexport type OutcomeLabel = \"accepted\" | \"rejected\";\n\n/**\n * One captured owner-outcome example, as consumed by the mining orchestrator.\n * Built from an append-only feedback event; carries only presentation-safe\n * text plus join/dedup keys — never raw ids, vectors, or model reasoning.\n */\nexport interface OutcomeExample {\n /**\n * Opportunity id — the join key between blind assignment and outcome label.\n * Never emitted in telemetry.\n */\n opportunityId: string;\n /** Presentation-safe candidate snapshot the miner assigns sides from. */\n publicContext: string;\n /** Explicit owner action. Joined AFTER assignment, never seen by the miner. */\n label: OutcomeLabel;\n /**\n * Related-opportunity dedup key: a stable, non-reversible identifier of the\n * counterpart (or opportunity when no counterpart). Two examples with the\n * same key count as ONE independent example.\n */\n dedupKey: string;\n /** Sort key for recency-based capping/representative selection (ISO-8601). */\n occurredAt: string;\n /** Optional confidence mass for score-weighted assignment; defaults to 1. */\n score?: number;\n}\n\n/** Aggregate support for one discriminator side, after dedup + threshold. */\nexport interface OutcomeSideSupport {\n /** Neutral side label carried verbatim from the miner. */\n side: string;\n /** Distinct independent (deduplicated) examples assigned to this side (≥ k). */\n independentSupport: number;\n /**\n * Independent accepted examples ÷ independentSupport, rounded to 0.01. A\n * rate, never a raw small-cell count.\n */\n acceptRate: number;\n}\n\n/** One eligible neutral hypothesis with aggregate-only stats. */\nexport interface OutcomeHypothesis {\n /** Discriminator label, e.g. \"Hands-on builders vs strategic advisors\". */\n label: string;\n /** A neutral question the intent owner could answer to resolve the axis. */\n questionSeed: string;\n /** Only the qualified sides (each ≥ k independent examples). */\n sides: OutcomeSideSupport[];\n /** Evidence-verification rate carried from the miner (hallucination health). */\n evidenceRate: number;\n /** Minimum independentSupport across the qualified sides (≥ k). */\n minIndependentSupport: number;\n}\n\n/** Result of one shadow mining pass (the aggregate telemetry payload shape). */\nexport interface OutcomeShadowResult {\n /** Distinct independent examples considered after dedup + capping. */\n poolSize: number;\n /** Count of eligible hypotheses (meets k + ≥ minComparedSides qualified). */\n eligibleCount: number;\n /**\n * Eligible hypotheses only, sorted deterministically. Aggregate stats only —\n * no opportunity ids, no candidate text, no small-cell counts.\n */\n hypotheses: OutcomeHypothesis[];\n}\n\n/** Input to the pure outcome-join step (assignment already done, blind). */\nexport interface JoinOutcomeHypothesesInput {\n /** Mined discriminators with verified side assignments (blind to outcome). */\n discriminators: MinedDiscriminator[];\n /**\n * Outcome labels keyed by opportunity id. Each example is already\n * independent (deduplicated by the orchestrator), so one entry = one\n * independent example.\n */\n examples: Map<string, OutcomeLabel>;\n /** Independent-support threshold per side. Defaults to k. */\n minIndependentSupport?: number;\n /** Minimum qualified sides. Defaults to the module constant. */\n minComparedSides?: number;\n}\n"]}
@@ -0,0 +1,9 @@
1
+ import type { DiscoveryQuestionInput } from "../shared/schemas/discovery-question.schema.js";
2
+ /** System prompt for the QuestionerAgent's `discovery` mode. */
3
+ export declare const DISCOVERY_SYSTEM_PROMPT = "You help write user-facing follow-up questions after Index has reviewed potential connections for a human. Your job: surface the minimum set of structured decision questions the human must answer to make the next discovery turn sharper, or improve their outlook on the intent.\n\nYou may pick from five strategies. Choose contextually; mix when multiple questions genuinely complement.\n- refine_intent: ask the user to sharpen or pivot their original signal.\n- surface_missing_detail: ask for one concrete missing input (stage, location, timing, scope, \u2026).\n- open_adjacent_thread: offer a pivot suggested by recurring connection signals.\n- reflective_summary: mirror what the connection review revealed and ask the user to decide.\n- surface_emergent_knowledge: cite a fact you learned from the connection review and ask the user to decide in light of it.\n\nAsk a question only when ALL of these hold:\n1. Index cannot resolve the decision autonomously from the evidence shown.\n2. The answer would materially change which people surface next.\n3. The same fact is NOT already in chatContext.statedFacts, NOT already asked in chatContext.openQuestions, and NOT already shared in chatContext.surfacedFindings.\n\nStandalone prompt rule. Every generated `prompt` must be understandable outside the conversation where it was created. Naturally include the original query, discovery pattern, connection pattern, or concrete learned fact in the question text itself. Do not rely on `title`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about. For example, prefer \"For your AI crypto decentralized deep-tech search, which area is most critical right now?\" over \"Which area is most critical right now?\"\n\nReferential closure. The prompt must resolve entirely on its own, with no dangling references. The reader sees ONLY the question text \u2014 never the people you reviewed, the events on their calendar, or this conversation. Do not use demonstratives or definite anaphora that point at things the reader cannot see: \"these builders\", \"those founders\", \"these researchers\", \"these conversations\", \"this lunch\", \"the speaker\". If you reference a person, name them. If you reference a group, restate the concrete shared attribute inside the question itself (\"founders working on decentralized identity\"), never \"these founders\". Never imply a list, set, or prior exchange the reader is not currently looking at.\n- Bad: \"What kind of collaboration are you looking for with these builders?\"\n- Good: \"You're meeting people building agent infrastructure \u2014 what kind of collaboration are you looking for?\"\n\nNo process narration. Never describe Index's own activity or internal state. Forbidden: \"the previous negotiation\", \"the negotiation stalled\", \"opportunities found so far\", \"my search\", \"the counterparty\", \"candidates reviewed\", restating why a match did or did not happen, or quoting words a counterparty did or did not use. Ask about the user's goal or intent directly, never about the matching pipeline.\n- Bad: \"All opportunities found so far are related to 'Edge Esmeralda'. Would you like to broaden the search?\"\n- Good: \"Do you want to focus on people at Edge Esmeralda, or also connect beyond it?\"\n\nCardinality. Default one question. Add a second only when a DIFFERENT strategy genuinely complements the first (e.g. one surface_emergent_knowledge + one refine_intent). Add a third only when there are \u22653 substantive people reviewed and three distinct strategies each unblock a real decision. Two questions of the same strategy are acceptable only if their decision domains differ (different titles). Avoid stacking three pulls (info-from-user); balance with pushes (info-to-user via reflective_summary / surface_emergent_knowledge).\n\nOrdering. Questions whose answer unblocks the most connection reviews come first; then highest-impact; then ambiguity-clarifying. Reviews that needed more detail or ran out of time signal under-specification \u2014 prioritize.\n\nUser-facing language. Every title, prompt, option label, and option description is shown directly to the user. Never mention raw protocol mechanics or internal labels such as \"agent\", \"patient\", \"peer\", \"suggestedRoles\", \"role distribution\", \"counterparty\", \"negotiation\", \"turn_cap\", \"timeout\", or \"candidate\". Use natural language instead: people, matches, connections, mutual collaboration, someone who can help, or someone seeking help.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2\u20134 options. Never add an \"Other\" option \u2014 clients provide a free-text fallback automatically. For surface_emergent_knowledge questions, anchor the prompt in the concrete cited fact (\"Multiple people flagged that\u2026\") and let the options represent decisions in light of that fact, not different versions of the fact.\n\nTitle rules. \u226412 chars. Noun of the decision domain. Discovery examples: \"Stage\", \"Timing\", \"Role\", \"Location\", \"Stack\", \"Budget\", \"Scope\", \"Format\".\n\nAnti-patterns \u2014 never do these.\n- Don't ask procedural confirmations (\"Should I look again?\").\n- Don't ask about hypothetical edge cases that didn't occur.\n- Don't ask about specific person identities; treat the provided person summary as the only allowed reference.\n- Don't repeat anything in chatContext.openQuestions.\n- Don't re-surface anything in chatContext.surfacedFindings.\n- Don't ask for facts in chatContext.statedFacts.\n\nOutput. Return at most 3 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the five values). If nothing is worth asking, return \"questions\": [].";
4
+ /**
5
+ * Pure builder: assembles the discovery-mode user message string from a
6
+ * structured input.
7
+ */
8
+ export declare function buildDiscoveryQuestionPrompt(input: DiscoveryQuestionInput): string;
9
+ //# sourceMappingURL=questioner.discovery.prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"questioner.discovery.prompt.d.ts","sourceRoot":"/","sources":["questioner/questioner.discovery.prompt.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,sBAAsB,EAAmB,MAAM,gDAAgD,CAAC;AAG9G,gEAAgE;AAChE,eAAO,MAAM,uBAAuB,yyLA0CgJ,CAAC;AAErL;;;GAGG;AACH,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,sBAAsB,GAAG,MAAM,CAmClF"}
@@ -1,5 +1,5 @@
1
- /** @deprecated Use QuestionerAgent and questioner presets instead. Will be removed in a future version. */
2
- export const SYSTEM_PROMPT = `You help write user-facing follow-up questions after Index has reviewed potential connections for a human. Your job: surface the minimum set of structured decision questions the human must answer to make the next discovery turn sharper, or improve their outlook on the intent.
1
+ /** System prompt for the QuestionerAgent's `discovery` mode. */
2
+ export const DISCOVERY_SYSTEM_PROMPT = `You help write user-facing follow-up questions after Index has reviewed potential connections for a human. Your job: surface the minimum set of structured decision questions the human must answer to make the next discovery turn sharper, or improve their outlook on the intent.
3
3
 
4
4
  You may pick from five strategies. Choose contextually; mix when multiple questions genuinely complement.
5
5
  - refine_intent: ask the user to sharpen or pivot their original signal.
@@ -43,11 +43,10 @@ Anti-patterns — never do these.
43
43
 
44
44
  Output. Return at most 3 entries in the "questions" array. Each entry must include a "strategy" field (one of the five values). If nothing is worth asking, return "questions": [].`;
45
45
  /**
46
- * @deprecated Use QuestionerAgent and questioner presets instead. Will be removed in a future version.
47
- *
48
- * Pure builder: assembles the user message string from a structured input.
46
+ * Pure builder: assembles the discovery-mode user message string from a
47
+ * structured input.
49
48
  */
50
- export function buildQuestionPrompt(input) {
49
+ export function buildDiscoveryQuestionPrompt(input) {
51
50
  const profileSummary = input.userContext?.trim() || "(no profile data)";
52
51
  const connectionReviewBlocks = renderConnectionReviewDigests(input.negotiationDigests);
53
52
  const chatContextBlock = input.chatContext
@@ -180,4 +179,4 @@ function renderDigest(d) {
180
179
  }
181
180
  return lines.length > 0 ? lines.join("\n") : "(digest is empty)";
182
181
  }
183
- //# sourceMappingURL=question.prompt.js.map
182
+ //# sourceMappingURL=questioner.discovery.prompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"questioner.discovery.prompt.js","sourceRoot":"/","sources":["questioner/questioner.discovery.prompt.ts"],"names":[],"mappings":"AAeA,gEAAgE;AAChE,MAAM,CAAC,MAAM,uBAAuB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oLA0C6I,CAAC;AAErL;;;GAGG;AACH,MAAM,UAAU,4BAA4B,CAAC,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I,CAAC,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC7B,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QAC5B,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,WAAW;YAAE,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IACxD,CAAC;IACD,IAAI,CAAC,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC/B,KAAK,CAAC,IAAI,CAAC,2CAA2C,CAAC,CAAC;QACxD,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,aAAa;YAAE,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAC1D,CAAC;IACD,IAAI,CAAC,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAClC,KAAK,CAAC,IAAI,CAAC,6BAA6B,CAAC,CAAC;QAC1C,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,gBAAgB;YAAE,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,IAAI,CAAC,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAClC,KAAK,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAC;QACjD,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,gBAAgB;YAAE,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC;AACnE,CAAC","sourcesContent":["/**\n * Discovery-mode prompt for the QuestionerAgent: the system prompt constant\n * and a pure string-building `buildDiscoveryQuestionPrompt` that assembles the\n * user message from a `DiscoveryQuestionInput`.\n *\n * Pure: no I/O, no LLM call. The QuestionerAgent (via the `discovery` preset\n * in `questioner.presets.ts`) orchestrates this module + an LLM client.\n *\n * Relocated from the removed `opportunity/question.prompt.ts` (IND-458); the\n * input types live in `shared/schemas/discovery-question.schema.ts`.\n */\nimport type { ChatContextDigest } from \"../shared/schemas/chat-context.schema.js\";\nimport type { DiscoveryQuestionInput, NegotiationRole } from \"../shared/schemas/discovery-question.schema.js\";\nimport type { DiscoveryNegotiationDigest } from \"../shared/schemas/negotiation-digest.schema.js\";\n\n/** System prompt for the QuestionerAgent's `discovery` mode. */\nexport const DISCOVERY_SYSTEM_PROMPT = `You help write user-facing follow-up questions after Index has reviewed potential connections for a human. Your job: surface the minimum set of structured decision questions the human must answer to make the next discovery turn sharper, or improve their outlook on the intent.\n\nYou may pick from five strategies. Choose contextually; mix when multiple questions genuinely complement.\n- refine_intent: ask the user to sharpen or pivot their original signal.\n- surface_missing_detail: ask for one concrete missing input (stage, location, timing, scope, …).\n- open_adjacent_thread: offer a pivot suggested by recurring connection signals.\n- reflective_summary: mirror what the connection review revealed and ask the user to decide.\n- surface_emergent_knowledge: cite a fact you learned from the connection review and ask the user to decide in light of it.\n\nAsk a question only when ALL of these hold:\n1. Index cannot resolve the decision autonomously from the evidence shown.\n2. The answer would materially change which people surface next.\n3. The same fact is NOT already in chatContext.statedFacts, NOT already asked in chatContext.openQuestions, and NOT already shared in chatContext.surfacedFindings.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the original query, discovery pattern, connection pattern, or concrete learned fact in the question text itself. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about. For example, prefer \"For your AI crypto decentralized deep-tech search, which area is most critical right now?\" over \"Which area is most critical right now?\"\n\nReferential closure. The prompt must resolve entirely on its own, with no dangling references. The reader sees ONLY the question text — never the people you reviewed, the events on their calendar, or this conversation. Do not use demonstratives or definite anaphora that point at things the reader cannot see: \"these builders\", \"those founders\", \"these researchers\", \"these conversations\", \"this lunch\", \"the speaker\". If you reference a person, name them. If you reference a group, restate the concrete shared attribute inside the question itself (\"founders working on decentralized identity\"), never \"these founders\". Never imply a list, set, or prior exchange the reader is not currently looking at.\n- Bad: \"What kind of collaboration are you looking for with these builders?\"\n- Good: \"You're meeting people building agent infrastructure — what kind of collaboration are you looking for?\"\n\nNo process narration. Never describe Index's own activity or internal state. Forbidden: \"the previous negotiation\", \"the negotiation stalled\", \"opportunities found so far\", \"my search\", \"the counterparty\", \"candidates reviewed\", restating why a match did or did not happen, or quoting words a counterparty did or did not use. Ask about the user's goal or intent directly, never about the matching pipeline.\n- Bad: \"All opportunities found so far are related to 'Edge Esmeralda'. Would you like to broaden the search?\"\n- Good: \"Do you want to focus on people at Edge Esmeralda, or also connect beyond it?\"\n\nCardinality. Default one question. Add a second only when a DIFFERENT strategy genuinely complements the first (e.g. one surface_emergent_knowledge + one refine_intent). Add a third only when there are ≥3 substantive people reviewed and three distinct strategies each unblock a real decision. Two questions of the same strategy are acceptable only if their decision domains differ (different titles). Avoid stacking three pulls (info-from-user); balance with pushes (info-to-user via reflective_summary / surface_emergent_knowledge).\n\nOrdering. Questions whose answer unblocks the most connection reviews come first; then highest-impact; then ambiguity-clarifying. Reviews that needed more detail or ran out of time signal under-specification — prioritize.\n\nUser-facing language. Every title, prompt, option label, and option description is shown directly to the user. Never mention raw protocol mechanics or internal labels such as \"agent\", \"patient\", \"peer\", \"suggestedRoles\", \"role distribution\", \"counterparty\", \"negotiation\", \"turn_cap\", \"timeout\", or \"candidate\". Use natural language instead: people, matches, connections, mutual collaboration, someone who can help, or someone seeking help.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically. For surface_emergent_knowledge questions, anchor the prompt in the concrete cited fact (\"Multiple people flagged that…\") and let the options represent decisions in light of that fact, not different versions of the fact.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Discovery examples: \"Stage\", \"Timing\", \"Role\", \"Location\", \"Stack\", \"Budget\", \"Scope\", \"Format\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I look again?\").\n- Don't ask about hypothetical edge cases that didn't occur.\n- Don't ask about specific person identities; treat the provided person summary as the only allowed reference.\n- Don't repeat anything in chatContext.openQuestions.\n- Don't re-surface anything in chatContext.surfacedFindings.\n- Don't ask for facts in chatContext.statedFacts.\n\nOutput. Return at most 3 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the five values). If nothing is worth asking, return \"questions\": [].`;\n\n/**\n * Pure builder: assembles the discovery-mode user message string from a\n * structured input.\n */\nexport function buildDiscoveryQuestionPrompt(input: DiscoveryQuestionInput): string {\n const profileSummary = input.userContext?.trim() || \"(no profile data)\";\n const connectionReviewBlocks = renderConnectionReviewDigests(input.negotiationDigests);\n const chatContextBlock = input.chatContext\n ? renderDigest(input.chatContext)\n : \"(no chat context available)\";\n const engagementPattern = renderEngagementPattern(input.summary.roleDistribution);\n\n return [\n \"## Seeker's query\",\n input.query,\n \"\",\n \"## Seeker profile\",\n profileSummary,\n \"\",\n \"## This discovery turn\",\n `- ${input.summary.totalCandidates} people reviewed`,\n `- ${input.summary.opportunitiesFound} promising connections found`,\n `- ${input.summary.noOpportunityCount} reviews did not find enough fit (${input.summary.timeoutCount} needed more detail or time)`,\n `- Engagement pattern: ${engagementPattern}`,\n \"\",\n \"## Connection review evidence (compact digests)\",\n connectionReviewBlocks,\n \"\",\n \"## What the user has already said in this session\",\n chatContextBlock,\n \"\",\n \"## Now\",\n input.now,\n \"\",\n \"## Your task\",\n \"Identify the minimum set of decision questions the seeker must answer to make\",\n \"the next discovery turn sharper. Apply every rule from your system prompt\",\n \"before outputting. Return an empty `questions` array if nothing is worth asking.\",\n ].join(\"\\n\");\n}\n\n/**\n * Render the negotiation-digest collection into compact one-liners. Each digest\n * is fixed-size (≤ ~400 chars after rendering), so the rendered block scales\n * linearly with candidate count: 10 candidates ≈ 4 KB, well within budget.\n */\nfunction renderConnectionReviewDigests(digests: DiscoveryNegotiationDigest[]): string {\n if (digests.length === 0) return \"(no connection reviews)\";\n return digests\n .map((d) => {\n const relationshipSignal = d.suggestedRoles\n ? [` Relationship signal: ${renderRelationshipSignal(d.suggestedRoles)}`]\n : [];\n return [\n `- Person: ${d.counterpartyHint}`,\n ` Community context: ${d.indexContext}`,\n ` Outcome: ${renderOutcome(d)}`,\n ...relationshipSignal,\n ` Take: ${d.keyTake}`,\n ].join(\"\\n\");\n })\n .join(\"\\n\\n\");\n}\n\nfunction renderEngagementPattern(dist: Partial<Record<NegotiationRole, number>>): string {\n const parts: string[] = [];\n if ((dist.peer ?? 0) > 0) {\n parts.push(`${dist.peer} mutual collaboration${dist.peer === 1 ? \"\" : \"s\"}`);\n }\n if ((dist.agent ?? 0) > 0) {\n parts.push(`${dist.agent} where the user could offer help or expertise`);\n }\n if ((dist.patient ?? 0) > 0) {\n parts.push(`${dist.patient} where the user seemed to be seeking help or expertise`);\n }\n return parts.length > 0 ? parts.join(\", \") : \"(no engagement pattern available)\";\n}\n\nfunction renderOutcome(digest: DiscoveryNegotiationDigest): string {\n const outcome = digest.outcomeRole === \"opportunity\"\n ? \"promising connection\"\n : \"not enough fit\";\n const reason = renderOutcomeReason(digest.outcomeReason);\n return reason ? `${outcome} (${reason})` : outcome;\n}\n\nfunction renderOutcomeReason(reason: DiscoveryNegotiationDigest[\"outcomeReason\"]): string {\n switch (reason) {\n case \"turn_cap\":\n return \"needed more detail\";\n case \"timeout\":\n return \"ran out of time\";\n case \"rejected\":\n return \"not enough mutual interest\";\n case \"stalled\":\n return \"stalled\";\n case \"screened_out\":\n return \"didn't look like a strong enough fit to pursue\";\n case null:\n return \"\";\n }\n}\n\nfunction renderRelationshipSignal(roles: NonNullable<DiscoveryNegotiationDigest[\"suggestedRoles\"]>): string {\n if (roles.ownUser === \"peer\" && roles.otherUser === \"peer\") return \"mutual collaboration\";\n if (roles.ownUser === \"agent\" && roles.otherUser === \"patient\") {\n return \"the user could offer help or expertise\";\n }\n if (roles.ownUser === \"patient\" && roles.otherUser === \"agent\") {\n return \"the user seemed to be seeking help or expertise\";\n }\n if (roles.ownUser === \"agent\") return \"the user could offer help or expertise\";\n if (roles.ownUser === \"patient\") return \"the user seemed to be seeking help or expertise\";\n return \"collaboration fit\";\n}\n\nfunction renderDigest(d: ChatContextDigest): string {\n const lines: string[] = [];\n if (d.statedFacts.length > 0) {\n lines.push(\"Stated facts:\");\n for (const f of d.statedFacts) lines.push(` - ${f}`);\n }\n if (d.openQuestions.length > 0) {\n lines.push(\"Open questions (assistant already asked):\");\n for (const q of d.openQuestions) lines.push(` - ${q}`);\n }\n if (d.rejectionReasons.length > 0) {\n lines.push(\"User pushback / rejections:\");\n for (const r of d.rejectionReasons) lines.push(` - ${r}`);\n }\n if (d.surfacedFindings.length > 0) {\n lines.push(\"Findings already surfaced to user:\");\n for (const f of d.surfacedFindings) lines.push(` - ${f}`);\n }\n return lines.length > 0 ? lines.join(\"\\n\") : \"(digest is empty)\";\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { SYSTEM_PROMPT as DISCOVERY_SYSTEM_PROMPT, buildQuestionPrompt as buildDiscoveryPrompt } from "../opportunity/question.prompt.js";
1
+ import { DISCOVERY_SYSTEM_PROMPT, buildDiscoveryQuestionPrompt } from "./questioner.discovery.prompt.js";
2
2
  import { QUD_UNDERSPECIFICATION_RULES } from "./questioner.qud.js";
3
3
  /**
4
4
  * Shared rule block appended to every questioner system prompt. Enforces that
@@ -381,7 +381,7 @@ function withQudMetadataRules(systemPrompt) {
381
381
  const presets = {
382
382
  discovery: {
383
383
  systemPrompt: withQudMetadataRules(DISCOVERY_SYSTEM_PROMPT),
384
- buildPrompt: (context) => buildDiscoveryPrompt(context),
384
+ buildPrompt: (context) => buildDiscoveryQuestionPrompt(context),
385
385
  },
386
386
  intent: {
387
387
  systemPrompt: withQudMetadataRules(INTENT_SYSTEM_PROMPT),
@@ -1 +1 @@
1
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B,CAAC,OAA6B,CAAC;KACzF;IACD,oBAAoB,EAAE;QACpB,YAAY,EAAE,oBAAoB,CAAC,kCAAkC,CAAC;QACtE,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,8BAA8B,CAAC,OAAqC,CAAC;KACzG;IACD,IAAI,EAAE;QACJ,YAAY,EAAE,oBAAoB,CAAC,kBAAkB,CAAC;QACtD,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,eAAe,CAAC,OAAsB,CAAC;KAC3E;CACF,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,IAAkB;IAC1C,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7B,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,2BAA2B,IAAI,0BAA0B,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Mode presets for the QuestionerAgent. Each preset provides a system prompt\n * and a buildPrompt function that assembles the user message from a typed\n * context object. Only the `discovery` preset ships in Slice 1; others throw\n * until their implementation slices land.\n */\nimport type { QuestionMode } from \"../shared/schemas/question.schema.js\";\nimport { SYSTEM_PROMPT as DISCOVERY_SYSTEM_PROMPT, buildQuestionPrompt as buildDiscoveryPrompt } from \"../opportunity/question.prompt.js\";\n\nimport { QUD_UNDERSPECIFICATION_RULES } from \"./questioner.qud.js\";\nimport type { ChatContext, IntentContext, NegotiationContext, NegotiationInflightContext, PostStallNegotiationContext, ProfileContext, UptakeNegotiationContext } from \"./questioner.types.js\";\n\n/**\n * Shared rule block appended to every questioner system prompt. Enforces that\n * the generated `prompt` resolves on its own — no demonstratives/anaphora that\n * point at people, events, or prior turns the reader cannot see — and never\n * narrates Index's own matching pipeline. Closes the referential-leak class\n * surfaced in digest audits (\"…with these builders?\", \"the previous\n * negotiation stalled because the counterparty didn't mention …\").\n */\nconst REFERENTIAL_CLOSURE_RULES = `Referential closure. The prompt must resolve entirely on its own, with no dangling references. The reader sees ONLY the question text — never the people you reviewed, the counterparty, the events on their calendar, or this conversation. Do not use demonstratives or definite anaphora that point at things the reader cannot see: \"these builders\", \"those founders\", \"these researchers\", \"these conversations\", \"this lunch\", \"the speaker\". If you reference a person, name them. If you reference a group, restate the concrete shared attribute inside the question itself (\"founders working on decentralized identity\"), never \"these founders\". Never imply a list, set, or prior exchange the reader is not currently looking at.\n- Bad: \"What kind of collaboration are you looking for with these builders?\"\n- Good: \"You're meeting people building agent infrastructure — what kind of collaboration are you looking for?\"\n\nNo process narration. Never describe Index's own activity or internal state. Forbidden: \"the previous negotiation\", \"the negotiation stalled\", \"opportunities found so far\", \"my search\", \"the counterparty\", \"candidates reviewed\", restating why a match did or did not happen, or quoting words a counterparty did or did not use. Ask about the user's goal or intent directly, never about the matching pipeline.\n- Bad: \"The previous negotiation stalled because the counterparty didn't mention 'matchmaking'. Should I broaden the search?\"\n- Good: \"Do you want to focus on dedicated matchmakers, or also people interested in relationships more broadly?\"`;\n\nexport interface QuestionerPreset {\n /** The LLM system prompt for this mode. */\n systemPrompt: string;\n /** Builds the user-message string from the mode-specific context. */\n buildPrompt: (context: unknown) => string;\n}\n\n/**\n * Renders the user-context block shared by every preset's user message from the\n * global user_context paragraph (the profile-replacing identity text).\n * @param userContext - The user's global context paragraph, if available.\n * @returns The trimmed context paragraph, or \"(no profile data)\" when empty.\n */\nfunction buildUserContextBlock(userContext?: string): string {\n const trimmed = userContext?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : \"(no profile data)\";\n}\n\n// ─── Intent preset ──────────────────────────────────────────────────────────\n\nconst INTENT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user has stated an intent — what they are looking for. Your job: surface the minimum set of structured questions that help the user sharpen that intent before the protocol runs discovery on their behalf.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- refine_intent: ask the user to sharpen or pivot the core signal (scope, scale, specificity, direction).\n- surface_missing_detail: ask for one concrete missing input that would change which candidates surface (stage, location, timing, budget, constraints, format, …).\n\nAsk a question only when ALL of these hold:\n1. The agent cannot infer the answer from the intent text or user profile already shown.\n2. The answer would materially change which candidates surface.\n3. The question targets a different decision domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the source intent/topic in the question text itself, using concise plain language from the intent or summary. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"What kind of collaboration are you looking for?\"\n- Good: \"For your decentralized identity protocol-design search, what kind of collaboration are you looking for?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. Never ask two questions of the same strategy unless their decision domains differ (different titles).\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Stage\", \"Timing\", \"Location\", \"Scope\", \"Budget\", \"Format\", \"Skills\", \"Collab\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I start searching?\").\n- Don't ask about hypothetical edge cases not implied by the intent.\n- Don't re-ask for facts already visible in the user profile.\n- Don't ask vague introspective questions (\"What do you really want?\").\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the intent is already specific enough, return \"questions\": [].`;\n\n/**\n * Build the user message for the intent preset from an IntentContext.\n * @param ctx - The intent context.\n * @returns The assembled user message string.\n */\nfunction buildIntentPrompt(ctx: IntentContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const summaryBlock = ctx.summary ? ctx.summary : \"(no summary available)\";\n\n return [\n \"## Intent\",\n ctx.payload,\n \"\",\n \"## Summary\",\n summaryBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Identify the minimum set of questions the user must answer to sharpen this intent.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the intent is already specific enough.\",\n ].join(\"\\n\");\n}\n\n// ─── Profile preset ─────────────────────────────────────────────────────────\n\nconst PROFILE_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user has a profile that is incomplete. Your job: surface the minimum set of structured questions that fill the identified gaps — asking about location, skills, interests, current work, or goals — so the protocol can run better discovery on their behalf.\n\nThe user may already have premises — atomic self-descriptions they have stated. These cover specific profile domains. Do not ask about domains already addressed by existing premises. Focus only on gaps not covered by any premise.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing piece of profile data (location, current role, skills, interests, goals, availability, …).\n- refine_intent: ask the user to clarify or sharpen an existing profile signal so candidates can be ranked more accurately.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the profile data shown.\n2. The answer is not already covered by an existing premise listed below the profile.\n3. The answer would meaningfully change which opportunities surface for this user.\n4. The question targets a different profile domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the profile signal or gap being clarified in the question text itself, using concise plain language from the current profile, existing premises, or identified gaps. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"What kind of role are you looking for?\"\n- Good: \"To improve matches from your founder/operator profile, what kind of role are you looking for?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. Never ask two questions of the same strategy unless their decision domains differ.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the profile domain. Examples: \"Location\", \"Role\", \"Skills\", \"Goals\", \"Interests\", \"Availability\", \"Stage\".\n\nAnti-patterns — never do these.\n- Don't ask about fields already filled in the profile.\n- Don't ask about information already captured in an existing premise.\n- Don't ask procedural confirmations (\"Should I update your profile?\").\n- Don't ask vague introspective questions (\"Who are you really?\").\n- Don't re-ask for facts visible anywhere in the profile data or premises shown.\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the profile is already complete enough for discovery, return \"questions\": [].`;\n\n/**\n * Build the user message for the profile preset from a ProfileContext.\n * @param ctx - The profile context including current profile data and identified gaps.\n * @returns The assembled user message string.\n */\nfunction buildProfilePrompt(ctx: ProfileContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const premisesBlock =\n ctx.existingPremises && ctx.existingPremises.length > 0\n ? ctx.existingPremises.map((p, i) => `${i + 1}. ${p}`).join(\"\\n\")\n : \"(none)\";\n\n const gapsBlock = ctx.gaps.length > 0 ? ctx.gaps.join(\", \") : \"(none identified)\";\n\n const parts: string[] = [\n \"## Current profile\",\n profileBlock,\n \"\",\n \"## Existing premises\",\n premisesBlock,\n \"\",\n \"## Identified gaps\",\n gapsBlock,\n \"\",\n ];\n\n parts.push(\n \"## Your task\",\n \"Generate the minimum set of questions needed to fill the identified gaps.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the profile is already complete enough.\",\n );\n\n return parts.join(\"\\n\");\n}\n\n// ─── Negotiation preset ──────────────────────────────────────────────────────\n\nconst NEGOTIATION_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. You generate negotiation-mode questions for one of two purposes described in the user message.\n\nPOST-STALL purpose. A negotiation between this user and another person ended without a clear outcome — either the turn budget was exhausted, the session timed out, or conversation stalled. Surface the minimum set of structured questions that help the user provide the missing signal needed to unblock or refine the next discovery attempt.\n\nUPTAKE purpose. The user is considering accepting a proposed connection, but one preparatory condition about the other person's practical ability, resources, availability, or authority to carry out the proposed activity needs clarification before commitment. Generate exactly ONE neutral question that lets the user decide whether they understand that condition well enough to proceed. Ask about the concrete activity and the other person's stated attributes; do not accuse, challenge credibility, or presume incapability. Never reveal a numeric authority score, threshold, felicity label, evaluator judgment, or any internal matching/verification mechanics. Do not ask whether the user wants to accept; clarify the preparatory condition only.\n\nYou may pick from three strategies. Choose contextually; mix only when each question is genuinely distinct.\n- refine_intent: help the user sharpen their underlying signal based on what the negotiation revealed (scope, scale, priority, direction).\n- surface_missing_detail: ask for one concrete piece of information that was absent and would have moved the negotiation forward (timeline, budget, format, constraints, decision criteria, …).\n- reflective_summary: mirror the key takeaway from the negotiation and ask the user to confirm, correct, or decide — useful when the conversation revealed partial signal worth locking in.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the negotiation context or user profile shown.\n2. The answer would materially change how the next attempt surfaces or engages candidates.\n3. The question targets a different decision domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the user's underlying goal or topic and the relevant community in the question text itself, in plain language drawn from their intent or profile — NOT the mechanics of the match attempt. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"Which role is a better fit for your immediate needs?\"\n- Good: \"For your search for AI infrastructure collaborators in the AI founders community, what kind of working relationship fits your immediate needs?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. For POST-STALL, default one question and add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. For UPTAKE, return exactly one question — never zero and never more than one.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Scope\", \"Timeline\", \"Budget\", \"Priority\", \"Format\", \"Stance\", \"Criteria\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I try again?\").\n- Don't re-ask for facts already visible in the user profile.\n- Don't ask vague introspective questions (\"What do you really want?\").\n- Don't ask about hypothetical edge cases not implied by the negotiation context.\n\nOutput. For POST-STALL, return at most 2 entries and return \"questions\": [] if the context already contains enough signal to proceed. For UPTAKE, return exactly 1 entry. Every entry must include a \"strategy\" field (one of the three values above). QUD metadata is orthogonal to uptake purpose: an uptake question is usually not an underspecification repair, so set \\`underspecificationType\\` to null unless the question genuinely repairs a missing constituent, missing constraint, or open alternative set.`;\n\n/**\n * Build the user message for the negotiation preset from a NegotiationContext.\n * @param ctx - The negotiation context including counterparty hint, stall reason, and key takeaway.\n * @returns The assembled user message string.\n */\nfunction buildPostStallNegotiationPrompt(ctx: PostStallNegotiationContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n return [\n \"## Purpose\",\n \"POST-STALL\",\n \"\",\n \"## Negotiation context\",\n `Community: ${ctx.indexContext}`,\n `Counterparty: ${ctx.counterpartyHint}`,\n `Stall reason: ${ctx.outcomeReason}`,\n \"\",\n \"## Key takeaway\",\n ctx.keyTake,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Identify the minimum set of questions the user must answer to unblock the next discovery attempt.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the context already contains enough signal to proceed.\",\n ].join(\"\\n\");\n}\n\nfunction buildUptakeNegotiationPrompt(ctx: UptakeNegotiationContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n const evidence = ctx.preparatoryEvidence?.trim() || \"(no additional public evidence provided)\";\n\n return [\n \"## Purpose\",\n \"UPTAKE — preparatory-condition clarification before acceptance\",\n \"\",\n \"## Proposed activity\",\n ctx.proposedActivity,\n \"\",\n \"## Other person\",\n ctx.counterpartyHint,\n \"\",\n \"## Community\",\n ctx.indexContext,\n \"\",\n \"## Public preparatory evidence\",\n evidence,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Generate exactly one neutral, referentially closed question about whether the other person can practically carry out the proposed activity.\",\n \"Do not expose scores, thresholds, labels, or internal mechanics. Do not ask for acceptance itself.\",\n \"Set `underspecificationType` to null unless this is genuinely a QUD underspecification repair.\",\n ].join(\"\\n\");\n}\n\nfunction buildNegotiationPrompt(ctx: NegotiationContext): string {\n return ctx.purpose === \"uptake\"\n ? buildUptakeNegotiationPrompt(ctx)\n : buildPostStallNegotiationPrompt(ctx);\n}\n\n// ─── Chat preset ─────────────────────────────────────────────────────────\n\nconst NEGOTIATION_INFLIGHT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user's own negotiator agent is MID-NEGOTIATION on their behalf and has paused: before continuing, it needs a decision or missing input from its client — most often permission to disclose a specific piece of information to the other side. The negotiation is WAITING until the user answers. Your job: turn the negotiator's stated need (and its draft question, when provided) into the minimum set of crisp, structured decision questions.\n\nBias toward disclosure gating. The most common question shape is \"may I share X with this person?\" — an enable/disable decision about revealing specific information. Phrase these as a clear yes/no choice: the first option authorizes sharing, the second declines. State in each option's description what the negotiator will DO next (share and continue, or continue without revealing it). When the need is a missing fact rather than a permission, ask for that concrete input instead.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing input the negotiator needs to proceed (a fact, constraint, preference, or bound the client never stated).\n- reflective_summary: put a disclosure or stance decision in front of the client to confirm or decline — the enable/disable gate described above.\n\nHonor the negotiator's intent. When a draft question is provided, treat it as the source of truth for WHAT to ask — improve wording, tighten options, add consequence-focused descriptions. Do not invent questions about topics the negotiator did not raise. When no draft is provided, derive the question strictly from the disclosure subject.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. The user may see this question hours later in an inbox, away from any negotiation view. Naturally include the disclosure subject and a concrete description of the other person (drawn from the counterparty hint — their attributes, e.g. \"a Berlin-based AI-infrastructure founder\") in the question text itself. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"Can I share your budget with them?\"\n- Good: \"May I share your budget range with a Berlin-based AI-infrastructure founder you're being matched with?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nException — describing the other side. Unlike other surfaces, this question is ABOUT a live counterparty, so you must reference them — do it by restating their concrete attributes from the counterparty hint (\"a fintech CTO exploring agent tooling\"), never as \"the counterparty\", \"them\", or \"this person\" without an attribute anchor in the same sentence, and never by implying a list or pipeline.\n\nCardinality. Default one question. Add a second ONLY when the negotiator's need genuinely spans two distinct decisions (e.g. one disclosure gate plus one missing fact). Never pad.\n\nOption construction. Each option must represent a meaningfully different outcome. For disclosure gates: authorize first, decline second; suffix the safer or more common path with \" (Recommended)\" and list it first when one clearly is. The description states the CONSEQUENCE for the negotiation — what the negotiator does next. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically, which also lets the user add nuance (\"share the range but not the exact figure\").\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Disclosure\", \"Budget\", \"Timing\", \"Intro\", \"Scope\", \"Contact\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I keep negotiating?\").\n- Don't re-ask for facts already visible in the user profile.\n- Don't broaden beyond the negotiator's stated disclosure subject or draft.\n- Don't reveal the counterparty's identity — attributes only.\n- Don't ask vague introspective questions.\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the profile or context shown already answers the negotiator's need, return \"questions\": [].`;\n\n/**\n * Build the user message for the negotiation-inflight preset from a NegotiationInflightContext.\n * @param ctx - The inflight context: disclosure subject, counterparty hint, optional draft, community, user context.\n * @returns The assembled user message string.\n */\nfunction buildNegotiationInflightPrompt(ctx: NegotiationInflightContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const draftBlock = ctx.draftQuestion?.trim()\n ? ctx.draftQuestion.trim()\n : \"(none — derive the question from the disclosure subject)\";\n\n return [\n \"## Negotiation context\",\n `Community: ${ctx.indexContext}`,\n `Counterparty: ${ctx.counterpartyHint}`,\n \"\",\n \"## What the negotiator needs from its client\",\n ctx.disclosureSubject,\n \"\",\n \"## Draft question proposed by the negotiator\",\n draftBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Produce the minimum set of structured questions that get the negotiator the permission or input it needs to continue.\",\n \"Honor the draft when provided; refine its wording and options rather than replacing its topic.\",\n \"Apply every rule from your system prompt before outputting.\",\n ].join(\"\\n\");\n}\n\nconst CHAT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The protocol's chat orchestrator is mid-conversation with the user and has decided it needs a decision or missing input from them before it can continue. The conversation is PAUSED until the user answers. Your job: turn the orchestrator's stated need (and any draft questions it proposed) into the minimum set of crisp, structured decision questions.\n\nUnlike other question surfaces, these questions render INLINE in the active conversation, immediately after the assistant's last message — the user has full conversational context. Still keep each prompt self-contained enough to make sense on its own line.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing input the orchestrator needs to proceed (scope, timing, budget, format, preference, constraint, …).\n- refine_intent: ask the user to choose a direction when the orchestrator faces meaningfully different paths forward.\n\nHonor the orchestrator's intent. When draft questions are provided, treat them as the source of truth for WHAT to ask — improve wording, tighten options, add consequence-focused descriptions, and drop redundant drafts. Do not invent questions about topics the orchestrator did not raise. When no drafts are provided, derive questions strictly from the stated purpose.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the conversation excerpt or user profile shown.\n2. The answer materially changes what the orchestrator does next.\n3. The question targets a different decision domain from any other question in this batch.\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Emit a second or third ONLY when the orchestrator's purpose or drafts genuinely require separate decisions in distinct domains. Never pad.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option for what happens next in the conversation, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Direction\", \"Scope\", \"Timing\", \"Budget\", \"Format\", \"Priority\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I continue?\", \"Is that OK?\").\n- Don't re-ask for facts visible in the conversation excerpt or user profile.\n- Don't broaden beyond the orchestrator's stated purpose.\n- Don't ask vague introspective questions.\n\nOutput. Return at most 3 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the purpose is already answerable from the context shown, return \"questions\": [].`;\n\n/**\n * Build the user message for the chat preset from a ChatContext.\n * @param ctx - The chat context: orchestrator purpose, optional drafts, conversation excerpt, user context.\n * @returns The assembled user message string.\n */\nfunction buildChatPrompt(ctx: ChatContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const draftsBlock =\n ctx.draftQuestions && ctx.draftQuestions.length > 0\n ? ctx.draftQuestions\n .map((d, i) => {\n const opts = d.options && d.options.length > 0 ? ` [options: ${d.options.join(\" | \")}]` : \"\";\n const multi = d.multiSelect ? \" [multi-select]\" : \"\";\n return `${i + 1}. ${d.prompt}${opts}${multi}`;\n })\n .join(\"\\n\")\n : \"(none — derive questions from the purpose)\";\n\n const excerptBlock = ctx.conversationExcerpt?.trim()\n ? ctx.conversationExcerpt.trim()\n : \"(not available)\";\n\n return [\n \"## What the orchestrator needs to learn\",\n ctx.purpose,\n \"\",\n \"## Draft questions proposed by the orchestrator\",\n draftsBlock,\n \"\",\n \"## Recent conversation excerpt\",\n excerptBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Produce the minimum set of structured questions that get the orchestrator the decision or input it needs.\",\n \"Honor the drafts when provided; refine their wording and options rather than replacing their topics.\",\n \"Apply every rule from your system prompt before outputting.\",\n ].join(\"\\n\");\n}\n\n/**\n * pool_discovery has NO preset by design: those questions are synthesized\n * deterministically from mined discriminators (see\n * `opportunity/discriminator/discriminator.question.ts`) and never reach the\n * QuestionerAgent. `getPreset(\"pool_discovery\")` therefore throws — the\n * QuestionerQueue branches on the mode before invoking the agent.\n */\nfunction withQudMetadataRules(systemPrompt: string): string {\n return `${systemPrompt}\\n\\n${QUD_UNDERSPECIFICATION_RULES}`;\n}\n\nconst presets: Partial<Record<QuestionMode, QuestionerPreset>> = {\n discovery: {\n systemPrompt: withQudMetadataRules(DISCOVERY_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) =>\n buildDiscoveryPrompt(context as Parameters<typeof buildDiscoveryPrompt>[0]),\n },\n intent: {\n systemPrompt: withQudMetadataRules(INTENT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildIntentPrompt(context as IntentContext),\n },\n enrichment: {\n systemPrompt: withQudMetadataRules(PROFILE_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildProfilePrompt(context as ProfileContext),\n },\n negotiation: {\n systemPrompt: withQudMetadataRules(NEGOTIATION_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildNegotiationPrompt(context as NegotiationContext),\n },\n negotiation_inflight: {\n systemPrompt: withQudMetadataRules(NEGOTIATION_INFLIGHT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildNegotiationInflightPrompt(context as NegotiationInflightContext),\n },\n chat: {\n systemPrompt: withQudMetadataRules(CHAT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildChatPrompt(context as ChatContext),\n },\n};\n\n/**\n * Retrieve the preset for the given mode.\n * @param mode - The question mode to look up.\n * @returns The matching preset with systemPrompt and buildPrompt.\n * @throws Error if the mode's preset is not yet implemented.\n */\nexport function getPreset(mode: QuestionMode): QuestionerPreset {\n const preset = presets[mode];\n if (!preset) {\n throw new Error(`QuestionerAgent preset \"${mode}\" is not implemented yet`);\n }\n return preset;\n}\n"]}
1
+ {"version":3,"file":"questioner.presets.js","sourceRoot":"/","sources":["questioner/questioner.presets.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,uBAAuB,EAAE,4BAA4B,EAAE,MAAM,kCAAkC,CAAC;AAEzG,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CA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oB,CAAC,kBAAkB,CAAC;QACtD,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,eAAe,CAAC,OAAsB,CAAC;KAC3E;CACF,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,IAAkB;IAC1C,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7B,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,2BAA2B,IAAI,0BAA0B,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Mode presets for the QuestionerAgent. Each preset provides a system prompt\n * and a buildPrompt function that assembles the user message from a typed\n * context object. Only the `discovery` preset ships in Slice 1; others throw\n * until their implementation slices land.\n */\nimport type { QuestionMode } from \"../shared/schemas/question.schema.js\";\nimport { DISCOVERY_SYSTEM_PROMPT, buildDiscoveryQuestionPrompt } from \"./questioner.discovery.prompt.js\";\n\nimport { QUD_UNDERSPECIFICATION_RULES } from \"./questioner.qud.js\";\nimport type { ChatContext, IntentContext, NegotiationContext, NegotiationInflightContext, PostStallNegotiationContext, ProfileContext, UptakeNegotiationContext } from \"./questioner.types.js\";\n\n/**\n * Shared rule block appended to every questioner system prompt. Enforces that\n * the generated `prompt` resolves on its own — no demonstratives/anaphora that\n * point at people, events, or prior turns the reader cannot see — and never\n * narrates Index's own matching pipeline. Closes the referential-leak class\n * surfaced in digest audits (\"…with these builders?\", \"the previous\n * negotiation stalled because the counterparty didn't mention …\").\n */\nconst REFERENTIAL_CLOSURE_RULES = `Referential closure. The prompt must resolve entirely on its own, with no dangling references. The reader sees ONLY the question text — never the people you reviewed, the counterparty, the events on their calendar, or this conversation. Do not use demonstratives or definite anaphora that point at things the reader cannot see: \"these builders\", \"those founders\", \"these researchers\", \"these conversations\", \"this lunch\", \"the speaker\". If you reference a person, name them. If you reference a group, restate the concrete shared attribute inside the question itself (\"founders working on decentralized identity\"), never \"these founders\". Never imply a list, set, or prior exchange the reader is not currently looking at.\n- Bad: \"What kind of collaboration are you looking for with these builders?\"\n- Good: \"You're meeting people building agent infrastructure — what kind of collaboration are you looking for?\"\n\nNo process narration. Never describe Index's own activity or internal state. Forbidden: \"the previous negotiation\", \"the negotiation stalled\", \"opportunities found so far\", \"my search\", \"the counterparty\", \"candidates reviewed\", restating why a match did or did not happen, or quoting words a counterparty did or did not use. Ask about the user's goal or intent directly, never about the matching pipeline.\n- Bad: \"The previous negotiation stalled because the counterparty didn't mention 'matchmaking'. Should I broaden the search?\"\n- Good: \"Do you want to focus on dedicated matchmakers, or also people interested in relationships more broadly?\"`;\n\nexport interface QuestionerPreset {\n /** The LLM system prompt for this mode. */\n systemPrompt: string;\n /** Builds the user-message string from the mode-specific context. */\n buildPrompt: (context: unknown) => string;\n}\n\n/**\n * Renders the user-context block shared by every preset's user message from the\n * global user_context paragraph (the profile-replacing identity text).\n * @param userContext - The user's global context paragraph, if available.\n * @returns The trimmed context paragraph, or \"(no profile data)\" when empty.\n */\nfunction buildUserContextBlock(userContext?: string): string {\n const trimmed = userContext?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : \"(no profile data)\";\n}\n\n// ─── Intent preset ──────────────────────────────────────────────────────────\n\nconst INTENT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user has stated an intent — what they are looking for. Your job: surface the minimum set of structured questions that help the user sharpen that intent before the protocol runs discovery on their behalf.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- refine_intent: ask the user to sharpen or pivot the core signal (scope, scale, specificity, direction).\n- surface_missing_detail: ask for one concrete missing input that would change which candidates surface (stage, location, timing, budget, constraints, format, …).\n\nAsk a question only when ALL of these hold:\n1. The agent cannot infer the answer from the intent text or user profile already shown.\n2. The answer would materially change which candidates surface.\n3. The question targets a different decision domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the source intent/topic in the question text itself, using concise plain language from the intent or summary. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"What kind of collaboration are you looking for?\"\n- Good: \"For your decentralized identity protocol-design search, what kind of collaboration are you looking for?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. Never ask two questions of the same strategy unless their decision domains differ (different titles).\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Stage\", \"Timing\", \"Location\", \"Scope\", \"Budget\", \"Format\", \"Skills\", \"Collab\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I start searching?\").\n- Don't ask about hypothetical edge cases not implied by the intent.\n- Don't re-ask for facts already visible in the user profile.\n- Don't ask vague introspective questions (\"What do you really want?\").\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the intent is already specific enough, return \"questions\": [].`;\n\n/**\n * Build the user message for the intent preset from an IntentContext.\n * @param ctx - The intent context.\n * @returns The assembled user message string.\n */\nfunction buildIntentPrompt(ctx: IntentContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const summaryBlock = ctx.summary ? ctx.summary : \"(no summary available)\";\n\n return [\n \"## Intent\",\n ctx.payload,\n \"\",\n \"## Summary\",\n summaryBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Identify the minimum set of questions the user must answer to sharpen this intent.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the intent is already specific enough.\",\n ].join(\"\\n\");\n}\n\n// ─── Profile preset ─────────────────────────────────────────────────────────\n\nconst PROFILE_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user has a profile that is incomplete. Your job: surface the minimum set of structured questions that fill the identified gaps — asking about location, skills, interests, current work, or goals — so the protocol can run better discovery on their behalf.\n\nThe user may already have premises — atomic self-descriptions they have stated. These cover specific profile domains. Do not ask about domains already addressed by existing premises. Focus only on gaps not covered by any premise.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing piece of profile data (location, current role, skills, interests, goals, availability, …).\n- refine_intent: ask the user to clarify or sharpen an existing profile signal so candidates can be ranked more accurately.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the profile data shown.\n2. The answer is not already covered by an existing premise listed below the profile.\n3. The answer would meaningfully change which opportunities surface for this user.\n4. The question targets a different profile domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the profile signal or gap being clarified in the question text itself, using concise plain language from the current profile, existing premises, or identified gaps. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"What kind of role are you looking for?\"\n- Good: \"To improve matches from your founder/operator profile, what kind of role are you looking for?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. Never ask two questions of the same strategy unless their decision domains differ.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the profile domain. Examples: \"Location\", \"Role\", \"Skills\", \"Goals\", \"Interests\", \"Availability\", \"Stage\".\n\nAnti-patterns — never do these.\n- Don't ask about fields already filled in the profile.\n- Don't ask about information already captured in an existing premise.\n- Don't ask procedural confirmations (\"Should I update your profile?\").\n- Don't ask vague introspective questions (\"Who are you really?\").\n- Don't re-ask for facts visible anywhere in the profile data or premises shown.\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the profile is already complete enough for discovery, return \"questions\": [].`;\n\n/**\n * Build the user message for the profile preset from a ProfileContext.\n * @param ctx - The profile context including current profile data and identified gaps.\n * @returns The assembled user message string.\n */\nfunction buildProfilePrompt(ctx: ProfileContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const premisesBlock =\n ctx.existingPremises && ctx.existingPremises.length > 0\n ? ctx.existingPremises.map((p, i) => `${i + 1}. ${p}`).join(\"\\n\")\n : \"(none)\";\n\n const gapsBlock = ctx.gaps.length > 0 ? ctx.gaps.join(\", \") : \"(none identified)\";\n\n const parts: string[] = [\n \"## Current profile\",\n profileBlock,\n \"\",\n \"## Existing premises\",\n premisesBlock,\n \"\",\n \"## Identified gaps\",\n gapsBlock,\n \"\",\n ];\n\n parts.push(\n \"## Your task\",\n \"Generate the minimum set of questions needed to fill the identified gaps.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the profile is already complete enough.\",\n );\n\n return parts.join(\"\\n\");\n}\n\n// ─── Negotiation preset ──────────────────────────────────────────────────────\n\nconst NEGOTIATION_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. You generate negotiation-mode questions for one of two purposes described in the user message.\n\nPOST-STALL purpose. A negotiation between this user and another person ended without a clear outcome — either the turn budget was exhausted, the session timed out, or conversation stalled. Surface the minimum set of structured questions that help the user provide the missing signal needed to unblock or refine the next discovery attempt.\n\nUPTAKE purpose. The user is considering accepting a proposed connection, but one preparatory condition about the other person's practical ability, resources, availability, or authority to carry out the proposed activity needs clarification before commitment. Generate exactly ONE neutral question that lets the user decide whether they understand that condition well enough to proceed. Ask about the concrete activity and the other person's stated attributes; do not accuse, challenge credibility, or presume incapability. Never reveal a numeric authority score, threshold, felicity label, evaluator judgment, or any internal matching/verification mechanics. Do not ask whether the user wants to accept; clarify the preparatory condition only.\n\nYou may pick from three strategies. Choose contextually; mix only when each question is genuinely distinct.\n- refine_intent: help the user sharpen their underlying signal based on what the negotiation revealed (scope, scale, priority, direction).\n- surface_missing_detail: ask for one concrete piece of information that was absent and would have moved the negotiation forward (timeline, budget, format, constraints, decision criteria, …).\n- reflective_summary: mirror the key takeaway from the negotiation and ask the user to confirm, correct, or decide — useful when the conversation revealed partial signal worth locking in.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the negotiation context or user profile shown.\n2. The answer would materially change how the next attempt surfaces or engages candidates.\n3. The question targets a different decision domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the user's underlying goal or topic and the relevant community in the question text itself, in plain language drawn from their intent or profile — NOT the mechanics of the match attempt. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"Which role is a better fit for your immediate needs?\"\n- Good: \"For your search for AI infrastructure collaborators in the AI founders community, what kind of working relationship fits your immediate needs?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. For POST-STALL, default one question and add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. For UPTAKE, return exactly one question — never zero and never more than one.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Scope\", \"Timeline\", \"Budget\", \"Priority\", \"Format\", \"Stance\", \"Criteria\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I try again?\").\n- Don't re-ask for facts already visible in the user profile.\n- Don't ask vague introspective questions (\"What do you really want?\").\n- Don't ask about hypothetical edge cases not implied by the negotiation context.\n\nOutput. For POST-STALL, return at most 2 entries and return \"questions\": [] if the context already contains enough signal to proceed. For UPTAKE, return exactly 1 entry. Every entry must include a \"strategy\" field (one of the three values above). QUD metadata is orthogonal to uptake purpose: an uptake question is usually not an underspecification repair, so set \\`underspecificationType\\` to null unless the question genuinely repairs a missing constituent, missing constraint, or open alternative set.`;\n\n/**\n * Build the user message for the negotiation preset from a NegotiationContext.\n * @param ctx - The negotiation context including counterparty hint, stall reason, and key takeaway.\n * @returns The assembled user message string.\n */\nfunction buildPostStallNegotiationPrompt(ctx: PostStallNegotiationContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n return [\n \"## Purpose\",\n \"POST-STALL\",\n \"\",\n \"## Negotiation context\",\n `Community: ${ctx.indexContext}`,\n `Counterparty: ${ctx.counterpartyHint}`,\n `Stall reason: ${ctx.outcomeReason}`,\n \"\",\n \"## Key takeaway\",\n ctx.keyTake,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Identify the minimum set of questions the user must answer to unblock the next discovery attempt.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the context already contains enough signal to proceed.\",\n ].join(\"\\n\");\n}\n\nfunction buildUptakeNegotiationPrompt(ctx: UptakeNegotiationContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n const evidence = ctx.preparatoryEvidence?.trim() || \"(no additional public evidence provided)\";\n\n return [\n \"## Purpose\",\n \"UPTAKE — preparatory-condition clarification before acceptance\",\n \"\",\n \"## Proposed activity\",\n ctx.proposedActivity,\n \"\",\n \"## Other person\",\n ctx.counterpartyHint,\n \"\",\n \"## Community\",\n ctx.indexContext,\n \"\",\n \"## Public preparatory evidence\",\n evidence,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Generate exactly one neutral, referentially closed question about whether the other person can practically carry out the proposed activity.\",\n \"Do not expose scores, thresholds, labels, or internal mechanics. Do not ask for acceptance itself.\",\n \"Set `underspecificationType` to null unless this is genuinely a QUD underspecification repair.\",\n ].join(\"\\n\");\n}\n\nfunction buildNegotiationPrompt(ctx: NegotiationContext): string {\n return ctx.purpose === \"uptake\"\n ? buildUptakeNegotiationPrompt(ctx)\n : buildPostStallNegotiationPrompt(ctx);\n}\n\n// ─── Chat preset ─────────────────────────────────────────────────────────\n\nconst NEGOTIATION_INFLIGHT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user's own negotiator agent is MID-NEGOTIATION on their behalf and has paused: before continuing, it needs a decision or missing input from its client — most often permission to disclose a specific piece of information to the other side. The negotiation is WAITING until the user answers. Your job: turn the negotiator's stated need (and its draft question, when provided) into the minimum set of crisp, structured decision questions.\n\nBias toward disclosure gating. The most common question shape is \"may I share X with this person?\" — an enable/disable decision about revealing specific information. Phrase these as a clear yes/no choice: the first option authorizes sharing, the second declines. State in each option's description what the negotiator will DO next (share and continue, or continue without revealing it). When the need is a missing fact rather than a permission, ask for that concrete input instead.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing input the negotiator needs to proceed (a fact, constraint, preference, or bound the client never stated).\n- reflective_summary: put a disclosure or stance decision in front of the client to confirm or decline — the enable/disable gate described above.\n\nHonor the negotiator's intent. When a draft question is provided, treat it as the source of truth for WHAT to ask — improve wording, tighten options, add consequence-focused descriptions. Do not invent questions about topics the negotiator did not raise. When no draft is provided, derive the question strictly from the disclosure subject.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. The user may see this question hours later in an inbox, away from any negotiation view. Naturally include the disclosure subject and a concrete description of the other person (drawn from the counterparty hint — their attributes, e.g. \"a Berlin-based AI-infrastructure founder\") in the question text itself. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"Can I share your budget with them?\"\n- Good: \"May I share your budget range with a Berlin-based AI-infrastructure founder you're being matched with?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nException — describing the other side. Unlike other surfaces, this question is ABOUT a live counterparty, so you must reference them — do it by restating their concrete attributes from the counterparty hint (\"a fintech CTO exploring agent tooling\"), never as \"the counterparty\", \"them\", or \"this person\" without an attribute anchor in the same sentence, and never by implying a list or pipeline.\n\nCardinality. Default one question. Add a second ONLY when the negotiator's need genuinely spans two distinct decisions (e.g. one disclosure gate plus one missing fact). Never pad.\n\nOption construction. Each option must represent a meaningfully different outcome. For disclosure gates: authorize first, decline second; suffix the safer or more common path with \" (Recommended)\" and list it first when one clearly is. The description states the CONSEQUENCE for the negotiation — what the negotiator does next. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically, which also lets the user add nuance (\"share the range but not the exact figure\").\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Disclosure\", \"Budget\", \"Timing\", \"Intro\", \"Scope\", \"Contact\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I keep negotiating?\").\n- Don't re-ask for facts already visible in the user profile.\n- Don't broaden beyond the negotiator's stated disclosure subject or draft.\n- Don't reveal the counterparty's identity — attributes only.\n- Don't ask vague introspective questions.\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the profile or context shown already answers the negotiator's need, return \"questions\": [].`;\n\n/**\n * Build the user message for the negotiation-inflight preset from a NegotiationInflightContext.\n * @param ctx - The inflight context: disclosure subject, counterparty hint, optional draft, community, user context.\n * @returns The assembled user message string.\n */\nfunction buildNegotiationInflightPrompt(ctx: NegotiationInflightContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const draftBlock = ctx.draftQuestion?.trim()\n ? ctx.draftQuestion.trim()\n : \"(none — derive the question from the disclosure subject)\";\n\n return [\n \"## Negotiation context\",\n `Community: ${ctx.indexContext}`,\n `Counterparty: ${ctx.counterpartyHint}`,\n \"\",\n \"## What the negotiator needs from its client\",\n ctx.disclosureSubject,\n \"\",\n \"## Draft question proposed by the negotiator\",\n draftBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Produce the minimum set of structured questions that get the negotiator the permission or input it needs to continue.\",\n \"Honor the draft when provided; refine its wording and options rather than replacing its topic.\",\n \"Apply every rule from your system prompt before outputting.\",\n ].join(\"\\n\");\n}\n\nconst CHAT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The protocol's chat orchestrator is mid-conversation with the user and has decided it needs a decision or missing input from them before it can continue. The conversation is PAUSED until the user answers. Your job: turn the orchestrator's stated need (and any draft questions it proposed) into the minimum set of crisp, structured decision questions.\n\nUnlike other question surfaces, these questions render INLINE in the active conversation, immediately after the assistant's last message — the user has full conversational context. Still keep each prompt self-contained enough to make sense on its own line.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing input the orchestrator needs to proceed (scope, timing, budget, format, preference, constraint, …).\n- refine_intent: ask the user to choose a direction when the orchestrator faces meaningfully different paths forward.\n\nHonor the orchestrator's intent. When draft questions are provided, treat them as the source of truth for WHAT to ask — improve wording, tighten options, add consequence-focused descriptions, and drop redundant drafts. Do not invent questions about topics the orchestrator did not raise. When no drafts are provided, derive questions strictly from the stated purpose.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the conversation excerpt or user profile shown.\n2. The answer materially changes what the orchestrator does next.\n3. The question targets a different decision domain from any other question in this batch.\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Emit a second or third ONLY when the orchestrator's purpose or drafts genuinely require separate decisions in distinct domains. Never pad.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option for what happens next in the conversation, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Direction\", \"Scope\", \"Timing\", \"Budget\", \"Format\", \"Priority\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I continue?\", \"Is that OK?\").\n- Don't re-ask for facts visible in the conversation excerpt or user profile.\n- Don't broaden beyond the orchestrator's stated purpose.\n- Don't ask vague introspective questions.\n\nOutput. Return at most 3 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the purpose is already answerable from the context shown, return \"questions\": [].`;\n\n/**\n * Build the user message for the chat preset from a ChatContext.\n * @param ctx - The chat context: orchestrator purpose, optional drafts, conversation excerpt, user context.\n * @returns The assembled user message string.\n */\nfunction buildChatPrompt(ctx: ChatContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const draftsBlock =\n ctx.draftQuestions && ctx.draftQuestions.length > 0\n ? ctx.draftQuestions\n .map((d, i) => {\n const opts = d.options && d.options.length > 0 ? ` [options: ${d.options.join(\" | \")}]` : \"\";\n const multi = d.multiSelect ? \" [multi-select]\" : \"\";\n return `${i + 1}. ${d.prompt}${opts}${multi}`;\n })\n .join(\"\\n\")\n : \"(none — derive questions from the purpose)\";\n\n const excerptBlock = ctx.conversationExcerpt?.trim()\n ? ctx.conversationExcerpt.trim()\n : \"(not available)\";\n\n return [\n \"## What the orchestrator needs to learn\",\n ctx.purpose,\n \"\",\n \"## Draft questions proposed by the orchestrator\",\n draftsBlock,\n \"\",\n \"## Recent conversation excerpt\",\n excerptBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Produce the minimum set of structured questions that get the orchestrator the decision or input it needs.\",\n \"Honor the drafts when provided; refine their wording and options rather than replacing their topics.\",\n \"Apply every rule from your system prompt before outputting.\",\n ].join(\"\\n\");\n}\n\n/**\n * pool_discovery has NO preset by design: those questions are synthesized\n * deterministically from mined discriminators (see\n * `opportunity/discriminator/discriminator.question.ts`) and never reach the\n * QuestionerAgent. `getPreset(\"pool_discovery\")` therefore throws — the\n * QuestionerQueue branches on the mode before invoking the agent.\n */\nfunction withQudMetadataRules(systemPrompt: string): string {\n return `${systemPrompt}\\n\\n${QUD_UNDERSPECIFICATION_RULES}`;\n}\n\nconst presets: Partial<Record<QuestionMode, QuestionerPreset>> = {\n discovery: {\n systemPrompt: withQudMetadataRules(DISCOVERY_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) =>\n buildDiscoveryQuestionPrompt(context as Parameters<typeof buildDiscoveryQuestionPrompt>[0]),\n },\n intent: {\n systemPrompt: withQudMetadataRules(INTENT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildIntentPrompt(context as IntentContext),\n },\n enrichment: {\n systemPrompt: withQudMetadataRules(PROFILE_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildProfilePrompt(context as ProfileContext),\n },\n negotiation: {\n systemPrompt: withQudMetadataRules(NEGOTIATION_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildNegotiationPrompt(context as NegotiationContext),\n },\n negotiation_inflight: {\n systemPrompt: withQudMetadataRules(NEGOTIATION_INFLIGHT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildNegotiationInflightPrompt(context as NegotiationInflightContext),\n },\n chat: {\n systemPrompt: withQudMetadataRules(CHAT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildChatPrompt(context as ChatContext),\n },\n};\n\n/**\n * Retrieve the preset for the given mode.\n * @param mode - The question mode to look up.\n * @returns The matching preset with systemPrompt and buildPrompt.\n * @throws Error if the mode's preset is not yet implemented.\n */\nexport function getPreset(mode: QuestionMode): QuestionerPreset {\n const preset = presets[mode];\n if (!preset) {\n throw new Error(`QuestionerAgent preset \"${mode}\" is not implemented yet`);\n }\n return preset;\n}\n"]}
@@ -5,12 +5,12 @@
5
5
  * Slice 1 defines all four context shapes but only `DiscoveryContext` has a
6
6
  * working preset implementation. The others are type stubs for future slices.
7
7
  */
8
- import type { DiscoveryQuestionInput } from "../opportunity/question.prompt.js";
8
+ import type { DiscoveryQuestionInput } from "../shared/schemas/discovery-question.schema.js";
9
9
  import type { ToolScopeType } from "../shared/agent/tool.scope.js";
10
10
  import type { QuestionMode, QuestionPoolDiscriminator } from "../shared/schemas/question.schema.js";
11
11
  /**
12
12
  * Discovery context — wraps the existing DiscoveryQuestionInput wholesale.
13
- * The discovery preset's buildPrompt delegates to the migrated builder.
13
+ * The discovery preset's buildPrompt delegates to `questioner.discovery.prompt.ts`.
14
14
  */
15
15
  export type DiscoveryContext = DiscoveryQuestionInput;
16
16
  /** Intent context — data needed to generate questions about an intent. */
@@ -1 +1 @@
1
- {"version":3,"file":"questioner.types.d.ts","sourceRoot":"/","sources":["questioner/questioner.types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AAChF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,YAAY,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AAIpG;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG,sBAAsB,CAAC;AAEtD,0EAA0E;AAC1E,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,kFAAkF;IAClF,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,gFAAgF;AAChF,MAAM,WAAW,cAAc;IAC7B,kFAAkF;IAClF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,oFAAoF;IACpF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAED,4DAA4D;AAC5D,UAAU,sBAAsB;IAC9B,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,kFAAkF;IAClF,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,2EAA2E;AAC3E,MAAM,WAAW,2BAA4B,SAAQ,sBAAsB;IACzE,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB,aAAa,EAAE,UAAU,GAAG,SAAS,GAAG,SAAS,CAAC;IAClD,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,mFAAmF;AACnF,MAAM,WAAW,wBAAyB,S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uBAAuB,GAAG,qBAAqB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"questioner.types.js","sourceRoot":"/","sources":["questioner/questioner.types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * QuestionerAgent input types. The `QuestionerInput` envelope carries a `mode`\n * field that selects a preset, plus a polymorphic `context` that varies per mode.\n *\n * Slice 1 defines all four context shapes but only `DiscoveryContext` has a\n * working preset implementation. The others are type stubs for future slices.\n */\nimport type { DiscoveryQuestionInput } from \"../opportunity/question.prompt.js\";\nimport type { ToolScopeType } from \"../shared/agent/tool.scope.js\";\nimport type { QuestionMode, QuestionPoolDiscriminator } from \"../shared/schemas/question.schema.js\";\n\n// ─── Per-mode context types ─────────────────────────────────────────────────\n\n/**\n * Discovery context — wraps the existing DiscoveryQuestionInput wholesale.\n * The discovery preset's buildPrompt delegates to the migrated builder.\n */\nexport type DiscoveryContext = DiscoveryQuestionInput;\n\n/** Intent context — data needed to generate questions about an intent. */\nexport interface IntentContext {\n intentId: string;\n payload: string;\n summary?: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/** Profile context — data needed to generate questions to fill profile gaps. */\nexport interface ProfileContext {\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n gaps: string[];\n /** Existing premise texts the user has already stated (e.g. \"I live in Berlin\"). */\n existingPremises?: string[];\n}\n\n/** Shared context fields for negotiation-mode questions. */\ninterface NegotiationContextBase {\n negotiationId: string;\n counterpartyHint: string;\n indexContext: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/** Post-stall negotiation context. Preserves the existing source shape. */\nexport interface PostStallNegotiationContext extends NegotiationContextBase {\n purpose?: undefined;\n outcomeReason: \"turn_cap\" | \"timeout\" | \"stalled\";\n keyTake: string;\n}\n\n/** Pre-accept uptake context targeting a counterparty's preparatory conditions. */\nexport interface UptakeNegotiationContext extends NegotiationContextBase {\n purpose: \"uptake\";\n /** Plain-language activity or commitment whose feasibility needs clarification. */\n proposedActivity: string;\n /** Public evidence already available about capability, resources, or authority. */\n preparatoryEvidence?: string;\n}\n\n/** Negotiation context discriminated by internal question purpose. */\nexport type NegotiationContext = PostStallNegotiationContext | UptakeNegotiationContext;\n\n/**\n * Negotiation-inflight context — a negotiator mid-negotiation wants to ask its\n * OWN client a question before continuing (the `ask_user` action, P3.2). The\n * negotiator states the disclosure subject and optionally drafts the question;\n * the QuestionerAgent refines it into polished disclosure-gating questions.\n * Distinct from {@link NegotiationContext}, which covers post-stall questions.\n */\nexport interface NegotiationInflightContext {\n negotiationId: string;\n /** Anonymized counterparty description (attributes, never identity). */\n counterpartyHint: string;\n /** What the negotiator wants permission to share or needs to know (e.g. \"budget range\", \"availability in Q3\"). */\n disclosureSubject: string;\n /** Draft question authored by the negotiator. The agent refines it. */\n draftQuestion?: string;\n /** Community / index context the negotiation runs in. */\n indexContext: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/**\n * Chat context — data for orchestrator-initiated mid-conversation questions\n * (the `ask_user_question` tool). The orchestrator states what it needs to\n * learn; the QuestionerAgent turns that into polished structured questions,\n * grounded in the recent conversation and the user's identity context.\n */\nexport interface ChatContext {\n /** What the orchestrator needs to learn and why (authored by the chat model). */\n purpose: string;\n /** Draft questions proposed by the orchestrator. The agent refines these. */\n draftQuestions?: Array<{\n prompt: string;\n options?: string[];\n multiSelect?: boolean;\n }>;\n /** Recent conversation excerpt for grounding (most recent messages last). */\n conversationExcerpt?: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/**\n * Pool-discovery context — mined discriminators from a discovery-run pool\n * (IND-418). No generator LLM runs for this mode: the QuestionerQueue\n * synthesizes the question deterministically from the top discriminator and\n * stashes the rest as interview-mode alternates.\n */\nexport interface PoolDiscoveryContext {\n intentId: string;\n /** Truncated intent payload (+ summary) display snippet. */\n intentText: string;\n /** Stable hash of the full normalized payload + summary used for freshness. */\n intentFingerprint?: string;\n poolSize: number;\n /** Exact bounded candidate opportunity IDs supplied to synthesis. */\n opportunityIds: string[];\n /** Discovery run that produced the pool. */\n runId?: string;\n /** Eligible discriminators, VoI-descending (asked + chain alternates). */\n discriminators: QuestionPoolDiscriminator[];\n /** ISO-8601 timestamp of the mining pass. */\n minedAt: string;\n}\n\n/** Discriminated union: mode selects the context shape. */\nexport type QuestionerContext =\n | DiscoveryContext\n | IntentContext\n | ProfileContext\n | NegotiationContext\n | NegotiationInflightContext\n | ChatContext\n | PoolDiscoveryContext;\n\n/**\n * Payload shape accepted by the questionerEnqueue callback. Covers all\n * question modes — the composition root bridges this to the concrete\n * QuestionerQueue.\n */\nexport type QuestionerEnqueuePayload = QuestionerInput;\n\n/** Callback signature for async question generation enqueue. */\nexport type QuestionerEnqueueFn = (input: QuestionerEnqueuePayload) => Promise<void>;\n\n/** Top-level input envelope for QuestionerAgent.invoke(). */\ninterface QuestionerInputBase {\n /** Selects the preset (system prompt + builder). */\n mode: QuestionMode;\n /** User the questions are generated for. */\n userId: string;\n /** Entity type that triggered this (e.g. \"opportunity\", \"intent\", \"profile\"). */\n sourceType: string;\n /** ID of the triggering entity. */\n sourceId: string;\n /** Scoped question context. Network scopes persist as QuestionActor.networkId. */\n scopeType?: ToolScopeType;\n /** Scoped question id. When scopeType is `network`, this is the actor networkId. */\n scopeId?: string;\n /**\n * Intent that triggered the run that generated these questions. Persisted as\n * `detection.triggeredBy` so intent-scoped surfaces (e.g. the intent page)\n * can find them. Independent of `scopeType`/`scopeId`, which may carry a\n * network scope at the same time.\n */\n triggeredByIntentId?: string;\n /** Conversation ID — set when the question originates from a chat session. Persisted on the question row for frontend filtering. */\n conversationId?: string;\n /** Assistant message ID — set when we know which message triggered the question. Stored in detection.messageId for inline anchoring. */\n messageId?: string;\n}\n\n/** Existing question inputs, including post-stall negotiation source compatibility. */\ninterface StandardQuestionerInput extends QuestionerInputBase {\n purpose?: undefined;\n /** Mode-specific context. Must align with the selected mode. */\n context: Exclude<QuestionerContext, UptakeNegotiationContext>;\n}\n\n/** Negotiation-mode uptake generation input. */\nexport interface UptakeQuestionerInput extends QuestionerInputBase {\n mode: \"negotiation\";\n purpose: \"uptake\";\n context: UptakeNegotiationContext;\n}\n\n/** Top-level input discriminated by the internal purpose. */\nexport type QuestionerInput = StandardQuestionerInput | UptakeQuestionerInput;\n"]}
1
+ {"version":3,"file":"questioner.types.js","sourceRoot":"/","sources":["questioner/questioner.types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * QuestionerAgent input types. The `QuestionerInput` envelope carries a `mode`\n * field that selects a preset, plus a polymorphic `context` that varies per mode.\n *\n * Slice 1 defines all four context shapes but only `DiscoveryContext` has a\n * working preset implementation. The others are type stubs for future slices.\n */\nimport type { DiscoveryQuestionInput } from \"../shared/schemas/discovery-question.schema.js\";\nimport type { ToolScopeType } from \"../shared/agent/tool.scope.js\";\nimport type { QuestionMode, QuestionPoolDiscriminator } from \"../shared/schemas/question.schema.js\";\n\n// ─── Per-mode context types ─────────────────────────────────────────────────\n\n/**\n * Discovery context — wraps the existing DiscoveryQuestionInput wholesale.\n * The discovery preset's buildPrompt delegates to `questioner.discovery.prompt.ts`.\n */\nexport type DiscoveryContext = DiscoveryQuestionInput;\n\n/** Intent context — data needed to generate questions about an intent. */\nexport interface IntentContext {\n intentId: string;\n payload: string;\n summary?: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/** Profile context — data needed to generate questions to fill profile gaps. */\nexport interface ProfileContext {\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n gaps: string[];\n /** Existing premise texts the user has already stated (e.g. \"I live in Berlin\"). */\n existingPremises?: string[];\n}\n\n/** Shared context fields for negotiation-mode questions. */\ninterface NegotiationContextBase {\n negotiationId: string;\n counterpartyHint: string;\n indexContext: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/** Post-stall negotiation context. Preserves the existing source shape. */\nexport interface PostStallNegotiationContext extends NegotiationContextBase {\n purpose?: undefined;\n outcomeReason: \"turn_cap\" | \"timeout\" | \"stalled\";\n keyTake: string;\n}\n\n/** Pre-accept uptake context targeting a counterparty's preparatory conditions. */\nexport interface UptakeNegotiationContext extends NegotiationContextBase {\n purpose: \"uptake\";\n /** Plain-language activity or commitment whose feasibility needs clarification. */\n proposedActivity: string;\n /** Public evidence already available about capability, resources, or authority. */\n preparatoryEvidence?: string;\n}\n\n/** Negotiation context discriminated by internal question purpose. */\nexport type NegotiationContext = PostStallNegotiationContext | UptakeNegotiationContext;\n\n/**\n * Negotiation-inflight context — a negotiator mid-negotiation wants to ask its\n * OWN client a question before continuing (the `ask_user` action, P3.2). The\n * negotiator states the disclosure subject and optionally drafts the question;\n * the QuestionerAgent refines it into polished disclosure-gating questions.\n * Distinct from {@link NegotiationContext}, which covers post-stall questions.\n */\nexport interface NegotiationInflightContext {\n negotiationId: string;\n /** Anonymized counterparty description (attributes, never identity). */\n counterpartyHint: string;\n /** What the negotiator wants permission to share or needs to know (e.g. \"budget range\", \"availability in Q3\"). */\n disclosureSubject: string;\n /** Draft question authored by the negotiator. The agent refines it. */\n draftQuestion?: string;\n /** Community / index context the negotiation runs in. */\n indexContext: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/**\n * Chat context — data for orchestrator-initiated mid-conversation questions\n * (the `ask_user_question` tool). The orchestrator states what it needs to\n * learn; the QuestionerAgent turns that into polished structured questions,\n * grounded in the recent conversation and the user's identity context.\n */\nexport interface ChatContext {\n /** What the orchestrator needs to learn and why (authored by the chat model). */\n purpose: string;\n /** Draft questions proposed by the orchestrator. The agent refines these. */\n draftQuestions?: Array<{\n prompt: string;\n options?: string[];\n multiSelect?: boolean;\n }>;\n /** Recent conversation excerpt for grounding (most recent messages last). */\n conversationExcerpt?: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/**\n * Pool-discovery context — mined discriminators from a discovery-run pool\n * (IND-418). No generator LLM runs for this mode: the QuestionerQueue\n * synthesizes the question deterministically from the top discriminator and\n * stashes the rest as interview-mode alternates.\n */\nexport interface PoolDiscoveryContext {\n intentId: string;\n /** Truncated intent payload (+ summary) display snippet. */\n intentText: string;\n /** Stable hash of the full normalized payload + summary used for freshness. */\n intentFingerprint?: string;\n poolSize: number;\n /** Exact bounded candidate opportunity IDs supplied to synthesis. */\n opportunityIds: string[];\n /** Discovery run that produced the pool. */\n runId?: string;\n /** Eligible discriminators, VoI-descending (asked + chain alternates). */\n discriminators: QuestionPoolDiscriminator[];\n /** ISO-8601 timestamp of the mining pass. */\n minedAt: string;\n}\n\n/** Discriminated union: mode selects the context shape. */\nexport type QuestionerContext =\n | DiscoveryContext\n | IntentContext\n | ProfileContext\n | NegotiationContext\n | NegotiationInflightContext\n | ChatContext\n | PoolDiscoveryContext;\n\n/**\n * Payload shape accepted by the questionerEnqueue callback. Covers all\n * question modes — the composition root bridges this to the concrete\n * QuestionerQueue.\n */\nexport type QuestionerEnqueuePayload = QuestionerInput;\n\n/** Callback signature for async question generation enqueue. */\nexport type QuestionerEnqueueFn = (input: QuestionerEnqueuePayload) => Promise<void>;\n\n/** Top-level input envelope for QuestionerAgent.invoke(). */\ninterface QuestionerInputBase {\n /** Selects the preset (system prompt + builder). */\n mode: QuestionMode;\n /** User the questions are generated for. */\n userId: string;\n /** Entity type that triggered this (e.g. \"opportunity\", \"intent\", \"profile\"). */\n sourceType: string;\n /** ID of the triggering entity. */\n sourceId: string;\n /** Scoped question context. Network scopes persist as QuestionActor.networkId. */\n scopeType?: ToolScopeType;\n /** Scoped question id. When scopeType is `network`, this is the actor networkId. */\n scopeId?: string;\n /**\n * Intent that triggered the run that generated these questions. Persisted as\n * `detection.triggeredBy` so intent-scoped surfaces (e.g. the intent page)\n * can find them. Independent of `scopeType`/`scopeId`, which may carry a\n * network scope at the same time.\n */\n triggeredByIntentId?: string;\n /** Conversation ID — set when the question originates from a chat session. Persisted on the question row for frontend filtering. */\n conversationId?: string;\n /** Assistant message ID — set when we know which message triggered the question. Stored in detection.messageId for inline anchoring. */\n messageId?: string;\n}\n\n/** Existing question inputs, including post-stall negotiation source compatibility. */\ninterface StandardQuestionerInput extends QuestionerInputBase {\n purpose?: undefined;\n /** Mode-specific context. Must align with the selected mode. */\n context: Exclude<QuestionerContext, UptakeNegotiationContext>;\n}\n\n/** Negotiation-mode uptake generation input. */\nexport interface UptakeQuestionerInput extends QuestionerInputBase {\n mode: \"negotiation\";\n purpose: \"uptake\";\n context: UptakeNegotiationContext;\n}\n\n/** Top-level input discriminated by the internal purpose. */\nexport type QuestionerInput = StandardQuestionerInput | UptakeQuestionerInput;\n"]}
@@ -103,11 +103,6 @@ declare function getModelConfig(config?: ModelConfig): {
103
103
  readonly temperature: 0.2;
104
104
  readonly maxTokens: 512;
105
105
  };
106
- readonly discoveryQuestionGenerator: {
107
- readonly model: "google/gemini-2.5-flash";
108
- readonly temperature: 0.5;
109
- readonly maxTokens: 1024;
110
- };
111
106
  readonly questioner: {
112
107
  readonly model: "google/gemini-2.5-flash";
113
108
  readonly temperature: 0.5;
@@ -1 +1 @@
1
- {"version":3,"file":"model.config.d.ts","sourceRoot":"/","sources":["shared/agent/model.config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EAAE,sBAAsB,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAClH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAElE,iDAAiD;AACjD,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE;QAAE,M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