@indexnetwork/protocol 3.6.3-rc.271.1 → 3.6.3-rc.272.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 (76) hide show
  1. package/dist/agent/tests/fakes.d.ts.map +1 -1
  2. package/dist/agent/tests/fakes.js.map +1 -1
  3. package/dist/chat/chat.agent.d.ts.map +1 -1
  4. package/dist/chat/chat.agent.js +3 -3
  5. package/dist/chat/chat.agent.js.map +1 -1
  6. package/dist/chat/chat.streamer.d.ts.map +1 -1
  7. package/dist/chat/chat.streamer.js +1 -1
  8. package/dist/chat/chat.streamer.js.map +1 -1
  9. package/dist/chat/chat.summarizer.d.ts.map +1 -1
  10. package/dist/chat/chat.summarizer.js +1 -1
  11. package/dist/chat/chat.summarizer.js.map +1 -1
  12. package/dist/chat/tests/chat.graph.mocks.d.ts.map +1 -1
  13. package/dist/chat/tests/chat.graph.mocks.js +0 -1
  14. package/dist/chat/tests/chat.graph.mocks.js.map +1 -1
  15. package/dist/index.d.ts +21 -21
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +10 -10
  18. package/dist/index.js.map +1 -1
  19. package/dist/intent/intent.graph.js +1 -1
  20. package/dist/intent/intent.graph.js.map +1 -1
  21. package/dist/maintenance/maintenance.graph.d.ts.map +1 -1
  22. package/dist/maintenance/maintenance.graph.js +1 -1
  23. package/dist/maintenance/maintenance.graph.js.map +1 -1
  24. package/dist/negotiation/negotiation.agent.d.ts.map +1 -1
  25. package/dist/negotiation/negotiation.agent.js +1 -1
  26. package/dist/negotiation/negotiation.agent.js.map +1 -1
  27. package/dist/negotiation/negotiation.summarizer.d.ts.map +1 -1
  28. package/dist/negotiation/negotiation.summarizer.js +1 -1
  29. package/dist/negotiation/negotiation.summarizer.js.map +1 -1
  30. package/dist/network/indexer/indexer.graph.d.ts.map +1 -1
  31. package/dist/network/indexer/indexer.graph.js +2 -2
  32. package/dist/network/indexer/indexer.graph.js.map +1 -1
  33. package/dist/opportunity/discovery-question.helper.d.ts.map +1 -1
  34. package/dist/opportunity/discovery-question.helper.js.map +1 -1
  35. package/dist/opportunity/feed/feed.graph.d.ts.map +1 -1
  36. package/dist/opportunity/feed/feed.graph.js +1 -1
  37. package/dist/opportunity/feed/feed.graph.js.map +1 -1
  38. package/dist/opportunity/negotiation-summary.builder.d.ts.map +1 -1
  39. package/dist/opportunity/negotiation-summary.builder.js.map +1 -1
  40. package/dist/opportunity/opportunity.discover.d.ts.map +1 -1
  41. package/dist/opportunity/opportunity.discover.js +1 -1
  42. package/dist/opportunity/opportunity.discover.js.map +1 -1
  43. package/dist/opportunity/opportunity.enricher.d.ts.map +1 -1
  44. package/dist/opportunity/opportunity.enricher.js.map +1 -1
  45. package/dist/opportunity/opportunity.graph.d.ts.map +1 -1
  46. package/dist/opportunity/opportunity.graph.js +5 -5
  47. package/dist/opportunity/opportunity.graph.js.map +1 -1
  48. package/dist/opportunity/opportunity.persist.d.ts.map +1 -1
  49. package/dist/opportunity/opportunity.persist.js.map +1 -1
  50. package/dist/opportunity/question.generator.d.ts.map +1 -1
  51. package/dist/opportunity/question.generator.js +2 -2
  52. package/dist/opportunity/question.generator.js.map +1 -1
  53. package/dist/premise/premise.graph.d.ts.map +1 -1
  54. package/dist/premise/premise.graph.js +1 -1
  55. package/dist/premise/premise.graph.js.map +1 -1
  56. package/dist/profile/profile.graph.js +1 -1
  57. package/dist/profile/profile.graph.js.map +1 -1
  58. package/dist/questioner/questioner.agent.d.ts.map +1 -1
  59. package/dist/questioner/questioner.agent.js +1 -1
  60. package/dist/questioner/questioner.agent.js.map +1 -1
  61. package/dist/questioner/questioner.presets.d.ts.map +1 -1
  62. package/dist/questioner/questioner.presets.js +1 -1
  63. package/dist/questioner/questioner.presets.js.map +1 -1
  64. package/dist/shared/agent/response.streamer.d.ts.map +1 -1
  65. package/dist/shared/agent/response.streamer.js +1 -1
  66. package/dist/shared/agent/response.streamer.js.map +1 -1
  67. package/dist/shared/agent/tool.factory.d.ts.map +1 -1
  68. package/dist/shared/agent/tool.factory.js +1 -1
  69. package/dist/shared/agent/tool.factory.js.map +1 -1
  70. package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
  71. package/dist/shared/agent/tool.helpers.js.map +1 -1
  72. package/dist/shared/assignment/network-assignment.policy.d.ts.map +1 -1
  73. package/dist/shared/assignment/network-assignment.policy.js.map +1 -1
  74. package/dist/shared/interfaces/questioner.interface.d.ts.map +1 -1
  75. package/dist/shared/interfaces/questioner.interface.js.map +1 -1
  76. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"opportunity.persist.d.ts","sourceRoot":"/","sources":["opportunity/opportunity.persist.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EACV,qBAAqB,EACrB,WAAW,EACX,iBAAiB,EAClB,MAAM,4CAA4C,CAAC;AACpD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4CAA4C,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAMlE,MAAM,MAAM,0BAA0B,GAAG,gBAAgB,GAAG;IAC1D,iBAAiB,CAAC,IAAI,EAAE,qBAAqB,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IACrE,uBAAuB,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,GAAG,WAAW,GAAG,IAAI,CAAC,CAAC;IACnG,6BAA6B,CAAC,CAC5B,IAAI,EAAE,qBAAqB,EAC3B,SAAS,EAAE,MAAM,EAAE,GAClB,OAAO,CAAC;QAAE,OAAO,EAAE,WAAW,CAAC;QAAC,OAAO,EAAE,WAAW,EAAE,CAAA;KAAE,CAAC,CAAC;IAC7D,kEAAkE;IAClE,cAAc,CAAC,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;CAC1D,CAAC;AAEF,MAAM,WAAW,0BAA0B;IACz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AAE,CAAC;wBAC5B,KAAK,MAAM,EAAE,IAAI,UAAU,CAAC,UAAU,EAAE,CAAC;4BACvC,MAAM,GAAG,GAAG,MAAM,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC;4BAC9C,IAAI,GAAG;gCAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;wBAC7B,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;YAED,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAChD,IAAI,WAAW,EAAE,MAAM,KAAK,SAAS,IAAI,UAAU,EAAE,CAAC;gBACpD,MAAM,UAAU,CAAC,WAAW,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;oBAC1C,MAAM,CAAC,IAAI,CAAC,8CAA8C,EAAE,EAAE,aAAa,EAAE,WAAW,CAAC,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;gBAC7G,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;YACvC,MAAM,CAAC,IAAI,CAAC,oCAAoC,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;QAC/E,CAAC;IACH,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACxE,CAAC","sourcesContent":["/**\n * Shared persist phase for opportunity creation: enrichOrCreate → create (or create+expire) → optional chat injection.\n * Used by the opportunity graph persist node and by the manual opportunity service for consistency.\n */\n\nimport type {\n CreateOpportunityData,\n Opportunity,\n OpportunityStatus,\n} from '../shared/interfaces/database.interface.js';\nimport type { Embedder } from '../shared/interfaces/embedder.interface.js';\nimport type { EnricherDatabase } from './opportunity.enricher.js';\nimport { enrichOrCreate } from './opportunity.enricher.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('OpportunityPersist');\n\nexport type PersistOpportunityDatabase = EnricherDatabase & {\n createOpportunity(data: CreateOpportunityData): Promise<Opportunity>;\n updateOpportunityStatus(id: string, status: OpportunityStatus): Promise<void | Opportunity | null>;\n createOpportunityAndExpireIds?(\n data: CreateOpportunityData,\n expireIds: string[]\n ): Promise<{ created: Opportunity; expired: Opportunity[] }>;\n /** Optional: used to populate expired list in non-atomic path. */\n getOpportunity?(id: string): Promise<Opportunity | null>;\n};\n\nexport interface PersistOpportunitiesParams {\n database: PersistOpportunityDatabase;\n embedder: Embedder;\n items: CreateOpportunityData[];\n injectChat?: (opportunity: Opportunity) => Promise<unknown>;\n}\n\nexport interface PersistOpportunitiesError {\n itemIndex: number;\n error: unknown;\n}\n\nexport interface PersistOpportunitiesResult {\n created: Opportunity[];\n expired: Opportunity[];\n errors?: PersistOpportunitiesError[];\n}\n\n/**\n * Persist one or more opportunities: enrich (merge overlapping), create, expire replaced, optional chat injection.\n * When the database has createOpportunityAndExpireIds and enrichment produced expireIds, uses it for atomic create+expire.\n * Returns both created and expired so callers can emit events (e.g. manual service).\n */\nexport async function persistOpportunities(params: PersistOpportunitiesParams): Promise<PersistOpportunitiesResult> {\n const { database, embedder, items, injectChat } = params;\n const created: Opportunity[] = [];\n const expired: Opportunity[] = [];\n const errors: PersistOpportunitiesError[] = [];\n\n for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {\n const data = items[itemIndex];\n try {\n const enrichment = await enrichOrCreate(database, embedder, data);\n const toCreate = enrichment.data;\n if (enrichment.enriched) {\n toCreate.status = enrichment.resolvedStatus;\n }\n\n if (\n database.createOpportunityAndExpireIds &&\n enrichment.enriched &&\n enrichment.expiredIds.length > 0\n ) {\n const result = await database.createOpportunityAndExpireIds(toCreate, enrichment.expiredIds);\n created.push(result.created);\n expired.push(...result.expired);\n } else {\n const c = await database.createOpportunity(toCreate);\n created.push(c);\n if (enrichment.enriched && enrichment.expiredIds.length > 0) {\n for (const id of enrichment.expiredIds) {\n await database.updateOpportunityStatus(id, 'expired');\n }\n if (database.getOpportunity) {\n for (const id of enrichment.expiredIds) {\n const opp = await database.getOpportunity(id);\n if (opp) expired.push(opp);\n }\n }\n }\n }\n\n const lastCreated = created[created.length - 1];\n if (lastCreated?.status === 'pending' && injectChat) {\n await injectChat(lastCreated).catch((err) => {\n logger.warn('[PersistOpportunities] Chat injection failed', { opportunityId: lastCreated.id, error: err });\n });\n }\n } catch (err) {\n errors.push({ itemIndex, error: err });\n logger.warn('[PersistOpportunities] Item failed', { itemIndex, error: err });\n }\n }\n\n return { created, expired, ...(errors.length > 0 ? { errors } : {}) };\n}\n"]}
1
+ {"version":3,"file":"opportunity.persist.js","sourceRoot":"/","sources":["opportunity/opportunity.persist.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,oBAAoB,CAAC,CAAC;AA+BpD;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,MAAkC;IAC3E,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IACzD,MAAM,OAAO,GAAkB,EAAE,CAAC;IAClC,MAAM,OAAO,GAAkB,EAAE,CAAC;IAClC,MAAM,MAAM,GAAgC,EAAE,CAAC;IAE/C,KAAK,IAAI,SAAS,GAAG,CAAC,EAAE,SAAS,GAAG,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,CAAC;QAC9D,MAAM,IAAI,GAAG,KAAK,CAAC,SAAS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AAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;wBAC7B,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;YAED,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAChD,IAAI,WAAW,EAAE,MAAM,KAAK,SAAS,IAAI,UAAU,EAAE,CAAC;gBACpD,MAAM,UAAU,CAAC,WAAW,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;oBAC1C,MAAM,CAAC,IAAI,CAAC,8CAA8C,EAAE,EAAE,aAAa,EAAE,WAAW,CAAC,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;gBAC7G,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;YACvC,MAAM,CAAC,IAAI,CAAC,oCAAoC,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;QAC/E,CAAC;IACH,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACxE,CAAC","sourcesContent":["/**\n * Shared persist phase for opportunity creation: enrichOrCreate → create (or create+expire) → optional chat injection.\n * Used by the opportunity graph persist node and by the manual opportunity service for consistency.\n */\n\nimport type { CreateOpportunityData, Opportunity, OpportunityStatus } from '../shared/interfaces/database.interface.js';\nimport type { Embedder } from '../shared/interfaces/embedder.interface.js';\nimport type { EnricherDatabase } from './opportunity.enricher.js';\nimport { enrichOrCreate } from './opportunity.enricher.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('OpportunityPersist');\n\nexport type PersistOpportunityDatabase = EnricherDatabase & {\n createOpportunity(data: CreateOpportunityData): Promise<Opportunity>;\n updateOpportunityStatus(id: string, status: OpportunityStatus): Promise<void | Opportunity | null>;\n createOpportunityAndExpireIds?(\n data: CreateOpportunityData,\n expireIds: string[]\n ): Promise<{ created: Opportunity; expired: Opportunity[] }>;\n /** Optional: used to populate expired list in non-atomic path. */\n getOpportunity?(id: string): Promise<Opportunity | null>;\n};\n\nexport interface PersistOpportunitiesParams {\n database: PersistOpportunityDatabase;\n embedder: Embedder;\n items: CreateOpportunityData[];\n injectChat?: (opportunity: Opportunity) => Promise<unknown>;\n}\n\nexport interface PersistOpportunitiesError {\n itemIndex: number;\n error: unknown;\n}\n\nexport interface PersistOpportunitiesResult {\n created: Opportunity[];\n expired: Opportunity[];\n errors?: PersistOpportunitiesError[];\n}\n\n/**\n * Persist one or more opportunities: enrich (merge overlapping), create, expire replaced, optional chat injection.\n * When the database has createOpportunityAndExpireIds and enrichment produced expireIds, uses it for atomic create+expire.\n * Returns both created and expired so callers can emit events (e.g. manual service).\n */\nexport async function persistOpportunities(params: PersistOpportunitiesParams): Promise<PersistOpportunitiesResult> {\n const { database, embedder, items, injectChat } = params;\n const created: Opportunity[] = [];\n const expired: Opportunity[] = [];\n const errors: PersistOpportunitiesError[] = [];\n\n for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {\n const data = items[itemIndex];\n try {\n const enrichment = await enrichOrCreate(database, embedder, data);\n const toCreate = enrichment.data;\n if (enrichment.enriched) {\n toCreate.status = enrichment.resolvedStatus;\n }\n\n if (\n database.createOpportunityAndExpireIds &&\n enrichment.enriched &&\n enrichment.expiredIds.length > 0\n ) {\n const result = await database.createOpportunityAndExpireIds(toCreate, enrichment.expiredIds);\n created.push(result.created);\n expired.push(...result.expired);\n } else {\n const c = await database.createOpportunity(toCreate);\n created.push(c);\n if (enrichment.enriched && enrichment.expiredIds.length > 0) {\n for (const id of enrichment.expiredIds) {\n await database.updateOpportunityStatus(id, 'expired');\n }\n if (database.getOpportunity) {\n for (const id of enrichment.expiredIds) {\n const opp = await database.getOpportunity(id);\n if (opp) expired.push(opp);\n }\n }\n }\n }\n\n const lastCreated = created[created.length - 1];\n if (lastCreated?.status === 'pending' && injectChat) {\n await injectChat(lastCreated).catch((err) => {\n logger.warn('[PersistOpportunities] Chat injection failed', { opportunityId: lastCreated.id, error: err });\n });\n }\n } catch (err) {\n errors.push({ itemIndex, error: err });\n logger.warn('[PersistOpportunities] Item failed', { itemIndex, error: err });\n }\n }\n\n return { created, expired, ...(errors.length > 0 ? { errors } : {}) };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"question.generator.d.ts","sourceRoot":"/","sources":["opportunity/question.generator.ts"],"names":[],"mappings":"AAkBA,OAAO,EAGL,KAAK,wBAAwB,EAG9B,MAAM,sCAAsC,CAAC;AAK9C,OAAO,EAGL,KAAK,sBAAsB,EAC5B,MAAM,sBAAsB,CAAC;AAO9B,oFAAoF;AACpF,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,KAAK,CAAiD;;IAS9D;;;;;;;;;;OAUG;IAEG,QAAQ,CACZ,KAAK,EAAE,sBAAsB,EAC7B,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GACjC,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC;CAyC5C"}
1
+ {"version":3,"file":"question.generator.d.ts","sourceRoot":"/","sources":["opportunity/question.generator.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAkD,KAAK,wBAAwB,EAAoD,MAAM,sCAAsC,CAAC;AAKvL,OAAO,EAAsC,KAAK,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAOvG,oFAAoF;AACpF,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,KAAK,CAAiD;;IAS9D;;;;;;;;;;OAUG;IAEG,QAAQ,CACZ,KAAK,EAAE,sBAAsB,EAC7B,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GACjC,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC;CAyC5C"}
@@ -8,12 +8,12 @@ var __metadata = (this && this.__metadata) || function (k, v) {
8
8
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
9
  };
10
10
  import { HumanMessage, SystemMessage } from "@langchain/core/messages";
11
- import { QuestionGeneratorResponseSchema, } from "../shared/schemas/question.schema.js";
11
+ import { QuestionGeneratorResponseSchema } from "../shared/schemas/question.schema.js";
12
12
  import { createModel } from "../shared/agent/model.config.js";
13
13
  import { invokeWithAbortSignal } from "../shared/agent/model-signal.js";
14
14
  import { protocolLogger } from "../shared/observability/protocol.logger.js";
15
15
  import { Timed } from "../shared/observability/performance.js";
16
- import { SYSTEM_PROMPT, buildQuestionPrompt, } from "./question.prompt.js";
16
+ import { SYSTEM_PROMPT, buildQuestionPrompt } from "./question.prompt.js";
17
17
  const logger = protocolLogger("QuestionGenerator");
18
18
  /** Maximum same-strategy questions allowed in a single emission. */
19
19
  const MAX_SAME_STRATEGY = 2;
@@ -1 +1 @@
1
- {"version":3,"file":"question.generator.js","sourceRoot":"/","sources":["opportunity/question.generator.ts"],"names":[],"mappings":";;;;;;;;;AAgBA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEvE,OAAO,EACL,+BAA+B,GAKhC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EACL,aAAa,EACb,mBAAmB,GAEpB,MAAM,sBAAsB,CAAC;AAE9B,MAAM,MAAM,GAAG,cAAc,CAAC,mBAAmB,CAAC,CAAC;AAEnD,oEAAoE;AACp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AC,CAAC;IACd,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED;;;;;GAKG;AACH,SAAS,wBAAwB,CAC/B,SAAiC;IAEjC,MAAM,MAAM,GAAG,IAAI,GAAG,EAA4B,CAAC;IACnD,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,KAAK,MAAM,CAAC,IAAI,SAAS,EAAE,CAAC;QAC1B,MAAM,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACtC,IAAI,CAAC,IAAI,iBAAiB;YAAE,SAAS;QACrC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QAC9B,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,aAAa,CAAC,CAAuB;IAC5C,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,WAAW,EAAE,GAAG,CAAC,CAAC;IAClD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["/**\n * @deprecated Use QuestionerAgent instead. Will be removed in a future version.\n *\n * QuestionGenerator — pure LLM pass that turns a structured DiscoveryQuestionInput\n * into 0–3 decision questions. No DB, no events, no caller wired here; Slice 3\n * (opportunity.discover.ts) is the first consumer.\n *\n * Flow:\n * 1. buildQuestionPrompt(input) → user message string.\n * 2. model.invoke([system, user]) returns a structured payload.\n * 3. safeParse via QuestionGeneratorResponseSchema → null on failure.\n * 4. Guardrails: dedup by title, then strategy-diversity (never 3 same).\n * 5. If empty, return null. Otherwise split into public Question[] + parallel\n * QuestionStrategy[] (debug-only; strategy is NEVER on the public shape).\n */\nimport type { ChatOpenAI } from \"@langchain/openai\";\nimport { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\n\nimport {\n QuestionGeneratorResponseSchema,\n type Question,\n type QuestionGenerationResult,\n type QuestionStrategy,\n type QuestionWithStrategy,\n} from \"../shared/schemas/question.schema.js\";\nimport { createModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport {\n SYSTEM_PROMPT,\n buildQuestionPrompt,\n type DiscoveryQuestionInput,\n} from \"./question.prompt.js\";\n\nconst logger = protocolLogger(\"QuestionGenerator\");\n\n/** Maximum same-strategy questions allowed in a single emission. */\nconst MAX_SAME_STRATEGY = 2;\n\n/** @deprecated Use QuestionerAgent instead. Will be removed in a future version. */\nexport class QuestionGenerator {\n private model: ReturnType<ChatOpenAI[\"withStructuredOutput\"]>;\n\n constructor() {\n const llm = createModel(\"discoveryQuestionGenerator\");\n this.model = llm.withStructuredOutput(QuestionGeneratorResponseSchema, {\n name: \"clarifying_questions\",\n });\n }\n\n /**\n * Generate up to 3 decision questions from the given discovery turn.\n *\n * @param input Discovery turn payload.\n * @param options.signal Optional AbortSignal. Passed to LangChain so an\n * aborted call cancels the underlying HTTP fetch instead of leaving a\n * floating promise burning OpenRouter capacity.\n * @returns A result with parallel questions[] and strategies[] arrays,\n * or null when the LLM fails, the output is malformed, the call was\n * aborted, or the guardrails leave zero questions standing.\n */\n @Timed()\n async generate(\n input: DiscoveryQuestionInput,\n options?: { signal?: AbortSignal },\n ): Promise<QuestionGenerationResult | null> {\n const user = buildQuestionPrompt(input);\n\n let raw: unknown;\n try {\n raw = await invokeWithAbortSignal(\n this.model,\n [new SystemMessage(SYSTEM_PROMPT), new HumanMessage(user)],\n options?.signal,\n );\n } catch (err) {\n // AbortError is the expected outcome under deadline pressure — caller\n // already wants to skip questions in that case, so log at info rather\n // than warn to keep dashboards clean.\n const aborted = options?.signal?.aborted ?? false;\n if (aborted) {\n logger.info(\"QuestionGenerator aborted by signal\", {\n reason: options?.signal?.reason instanceof Error ? options.signal.reason.message : String(options?.signal?.reason ?? \"unknown\"),\n });\n } else {\n logger.warn(\"QuestionGenerator LLM call failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n return null;\n }\n\n const parsed = QuestionGeneratorResponseSchema.safeParse(raw);\n if (!parsed.success) {\n logger.warn(\"QuestionGenerator parse failed\", { error: parsed.error.message });\n return null;\n }\n\n const filtered = applyGuardrails(parsed.data.questions);\n if (filtered.length === 0) return null;\n\n return {\n questions: filtered.map(stripStrategy),\n strategies: filtered.map((q) => q.strategy),\n };\n }\n}\n\n/**\n * Guardrail pipeline. Order matters:\n * 1. Dedup by title (keep first occurrence). Title uniqueness is a hard UX\n * requirement for the renderer — two questions cannot share a chip label.\n * 2. Strategy diversity: cap same-strategy entries at MAX_SAME_STRATEGY,\n * dropping overflow unconditionally (does NOT depend on whether a\n * distinct-strategy alternative exists in the batch). The cap exists to\n * enforce the \"never 3 of the same kind\" guidance from the spec.\n */\nfunction applyGuardrails(questions: QuestionWithStrategy[]): QuestionWithStrategy[] {\n const dedupedByTitle = dedupByTitle(questions);\n return enforceStrategyDiversity(dedupedByTitle);\n}\n\nfunction dedupByTitle(questions: QuestionWithStrategy[]): QuestionWithStrategy[] {\n const seen = new Set<string>();\n const out: QuestionWithStrategy[] = [];\n for (const q of questions) {\n if (seen.has(q.title)) continue;\n seen.add(q.title);\n out.push(q);\n }\n return out;\n}\n\n/**\n * Enforce the \"never 3 same-strategy\" rule. Walks the array in order; once a\n * given strategy has appeared MAX_SAME_STRATEGY times, subsequent entries with\n * the same strategy are dropped. Distinct-strategy entries are always kept\n * (subject to the schema's overall 3-question cap, which has already applied).\n */\nfunction enforceStrategyDiversity(\n questions: QuestionWithStrategy[],\n): QuestionWithStrategy[] {\n const counts = new Map<QuestionStrategy, number>();\n const out: QuestionWithStrategy[] = [];\n for (const q of questions) {\n const n = counts.get(q.strategy) ?? 0;\n if (n >= MAX_SAME_STRATEGY) continue;\n counts.set(q.strategy, n + 1);\n out.push(q);\n }\n return out;\n}\n\nfunction stripStrategy(q: QuestionWithStrategy): Question {\n const { strategy: _strategy, ...publicShape } = q;\n return publicShape;\n}\n"]}
1
+ {"version":3,"file":"question.generator.js","sourceRoot":"/","sources":["opportunity/question.generator.ts"],"names":[],"mappings":";;;;;;;;;AAgBA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEvE,OAAO,EAAE,+BAA+B,EAAkG,MAAM,sCAAsC,CAAC;AACvL,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAA+B,MAAM,sBAAsB,CAAC;AAEvG,MAAM,MAAM,GAAG,cAAc,CAAC,mBAAmB,CAAC,CAAC;AAEnD,oEAAoE;AACpE,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAE5B,oFAAoF;AACpF,MAAM,OAAO,iBAAiB;IAG5B;QACE,MAAM,GAAG,GAAG,WAAW,CAAC,4BAA4B,CAAC,CAAC;QACtD,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,oBAAoB,CAAC,+BAA+B,EAAE;YACrE,IAAI,EAAE,sBAAsB;SAC7B,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;OAUG;IAEG,AAAN,KAAK,CAAC,QAAQ,CACZ,KAA6B,EAC7B,OAAkC;QAElC,MAAM,IAAI,GAAG,mBAAmB,CAAC,KAAK,CAAC,CAAC;QAExC,IAAI,GAAY,CAAC;QACjB,IAAI,CAAC;YACH,GAAG,GAAG,MAAM,qBAAqB,CAC/B,IAAI,CAAC,KAAK,EACV,CAAC,IAAI,aAAa,CAAC,aAAa,CAAC,EAAE,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC,EAC1D,OAAO,EAAE,MAAM,CAChB,CAAC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S,EAAE,GAAG,WAAW,EAAE,GAAG,CAAC,CAAC;IAClD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["/**\n * @deprecated Use QuestionerAgent instead. Will be removed in a future version.\n *\n * QuestionGenerator — pure LLM pass that turns a structured DiscoveryQuestionInput\n * into 0–3 decision questions. No DB, no events, no caller wired here; Slice 3\n * (opportunity.discover.ts) is the first consumer.\n *\n * Flow:\n * 1. buildQuestionPrompt(input) → user message string.\n * 2. model.invoke([system, user]) returns a structured payload.\n * 3. safeParse via QuestionGeneratorResponseSchema → null on failure.\n * 4. Guardrails: dedup by title, then strategy-diversity (never 3 same).\n * 5. If empty, return null. Otherwise split into public Question[] + parallel\n * QuestionStrategy[] (debug-only; strategy is NEVER on the public shape).\n */\nimport type { ChatOpenAI } from \"@langchain/openai\";\nimport { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\n\nimport { QuestionGeneratorResponseSchema, type Question, type QuestionGenerationResult, type QuestionStrategy, type QuestionWithStrategy } from \"../shared/schemas/question.schema.js\";\nimport { createModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport { SYSTEM_PROMPT, buildQuestionPrompt, type DiscoveryQuestionInput } from \"./question.prompt.js\";\n\nconst logger = protocolLogger(\"QuestionGenerator\");\n\n/** Maximum same-strategy questions allowed in a single emission. */\nconst MAX_SAME_STRATEGY = 2;\n\n/** @deprecated Use QuestionerAgent instead. Will be removed in a future version. */\nexport class QuestionGenerator {\n private model: ReturnType<ChatOpenAI[\"withStructuredOutput\"]>;\n\n constructor() {\n const llm = createModel(\"discoveryQuestionGenerator\");\n this.model = llm.withStructuredOutput(QuestionGeneratorResponseSchema, {\n name: \"clarifying_questions\",\n });\n }\n\n /**\n * Generate up to 3 decision questions from the given discovery turn.\n *\n * @param input Discovery turn payload.\n * @param options.signal Optional AbortSignal. Passed to LangChain so an\n * aborted call cancels the underlying HTTP fetch instead of leaving a\n * floating promise burning OpenRouter capacity.\n * @returns A result with parallel questions[] and strategies[] arrays,\n * or null when the LLM fails, the output is malformed, the call was\n * aborted, or the guardrails leave zero questions standing.\n */\n @Timed()\n async generate(\n input: DiscoveryQuestionInput,\n options?: { signal?: AbortSignal },\n ): Promise<QuestionGenerationResult | null> {\n const user = buildQuestionPrompt(input);\n\n let raw: unknown;\n try {\n raw = await invokeWithAbortSignal(\n this.model,\n [new SystemMessage(SYSTEM_PROMPT), new HumanMessage(user)],\n options?.signal,\n );\n } catch (err) {\n // AbortError is the expected outcome under deadline pressure — caller\n // already wants to skip questions in that case, so log at info rather\n // than warn to keep dashboards clean.\n const aborted = options?.signal?.aborted ?? false;\n if (aborted) {\n logger.info(\"QuestionGenerator aborted by signal\", {\n reason: options?.signal?.reason instanceof Error ? options.signal.reason.message : String(options?.signal?.reason ?? \"unknown\"),\n });\n } else {\n logger.warn(\"QuestionGenerator LLM call failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n return null;\n }\n\n const parsed = QuestionGeneratorResponseSchema.safeParse(raw);\n if (!parsed.success) {\n logger.warn(\"QuestionGenerator parse failed\", { error: parsed.error.message });\n return null;\n }\n\n const filtered = applyGuardrails(parsed.data.questions);\n if (filtered.length === 0) return null;\n\n return {\n questions: filtered.map(stripStrategy),\n strategies: filtered.map((q) => q.strategy),\n };\n }\n}\n\n/**\n * Guardrail pipeline. Order matters:\n * 1. Dedup by title (keep first occurrence). Title uniqueness is a hard UX\n * requirement for the renderer — two questions cannot share a chip label.\n * 2. Strategy diversity: cap same-strategy entries at MAX_SAME_STRATEGY,\n * dropping overflow unconditionally (does NOT depend on whether a\n * distinct-strategy alternative exists in the batch). The cap exists to\n * enforce the \"never 3 of the same kind\" guidance from the spec.\n */\nfunction applyGuardrails(questions: QuestionWithStrategy[]): QuestionWithStrategy[] {\n const dedupedByTitle = dedupByTitle(questions);\n return enforceStrategyDiversity(dedupedByTitle);\n}\n\nfunction dedupByTitle(questions: QuestionWithStrategy[]): QuestionWithStrategy[] {\n const seen = new Set<string>();\n const out: QuestionWithStrategy[] = [];\n for (const q of questions) {\n if (seen.has(q.title)) continue;\n seen.add(q.title);\n out.push(q);\n }\n return out;\n}\n\n/**\n * Enforce the \"never 3 same-strategy\" rule. Walks the array in order; once a\n * given strategy has appeared MAX_SAME_STRATEGY times, subsequent entries with\n * the same strategy are dropped. Distinct-strategy entries are always kept\n * (subject to the schema's overall 3-question cap, which has already applied).\n */\nfunction enforceStrategyDiversity(\n questions: QuestionWithStrategy[],\n): QuestionWithStrategy[] {\n const counts = new Map<QuestionStrategy, number>();\n const out: QuestionWithStrategy[] = [];\n for (const q of questions) {\n const n = counts.get(q.strategy) ?? 0;\n if (n >= MAX_SAME_STRATEGY) continue;\n counts.set(q.strategy, n + 1);\n out.push(q);\n }\n return out;\n}\n\nfunction stripStrategy(q: QuestionWithStrategy): Question {\n const { strategy: _strategy, ...publicShape } = q;\n return publicShape;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"premise.graph.d.ts","sourceRoot":"/","sources":["premise/premise.graph.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAOtD,OAAO,KAAK,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC;AACxG,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4CAA4C,CAAC;AAG3E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAItE;;GAEG;AACH,qBAAa,mBAAmB;IAE5B,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,cAAc;gBAFd,QAAQ,EAAE,oBAAoB,EAC9B,QAAQ,EAAE,QAAQ,EAClB,cAAc,GAAE,cAAqC;IAG/D;;;;OAIG;IACI,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BA6H0B,MAAM;gCAAkB,MAAM;;;;;CAuF3E"}
1
+ {"version":3,"file":"premise.graph.d.ts","sourceRoot":"/","sources":["premise/premise.graph.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAItD,OAAO,KAAK,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC;AACxG,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4CAA4C,CAAC;AAG3E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAItE;;GAEG;AACH,qBAAa,mBAAmB;IAE5B,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,cAAc;gBAFd,QAAQ,EAAE,oBAAoB,EAC9B,QAAQ,EAAE,QAAQ,EAClB,cAAc,GAAE,cAAqC;IAG/D;;;;OAIG;IACI,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BA6H0B,MAAM;gCAAkB,MAAM;;;;;CAuF3E"}
@@ -2,7 +2,7 @@ import { StateGraph, START, END } from "@langchain/langgraph";
2
2
  import { PremiseGraphState } from "./premise.state.js";
3
3
  import { PremiseAnalyzer } from "./premise.analyzer.js";
4
4
  import { PremiseIndexer } from "./premise.indexer.js";
5
- import { buildNetworkAssignmentDecision, resolveAssignmentNetworkScope, } from "../shared/assignment/network-assignment.policy.js";
5
+ import { buildNetworkAssignmentDecision, resolveAssignmentNetworkScope } from "../shared/assignment/network-assignment.policy.js";
6
6
  import { getAbortSignalConfig } from "../shared/agent/model-signal.js";
7
7
  import { protocolLogger } from "../shared/observability/protocol.logger.js";
8
8
  import { timed } from "../shared/observability/performance.js";
@@ -1 +1 @@
1
- {"version":3,"file":"premise.graph.js","sourceRoot":"/","sources":["premise/premise.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,EACL,8BAA8B,EAC9B,6BAA6B,GAC9B,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAGvE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAG/D,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAErD;;GAEG;AACH,MAAM,OAAO,mBAAmB;IAC9B,YACU,QAA8B,EAC9B,QAAkB,EAClB,iBAAiC,IAAI,cAAc,EAAE;QAFrD,aAAQ,GAAR,QAAQ,CAAsB;QAC9B,aAAQ,GAAR,QAAQ,CAAU;QAClB,mBAAc,GAAd,cAAc,CAAuC;IAC5D,CAAC;IAEJ;;;;OAIG;IACI,WAAW;QAChB,MAAM,QAAQ,GAAG,IAAI,eAAe,EAAE,CAAC;QACvC,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC;QAEpC,MAAM,SAAS,GAAG,KAAK,EAAE,KAAqC,EAAE,EAAE;YAChE,OAAO,KAAK,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AAG,EAAE,CAAC,CAAC;oBAChG,CAAC;gBACH,CAAC;gBAED,MAAM,CAAC,OAAO,CAAC,oCAAoC,WAAW,CAAC,MAAM,WAAW,CAAC,CAAC;gBAElF,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,YAAY,EAAE,CAAC;YAC3D,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,MAAM,WAAW,GAAG,CAAC,KAAqC,EAAE,EAAE;YAC5D,IAAI,KAAK,CAAC,KAAK;gBAAE,OAAO,KAAK,CAAC;YAC9B,IAAI,KAAK,CAAC,aAAa,KAAK,OAAO;gBAAE,OAAO,OAAO,CAAC;YACpD,OAAO,SAAS,CAAC;QACnB,CAAC,CAAC;QAEF,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,iBAAiB,CAAC;aAC5C,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC;aAC3B,OAAO,CAAC,SAAS,EAAE,WAAW,CAAC;aAC/B,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC;aAC3B,OAAO,CAAC,SAAS,EAAE,WAAW,CAAC;aAC/B,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC;aAC3B,mBAAmB,CAAC,KAAK,EAAE,WAAW,EAAE;YACvC,KAAK,EAAE,OAAO;YACd,OAAO,EAAE,SAAS;YAClB,GAAG,EAAE,GAAG;SACT,CAAC;aACD,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;aACrB,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC;aAC3B,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC;aAC3B,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC;aAC3B,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;QAEzB,OAAO,KAAK,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\n\nimport { PremiseGraphState } from \"./premise.state.js\";\nimport { PremiseAnalyzer } from \"./premise.analyzer.js\";\nimport { PremiseIndexer } from \"./premise.indexer.js\";\n\nimport {\n buildNetworkAssignmentDecision,\n resolveAssignmentNetworkScope,\n} from \"../shared/assignment/network-assignment.policy.js\";\nimport { getAbortSignalConfig } from \"../shared/agent/model-signal.js\";\nimport type { PremiseGraphDatabase, PremiseAnalysis } from \"../shared/interfaces/database.interface.js\";\nimport type { Embedder } from \"../shared/interfaces/embedder.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { timed } from \"../shared/observability/performance.js\";\nimport type { DebugMetaAgent } from \"../chat/chat-streaming.types.js\";\n\nconst logger = protocolLogger(\"PremiseGraphFactory\");\n\n/**\n * Graph factory for premise lifecycle: create, update, and query modes.\n */\nexport class PremiseGraphFactory {\n constructor(\n private database: PremiseGraphDatabase,\n private embedder: Embedder,\n private premiseIndexer: PremiseIndexer = new PremiseIndexer(),\n ) {}\n\n /**\n * Compiles and returns the premise lifecycle graph.\n *\n * @returns A compiled LangGraph graph handling create, update, and query modes.\n */\n public createGraph() {\n const analyzer = new PremiseAnalyzer();\n const indexer = this.premiseIndexer;\n\n const queryNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.query\", async () => {\n logger.verbose(`[PremiseGraph.query] Fetching premises for user ${state.userId}`);\n const premises = await this.database.getPremisesForUser(state.userId, 'ACTIVE');\n return {\n readResult: {\n premises,\n count: premises.length,\n },\n };\n });\n };\n\n const analyzeNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.analyze\", async () => {\n if (!state.assertionText) {\n return { error: \"assertionText is required for create/update mode\" };\n }\n\n logger.verbose(`[PremiseGraph.analyze] Analyzing: \"${state.assertionText.substring(0, 50)}...\"`);\n\n const start = Date.now();\n const result = await analyzer.invoke(state.assertionText);\n const timing: DebugMetaAgent = {\n name: \"premise-analyzer\",\n durationMs: Date.now() - start,\n };\n\n const analysis: PremiseAnalysis = {\n speechActType: result.speechActType,\n felicityAuthority: result.felicityAuthority,\n felicitySincerity: result.felicitySincerity,\n felicityClarity: result.felicityClarity,\n semanticEntropy: result.semanticEntropy,\n };\n\n return { analysis, agentTimings: [timing] };\n });\n };\n\n const embedNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.embed\", async () => {\n if (state.error) return {};\n\n if (!state.assertionText) {\n return { error: \"assertionText is required for embedding\" };\n }\n\n logger.verbose(`[PremiseGraph.embed] Generating embedding for premise`);\n\n // Embedder.generate returns number[] | number[][], cast for single string input\n const embedding = await this.embedder.generate(state.assertionText, undefined, getAbortSignalConfig()) as number[];\n return { embedding };\n });\n };\n\n const persistNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.persist\", async () => {\n if (state.error) return {};\n\n if (state.operationMode === 'update' && !state.targetPremiseId) {\n return { error: \"targetPremiseId is required for update mode\" };\n }\n\n if (state.operationMode === 'update' && state.targetPremiseId) {\n logger.verbose(`[PremiseGraph.persist] Updating premise ${state.targetPremiseId}`);\n\n const updated = await this.database.updatePremise(state.targetPremiseId, {\n assertion: {\n text: state.assertionText!,\n tier: state.tier,\n },\n analysis: state.analysis ?? undefined,\n validity: {\n validFrom: state.validFrom,\n validUntil: state.validUntil,\n volatile: state.volatile,\n },\n embedding: state.embedding,\n });\n return { premise: updated };\n }\n\n logger.verbose(`[PremiseGraph.persist] Creating new premise for user ${state.userId}`);\n\n const premise = await this.database.createPremise({\n userId: state.userId,\n assertion: {\n text: state.assertionText!,\n tier: state.tier,\n },\n provenance: {\n source: state.provenanceSource ?? 'explicit',\n sourceId: state.provenanceSourceId,\n confidence: state.provenanceConfidence ?? 1.0,\n timestamp: new Date().toISOString(),\n },\n analysis: state.analysis ?? undefined,\n validity: {\n validFrom: state.validFrom,\n validUntil: state.validUntil,\n volatile: state.volatile,\n },\n embedding: state.embedding,\n });\n return { premise };\n });\n };\n\n const indexNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.index\", async () => {\n if (!state.premise) return {};\n\n logger.verbose(`[PremiseGraph.index] Scoring premise against user networks`);\n\n const membershipNetworkIds = await this.database.getAssignmentNetworkIdsForUser(state.userId);\n const indexIds = resolveAssignmentNetworkScope({\n memberships: membershipNetworkIds,\n networkScopeId: state.networkScopeId,\n });\n const scope = state.networkScopeId ? \"network\" : \"global\";\n const assignments: Array<{ networkId: string; relevancyScore: number }> = [];\n const agentTimings: DebugMetaAgent[] = [];\n\n for (const networkId of indexIds) {\n try {\n const assignmentContext = await this.database.getNetworkAssignmentContext(networkId, state.userId);\n if (!assignmentContext) continue;\n const indexPrompt = assignmentContext.indexPrompt;\n const memberPrompt = assignmentContext.memberPrompt;\n const hasPrompts = !!indexPrompt?.trim() || !!memberPrompt?.trim();\n let rawScores: { indexScore?: number; memberScore?: number } | undefined;\n let reason: string | undefined;\n\n if (hasPrompts) {\n const start = Date.now();\n const result = await indexer.invoke({\n premiseText: state.assertionText!,\n indexPrompt: indexPrompt ?? \"\",\n memberPrompt: memberPrompt ?? undefined,\n });\n const timing: DebugMetaAgent = {\n name: \"premise-indexer\",\n durationMs: Date.now() - start,\n };\n rawScores = { indexScore: result.indexScore, memberScore: result.memberScore };\n reason = result.reasoning;\n agentTimings.push(timing);\n }\n\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"premise\",\n mode: \"automatic\",\n scope,\n indexPrompt,\n memberPrompt,\n rawScores,\n evaluator: \"premise-indexer\",\n source: \"premise-graph\",\n reason,\n createdAt: new Date().toISOString(),\n });\n\n if (decision.assigned) {\n await this.database.assignPremiseToNetwork(\n state.premise.id,\n networkId,\n decision.finalScore,\n decision.metadata,\n );\n assignments.push({ networkId, relevancyScore: decision.finalScore });\n }\n } catch (err) {\n logger.verbose(`[PremiseGraph.index] Failed to score network ${networkId}, skipping: ${err}`);\n }\n }\n\n logger.verbose(`[PremiseGraph.index] Assigned to ${assignments.length} networks`);\n\n return { networkAssignments: assignments, agentTimings };\n });\n };\n\n const routeByMode = (state: typeof PremiseGraphState.State) => {\n if (state.error) return \"end\";\n if (state.operationMode === 'query') return \"query\";\n return \"analyze\";\n };\n\n const graph = new StateGraph(PremiseGraphState)\n .addNode(\"query\", queryNode)\n .addNode(\"analyze\", analyzeNode)\n .addNode(\"embed\", embedNode)\n .addNode(\"persist\", persistNode)\n .addNode(\"index\", indexNode)\n .addConditionalEdges(START, routeByMode, {\n query: \"query\",\n analyze: \"analyze\",\n end: END,\n })\n .addEdge(\"query\", END)\n .addEdge(\"analyze\", \"embed\")\n .addEdge(\"embed\", \"persist\")\n .addEdge(\"persist\", \"index\")\n .addEdge(\"index\", END);\n\n return graph.compile();\n }\n}\n"]}
1
+ {"version":3,"file":"premise.graph.js","sourceRoot":"/","sources":["premise/premise.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,EAAE,8BAA8B,EAAE,6BAA6B,EAAE,MAAM,mDAAmD,CAAC;AAClI,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAGvE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAG/D,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAErD;;GAEG;AACH,MAAM,OAAO,mBAAmB;IAC9B,YACU,QAA8B,EAC9B,QAAkB,EAClB,iBAAiC,IAAI,cAAc,EAAE;QAFrD,aAAQ,GAAR,QAAQ,CAAsB;QAC9B,aAAQ,GAAR,QAAQ,CAAU;QAClB,mBAAc,GAAd,cAAc,CAAuC;IAC5D,CAAC;IAEJ;;;;OAIG;IACI,WAAW;QAChB,MAAM,QAAQ,GAAG,IAAI,eA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O,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\n\nimport { PremiseGraphState } from \"./premise.state.js\";\nimport { PremiseAnalyzer } from \"./premise.analyzer.js\";\nimport { PremiseIndexer } from \"./premise.indexer.js\";\n\nimport { buildNetworkAssignmentDecision, resolveAssignmentNetworkScope } from \"../shared/assignment/network-assignment.policy.js\";\nimport { getAbortSignalConfig } from \"../shared/agent/model-signal.js\";\nimport type { PremiseGraphDatabase, PremiseAnalysis } from \"../shared/interfaces/database.interface.js\";\nimport type { Embedder } from \"../shared/interfaces/embedder.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { timed } from \"../shared/observability/performance.js\";\nimport type { DebugMetaAgent } from \"../chat/chat-streaming.types.js\";\n\nconst logger = protocolLogger(\"PremiseGraphFactory\");\n\n/**\n * Graph factory for premise lifecycle: create, update, and query modes.\n */\nexport class PremiseGraphFactory {\n constructor(\n private database: PremiseGraphDatabase,\n private embedder: Embedder,\n private premiseIndexer: PremiseIndexer = new PremiseIndexer(),\n ) {}\n\n /**\n * Compiles and returns the premise lifecycle graph.\n *\n * @returns A compiled LangGraph graph handling create, update, and query modes.\n */\n public createGraph() {\n const analyzer = new PremiseAnalyzer();\n const indexer = this.premiseIndexer;\n\n const queryNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.query\", async () => {\n logger.verbose(`[PremiseGraph.query] Fetching premises for user ${state.userId}`);\n const premises = await this.database.getPremisesForUser(state.userId, 'ACTIVE');\n return {\n readResult: {\n premises,\n count: premises.length,\n },\n };\n });\n };\n\n const analyzeNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.analyze\", async () => {\n if (!state.assertionText) {\n return { error: \"assertionText is required for create/update mode\" };\n }\n\n logger.verbose(`[PremiseGraph.analyze] Analyzing: \"${state.assertionText.substring(0, 50)}...\"`);\n\n const start = Date.now();\n const result = await analyzer.invoke(state.assertionText);\n const timing: DebugMetaAgent = {\n name: \"premise-analyzer\",\n durationMs: Date.now() - start,\n };\n\n const analysis: PremiseAnalysis = {\n speechActType: result.speechActType,\n felicityAuthority: result.felicityAuthority,\n felicitySincerity: result.felicitySincerity,\n felicityClarity: result.felicityClarity,\n semanticEntropy: result.semanticEntropy,\n };\n\n return { analysis, agentTimings: [timing] };\n });\n };\n\n const embedNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.embed\", async () => {\n if (state.error) return {};\n\n if (!state.assertionText) {\n return { error: \"assertionText is required for embedding\" };\n }\n\n logger.verbose(`[PremiseGraph.embed] Generating embedding for premise`);\n\n // Embedder.generate returns number[] | number[][], cast for single string input\n const embedding = await this.embedder.generate(state.assertionText, undefined, getAbortSignalConfig()) as number[];\n return { embedding };\n });\n };\n\n const persistNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.persist\", async () => {\n if (state.error) return {};\n\n if (state.operationMode === 'update' && !state.targetPremiseId) {\n return { error: \"targetPremiseId is required for update mode\" };\n }\n\n if (state.operationMode === 'update' && state.targetPremiseId) {\n logger.verbose(`[PremiseGraph.persist] Updating premise ${state.targetPremiseId}`);\n\n const updated = await this.database.updatePremise(state.targetPremiseId, {\n assertion: {\n text: state.assertionText!,\n tier: state.tier,\n },\n analysis: state.analysis ?? undefined,\n validity: {\n validFrom: state.validFrom,\n validUntil: state.validUntil,\n volatile: state.volatile,\n },\n embedding: state.embedding,\n });\n return { premise: updated };\n }\n\n logger.verbose(`[PremiseGraph.persist] Creating new premise for user ${state.userId}`);\n\n const premise = await this.database.createPremise({\n userId: state.userId,\n assertion: {\n text: state.assertionText!,\n tier: state.tier,\n },\n provenance: {\n source: state.provenanceSource ?? 'explicit',\n sourceId: state.provenanceSourceId,\n confidence: state.provenanceConfidence ?? 1.0,\n timestamp: new Date().toISOString(),\n },\n analysis: state.analysis ?? undefined,\n validity: {\n validFrom: state.validFrom,\n validUntil: state.validUntil,\n volatile: state.volatile,\n },\n embedding: state.embedding,\n });\n return { premise };\n });\n };\n\n const indexNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.index\", async () => {\n if (!state.premise) return {};\n\n logger.verbose(`[PremiseGraph.index] Scoring premise against user networks`);\n\n const membershipNetworkIds = await this.database.getAssignmentNetworkIdsForUser(state.userId);\n const indexIds = resolveAssignmentNetworkScope({\n memberships: membershipNetworkIds,\n networkScopeId: state.networkScopeId,\n });\n const scope = state.networkScopeId ? \"network\" : \"global\";\n const assignments: Array<{ networkId: string; relevancyScore: number }> = [];\n const agentTimings: DebugMetaAgent[] = [];\n\n for (const networkId of indexIds) {\n try {\n const assignmentContext = await this.database.getNetworkAssignmentContext(networkId, state.userId);\n if (!assignmentContext) continue;\n const indexPrompt = assignmentContext.indexPrompt;\n const memberPrompt = assignmentContext.memberPrompt;\n const hasPrompts = !!indexPrompt?.trim() || !!memberPrompt?.trim();\n let rawScores: { indexScore?: number; memberScore?: number } | undefined;\n let reason: string | undefined;\n\n if (hasPrompts) {\n const start = Date.now();\n const result = await indexer.invoke({\n premiseText: state.assertionText!,\n indexPrompt: indexPrompt ?? \"\",\n memberPrompt: memberPrompt ?? undefined,\n });\n const timing: DebugMetaAgent = {\n name: \"premise-indexer\",\n durationMs: Date.now() - start,\n };\n rawScores = { indexScore: result.indexScore, memberScore: result.memberScore };\n reason = result.reasoning;\n agentTimings.push(timing);\n }\n\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"premise\",\n mode: \"automatic\",\n scope,\n indexPrompt,\n memberPrompt,\n rawScores,\n evaluator: \"premise-indexer\",\n source: \"premise-graph\",\n reason,\n createdAt: new Date().toISOString(),\n });\n\n if (decision.assigned) {\n await this.database.assignPremiseToNetwork(\n state.premise.id,\n networkId,\n decision.finalScore,\n decision.metadata,\n );\n assignments.push({ networkId, relevancyScore: decision.finalScore });\n }\n } catch (err) {\n logger.verbose(`[PremiseGraph.index] Failed to score network ${networkId}, skipping: ${err}`);\n }\n }\n\n logger.verbose(`[PremiseGraph.index] Assigned to ${assignments.length} networks`);\n\n return { networkAssignments: assignments, agentTimings };\n });\n };\n\n const routeByMode = (state: typeof PremiseGraphState.State) => {\n if (state.error) return \"end\";\n if (state.operationMode === 'query') return \"query\";\n return \"analyze\";\n };\n\n const graph = new StateGraph(PremiseGraphState)\n .addNode(\"query\", queryNode)\n .addNode(\"analyze\", analyzeNode)\n .addNode(\"embed\", embedNode)\n .addNode(\"persist\", persistNode)\n .addNode(\"index\", indexNode)\n .addConditionalEdges(START, routeByMode, {\n query: \"query\",\n analyze: \"analyze\",\n end: END,\n })\n .addEdge(\"query\", END)\n .addEdge(\"analyze\", \"embed\")\n .addEdge(\"embed\", \"persist\")\n .addEdge(\"persist\", \"index\")\n .addEdge(\"index\", END);\n\n return graph.compile();\n }\n}\n"]}
@@ -117,7 +117,7 @@ export class ProfileGraphFactory {
117
117
  const willNeedScraping = needsProfileGeneration && !hasMeaningfulInput;
118
118
  // If we need to scrape, check if we have sufficient user information
119
119
  let needsUserInfo = false;
120
- let missingUserInfo = [];
120
+ const missingUserInfo = [];
121
121
  if (willNeedScraping) {
122
122
  logger.verbose("Will need scraping - checking user information...");
123
123
  const user = await this.database.getUser(state.userId);