@saptools/service-flow 0.1.48 → 0.1.49

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.
@@ -5,13 +5,13 @@ import { resolveOperation } from '../linker/service-resolver.js';
5
5
  import type { ImplementationHint, TraceEdge, TraceResult, TraceStart } from '../types.js';
6
6
  import { baseTraceEvidence, edgeTarget, runtimeResolution, runtimeVariableDiagnostic, type TraceGraphRow } from './evidence.js';
7
7
  import { implementationHintDiagnostic, selectImplementation, type ImplementationSelection } from './implementation-hints.js';
8
-
9
8
  interface RepoRef {
10
9
  id: number;
11
10
  name: string;
12
11
  }
13
12
  interface StartScope {
14
13
  repo?: RepoRef;
14
+ executionRepoId?: number;
15
15
  sourceFiles?: Set<string>;
16
16
  symbolIds?: Set<number>;
17
17
  selectorMatched: boolean;
@@ -40,7 +40,7 @@ interface GraphRow extends Record<string, unknown> {
40
40
  status?: string;
41
41
  }
42
42
  interface ContextBinding {
43
- bindingId: number;
43
+ bindingId?: number;
44
44
  alias?: string;
45
45
  aliasExpr?: string;
46
46
  destinationExpr?: string;
@@ -62,6 +62,8 @@ interface ContextBinding {
62
62
  calleeReceiver: string;
63
63
  callerSite?: { sourceFile?: string; sourceLine?: number };
64
64
  calleeSite?: { sourceFile?: string; sourceLine?: number };
65
+ resolutionStatus?: 'selected' | 'ambiguous';
66
+ bindingCandidates?: Array<Record<string, unknown>>;
65
67
  }
66
68
  interface ImplementationHintOptions {
67
69
  implementationRepo?: string;
@@ -74,42 +76,75 @@ function normalizeOperation(value: string | undefined): string | undefined {
74
76
  function positiveDepth(value: number): number {
75
77
  return Number.isFinite(value) && value > 0 ? Math.floor(value) : 25;
76
78
  }
77
-
78
- function operationStartScope(db: Db, repoId: number | undefined, start: TraceStart, hintOptions: ImplementationHintOptions): { files?: Set<string>; symbols?: Set<number>; operationId?: string; diagnostics?: Array<Record<string, unknown>> } | undefined {
79
+ function operationStartScope(db: Db, repoId: number | undefined, start: TraceStart, hintOptions: ImplementationHintOptions): { files?: Set<string>; symbols?: Set<number>; repoId?: number; operationId?: string; diagnostics?: Array<Record<string, unknown>> } | undefined {
79
80
  const requested = normalizeOperation(start.operationPath ?? start.operation);
80
81
  if (!requested) return undefined;
81
- const rows = db.prepare(`SELECT o.id operationId,o.operation_name operationName,o.operation_path operationPath,s.service_path servicePath,r.id repoId,r.name repoName
82
+ const rows = db.prepare(`SELECT o.id operationId,o.operation_name operationName,o.operation_path operationPath,o.source_file sourceFile,o.source_line sourceLine,s.service_path servicePath,r.id repoId,r.name repoName
82
83
  FROM cds_operations o JOIN cds_services s ON s.id=o.service_id JOIN repositories r ON r.id=s.repo_id
83
84
  WHERE (? IS NULL OR r.id=?) AND (? IS NULL OR s.service_path=?) AND (o.operation_name=? OR o.operation_path=? OR o.operation_path=?)
84
85
  ORDER BY r.name,s.service_path,o.operation_name,o.id`).all(repoId, repoId, start.servicePath, start.servicePath, requested, requested, requested.startsWith('/') ? requested : `/${requested}`) as Array<Record<string, unknown>>;
85
86
  if (rows.length === 0) return undefined;
86
87
  const repoCount = new Set(rows.map((row) => String(row.repoName))).size;
87
88
  const serviceCount = new Set(rows.map((row) => `${String(row.repoName)}:${String(row.servicePath)}`)).size;
88
- if (!repoId && repoCount > 1) return { diagnostics: [{ severity: 'warning', code: 'trace_start_ambiguous', message: 'Operation trace start matched multiple repositories; add --repo to disambiguate', normalizedSelectorValue: requested, resolutionStage: 'operation', resolutionStatus: 'ambiguous_operation', candidates: rows }] };
89
- if (!start.servicePath && serviceCount > 1) return { diagnostics: [{ severity: 'warning', code: 'trace_start_ambiguous', message: 'Operation trace start matched multiple services; add --service to disambiguate', normalizedSelectorValue: requested, resolutionStage: 'operation', resolutionStatus: 'ambiguous_operation', candidates: rows }] };
90
- if (rows.length !== 1) return { diagnostics: [{ severity: 'warning', code: 'trace_start_ambiguous', message: 'Operation trace start matched multiple indexed operations', normalizedSelectorValue: requested, resolutionStage: 'operation', resolutionStatus: 'ambiguous_operation', candidates: rows }] };
89
+ if (!repoId && repoCount > 1)
90
+ return { diagnostics: [ambiguousStartDiagnostic(requested, rows, 'Operation trace start matched multiple repositories; add --repo to disambiguate')] };
91
+ if (!start.servicePath && serviceCount > 1)
92
+ return { diagnostics: [ambiguousStartDiagnostic(requested, rows, 'Operation trace start matched multiple services; add --service to disambiguate')] };
93
+ if (rows.length !== 1)
94
+ return { diagnostics: [ambiguousStartDiagnostic(requested, rows, 'Operation trace start matched multiple indexed operations')] };
91
95
  const operationId = String(rows[0]?.operationId);
92
96
  const impl = implementationScope(db, operationId);
93
- if (impl.edge?.status === 'resolved' && impl.files.size > 0) return { files: impl.files, symbols: impl.symbolId ? new Set([impl.symbolId]) : undefined, operationId, diagnostics: [] };
97
+ if (impl.edge?.status === 'resolved' && impl.files.size > 0) return { files: impl.files, symbols: impl.symbolId ? new Set([impl.symbolId]) : undefined, repoId: impl.repoId, operationId, diagnostics: [] };
94
98
  const hinted = implementationMethodIdFromHint(impl.edge, hintOptions);
95
99
  if (hinted.methodId) {
96
100
  const hintedScope = handlerScope(db, hinted.methodId);
97
- if (hintedScope?.files.size) return { files: hintedScope.files, symbols: hintedScope.symbolId ? new Set([hintedScope.symbolId]) : undefined, operationId, diagnostics: [] };
101
+ if (hintedScope?.files.size) return { files: hintedScope.files, symbols: hintedScope.symbolId ? new Set([hintedScope.symbolId]) : undefined, repoId: hintedScope.repoId, operationId, diagnostics: [] };
98
102
  }
99
103
  if (impl.edge) {
100
104
  const evidence = parseEvidence(impl.edge.evidence_json);
101
105
  const hintDiagnostic = implementationHintDiagnostic(hinted, evidence.implementationHintSuggestions);
102
- const diagnostics = [{ severity: 'warning', code: impl.edge.status === 'ambiguous' ? 'trace_start_ambiguous' : 'trace_start_implementation_unresolved', message: `Indexed operation matched but implementation edge is ${String(impl.edge.status ?? 'unresolved')}`, resolutionStage: 'implementation', resolutionStatus: impl.edge.status === 'ambiguous' ? 'ambiguous_implementation' : 'rejected_implementation', implementationEdgeId: impl.edge.id, implementationStatus: impl.edge.status, implementationAmbiguityReasons: evidence.ambiguityReasons, implementationHintSuggestions: evidence.implementationHintSuggestions, candidates: evidence.candidates }];
106
+ const diagnostics = [{ severity: 'warning', code: impl.edge.status === 'ambiguous' ? 'trace_start_ambiguous' : 'trace_start_implementation_unresolved', message: `Indexed operation matched but implementation edge is ${String(impl.edge.status ?? 'unresolved')}`, resolutionStage: 'implementation', resolutionStatus: impl.edge.status === 'ambiguous' ? 'ambiguous_implementation' : 'rejected_implementation', implementationEdgeId: impl.edge.id, implementationStatus: impl.edge.status, implementationAmbiguityReasons: evidence.ambiguityReasons, implementationRejectionReasons: implementationRejectionReasons(evidence), implementationHintSuggestions: evidence.implementationHintSuggestions, candidates: evidence.candidates }];
103
107
  return { operationId, diagnostics: hintDiagnostic ? [hintDiagnostic, ...diagnostics] : diagnostics };
104
108
  }
105
109
  return { operationId, diagnostics: [{ severity: 'warning', code: 'trace_start_implementation_unresolved', message: 'Indexed operation matched but no implementation candidate exists', resolutionStage: 'implementation', resolutionStatus: 'operation_without_implementation' }] };
106
110
  }
107
-
111
+ function implementationRejectionReasons(evidence: Record<string, unknown>): string[] {
112
+ const candidates = Array.isArray(evidence.candidates)
113
+ ? evidence.candidates.filter((item): item is Record<string, unknown> =>
114
+ Boolean(item && typeof item === 'object' && !Array.isArray(item)))
115
+ : [];
116
+ const reasons = candidates.flatMap((candidate) =>
117
+ Array.isArray(candidate.rejectedReasons)
118
+ ? candidate.rejectedReasons.filter((reason): reason is string =>
119
+ typeof reason === 'string')
120
+ : []);
121
+ return [...new Set(reasons)].sort();
122
+ }
123
+ function ambiguousStartDiagnostic(
124
+ requested: string,
125
+ candidates: Array<Record<string, unknown>>,
126
+ message: string,
127
+ ): Record<string, unknown> {
128
+ const serviceSuggestions = [...new Set(candidates
129
+ .flatMap((row) => typeof row.servicePath === 'string'
130
+ ? [`--service ${row.servicePath}`]
131
+ : []))].sort();
132
+ return {
133
+ severity: 'warning',
134
+ code: 'trace_start_ambiguous',
135
+ message,
136
+ normalizedSelectorValue: requested,
137
+ resolutionStage: 'operation',
138
+ resolutionStatus: 'ambiguous_operation',
139
+ candidates,
140
+ serviceSuggestions,
141
+ };
142
+ }
108
143
  function sourceFilesForStart(
109
144
  db: Db,
110
145
  repoId: number | undefined,
111
146
  start: TraceStart,
112
- ): { files?: Set<string>; symbols?: Set<number> } | undefined {
147
+ ): { files?: Set<string>; symbols?: Set<number>; repoId?: number } | undefined {
113
148
  const handler = start.handler;
114
149
  const operation = normalizeOperation(start.operation ?? start.operationPath);
115
150
  if (!handler && !operation) return undefined;
@@ -138,7 +173,7 @@ function sourceFilesForStart(
138
173
  operation,
139
174
  operation,
140
175
  ) as Array<{ sourceFile?: string; symbolId?: number }>;
141
- if (rows.length > 0) return { files: new Set(rows.map((row) => row.sourceFile).filter(Boolean) as string[]), symbols: new Set(rows.map((row) => Number(row.symbolId)).filter(Boolean)) };
176
+ if (rows.length > 0) return { files: new Set(rows.map((row) => row.sourceFile).filter(Boolean) as string[]), symbols: new Set(rows.map((row) => Number(row.symbolId)).filter(Boolean)), repoId };
142
177
  if (start.servicePath && operation) {
143
178
  const implRows = db.prepare(`SELECT DISTINCT hc.source_file sourceFile,sym.id symbolId
144
179
  FROM cds_services s JOIN cds_operations o ON o.service_id=s.id
@@ -147,7 +182,7 @@ function sourceFilesForStart(
147
182
  JOIN handler_classes hc ON hc.id=hm.handler_class_id
148
183
  LEFT JOIN symbols sym ON sym.repo_id=hc.repo_id AND sym.source_file=hc.source_file AND sym.name=hm.method_name
149
184
  WHERE (? IS NULL OR s.repo_id=?) AND s.service_path=? AND (o.operation_path=? OR o.operation_name=?)`).all(repoId, repoId, start.servicePath, operation, operation) as Array<{ sourceFile?: string; symbolId?: number }>;
150
- if (implRows.length > 0) return { files: new Set(implRows.map((row) => row.sourceFile).filter(Boolean) as string[]), symbols: new Set(implRows.map((row) => Number(row.symbolId)).filter(Boolean)) };
185
+ if (implRows.length > 0) return { files: new Set(implRows.map((row) => row.sourceFile).filter(Boolean) as string[]), symbols: new Set(implRows.map((row) => Number(row.symbolId)).filter(Boolean)), repoId };
151
186
  }
152
187
  return undefined;
153
188
  }
@@ -171,6 +206,7 @@ function startScope(db: Db, start: TraceStart, hintOptions: ImplementationHintOp
171
206
  return { repo, selectorMatched: false };
172
207
  return {
173
208
  repo,
209
+ executionRepoId: sourceScope?.repoId ?? repo?.id,
174
210
  sourceFiles,
175
211
  symbolIds: sourceScope?.symbols,
176
212
  selectorMatched: !terminalOperationScope && (!hasSelector || sourceFiles !== undefined),
@@ -201,7 +237,6 @@ function handlerFilesForOperation(db: Db, operationId: string): Set<string> {
201
237
  }>;
202
238
  return new Set(rows.map((row) => row.sourceFile).filter(Boolean) as string[]);
203
239
  }
204
-
205
240
  function implementationEdge(db: Db, operationId: string): GraphRow | undefined {
206
241
  return db.prepare("SELECT * FROM graph_edges WHERE edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND from_kind='operation' AND from_id=? ORDER BY CASE status WHEN 'resolved' THEN 0 WHEN 'ambiguous' THEN 1 ELSE 2 END,id LIMIT 1").get(operationId) as GraphRow | undefined;
207
242
  }
@@ -220,7 +255,6 @@ function implementationMethodIdFromHint(edge: GraphRow | undefined, options: Imp
220
255
  if (!edge || edge.status !== 'ambiguous') return { blocksAutomatic: false, evidence: { status: 'not_applicable' } };
221
256
  return selectImplementation(parseEvidence(edge.evidence_json), options.implementationHints, options.implementationRepo);
222
257
  }
223
-
224
258
  function contextImplementationMethodId(edge: GraphRow | undefined, callerRepoId: number | undefined, remoteEvidence: Record<string, unknown>, hintOptions: ImplementationHintOptions): ImplementationSelection {
225
259
  const hinted = implementationMethodIdFromHint(edge, hintOptions);
226
260
  if (hinted.methodId) return hinted;
@@ -331,21 +365,65 @@ function knownBindingsForCalls(db: Db, calls: CallRow[]): Map<string, ContextBin
331
365
  function knownBindingsForScope(db: Db, repoId: number | undefined, symbolIds: Set<number> | undefined, files: Set<string> | undefined): Map<string, ContextBinding> {
332
366
  const map = new Map<string, ContextBinding>();
333
367
  if (repoId === undefined) return map;
334
- type BindingRow = Omit<ContextBinding, 'bindingId' | 'source' | 'calleeReceiver'> & { id?: number; variableName?: string };
335
- const rows = db.prepare(`SELECT b.id,b.variable_name variableName,b.alias,b.alias_expr aliasExpr,b.destination_expr destinationExpr,b.service_path_expr servicePathExpr,b.source_file sourceFile,b.source_line sourceLine,req.service_path requireServicePath,req.destination requireDestination
368
+ type BindingRow = Omit<ContextBinding, 'bindingId' | 'source' | 'calleeReceiver'> & { id?: number; symbolId?: number | null; variableName?: string };
369
+ const rows = db.prepare(`SELECT b.id,b.symbol_id symbolId,b.variable_name variableName,b.alias,b.alias_expr aliasExpr,b.destination_expr destinationExpr,b.service_path_expr servicePathExpr,b.source_file sourceFile,b.source_line sourceLine,req.service_path requireServicePath,req.destination requireDestination
336
370
  FROM service_bindings b LEFT JOIN cds_requires req ON req.repo_id=b.repo_id AND req.alias=b.alias
337
371
  WHERE b.repo_id=?`).all(repoId) as BindingRow[];
338
372
  for (const row of rows) {
339
373
  if (!row.variableName) continue;
340
374
  if (files && !files.has(String(row.sourceFile))) continue;
341
- if (symbolIds && symbolIds.size > 0) {
342
- const owner = db.prepare('SELECT id FROM symbols WHERE id IN (' + [...symbolIds].map(() => '?').join(',') + ') AND source_file=? AND start_line<=? AND end_line>=? LIMIT 1').get(...symbolIds, row.sourceFile, row.sourceLine, row.sourceLine) as { id?: number } | undefined;
343
- if (!owner) continue;
375
+ if (symbolIds && symbolIds.size > 0 && row.symbolId != null
376
+ && !symbolIds.has(Number(row.symbolId))) continue;
377
+ const candidate = enrichBinding({
378
+ ...row,
379
+ bindingId: Number(row.id),
380
+ source: 'local_service_binding',
381
+ calleeReceiver: row.variableName,
382
+ resolutionStatus: 'selected',
383
+ });
384
+ const existing = map.get(row.variableName);
385
+ if (!existing) {
386
+ map.set(row.variableName, candidate);
387
+ continue;
344
388
  }
345
- map.set(row.variableName, enrichBinding({ ...row, bindingId: Number(row.id), source: 'local_service_binding', calleeReceiver: row.variableName }));
389
+ const candidates = uniqueBindingCandidates([
390
+ ...(existing.bindingCandidates ?? [bindingCandidateEvidence(existing)]),
391
+ bindingCandidateEvidence(candidate),
392
+ ]);
393
+ map.set(row.variableName, {
394
+ ...candidate,
395
+ bindingId: undefined,
396
+ source: 'ambiguous_local_service_bindings',
397
+ resolutionStatus: 'ambiguous',
398
+ bindingCandidates: candidates,
399
+ });
346
400
  }
347
401
  return map;
348
402
  }
403
+
404
+ function bindingCandidateEvidence(binding: ContextBinding): Record<string, unknown> {
405
+ return {
406
+ bindingId: binding.bindingId,
407
+ sourceFile: binding.sourceFile,
408
+ sourceLine: binding.sourceLine,
409
+ alias: binding.alias,
410
+ aliasExpr: binding.aliasExpr,
411
+ destinationExpr: binding.destinationExpr,
412
+ servicePathExpr: binding.servicePathExpr,
413
+ };
414
+ }
415
+
416
+ function uniqueBindingCandidates(
417
+ candidates: Array<Record<string, unknown>>,
418
+ ): Array<Record<string, unknown>> {
419
+ const seen = new Set<string>();
420
+ return candidates.filter((candidate) => {
421
+ const key = JSON.stringify(candidate);
422
+ if (seen.has(key)) return false;
423
+ seen.add(key);
424
+ return true;
425
+ });
426
+ }
349
427
  function contextForSymbolCall(db: Db, symbolCall: Record<string, unknown>, callerBindings: Map<string, ContextBinding>): Map<string, ContextBinding> {
350
428
  const next = new Map<string, ContextBinding>();
351
429
  if (callerBindings.size === 0) return next;
@@ -397,6 +475,21 @@ function contextForSymbolCall(db: Db, symbolCall: Record<string, unknown>, calle
397
475
  }
398
476
  function contextualRuntimeResolution(db: Db, call: CallRow, binding: ContextBinding | undefined, workspaceId: number | undefined, persistedRows: GraphRow[] = []): { row?: GraphRow; evidence?: Record<string, unknown>; unresolvedReason?: string } {
399
477
  if (!binding || String(call.call_type) !== 'remote_action' || call.operation_path_expr === undefined || call.operation_path_expr === null) return {};
478
+ if (binding.resolutionStatus === 'ambiguous') {
479
+ return {
480
+ evidence: {
481
+ contextualServiceBindingAttempted: true,
482
+ contextualBinding: {
483
+ source: binding.source,
484
+ status: 'tied',
485
+ candidates: binding.bindingCandidates,
486
+ },
487
+ contextualResolutionStatus: 'ambiguous',
488
+ contextualCandidateCount: binding.bindingCandidates?.length ?? 0,
489
+ },
490
+ unresolvedReason: 'Ambiguous contextual service binding candidates',
491
+ };
492
+ }
400
493
  const normalized = normalizeODataOperationInvocationPath(String(call.operation_path_expr));
401
494
  const op = normalized?.normalizedOperationPath ?? (String(call.operation_path_expr).startsWith('/') ? String(call.operation_path_expr) : `/${String(call.operation_path_expr)}`);
402
495
  const servicePath = binding.effectiveServicePath ?? binding.servicePathExpr ?? binding.requireServicePath;
@@ -445,7 +538,7 @@ export function trace(
445
538
  const seenEdges = new Set<number>();
446
539
  const queue: Array<{ repoId?: number; files?: Set<string>; symbolIds?: Set<number>; depth: number; context?: Map<string, ContextBinding> }> =
447
540
  scope.selectorMatched
448
- ? [{ repoId: scope.repo?.id, files: scope.sourceFiles, symbolIds: scope.symbolIds, depth: 1, context: new Map() }]
541
+ ? [{ repoId: scope.executionRepoId, files: scope.sourceFiles, symbolIds: scope.symbolIds, depth: 1, context: new Map() }]
449
542
  : [];
450
543
  if (scope.startOperationId && scope.selectorMatched) {
451
544
  const op = operationNode(db, scope.startOperationId);
@@ -521,7 +614,7 @@ export function trace(
521
614
  String(row.evidence_json || '{}'),
522
615
  ) as Record<string, unknown>;
523
616
  const rawEvidence = baseTraceEvidence(row as TraceGraphRow, call, persistedEvidence, contextual.evidence);
524
- const effective = runtimeResolution(db, row as TraceGraphRow, rawEvidence, options.vars, workspaceIdForCall(db, String(call.id)));
617
+ const effective = runtimeResolution(db, row as TraceGraphRow, rawEvidence, options.vars, workspaceIdForCall(db, String(call.id)), contextual.unresolvedReason);
525
618
  const evidence = effective.evidence;
526
619
  const effectiveRow = effective.row;
527
620
  const targetNode = `${effectiveRow.to_kind}:${effectiveRow.to_id}`;