@indexnetwork/protocol 14.3.2-rc.477.1 → 17.0.0-rc.479.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +141 -0
- package/IMPLEMENTATION.md +50 -52
- package/STABILITY.md +3 -3
- package/dist/chat/chat.agent.js +2 -3
- package/dist/chat/chat.graph.d.ts +41 -1
- package/dist/chat/chat.graph.js +108 -127
- package/dist/chat/negotiator.persona.d.ts +1 -1
- package/dist/chat/negotiator.persona.js +1 -4
- package/dist/chat/negotiator.prompt.js +1 -2
- package/dist/chat/onboarding.persona.js +0 -1
- package/dist/chat/reporter.persona.js +0 -1
- package/dist/chat/signal.persona.js +0 -1
- package/dist/contacts/application/contact.tools.d.ts +6 -9
- package/dist/contacts/application/contact.tools.js +11 -92
- package/dist/contacts/application/index.d.ts +2 -14
- package/dist/contacts/application/index.js +2 -13
- package/dist/contacts/domain/contact.types.d.ts +0 -23
- package/dist/contacts/domain/index.d.ts +2 -6
- package/dist/contacts/index.d.ts +1 -1
- package/dist/contacts/index.js +1 -1
- package/dist/contacts/ports/contact.repository.port.d.ts +5 -12
- package/dist/contacts/ports/contact.repository.port.js +4 -6
- package/dist/contacts/ports/contact.tools.port.d.ts +1 -3
- package/dist/contacts/ports/contact.tools.port.js +1 -2
- package/dist/contacts/ports/index.d.ts +1 -1
- package/dist/contacts/ports/index.js +1 -1
- package/dist/discovery/hyde.frame.d.ts +4 -4
- package/dist/discovery/hyde.graph.d.ts +71 -12
- package/dist/discovery/hyde.graph.js +337 -335
- package/dist/discovery/lens.inferrer.d.ts +6 -6
- package/dist/enrichment/enrichment.graph.d.ts +127 -9
- package/dist/enrichment/enrichment.graph.js +633 -655
- package/dist/enrichment/enrichment.state.d.ts +1 -1
- package/dist/enrichment/enrichment.tools.context-read.d.ts +10 -0
- package/dist/enrichment/enrichment.tools.context-read.js +353 -0
- package/dist/enrichment/enrichment.tools.context-write.d.ts +9 -0
- package/dist/enrichment/enrichment.tools.context-write.js +417 -0
- package/dist/enrichment/enrichment.tools.d.ts +11 -1
- package/dist/enrichment/enrichment.tools.helpers.d.ts +139 -0
- package/dist/enrichment/enrichment.tools.helpers.js +234 -0
- package/dist/enrichment/enrichment.tools.js +16 -975
- package/dist/index.d.ts +27 -50
- package/dist/index.js +17 -28
- package/dist/intents/application/intent.graph.d.ts +71 -67
- package/dist/intents/application/intent.graph.execute.d.ts +59 -0
- package/dist/intents/application/intent.graph.execute.js +301 -0
- package/dist/intents/application/intent.graph.infer.d.ts +44 -0
- package/dist/intents/application/intent.graph.infer.js +97 -0
- package/dist/intents/application/intent.graph.js +96 -888
- package/dist/intents/application/intent.graph.reconcile.d.ts +71 -0
- package/dist/intents/application/intent.graph.reconcile.js +274 -0
- package/dist/intents/application/intent.graph.shared.d.ts +70 -0
- package/dist/intents/application/intent.graph.shared.js +153 -0
- package/dist/intents/domain/intent.state.d.ts +1 -1
- package/dist/maintenance/maintenance.graph.d.ts +66 -3
- package/dist/maintenance/maintenance.graph.js +155 -156
- package/dist/mcp/mcp.authorization-policy.d.ts +24 -28
- package/dist/mcp/mcp.authorization-policy.js +14 -34
- package/dist/mcp/mcp.server.d.ts +3 -3
- package/dist/mcp/mcp.server.js +14 -20
- package/dist/negotiations/application/negotiation.candidates.d.ts +83 -0
- package/dist/negotiations/application/negotiation.candidates.js +162 -0
- package/dist/negotiations/application/negotiation.graph.d.ts +91 -157
- package/dist/negotiations/application/negotiation.graph.finalize.d.ts +5 -0
- package/dist/negotiations/application/negotiation.graph.finalize.js +280 -0
- package/dist/negotiations/application/negotiation.graph.init.d.ts +54 -0
- package/dist/negotiations/application/negotiation.graph.init.js +227 -0
- package/dist/negotiations/application/negotiation.graph.js +69 -1388
- package/dist/negotiations/application/negotiation.graph.screen.d.ts +23 -0
- package/dist/negotiations/application/negotiation.graph.screen.js +108 -0
- package/dist/negotiations/application/negotiation.graph.shared.d.ts +75 -0
- package/dist/negotiations/application/negotiation.graph.shared.js +125 -0
- package/dist/negotiations/application/negotiation.graph.turn.d.ts +105 -0
- package/dist/negotiations/application/negotiation.graph.turn.js +484 -0
- package/dist/negotiations/domain/negotiation.state.d.ts +1 -1
- package/dist/negotiations/domain/negotiation.state.js +0 -1
- package/dist/networks/application/indexer.graph.d.ts +165 -7
- package/dist/networks/application/indexer.graph.js +339 -388
- package/dist/networks/application/indexer.state.d.ts +1 -1
- package/dist/networks/application/membership.graph.d.ts +83 -5
- package/dist/networks/application/membership.graph.js +177 -207
- package/dist/networks/application/network.graph.d.ts +148 -5
- package/dist/networks/application/network.graph.js +249 -278
- package/dist/networks/domain/membership.state.d.ts +1 -1
- package/dist/networks/domain/network.state.d.ts +1 -1
- package/dist/opportunities/application/delivery-card.cache.d.ts +1 -1
- package/dist/opportunities/application/delivery-card.cache.js +2 -2
- package/dist/opportunities/application/index.d.ts +2 -2
- package/dist/opportunities/application/index.js +2 -2
- package/dist/opportunities/application/opportunity.evaluator.js +1 -1
- package/dist/opportunities/application/opportunity.graph.d.ts +686 -473
- package/dist/opportunities/application/opportunity.graph.discovery-strategies.d.ts +109 -0
- package/dist/opportunities/application/opportunity.graph.discovery-strategies.js +451 -0
- package/dist/opportunities/application/opportunity.graph.discovery.d.ts +69 -0
- package/dist/opportunities/application/opportunity.graph.discovery.js +397 -0
- package/dist/opportunities/application/opportunity.graph.evaluation.d.ts +82 -0
- package/dist/opportunities/application/opportunity.graph.evaluation.js +608 -0
- package/dist/opportunities/application/opportunity.graph.js +120 -3690
- package/dist/opportunities/application/opportunity.graph.modes.d.ts +538 -0
- package/dist/opportunities/application/opportunity.graph.modes.js +538 -0
- package/dist/opportunities/application/opportunity.graph.negotiate.d.ts +109 -0
- package/dist/opportunities/application/opportunity.graph.negotiate.js +392 -0
- package/dist/opportunities/application/opportunity.graph.persist-node.d.ts +93 -0
- package/dist/opportunities/application/opportunity.graph.persist-node.js +765 -0
- package/dist/opportunities/application/opportunity.graph.prep.d.ts +150 -0
- package/dist/opportunities/application/opportunity.graph.prep.js +381 -0
- package/dist/opportunities/application/opportunity.graph.shared.d.ts +173 -0
- package/dist/opportunities/application/opportunity.graph.shared.js +199 -0
- package/dist/opportunities/application/opportunity.presentation.d.ts +399 -0
- package/dist/opportunities/application/{opportunity.presenter.js → opportunity.presentation.js} +735 -9
- package/dist/opportunities/application/opportunity.tools.cards.d.ts +152 -0
- package/dist/opportunities/application/opportunity.tools.cards.js +235 -0
- package/dist/opportunities/application/opportunity.tools.d.ts +8 -114
- package/dist/opportunities/application/opportunity.tools.js +28 -711
- package/dist/opportunities/application/opportunity.tools.list.d.ts +10 -0
- package/dist/opportunities/application/opportunity.tools.list.js +493 -0
- package/dist/opportunities/domain/index.d.ts +3 -3
- package/dist/opportunities/domain/index.js +3 -3
- package/dist/opportunities/domain/opportunity.state.d.ts +19 -19
- package/dist/opportunities/index.d.ts +6 -6
- package/dist/opportunities/index.js +4 -4
- package/dist/opportunities/ports/opportunity.tools.port.d.ts +1 -1
- package/dist/opportunities/radar/radar.graph.d.ts +57 -13
- package/dist/opportunities/radar/radar.graph.js +470 -471
- package/dist/premises/premise.graph.d.ts +88 -20
- package/dist/premises/premise.graph.js +207 -218
- package/dist/questions/domain/question.schema.d.ts +40 -40
- package/dist/shared/agent/tool.factory.js +0 -8
- package/dist/shared/agent/tool.helpers.d.ts +21 -45
- package/dist/shared/agent/tool.helpers.js +1 -2
- package/dist/shared/agent/tool.registry.d.ts +4 -3
- package/dist/shared/agent/tool.registry.js +2 -4
- package/dist/shared/agent/tool.runtime.js +0 -2
- package/dist/shared/agent/utility.tools.js +9 -13
- package/dist/shared/interfaces/database.capabilities.d.ts +100 -0
- package/dist/shared/interfaces/database.capabilities.js +7 -0
- package/dist/shared/interfaces/database.entities.d.ts +533 -0
- package/dist/shared/interfaces/database.entities.js +10 -0
- package/dist/shared/interfaces/database.identity-queries.d.ts +294 -0
- package/dist/shared/interfaces/database.identity-queries.js +4 -0
- package/dist/shared/interfaces/database.interface.d.ts +15 -2277
- package/dist/shared/interfaces/database.interface.js +8 -0
- package/dist/shared/interfaces/database.member-queries.d.ts +221 -0
- package/dist/shared/interfaces/database.member-queries.js +4 -0
- package/dist/shared/interfaces/database.negotiation.d.ts +305 -0
- package/dist/shared/interfaces/database.negotiation.js +26 -0
- package/dist/shared/interfaces/database.network-queries.d.ts +277 -0
- package/dist/shared/interfaces/database.network-queries.js +4 -0
- package/dist/shared/interfaces/database.opportunity-queries.d.ts +285 -0
- package/dist/shared/interfaces/database.opportunity-queries.js +4 -0
- package/dist/shared/interfaces/database.port.d.ts +322 -0
- package/dist/shared/interfaces/database.port.js +29 -0
- package/dist/shared/schemas/discovery-question.schema.d.ts +14 -14
- package/dist/shared/schemas/negotiation-digest.schema.d.ts +2 -2
- package/package.json +2 -15
- package/dist/contacts/application/contact.inviter.d.ts +0 -49
- package/dist/contacts/application/contact.inviter.js +0 -64
- package/dist/integrations/application/index.d.ts +0 -14
- package/dist/integrations/application/index.js +0 -14
- package/dist/integrations/application/integration.tools.d.ts +0 -27
- package/dist/integrations/application/integration.tools.js +0 -98
- package/dist/integrations/domain/index.d.ts +0 -16
- package/dist/integrations/domain/index.js +0 -1
- package/dist/integrations/domain/integration.types.d.ts +0 -51
- package/dist/integrations/domain/integration.types.js +0 -9
- package/dist/integrations/index.d.ts +0 -10
- package/dist/integrations/index.js +0 -8
- package/dist/integrations/ports/index.d.ts +0 -25
- package/dist/integrations/ports/index.js +0 -23
- package/dist/integrations/ports/integration.adapter.port.d.ts +0 -62
- package/dist/integrations/ports/integration.adapter.port.js +0 -15
- package/dist/integrations/ports/integration.importer.port.d.ts +0 -31
- package/dist/integrations/ports/integration.importer.port.js +0 -15
- package/dist/integrations/ports/integration.tools.port.d.ts +0 -25
- package/dist/integrations/ports/integration.tools.port.js +0 -18
- package/dist/opportunities/application/opportunity.card-presentation.d.ts +0 -44
- package/dist/opportunities/application/opportunity.card-presentation.js +0 -93
- package/dist/opportunities/application/opportunity.presenter.d.ts +0 -156
- package/dist/opportunities/domain/opportunity.presentation-cache.d.ts +0 -5
- package/dist/opportunities/domain/opportunity.presentation-cache.js +0 -11
- package/dist/opportunities/domain/opportunity.presentation.d.ts +0 -76
- package/dist/opportunities/domain/opportunity.presentation.js +0 -516
- package/dist/opportunities/domain/opportunity.safe-presentation.d.ts +0 -104
- package/dist/opportunities/domain/opportunity.safe-presentation.js +0 -102
|
@@ -0,0 +1,765 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Discovery pipeline, stage 6: persistence.
|
|
3
|
+
*
|
|
4
|
+
* Three persistence paths share the node — chat introductions, introducer
|
|
5
|
+
* discovery (`onBehalfOfUserId`), and plain discovery. Each one decides whether
|
|
6
|
+
* an existing opportunity between the same people should be reactivated,
|
|
7
|
+
* upgraded, or suppressed before any row is written; only what survives that
|
|
8
|
+
* gate reaches `persistOpportunities`.
|
|
9
|
+
*/
|
|
10
|
+
import { timed } from '../../shared/observability/performance.js';
|
|
11
|
+
import { validateOpportunityActors } from '../domain/opportunity.utils.js';
|
|
12
|
+
import { hasUnsupportedOpportunityClaim } from '../../shared/utils/claim-safety.js';
|
|
13
|
+
import { normalizeOpportunityActorIntent } from '../domain/opportunity.actor.js';
|
|
14
|
+
import { persistOpportunities } from './opportunity.persist.js';
|
|
15
|
+
import { INTRODUCER_DISCOVERY_SOURCE } from './opportunity.introducer.js';
|
|
16
|
+
import { stampEligibleNewbornOpportunities } from './opportunity.newborn-stamping.js';
|
|
17
|
+
import { admitOpportunityPersistence, createEligibleOpportunityStatusUpdater } from './opportunity.persistence-admission.js';
|
|
18
|
+
import { belongsToOwnedIntent, DEDUP_WINDOW_MS, isActiveNegotiationTaskFresh, persistDedupLog, persistLog, persistPathLog, triggerForOwner } from './opportunity.graph.shared.js';
|
|
19
|
+
/**
|
|
20
|
+
* Only skip 'draft' (chat-only) opportunities during dedup.
|
|
21
|
+
* 'latent' must NOT be skipped — background discovery creates latent opportunities,
|
|
22
|
+
* and excluding them causes the same user pair to get duplicate opportunities
|
|
23
|
+
* when multiple intents trigger separate discovery jobs (IND-166).
|
|
24
|
+
*/
|
|
25
|
+
const DEDUP_SKIP_STATUSES = ['draft'];
|
|
26
|
+
/**
|
|
27
|
+
* Node 5: Persist
|
|
28
|
+
* Creates opportunities from evaluator-proposed actors (networkId, userId, role, optional intent).
|
|
29
|
+
*/
|
|
30
|
+
export async function persistNode(state, deps) {
|
|
31
|
+
return timed("OpportunityGraph.persist", async () => {
|
|
32
|
+
const startTime = Date.now();
|
|
33
|
+
const initialStatus = state.options.initialStatus ?? 'pending';
|
|
34
|
+
persistLog.verbose('Starting persistence (dedup-v2)', {
|
|
35
|
+
opportunitiesToCreate: state.evaluatedOpportunities.length,
|
|
36
|
+
initialStatus,
|
|
37
|
+
});
|
|
38
|
+
if (state.evaluatedOpportunities.length === 0) {
|
|
39
|
+
persistLog.verbose('No opportunities to persist', {
|
|
40
|
+
triggerIntentId: state.triggerIntentId,
|
|
41
|
+
reason: state.candidates.length === 0 ? 'no_search_candidates' : 'evaluator_rejected_all',
|
|
42
|
+
});
|
|
43
|
+
return {
|
|
44
|
+
opportunities: [],
|
|
45
|
+
persistenceOutcome: {
|
|
46
|
+
evaluatedCount: 0,
|
|
47
|
+
createdCount: 0,
|
|
48
|
+
reactivatedCount: 0,
|
|
49
|
+
sameTriggerDuplicateSuppressions: 0,
|
|
50
|
+
pairActiveNegotiationSuppressions: 0,
|
|
51
|
+
crossTriggerAllowedCount: 0,
|
|
52
|
+
finalAtomicConflictCount: 0,
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const finalTriggerIntentId = state.triggerIntentId;
|
|
58
|
+
const admission = await admitOpportunityPersistence(deps.database, {
|
|
59
|
+
ownerUserId: state.userId,
|
|
60
|
+
triggerIntentId: finalTriggerIntentId,
|
|
61
|
+
networkId: state.networkId,
|
|
62
|
+
indexScope: state.indexScope,
|
|
63
|
+
evaluatedOpportunities: state.evaluatedOpportunities,
|
|
64
|
+
});
|
|
65
|
+
if (admission.kind === 'empty_scope') {
|
|
66
|
+
persistLog.info('Skipped persistence because final discovery scope is empty', {
|
|
67
|
+
userId: state.userId,
|
|
68
|
+
triggerIntentId: finalTriggerIntentId,
|
|
69
|
+
});
|
|
70
|
+
return { opportunities: [] };
|
|
71
|
+
}
|
|
72
|
+
const { allowedNetworkIds: finalAllowedNetworkIds, networkEligibility, evaluatedOpportunities: evaluatedToPersist } = admission;
|
|
73
|
+
if (evaluatedToPersist.length < state.evaluatedOpportunities.length) {
|
|
74
|
+
persistLog.info('Skipped opportunities with inactive participant network pairs', {
|
|
75
|
+
before: state.evaluatedOpportunities.length,
|
|
76
|
+
after: evaluatedToPersist.length,
|
|
77
|
+
removed: state.evaluatedOpportunities.length - evaluatedToPersist.length,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
if (evaluatedToPersist.length === 0)
|
|
81
|
+
return { opportunities: [] };
|
|
82
|
+
const updateStatusIfStillEligible = createEligibleOpportunityStatusUpdater(deps.database, finalAllowedNetworkIds, networkEligibility, {
|
|
83
|
+
onUnavailableAdapter: () => {
|
|
84
|
+
persistLog.error('Network-eligible status update adapter is unavailable; failing closed');
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
const ledger = { reactivated: [], existingBetweenActors: [], crossTriggerAllowedCount: 0 };
|
|
88
|
+
const ctx = {
|
|
89
|
+
state,
|
|
90
|
+
deps,
|
|
91
|
+
ledger,
|
|
92
|
+
updateStatusIfStillEligible,
|
|
93
|
+
initialStatus,
|
|
94
|
+
now: new Date().toISOString(),
|
|
95
|
+
};
|
|
96
|
+
const itemsToPersist = [];
|
|
97
|
+
const introducerUserForOnBehalf = state.onBehalfOfUserId
|
|
98
|
+
? await deps.database.getUser(state.userId)
|
|
99
|
+
: null;
|
|
100
|
+
for (const evaluated of evaluatedToPersist) {
|
|
101
|
+
persistPathLog.verbose('Selecting persistence path', {
|
|
102
|
+
isIntroduction: !!state.introductionContext,
|
|
103
|
+
stateUserId: state.userId,
|
|
104
|
+
stateIndexId: state.networkId,
|
|
105
|
+
evaluatedActorUserIds: evaluated.actors.map(a => a.userId),
|
|
106
|
+
});
|
|
107
|
+
const data = state.introductionContext
|
|
108
|
+
? buildIntroductionOpportunity(ctx, evaluated)
|
|
109
|
+
: state.onBehalfOfUserId
|
|
110
|
+
? await buildIntroducerDiscoveryOpportunity(ctx, evaluated, introducerUserForOnBehalf?.name ?? undefined)
|
|
111
|
+
: await buildDiscoveryOpportunity(ctx, evaluated);
|
|
112
|
+
if (!data)
|
|
113
|
+
continue;
|
|
114
|
+
if (hasUnsupportedOpportunityClaim(data.interpretation.reasoning)) {
|
|
115
|
+
persistLog.warn('Skipping opportunity with unsupported affiliation/presence claim at persistence boundary', {
|
|
116
|
+
source: data.detection.source,
|
|
117
|
+
triggerIntentId: data.detection.triggeredBy,
|
|
118
|
+
});
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
validateOpportunityActors(data.actors);
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
persistLog.warn('Skipping opportunity with invalid actors', {
|
|
126
|
+
error: err instanceof Error ? err.message : String(err),
|
|
127
|
+
opportunityReasoning: evaluated.reasoning?.slice(0, 80),
|
|
128
|
+
});
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
itemsToPersist.push(data);
|
|
132
|
+
}
|
|
133
|
+
const itemsForPersistence = await stampEligibleNewbornOpportunities(itemsToPersist, {
|
|
134
|
+
ownerUserId: state.userId,
|
|
135
|
+
operationMode: state.operationMode,
|
|
136
|
+
hasIntroductionContext: Boolean(state.introductionContext),
|
|
137
|
+
onBehalfOfUserId: state.onBehalfOfUserId,
|
|
138
|
+
targetUserId: state.targetUserId,
|
|
139
|
+
discoverySource: state.discoverySource,
|
|
140
|
+
resolvedTriggerIntentId: state.resolvedTriggerIntentId,
|
|
141
|
+
indexedIntentIds: state.indexedIntents.map((intent) => intent.intentId),
|
|
142
|
+
}, deps.stampNewbornOpportunities, {
|
|
143
|
+
onUnsafeResult: ({ expected, actual }) => {
|
|
144
|
+
persistLog.warn('Newborn stamper returned unsafe length/order; persisting originals', { expected, actual });
|
|
145
|
+
},
|
|
146
|
+
onFailure: ({ intentId, error }) => {
|
|
147
|
+
persistLog.warn('Newborn stamper failed; persisting originals', {
|
|
148
|
+
intentId,
|
|
149
|
+
error: error instanceof Error ? error.message : String(error),
|
|
150
|
+
});
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
const intentDedupScope = finalTriggerIntentId && state.discoverySource === 'intent'
|
|
154
|
+
? { triggerIntentId: finalTriggerIntentId, dedupWindowMs: DEDUP_WINDOW_MS }
|
|
155
|
+
: undefined;
|
|
156
|
+
const { created: createdList, conflicts } = await persistOpportunities({
|
|
157
|
+
database: deps.database,
|
|
158
|
+
embedder: deps.embedder,
|
|
159
|
+
items: itemsForPersistence,
|
|
160
|
+
networkEligibility,
|
|
161
|
+
intentDedupScope,
|
|
162
|
+
});
|
|
163
|
+
for (const conflict of conflicts) {
|
|
164
|
+
const item = itemsForPersistence[conflict.itemIndex];
|
|
165
|
+
const candidateActor = item?.actors.find((actor) => actor.userId !== state.userId);
|
|
166
|
+
if (!candidateActor)
|
|
167
|
+
continue;
|
|
168
|
+
ledger.existingBetweenActors.push({
|
|
169
|
+
candidateUserId: candidateActor.userId,
|
|
170
|
+
networkId: candidateActor.networkId,
|
|
171
|
+
existingOpportunityId: conflict.existingOpportunityId,
|
|
172
|
+
existingStatus: conflict.existingStatus,
|
|
173
|
+
reason: conflict.reason,
|
|
174
|
+
...(conflict.existingTriggerIntentId
|
|
175
|
+
? { existingTriggerIntentId: conflict.existingTriggerIntentId }
|
|
176
|
+
: {}),
|
|
177
|
+
});
|
|
178
|
+
persistDedupLog.info('Final atomic persistence conflict', {
|
|
179
|
+
triggerIntentId: finalTriggerIntentId,
|
|
180
|
+
candidateUserId: candidateActor.userId,
|
|
181
|
+
existingOpportunityId: conflict.existingOpportunityId,
|
|
182
|
+
existingTriggerIntentId: conflict.existingTriggerIntentId,
|
|
183
|
+
existingStatus: conflict.existingStatus,
|
|
184
|
+
existingAgeMs: Date.now() - new Date(conflict.existingCreatedAt).getTime(),
|
|
185
|
+
reason: conflict.reason,
|
|
186
|
+
finalAtomic: true,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
const allOpportunities = [...ledger.reactivated, ...createdList];
|
|
190
|
+
persistLog.verbose('Persistence complete', {
|
|
191
|
+
created: createdList.length,
|
|
192
|
+
reactivated: ledger.reactivated.length,
|
|
193
|
+
existingBetweenActorsCount: ledger.existingBetweenActors.length,
|
|
194
|
+
status: initialStatus,
|
|
195
|
+
});
|
|
196
|
+
const persistenceOutcome = {
|
|
197
|
+
evaluatedCount: state.evaluatedOpportunities.length,
|
|
198
|
+
createdCount: createdList.length,
|
|
199
|
+
reactivatedCount: ledger.reactivated.length,
|
|
200
|
+
sameTriggerDuplicateSuppressions: ledger.existingBetweenActors.filter((entry) => entry.reason === 'same_trigger_recent_duplicate').length,
|
|
201
|
+
pairActiveNegotiationSuppressions: ledger.existingBetweenActors.filter((entry) => entry.reason === 'pair_active_negotiation').length,
|
|
202
|
+
crossTriggerAllowedCount: ledger.crossTriggerAllowedCount,
|
|
203
|
+
finalAtomicConflictCount: conflicts.length,
|
|
204
|
+
};
|
|
205
|
+
return {
|
|
206
|
+
opportunities: allOpportunities,
|
|
207
|
+
existingBetweenActors: ledger.existingBetweenActors,
|
|
208
|
+
persistenceOutcome,
|
|
209
|
+
trace: [{
|
|
210
|
+
node: "persist",
|
|
211
|
+
detail: `Created ${createdList.length}, reactivated ${ledger.reactivated.length}, ${ledger.existingBetweenActors.length} existing skipped`,
|
|
212
|
+
data: {
|
|
213
|
+
created: createdList.length,
|
|
214
|
+
reactivated: ledger.reactivated.length,
|
|
215
|
+
existingSkipped: ledger.existingBetweenActors.length,
|
|
216
|
+
totalOutput: allOpportunities.length,
|
|
217
|
+
persistenceOutcome,
|
|
218
|
+
durationMs: Date.now() - startTime,
|
|
219
|
+
},
|
|
220
|
+
}],
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
const errMsg = error instanceof Error ? error.message : String(error);
|
|
225
|
+
persistLog.error('Failed', { error });
|
|
226
|
+
return {
|
|
227
|
+
opportunities: [],
|
|
228
|
+
existingBetweenActors: [],
|
|
229
|
+
error: 'Failed to persist opportunities.',
|
|
230
|
+
trace: [{
|
|
231
|
+
node: "persist_fatal",
|
|
232
|
+
detail: `Persist failed: ${errMsg}`,
|
|
233
|
+
data: { error: errMsg },
|
|
234
|
+
}],
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
/** Map evaluator actors onto opportunity actors, defaulting the network. */
|
|
240
|
+
function toOpportunityActors(evaluated, fallbackNetworkId, premiseLookup) {
|
|
241
|
+
return evaluated.actors.map((a) => {
|
|
242
|
+
const intent = normalizeOpportunityActorIntent(a.intentId);
|
|
243
|
+
return {
|
|
244
|
+
networkId: a.networkId ?? fallbackNetworkId,
|
|
245
|
+
userId: a.userId,
|
|
246
|
+
role: a.role,
|
|
247
|
+
...(intent ? { intent: intent } : {}),
|
|
248
|
+
...(premiseLookup?.has(a.userId) ? { premise: premiseLookup.get(a.userId).premiseId } : {}),
|
|
249
|
+
};
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
/** Append the viewer as an unapproved introducer unless the evaluator already placed them. */
|
|
253
|
+
function withIntroducerActor(evaluatorActors, viewerUserId, networkId) {
|
|
254
|
+
return evaluatorActors.some(a => a.userId === viewerUserId)
|
|
255
|
+
? evaluatorActors
|
|
256
|
+
: [...evaluatorActors, { networkId, userId: viewerUserId, role: 'introducer', approved: false }];
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Introduction path: manual detection, introducer actor, curator_judgment signal.
|
|
260
|
+
*/
|
|
261
|
+
function buildIntroductionOpportunity(ctx, evaluated) {
|
|
262
|
+
const { state, initialStatus, now } = ctx;
|
|
263
|
+
const indexIdForActors = state.networkId ?? evaluated.actors[0]?.networkId;
|
|
264
|
+
if (indexIdForActors === undefined) {
|
|
265
|
+
persistLog.warn('Introduction path missing networkId; skipping opportunity', {
|
|
266
|
+
userId: state.userId,
|
|
267
|
+
actorsCount: evaluated.actors.length,
|
|
268
|
+
});
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
const actors = withIntroducerActor(toOpportunityActors(evaluated, indexIdForActors), state.userId, indexIdForActors);
|
|
272
|
+
return {
|
|
273
|
+
detection: {
|
|
274
|
+
source: 'manual',
|
|
275
|
+
createdBy: state.userId,
|
|
276
|
+
createdByName: state.introductionContext.createdByName,
|
|
277
|
+
timestamp: now,
|
|
278
|
+
},
|
|
279
|
+
actors,
|
|
280
|
+
interpretation: {
|
|
281
|
+
category: 'collaboration',
|
|
282
|
+
reasoning: evaluated.reasoning,
|
|
283
|
+
confidence: evaluated.score / 100,
|
|
284
|
+
signals: [
|
|
285
|
+
{
|
|
286
|
+
type: 'curator_judgment',
|
|
287
|
+
weight: 1,
|
|
288
|
+
detail: `Introduction by ${state.introductionContext.createdByName ?? 'a member'} via chat`,
|
|
289
|
+
},
|
|
290
|
+
],
|
|
291
|
+
},
|
|
292
|
+
context: {
|
|
293
|
+
networkId: state.networkId ?? indexIdForActors,
|
|
294
|
+
...(state.options.conversationId ? { conversationId: state.options.conversationId } : {}),
|
|
295
|
+
},
|
|
296
|
+
confidence: String(evaluated.score / 100),
|
|
297
|
+
status: initialStatus,
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Introducer discovery path: introducer is state.userId, target is onBehalfOfUserId.
|
|
302
|
+
*/
|
|
303
|
+
async function buildIntroducerDiscoveryOpportunity(ctx, evaluated, introducerName) {
|
|
304
|
+
const { state, deps, ledger, updateStatusIfStillEligible, initialStatus, now } = ctx;
|
|
305
|
+
const indexIdForActors = state.networkId ?? evaluated.actors[0]?.networkId;
|
|
306
|
+
if (indexIdForActors === undefined) {
|
|
307
|
+
persistLog.warn('Introducer discovery path missing networkId; skipping opportunity', {
|
|
308
|
+
userId: state.userId,
|
|
309
|
+
actorsCount: evaluated.actors.length,
|
|
310
|
+
});
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
const actors = withIntroducerActor(toOpportunityActors(evaluated, indexIdForActors), state.userId, indexIdForActors);
|
|
314
|
+
const candidateUserId = evaluated.actors.find((a) => a.userId !== state.onBehalfOfUserId)?.userId;
|
|
315
|
+
const overlapping = candidateUserId
|
|
316
|
+
? await deps.database.findOpportunitiesByActors([state.onBehalfOfUserId, candidateUserId], { excludeStatuses: DEDUP_SKIP_STATUSES })
|
|
317
|
+
: [];
|
|
318
|
+
if (overlapping.length > 0) {
|
|
319
|
+
const existing = overlapping[0];
|
|
320
|
+
const isRecent = new Date(existing.createdAt).getTime() > Date.now() - DEDUP_WINDOW_MS;
|
|
321
|
+
const sameIntroducer = existing.actors?.some((actor) => actor.role === 'introducer' && actor.userId === state.userId);
|
|
322
|
+
const suppressionNetworkId = (state.networkId ?? indexIdForActors ?? '');
|
|
323
|
+
if (existing.status === 'expired' || existing.status === 'stalled') {
|
|
324
|
+
// Reactivate expired or stalled opportunities (only if same introducer for expired).
|
|
325
|
+
// A different introducer creating for an expired pair falls through to new creation —
|
|
326
|
+
// the prior expiry belongs to the original introducer, not this one.
|
|
327
|
+
// Stalled opportunities are reactivated regardless of age: a stalled negotiation
|
|
328
|
+
// is still in-flight for this pair, so we resume it rather than create a parallel one.
|
|
329
|
+
if (existing.status === 'stalled' || sameIntroducer) {
|
|
330
|
+
// Introduction path always targets 'draft' (chat-only surface) rather than using
|
|
331
|
+
// initialStatus, because introductions are always chat-initiated, not background-discovered.
|
|
332
|
+
const reactivated = await updateStatusIfStillEligible(existing.id, 'draft', existing.actors, existing.status);
|
|
333
|
+
if (reactivated) {
|
|
334
|
+
persistLog.verbose('Reactivated opportunity (introduction path)', {
|
|
335
|
+
opportunityId: existing.id,
|
|
336
|
+
candidateUserId,
|
|
337
|
+
previousStatus: existing.status,
|
|
338
|
+
});
|
|
339
|
+
ledger.reactivated.push(reactivated);
|
|
340
|
+
}
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
else if (existing.status === 'negotiating') {
|
|
345
|
+
// Orphan heal (introduction path): same logic as discovery path
|
|
346
|
+
const priorTask = await deps.database.getNegotiationTaskForOpportunity(existing.id);
|
|
347
|
+
if (priorTask && isActiveNegotiationTaskFresh(priorTask)) {
|
|
348
|
+
ledger.existingBetweenActors.push({
|
|
349
|
+
candidateUserId: candidateUserId,
|
|
350
|
+
networkId: suppressionNetworkId,
|
|
351
|
+
existingOpportunityId: existing.id,
|
|
352
|
+
existingStatus: existing.status,
|
|
353
|
+
});
|
|
354
|
+
persistLog.verbose('Skipping negotiating opportunity with active task (introduction path)', {
|
|
355
|
+
opportunityId: existing.id,
|
|
356
|
+
candidateUserId,
|
|
357
|
+
taskState: priorTask.state,
|
|
358
|
+
});
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
const reactivated = await updateStatusIfStillEligible(existing.id, 'draft', existing.actors, existing.status);
|
|
362
|
+
if (reactivated) {
|
|
363
|
+
persistLog.info('Resuming orphaned negotiating opportunity (introduction path)', {
|
|
364
|
+
opportunityId: existing.id,
|
|
365
|
+
candidateUserId,
|
|
366
|
+
priorTaskState: priorTask?.state,
|
|
367
|
+
});
|
|
368
|
+
ledger.reactivated.push(reactivated);
|
|
369
|
+
}
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
else if (existing.status === 'latent') {
|
|
373
|
+
// Upgrade latent to draft for introduction path
|
|
374
|
+
const upgraded = await updateStatusIfStillEligible(existing.id, 'draft', existing.actors, existing.status);
|
|
375
|
+
if (upgraded) {
|
|
376
|
+
persistLog.verbose('Upgraded latent opportunity to draft (introduction path)', {
|
|
377
|
+
opportunityId: existing.id,
|
|
378
|
+
candidateUserId,
|
|
379
|
+
});
|
|
380
|
+
ledger.reactivated.push(upgraded);
|
|
381
|
+
}
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
else if (isRecent && candidateUserId) {
|
|
385
|
+
// Time-gated skip: only skip if opportunity was created within DEDUP_WINDOW_MS
|
|
386
|
+
ledger.existingBetweenActors.push({
|
|
387
|
+
candidateUserId: candidateUserId,
|
|
388
|
+
networkId: suppressionNetworkId,
|
|
389
|
+
existingOpportunityId: existing.id,
|
|
390
|
+
existingStatus: existing.status,
|
|
391
|
+
});
|
|
392
|
+
persistLog.verbose('Skipping recent duplicate (introduction path)', {
|
|
393
|
+
candidateUserId,
|
|
394
|
+
existingStatus: existing.status,
|
|
395
|
+
existingOpportunityId: existing.id,
|
|
396
|
+
});
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
// Else: existing opportunity is old enough, allow new opportunity creation
|
|
400
|
+
persistLog.verbose('Allowing new opportunity; existing is outside dedup window (introduction path)', {
|
|
401
|
+
candidateUserId,
|
|
402
|
+
existingStatus: existing.status,
|
|
403
|
+
existingOpportunityId: existing.id,
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
return {
|
|
407
|
+
detection: {
|
|
408
|
+
source: INTRODUCER_DISCOVERY_SOURCE,
|
|
409
|
+
createdBy: state.userId,
|
|
410
|
+
createdByName: introducerName,
|
|
411
|
+
timestamp: now,
|
|
412
|
+
},
|
|
413
|
+
actors,
|
|
414
|
+
interpretation: {
|
|
415
|
+
category: 'collaboration',
|
|
416
|
+
reasoning: evaluated.reasoning,
|
|
417
|
+
confidence: evaluated.score / 100,
|
|
418
|
+
signals: [{
|
|
419
|
+
type: 'curator_judgment',
|
|
420
|
+
weight: 1,
|
|
421
|
+
detail: `Introducer discovery for ${introducerName ?? 'a member'} via background maintenance`,
|
|
422
|
+
}],
|
|
423
|
+
},
|
|
424
|
+
context: {
|
|
425
|
+
networkId: state.networkId ?? indexIdForActors,
|
|
426
|
+
...(state.options.conversationId ? { conversationId: state.options.conversationId } : {}),
|
|
427
|
+
},
|
|
428
|
+
confidence: String(evaluated.score / 100),
|
|
429
|
+
status: initialStatus,
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Discovery path: opportunity_graph source, no introducer, lifecycle guard for agent/patient.
|
|
434
|
+
*/
|
|
435
|
+
async function buildDiscoveryOpportunity(ctx, evaluated) {
|
|
436
|
+
const { state, initialStatus, now } = ctx;
|
|
437
|
+
const indexIdForActors = state.networkId ?? evaluated.actors[0]?.networkId;
|
|
438
|
+
// Build premise lookup from discovery candidates for premise tracking.
|
|
439
|
+
// When multiple premise candidates exist for the same user, keep the highest-similarity one.
|
|
440
|
+
const premiseLookup = new Map();
|
|
441
|
+
for (const c of state.candidates ?? []) {
|
|
442
|
+
if (c.candidatePremiseId) {
|
|
443
|
+
const existing = premiseLookup.get(c.candidateUserId);
|
|
444
|
+
if (!existing || c.similarity > existing.similarity) {
|
|
445
|
+
premiseLookup.set(c.candidateUserId, { premiseId: c.candidatePremiseId, similarity: c.similarity });
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
const actors = toOpportunityActors(evaluated, indexIdForActors, premiseLookup);
|
|
450
|
+
applyDiscovererLifecycleSwap(actors, state.userId);
|
|
451
|
+
const suppressed = await suppressDiscoveryDuplicate(ctx, evaluated);
|
|
452
|
+
if (suppressed)
|
|
453
|
+
return null;
|
|
454
|
+
return {
|
|
455
|
+
detection: {
|
|
456
|
+
source: 'opportunity_graph',
|
|
457
|
+
createdBy: 'agent-opportunity-finder',
|
|
458
|
+
...(state.discoverySource === 'intent' && state.resolvedTriggerIntentId
|
|
459
|
+
? { triggeredBy: state.resolvedTriggerIntentId }
|
|
460
|
+
: {}),
|
|
461
|
+
timestamp: now,
|
|
462
|
+
},
|
|
463
|
+
actors,
|
|
464
|
+
interpretation: {
|
|
465
|
+
category: 'collaboration',
|
|
466
|
+
reasoning: evaluated.reasoning,
|
|
467
|
+
confidence: evaluated.score / 100,
|
|
468
|
+
signals: [
|
|
469
|
+
{
|
|
470
|
+
type: evaluated.actors.some((a) => a.intentId) ? 'intent_match' : 'profile_match',
|
|
471
|
+
weight: evaluated.score / 100,
|
|
472
|
+
detail: 'Entity-bundle evaluator',
|
|
473
|
+
},
|
|
474
|
+
],
|
|
475
|
+
},
|
|
476
|
+
context: {
|
|
477
|
+
...(state.networkId ? { networkId: state.networkId } : {}),
|
|
478
|
+
...(state.options.conversationId ? { conversationId: state.options.conversationId } : {}),
|
|
479
|
+
},
|
|
480
|
+
confidence: String(evaluated.score / 100),
|
|
481
|
+
status: initialStatus,
|
|
482
|
+
metadata: {
|
|
483
|
+
evidence: evaluated.evidence ?? [],
|
|
484
|
+
},
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* The discoverer must be the patient so the opportunity shows up in their
|
|
489
|
+
* lifecycle view; swap roles with the counterpart when the evaluator put them
|
|
490
|
+
* in the agent seat. Introduced opportunities keep the evaluator's roles.
|
|
491
|
+
*/
|
|
492
|
+
function applyDiscovererLifecycleSwap(actors, discovererUserId) {
|
|
493
|
+
if (actors.some(a => a.role === 'introducer'))
|
|
494
|
+
return;
|
|
495
|
+
const discovererIdx = actors.findIndex(a => a.userId === discovererUserId);
|
|
496
|
+
if (discovererIdx < 0 || actors[discovererIdx].role !== 'agent')
|
|
497
|
+
return;
|
|
498
|
+
const counterpartIdx = actors.findIndex((a, i) => i !== discovererIdx && a.role === 'patient');
|
|
499
|
+
actors[discovererIdx] = { ...actors[discovererIdx], role: 'patient' };
|
|
500
|
+
if (counterpartIdx >= 0) {
|
|
501
|
+
actors[counterpartIdx] = { ...actors[counterpartIdx], role: 'agent' };
|
|
502
|
+
}
|
|
503
|
+
persistLog.verbose('Swapped discoverer from agent to patient for lifecycle visibility', {
|
|
504
|
+
discovererId: discovererUserId,
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Index-agnostic dedup: find ANY existing opportunity between these users,
|
|
509
|
+
* regardless of which index it was created in or whether a focused network
|
|
510
|
+
* scope is set. Returns true when the pairing must not be persisted.
|
|
511
|
+
*/
|
|
512
|
+
async function suppressDiscoveryDuplicate(ctx, evaluated) {
|
|
513
|
+
const { state, deps, ledger, updateStatusIfStillEligible, initialStatus } = ctx;
|
|
514
|
+
const candidateUserId = evaluated.actors.find((a) => a.userId !== state.userId)?.userId;
|
|
515
|
+
persistDedupLog.verbose('Checking overlapping opportunities', {
|
|
516
|
+
stateUserId: state.userId,
|
|
517
|
+
candidateUserId: candidateUserId ?? 'NONE',
|
|
518
|
+
evaluatedActors: evaluated.actors.map(a => ({ userId: a.userId, role: a.role })),
|
|
519
|
+
});
|
|
520
|
+
const overlapping = candidateUserId
|
|
521
|
+
? await deps.database.findOpportunitiesByActors([state.userId, candidateUserId], { excludeStatuses: DEDUP_SKIP_STATUSES })
|
|
522
|
+
: [];
|
|
523
|
+
persistDedupLog.verbose('findOpportunitiesByActors result', {
|
|
524
|
+
count: overlapping.length,
|
|
525
|
+
results: overlapping.map(o => ({ id: o.id, status: o.status, actors: o.actors?.map((a) => ({ userId: a.userId, role: a.role })) })),
|
|
526
|
+
});
|
|
527
|
+
const ownedIntentTriggerId = state.discoverySource === 'intent'
|
|
528
|
+
&& state.triggerIntentId
|
|
529
|
+
&& state.resolvedTriggerIntentId === state.triggerIntentId
|
|
530
|
+
? state.triggerIntentId
|
|
531
|
+
: undefined;
|
|
532
|
+
if (ownedIntentTriggerId && candidateUserId) {
|
|
533
|
+
return suppressOwnedIntentDuplicate(ctx, overlapping, candidateUserId, ownedIntentTriggerId);
|
|
534
|
+
}
|
|
535
|
+
if (overlapping.length === 0)
|
|
536
|
+
return false;
|
|
537
|
+
const existing = overlapping[0];
|
|
538
|
+
const existingIndexId = (existing.context?.networkId ?? state.networkId ?? state.userNetworks?.[0] ?? '');
|
|
539
|
+
const isRecent = new Date(existing.createdAt).getTime() > Date.now() - DEDUP_WINDOW_MS;
|
|
540
|
+
if (existing.status === 'expired' || existing.status === 'stalled') {
|
|
541
|
+
// Reactivate expired or stalled opportunities.
|
|
542
|
+
// Stalled opportunities are reactivated regardless of age: a stalled negotiation
|
|
543
|
+
// is still in-flight for this pair, so we resume it rather than create a parallel one.
|
|
544
|
+
const reactivated = await updateStatusIfStillEligible(existing.id, initialStatus, existing.actors, existing.status);
|
|
545
|
+
if (reactivated) {
|
|
546
|
+
persistLog.verbose('Reactivated opportunity', {
|
|
547
|
+
opportunityId: existing.id,
|
|
548
|
+
candidateUserId,
|
|
549
|
+
previousStatus: existing.status,
|
|
550
|
+
newStatus: initialStatus,
|
|
551
|
+
});
|
|
552
|
+
ledger.reactivated.push(reactivated);
|
|
553
|
+
}
|
|
554
|
+
return true;
|
|
555
|
+
}
|
|
556
|
+
if (existing.status === 'negotiating') {
|
|
557
|
+
// Orphan heal: if a prior opportunity is stuck in 'negotiating' with a stale task,
|
|
558
|
+
// reactivate it so the new discovery run can reuse it instead of creating a duplicate.
|
|
559
|
+
const priorTask = await deps.database.getNegotiationTaskForOpportunity(existing.id);
|
|
560
|
+
if (priorTask && isActiveNegotiationTaskFresh(priorTask)) {
|
|
561
|
+
// Still active — skip (lock gate in init node will handle)
|
|
562
|
+
ledger.existingBetweenActors.push({
|
|
563
|
+
candidateUserId: candidateUserId,
|
|
564
|
+
networkId: existingIndexId,
|
|
565
|
+
existingOpportunityId: existing.id,
|
|
566
|
+
existingStatus: existing.status,
|
|
567
|
+
});
|
|
568
|
+
persistLog.verbose('Skipping negotiating opportunity with active task', {
|
|
569
|
+
opportunityId: existing.id,
|
|
570
|
+
candidateUserId,
|
|
571
|
+
taskState: priorTask.state,
|
|
572
|
+
});
|
|
573
|
+
return true;
|
|
574
|
+
}
|
|
575
|
+
// Task is stale or missing — reactivate the orphaned negotiating opportunity
|
|
576
|
+
const reactivated = await updateStatusIfStillEligible(existing.id, initialStatus, existing.actors, existing.status);
|
|
577
|
+
if (reactivated) {
|
|
578
|
+
persistLog.info('Resuming orphaned negotiating opportunity', {
|
|
579
|
+
opportunityId: existing.id,
|
|
580
|
+
candidateUserId,
|
|
581
|
+
priorTaskState: priorTask?.state,
|
|
582
|
+
});
|
|
583
|
+
ledger.reactivated.push(reactivated);
|
|
584
|
+
}
|
|
585
|
+
return true;
|
|
586
|
+
}
|
|
587
|
+
if (existing.status === 'latent' && initialStatus !== 'latent') {
|
|
588
|
+
// Upgrade latent (background-discovered) to the higher-priority status (e.g. pending)
|
|
589
|
+
const upgraded = await updateStatusIfStillEligible(existing.id, initialStatus, existing.actors, existing.status);
|
|
590
|
+
if (upgraded) {
|
|
591
|
+
persistLog.verbose('Upgraded latent opportunity to higher-priority status', {
|
|
592
|
+
opportunityId: existing.id,
|
|
593
|
+
candidateUserId,
|
|
594
|
+
previousStatus: 'latent',
|
|
595
|
+
newStatus: initialStatus,
|
|
596
|
+
});
|
|
597
|
+
ledger.reactivated.push(upgraded);
|
|
598
|
+
}
|
|
599
|
+
return true;
|
|
600
|
+
}
|
|
601
|
+
if (isRecent && candidateUserId) {
|
|
602
|
+
// Time-gated skip: only skip if opportunity was created within DEDUP_WINDOW_MS
|
|
603
|
+
// This prevents parallel job duplicates while allowing new discoveries for long-connected pairs
|
|
604
|
+
ledger.existingBetweenActors.push({
|
|
605
|
+
candidateUserId: candidateUserId,
|
|
606
|
+
networkId: existingIndexId,
|
|
607
|
+
existingOpportunityId: existing.id,
|
|
608
|
+
existingStatus: existing.status,
|
|
609
|
+
});
|
|
610
|
+
persistLog.verbose('Skipping recent duplicate; opportunity created within dedup window', {
|
|
611
|
+
candidateUserId,
|
|
612
|
+
existingStatus: existing.status,
|
|
613
|
+
existingOpportunityId: existing.id,
|
|
614
|
+
createdAt: existing.createdAt,
|
|
615
|
+
});
|
|
616
|
+
return true;
|
|
617
|
+
}
|
|
618
|
+
// Else: existing opportunity is old enough (outside the 30-day dedup window), allow new opportunity creation
|
|
619
|
+
persistLog.verbose('Allowing new opportunity; existing is outside dedup window', {
|
|
620
|
+
candidateUserId,
|
|
621
|
+
existingStatus: existing.status,
|
|
622
|
+
existingOpportunityId: existing.id,
|
|
623
|
+
createdAt: existing.createdAt,
|
|
624
|
+
});
|
|
625
|
+
return false;
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Dedup for a discovery run triggered by an intent the owner still holds.
|
|
629
|
+
* A pair-global active negotiation always wins; otherwise only opportunities
|
|
630
|
+
* carrying the *same* trigger intent can suppress this one.
|
|
631
|
+
*/
|
|
632
|
+
async function suppressOwnedIntentDuplicate(ctx, overlapping, candidateUserId, ownedIntentTriggerId) {
|
|
633
|
+
const { state, deps, ledger, updateStatusIfStillEligible, initialStatus } = ctx;
|
|
634
|
+
let activeNegotiation;
|
|
635
|
+
for (const opportunity of overlapping) {
|
|
636
|
+
if (opportunity.status !== 'negotiating')
|
|
637
|
+
continue;
|
|
638
|
+
const task = await deps.database.getNegotiationTaskForOpportunity(opportunity.id);
|
|
639
|
+
if (task && isActiveNegotiationTaskFresh(task)) {
|
|
640
|
+
activeNegotiation = { opportunity, taskState: task.state };
|
|
641
|
+
break;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
if (activeNegotiation) {
|
|
645
|
+
const existingTriggerIntentId = triggerForOwner(activeNegotiation.opportunity, state.userId);
|
|
646
|
+
ledger.existingBetweenActors.push({
|
|
647
|
+
candidateUserId,
|
|
648
|
+
networkId: (activeNegotiation.opportunity.context?.networkId ?? state.networkId ?? state.userNetworks?.[0] ?? ''),
|
|
649
|
+
existingOpportunityId: activeNegotiation.opportunity.id,
|
|
650
|
+
existingStatus: activeNegotiation.opportunity.status,
|
|
651
|
+
reason: 'pair_active_negotiation',
|
|
652
|
+
...(existingTriggerIntentId ? { existingTriggerIntentId } : {}),
|
|
653
|
+
});
|
|
654
|
+
persistDedupLog.info('Suppressing owned-intent match for pair-global active negotiation', {
|
|
655
|
+
triggerIntentId: ownedIntentTriggerId,
|
|
656
|
+
candidateUserId,
|
|
657
|
+
existingOpportunityId: activeNegotiation.opportunity.id,
|
|
658
|
+
existingTriggerIntentId,
|
|
659
|
+
existingStatus: activeNegotiation.opportunity.status,
|
|
660
|
+
existingAgeMs: Date.now() - new Date(activeNegotiation.opportunity.createdAt).getTime(),
|
|
661
|
+
taskState: activeNegotiation.taskState,
|
|
662
|
+
reason: 'pair_active_negotiation',
|
|
663
|
+
});
|
|
664
|
+
return true;
|
|
665
|
+
}
|
|
666
|
+
const sameTrigger = overlapping
|
|
667
|
+
.filter((opportunity) => belongsToOwnedIntent(opportunity, state.userId, ownedIntentTriggerId))
|
|
668
|
+
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
|
669
|
+
const otherTrigger = overlapping.filter((opportunity) => !belongsToOwnedIntent(opportunity, state.userId, ownedIntentTriggerId));
|
|
670
|
+
const existing = sameTrigger[0];
|
|
671
|
+
if (!existing) {
|
|
672
|
+
if (otherTrigger.length > 0) {
|
|
673
|
+
ledger.crossTriggerAllowedCount += 1;
|
|
674
|
+
persistDedupLog.info('Allowing cross-trigger match for owned intent', {
|
|
675
|
+
triggerIntentId: ownedIntentTriggerId,
|
|
676
|
+
candidateUserId,
|
|
677
|
+
reason: 'cross_trigger_match_allowed',
|
|
678
|
+
otherTriggers: otherTrigger.map((opportunity) => ({
|
|
679
|
+
opportunityId: opportunity.id,
|
|
680
|
+
triggerIntentId: triggerForOwner(opportunity, state.userId),
|
|
681
|
+
status: opportunity.status,
|
|
682
|
+
ageMs: Date.now() - new Date(opportunity.createdAt).getTime(),
|
|
683
|
+
})),
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
return false;
|
|
687
|
+
}
|
|
688
|
+
const existingIndexId = (existing.context?.networkId ?? state.networkId ?? state.userNetworks?.[0] ?? '');
|
|
689
|
+
const isRecent = new Date(existing.createdAt).getTime() > Date.now() - DEDUP_WINDOW_MS;
|
|
690
|
+
if (existing.status === 'expired' || existing.status === 'stalled') {
|
|
691
|
+
const reactivated = await updateStatusIfStillEligible(existing.id, initialStatus, existing.actors, existing.status);
|
|
692
|
+
if (reactivated) {
|
|
693
|
+
persistLog.info('Reactivated same-trigger opportunity', {
|
|
694
|
+
triggerIntentId: ownedIntentTriggerId,
|
|
695
|
+
opportunityId: existing.id,
|
|
696
|
+
candidateUserId,
|
|
697
|
+
previousStatus: existing.status,
|
|
698
|
+
newStatus: initialStatus,
|
|
699
|
+
});
|
|
700
|
+
ledger.reactivated.push(reactivated);
|
|
701
|
+
}
|
|
702
|
+
return true;
|
|
703
|
+
}
|
|
704
|
+
if (existing.status === 'negotiating') {
|
|
705
|
+
const reactivated = await updateStatusIfStillEligible(existing.id, initialStatus, existing.actors, existing.status);
|
|
706
|
+
if (reactivated) {
|
|
707
|
+
persistLog.info('Resuming same-trigger orphaned negotiating opportunity', {
|
|
708
|
+
triggerIntentId: ownedIntentTriggerId,
|
|
709
|
+
opportunityId: existing.id,
|
|
710
|
+
candidateUserId,
|
|
711
|
+
});
|
|
712
|
+
ledger.reactivated.push(reactivated);
|
|
713
|
+
}
|
|
714
|
+
return true;
|
|
715
|
+
}
|
|
716
|
+
if (existing.status === 'latent' && initialStatus !== 'latent') {
|
|
717
|
+
const upgraded = await updateStatusIfStillEligible(existing.id, initialStatus, existing.actors, existing.status);
|
|
718
|
+
if (upgraded) {
|
|
719
|
+
persistLog.info('Upgraded same-trigger latent opportunity', {
|
|
720
|
+
triggerIntentId: ownedIntentTriggerId,
|
|
721
|
+
opportunityId: existing.id,
|
|
722
|
+
candidateUserId,
|
|
723
|
+
newStatus: initialStatus,
|
|
724
|
+
});
|
|
725
|
+
ledger.reactivated.push(upgraded);
|
|
726
|
+
}
|
|
727
|
+
return true;
|
|
728
|
+
}
|
|
729
|
+
if (isRecent) {
|
|
730
|
+
ledger.existingBetweenActors.push({
|
|
731
|
+
candidateUserId,
|
|
732
|
+
networkId: existingIndexId,
|
|
733
|
+
existingOpportunityId: existing.id,
|
|
734
|
+
existingStatus: existing.status,
|
|
735
|
+
reason: 'same_trigger_recent_duplicate',
|
|
736
|
+
existingTriggerIntentId: ownedIntentTriggerId,
|
|
737
|
+
});
|
|
738
|
+
persistDedupLog.info('Suppressing recent same-trigger duplicate', {
|
|
739
|
+
triggerIntentId: ownedIntentTriggerId,
|
|
740
|
+
candidateUserId,
|
|
741
|
+
existingOpportunityId: existing.id,
|
|
742
|
+
existingTriggerIntentId: ownedIntentTriggerId,
|
|
743
|
+
existingStatus: existing.status,
|
|
744
|
+
existingAgeMs: Date.now() - new Date(existing.createdAt).getTime(),
|
|
745
|
+
reason: 'same_trigger_recent_duplicate',
|
|
746
|
+
});
|
|
747
|
+
return true;
|
|
748
|
+
}
|
|
749
|
+
persistDedupLog.info('Allowing same-trigger opportunity outside dedup window', {
|
|
750
|
+
triggerIntentId: ownedIntentTriggerId,
|
|
751
|
+
candidateUserId,
|
|
752
|
+
existingOpportunityId: existing.id,
|
|
753
|
+
existingStatus: existing.status,
|
|
754
|
+
existingAgeMs: Date.now() - new Date(existing.createdAt).getTime(),
|
|
755
|
+
});
|
|
756
|
+
return false;
|
|
757
|
+
}
|
|
758
|
+
/** Trace summary for {@link persistNode}. */
|
|
759
|
+
export function persistTraceSummary(result) {
|
|
760
|
+
const r = result;
|
|
761
|
+
if (r?.error)
|
|
762
|
+
return `error: ${r.error}`;
|
|
763
|
+
const opps = r?.opportunities;
|
|
764
|
+
return opps ? `Persisted ${opps.length} opportunity(ies)` : undefined;
|
|
765
|
+
}
|