From a9f4e45d0dfe5dc1716ced2972914c997d97148f Mon Sep 17 00:00:00 2001 From: Shreyansh Gupta Date: Fri, 27 Nov 2026 12:18:28 +0530 Subject: [PATCH 01/10] Group BizTalk flows deterministically and share common artifacts Discovery grouping was decided by Copilot, which took minutes, returned different groups on each run, and merged flows into very large groups once shared canonical-schema and common-code projects were added (every cross-group schema or binding edge was rejected). - Add FlowGroupDetector: orchestrations joined only by Call/Start Orchestration form a flow; maps, message schemas, pipelines, ports and projects attach to the flows that reference them; artifacts used by several flows (canonical schemas, binding files) are marked shared instead of merging flows. Same inventory -> same groups and IDs. - Attribute binding ports per flow (orchestration bindings, subscription filters, messaging-only routes) and scope shared binding files to each flow's ports when the analyser reads a group. - Report referenced projects missing from the source folder; offer to re-detect groups after a rescan changes the inventory, keeping progress of flows whose ID is unchanged. - Add discovery.groupingMode (auto/deterministic/copilot) and a Re-detect Logical Groups command; Copilot grouping now starts from the deterministic proposal. - Remove the contradictory "one group per receive location" instruction, allow shared artifacts in the store tool's independence check, and match call targets exactly. - Read map tree references, project references and send-port maps in the parsers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 12 + package.json | 39 +- resources/agents/migration-analyser.md | 6 +- .../analyse-source-design/biztalk/SKILL.md | 1 + .../detect-logical-groups/biztalk/SKILL.md | 63 +- .../detect-logical-groups/mulesoft/SKILL.md | 16 +- .../detect-logical-groups/tibco/SKILL.md | 16 +- src/commands/CommandRegistry.ts | 121 +- src/constants/ChatPrompts.ts | 5 +- src/constants/UserMessages.ts | 27 + src/copilot/MigrationLMTools.ts | 205 ++-- src/parsers/biztalk/BizTalkBindingsParser.ts | 2 + src/parsers/biztalk/BizTalkMapParser.ts | 9 +- src/parsers/biztalk/BizTalkProjectParser.ts | 1 + src/services/LLMFlowGenerator.ts | 47 +- src/stages/discovery/DiscoveryCacheService.ts | 33 +- src/stages/discovery/FlowGroupDetector.ts | 1034 +++++++++++++++++ src/test/unit/flow-group-detector.test.ts | 496 ++++++++ src/views/discovery/SourceFlowVisualizer.ts | 32 +- 19 files changed, 1986 insertions(+), 179 deletions(-) create mode 100644 src/stages/discovery/FlowGroupDetector.ts create mode 100644 src/test/unit/flow-group-detector.test.ts diff --git a/README.md b/README.md index 0633b90..2baa2d7 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,16 @@ Discovery → Planning → Conversion → Validation → Deployment 4. Select your source folder when prompted (or use the command palette: `Logic Apps Migration Agent: Select Source Folder`) 5. Follow the guided 5-stage workflow +### Logical groups + +After discovery, the extension groups BizTalk artifacts into logical flows without Copilot, in seconds, and returns the same groups and IDs for the same source: + +- Orchestrations linked by Call/Start Orchestration form one flow, named after the entry orchestration. Receive locations and send ports bound to it (or subscribed to its receive ports) belong to it; receive ports routed only by send-port filters become messaging routes. +- Maps, message schemas, pipelines and projects belong to the flows that reference them. Artifacts used by several flows — for example canonical schemas from a shared canonical data model project or one application binding file — are **shared**: they appear in each flow that uses them instead of merging flows, and analysis of a flow only covers its own ports. +- Referenced projects missing from the source folder are reported right away. After adding them, **Rescan Artifacts** offers to re-detect groups; flows that keep their ID keep their analysis, plan and conversion progress. You can also run **Re-detect Logical Groups** at any time. + +Set `logicAppsMigrationAgent.discovery.groupingMode` to `copilot` to let Copilot group the artifacts instead, starting from the same proposal. MuleSoft and TIBCO use Copilot grouping by default. + ### Decision-first planning Planning resolves important choices before generating workflow definitions. It reuses discovery results and saved answers, asks a short hosting question when no explicit deployment setting exists, then asks only consequential unresolved questions (typically broker choice and/or preserve-code versus native-first modernization). Minor, behavior-preserving mappings are chosen automatically. Canceling pauses planning without inventing answers; already answered choices are saved. @@ -119,6 +129,7 @@ Configure via `Settings > Extensions > Logic Apps Migration Agent`: | `logicAppsMigrationAgent.azure.subscriptionId` | Azure subscription ID for deployment | (empty) | | `logicAppsMigrationAgent.azure.resourceGroup` | Azure resource group for provisioning and testing | `integration-migration-tool-test-rg` | | `logicAppsMigrationAgent.azure.location` | Azure region for provisioning resources | `eastus` | +| `logicAppsMigrationAgent.discovery.groupingMode` | How logical groups are detected: `auto` (deterministic for BizTalk), `deterministic`, or `copilot` | `auto` | ## Command Palette @@ -127,6 +138,7 @@ Configure via `Settings > Extensions > Logic Apps Migration Agent`: | `Logic Apps Migration Agent: Select Source Folder` | Start migration by selecting a source project folder | | `Logic Apps Migration Agent: Reset Migration` | Reset all migration state and start over | | `Logic Apps Migration Agent: Show Extension Logs` | Open the extension output channel for debugging | +| `Logic Apps Migration Agent: Re-detect Logical Groups` | Re-group the current inventory, keeping progress of flows whose ID is unchanged | ## Architecture diff --git a/package.json b/package.json index 7dbe333..5ead207 100644 --- a/package.json +++ b/package.json @@ -178,7 +178,7 @@ "displayName": "Detect Flow Groups", "toolReferenceName": "migration_detectFlowGroups", "canBeReferencedInPrompt": true, - "modelDescription": "Builds a deterministic connection graph from all discovered integration artifacts. Returns artifact summaries (with receive/send endpoints, schemas, maps, filters) and a connection graph showing how artifacts are linked (subscription filters, schema references, map source/target, orchestration-calls via Call/Start Orchestration, etc.). Use this data to determine logical flow groups yourself. CRITICAL RULE: The connectionGraph includes 'orchestration-calls' edges when one orchestration calls or starts another via Call Orchestration or Start Orchestration shapes — orchestrations linked by these edges (directly or transitively) MUST be placed in the SAME group. If Orch-A calls Orch-B and Orch-B calls Orch-C, all three belong in ONE group. Each group should have one or more Orchestrations, related schemas/maps/pipelines, and entry/exit points. Transitively connected artifacts belong in the same group. If receiveLocationCount is 0, use fallback grouping: orchestration-root (one group per connected orchestration cluster), then trigger-capability, then connected-component. Pass the groups you determine to migration_discovery_storeFlowGroups. If you already know the groupId of a specific flow group (e.g. when generating a visualization for a specific group selected from the dropdown), pass groupId to retrieve the cached group and its artifact summaries directly — this avoids re-detecting all groups.", + "modelDescription": "Returns a deterministic grouping proposal (proposedGroups, proposedSharedArtifactIds, proposedUngroupedArtifactIds, missingProjects) computed from Call/Start Orchestration chains, map/schema references, port bindings and subscription filters, plus artifact summaries and the artifact connection graph. Store the proposed groups with migration_discovery_storeFlowGroups, keeping their ids, artifactIds and endpointNames; you may improve names and descriptions. Do not split proposed groups. Orchestrations linked by Call/Start Orchestration (directly or transitively) belong in ONE group; receive locations feeding the same orchestration belong to that orchestration's group. Artifacts used by several groups (canonical schemas, binding files, common code) are shared: list them in sharedArtifactIds and in every group that uses them instead of merging groups. Pass groupId to retrieve one cached group: its artifacts are returned with binding endpoints scoped to the flow's endpointNames and shared artifacts flagged.", "userDescription": "Analyze artifact connections and build connection graph", "inputSchema": { "type": "object", @@ -195,7 +195,7 @@ "displayName": "Store Flow Groups", "toolReferenceName": "migration_discovery_storeFlowGroups", "canBeReferencedInPrompt": true, - "modelDescription": "Stores the detected flow groups and shows a flow group selector in the webview. Call this after determining logical flow groups from the artifact connection graph returned by migration_detectFlowGroups. Each group must have an id, name, description, category, and a non-empty artifactIds array. The user will then select individual flows from the webview to trigger detailed analysis.", + "modelDescription": "Stores the detected flow groups (replacing earlier groups) and shows the flow group selector in the webview. Each group must have an id, name, description, category, and a non-empty artifactIds array. Artifacts used by several groups must be listed in sharedArtifactIds and in every group that uses them; other artifacts may belong to only one group, and groups may not depend on each other's non-shared artifacts. Set endpointNames to the receive locations/ports and send ports of each flow. The user will then select individual flows from the webview to trigger detailed analysis.", "userDescription": "Store detected flow groups and show flow selector", "inputSchema": { "type": "object", @@ -261,6 +261,13 @@ } } } + }, + "endpointNames": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Receive locations/ports, send ports and send port groups that belong to this flow (scopes shared binding files)" } }, "required": [ @@ -278,6 +285,13 @@ }, "description": "IDs of artifacts not belonging to any group" }, + "sharedArtifactIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "IDs of artifacts used by more than one group (e.g. canonical schemas, binding files, common code); list them in every group that uses them" + }, "explanation": { "type": "string", "description": "Explanation of how groups were determined" @@ -1776,6 +1790,12 @@ "title": "View Dependency Graph", "category": "Logic Apps Migration Agent" }, + { + "command": "logicAppsMigrationAgent.redetectFlowGroups", + "title": "Re-detect Logical Groups", + "category": "Logic Apps Migration Agent", + "icon": "$(refresh)" + }, { "command": "logicAppsMigrationAgent.openPlanningView", "title": "Open Planning View", @@ -1967,6 +1987,21 @@ "type": "string", "default": "eastus", "description": "Azure region for provisioning resources" + }, + "logicAppsMigrationAgent.discovery.groupingMode": { + "type": "string", + "enum": [ + "auto", + "deterministic", + "copilot" + ], + "enumDescriptions": [ + "Deterministic for BizTalk; Copilot for other platforms", + "Group by orchestration call chains, references and port bindings without Copilot (fast and repeatable)", + "Let Copilot group the artifacts, starting from the deterministic proposal" + ], + "default": "auto", + "markdownDescription": "How logical groups are detected. Deterministic grouping takes seconds, returns the same groups for the same source, and marks artifacts used by several flows (for example canonical schemas or binding files) as shared instead of merging flows." } } } diff --git a/resources/agents/migration-analyser.md b/resources/agents/migration-analyser.md index c2daa55..aef7d14 100644 --- a/resources/agents/migration-analyser.md +++ b/resources/agents/migration-analyser.md @@ -52,13 +52,13 @@ You are a **Migration Analyser** — an expert in integration platform architect ### Task A: Detect Flow Groups -1. Call `migration_detectFlowGroups` to get the connection graph. -2. Follow skill `detect-logical-groups` exactly to determine groups — **including §4 step 2**: if the connectionGraph has few/no call-chain edges, decompile DLLs and read orchestration source files to discover hidden call relationships before grouping. +1. Call `migration_detectFlowGroups` to get the deterministic `proposedGroups` and the connection graph. +2. Follow skill `detect-logical-groups` exactly: store the proposed groups (keep ids, artifactIds, endpointNames and shared artifacts; improve names/descriptions only). Decompile DLLs or read orchestration sources only when the skill says the proposal is empty or orchestrations exist only in compiled assemblies. 3. Call `migration_discovery_storeFlowGroups`. ### Task B: Analyse a Flow Group -1. Call `migration_detectFlowGroups` with the `groupId` to get the cached artifact list. +1. Call `migration_detectFlowGroups` with the `groupId` to get the cached artifact list. Analyse only this flow: when the group lists `endpointNames`, other ports in shared binding files belong to other flows; artifacts marked `sharedWithOtherFlows` are used here and elsewhere. 2. Read ALL artifacts per skill `analyse-source-design` §1. 3. When a DLL reference is encountered during artifact reading, decompile it per skill `dependency-and-decompilation-analysis` §2 — then recursively walk its dependency tree (§2.3) to decompile all child DLLs. Complete the decompilation checklist (§2.4) before proceeding. 4. Look up every component in skill `source-to-logic-apps-mapping`, then search reference docs. Follow the applicable skills to record source evidence, mapping decisions, and unresolved requirements. diff --git a/resources/skills/analyse-source-design/biztalk/SKILL.md b/resources/skills/analyse-source-design/biztalk/SKILL.md index b882d4b..0891a1e 100644 --- a/resources/skills/analyse-source-design/biztalk/SKILL.md +++ b/resources/skills/analyse-source-design/biztalk/SKILL.md @@ -14,6 +14,7 @@ description: Rules for analysing a single flow group's architecture. Covers sour - Call `migration_getArtifactDetails` AND `migration_readSourceFile` for EVERY artifact in the group. - Extract ALL configuration details — adapter type, paths, polling intervals, pipeline stages, port names, schema fields, orchestration shapes, map field mappings, retry config. - ZERO HALLUCINATION — every value in the architecture diagram MUST come from source files. +- FLOW SCOPE — binding files and shared artifacts (`sharedWithOtherFlows`) also contain ports, schemas or code of other flows. When the group lists `endpointNames`, include ONLY those receive locations/ports and send ports. Artifacts found through full-project lookup are external dependencies of this flow; report them under dependencies, not as flow components. - Check port bindings, address/transport assignments, and adapter overrides for runtime connection switching. Follow `connections-json-generation-rules` section 2.1 and the Runtime Destination Selection guidance in `source-to-logic-apps-mapping` only where dynamic connections are needed; otherwise preserve the normal connection approach. diff --git a/resources/skills/detect-logical-groups/biztalk/SKILL.md b/resources/skills/detect-logical-groups/biztalk/SKILL.md index c01d730..1cf1199 100644 --- a/resources/skills/detect-logical-groups/biztalk/SKILL.md +++ b/resources/skills/detect-logical-groups/biztalk/SKILL.md @@ -1,33 +1,37 @@ --- name: detect-logical-groups -description: Rules for detecting and grouping integration artifacts into logical flow groups using shared-orchestration strategy. Covers orchestration call-chain rules, fallback grouping when no receive locations exist, and required output fields. +description: Rules for detecting and grouping BizTalk artifacts into logical flow groups. Start from the deterministic proposal; orchestration call chains define a flow, shared artifacts (canonical schemas, binding files, common code) are listed in every flow that uses them instead of merging flows. Covers fallback grouping and required output fields. --- # Skill: Detecting Flow Groups > **Purpose**: Authoritative rules for how an AI agent should group discovered integration artifacts into logical flow groups. The agent MUST follow these rules exactly. +> The extension groups BizTalk sources deterministically by default (setting `logicAppsMigrationAgent.discovery.groupingMode`). This skill applies when Copilot stores the groups. + --- -## 1. Grouping Strategy (Shared Orchestration) +## 1. Grouping Strategy -- **HIGHEST PRIORITY**: If multiple Receive Locations feed into the SAME Orchestration (directly or transitively), they MUST be in the SAME group — the orchestration is the unifying element. -- **Orchestration Call Chains**: The `connectionGraph` includes `orchestration-calls` edges when one orchestration calls/starts another. Orchestrations linked by these edges (directly or transitively) MUST be in the SAME group. Example: If Orch-A calls Orch-B and Orch-B calls Orch-C, all three belong in ONE group. -- Only create separate groups for Receive Locations that feed into DIFFERENT orchestrations with no transitive connection. -- Transitively connected artifacts belong in the SAME group. -- Name each group by business purpose. +- **Start from `proposedGroups`** returned by `migration_detectFlowGroups`. They are computed from Call/Start Orchestration chains, map and message-type references, orchestration port bindings and send-port subscription filters, so the same source always yields the same groups. Keep each proposed `id`, `artifactIds`, `endpointNames`, `entryPoint` and `exitPoints`; improve only `name` and `description`. +- **Orchestration call chains define a flow**: orchestrations linked by `orchestration-calls` edges (Call or Start Orchestration, directly or transitively) MUST be in the SAME group. +- **Receive locations that feed the same orchestration** belong to that orchestration's group. Do NOT create one group per receive location. +- **Messaging-only routes**: a receive port routed to send ports by a subscription filter (`BTS.ReceivePortName == …`) without an orchestration is its own group. +- **Shared artifacts do not merge flows**: artifacts used by more than one flow — canonical/common schemas (e.g. a canonical data model project), common pipelines or helper code, and binding files that hold the ports of several flows — go in `sharedArtifactIds` AND in the `artifactIds` of every group that uses them. +- **Scope binding files**: set each group's `endpointNames` to its receive locations/ports and send ports. Ports of other flows in a shared binding file are not part of the group. +- Name each group after its main orchestration or business purpose so users can map it back to the source. --- -## 2. Fallback Rules (When receiveLocationCount = 0) +## 2. Fallback Rules (When receiveLocationCount = 0 or proposedGroups is empty) Do NOT return empty groups. Use this fallback order: 1. **Orchestration-root grouping** — one group per CONNECTED orchestration cluster. Follow `orchestration-calls` edges to find clusters. Do NOT create one group per individual orchestration when they call each other. 2. **Trigger-capability grouping** — file/queue/http/timer/db-poller entry-capable artifacts. -3. **Connected-component grouping** — from the graph edges. +3. **Connected-component grouping** — from the graph edges, ignoring edges into shared artifacts. -Only leave artifacts in `ungroupedArtifactIds` if they are truly isolated with no meaningful edges or entry semantics. +Only leave artifacts in `ungroupedArtifactIds` if no group references them. For fallback groups, set `entryPoint` to orchestration/trigger/internal-entry (not receive-location). @@ -37,33 +41,36 @@ For fallback groups, set `entryPoint` to orchestration/trigger/internal-entry (n Each group MUST have: -| Field | Type | Description | -| ------------- | -------- | ------------------------------------------------ | -| `id` | string | Unique group ID (e.g. `flow-1-order-processing`) | -| `name` | string | Human-readable name by business purpose | -| `description` | string | What this flow does | -| `category` | string | e.g. `message-flow`, `shared-infrastructure` | -| `artifactIds` | string[] | MUST NOT be empty | -| `entryPoint` | object | Entry point (type, name, messageType) | -| `exitPoints` | array | Exit points (type, name, messageType) | +| Field | Type | Description | +| --------------- | -------- | -------------------------------------------------------------------- | +| `id` | string | Unique group ID — keep the proposed ID (e.g. `flow-ordernotification`) | +| `name` | string | Human-readable name by main orchestration or business purpose | +| `description` | string | What this flow does | +| `category` | string | e.g. `message-flow`, `business-process` | +| `artifactIds` | string[] | MUST NOT be empty; includes the shared artifacts the flow uses | +| `entryPoint` | object | Entry point (type, name, messageType) | +| `exitPoints` | array | Exit points (type, name, messageType) | +| `endpointNames` | string[] | Receive locations/ports and send ports of this flow | + +Also pass `sharedArtifactIds` and `ungroupedArtifactIds` at the top level. --- ## 4. Procedure -1. Call `migration_detectFlowGroups` to get the artifact connection graph and summaries. -2. **If the connectionGraph has few or no `orchestration-calls` edges**, the call-chain data may be incomplete. In that case: +1. Call `migration_detectFlowGroups` to get `proposedGroups`, `proposedSharedArtifactIds`, `proposedUngroupedArtifactIds`, `missingProjects`, the artifact summaries and the connection graph. +2. If `proposedGroups` is not empty, store it as-is (improved names/descriptions only). Do NOT read or decompile sources to re-derive groups. +3. Only when orchestrations exist solely in compiled assemblies (no `.odx` artifacts) or `proposedGroups` is empty: a. Call `migration_listArtifacts` with `category="custom-code"` to find DLLs. - b. Decompile relevant DLLs per skill `dependency-and-decompilation-analysis` §2 to discover orchestration call relationships hidden in compiled code. - c. Read orchestration source files (`migration_readSourceFile`) to find `Call Orchestration` / `Start Orchestration` shapes and their targets. - d. Use the discovered call chains to merge groups that should be together. -3. Determine logical flow groups using the shared-orchestration strategy above, incorporating both graph edges AND any call chains discovered in step 2. -4. Call `migration_discovery_storeFlowGroups` with the groups array, `ungroupedArtifactIds`, and explanation. + b. Decompile relevant DLLs per skill `dependency-and-decompilation-analysis` §2 to discover orchestration call relationships. + c. Merge groups only with that direct call evidence and state it in `explanation`. +4. Call `migration_discovery_storeFlowGroups` with `groups`, `sharedArtifactIds`, `ungroupedArtifactIds`, and `explanation`. If `missingProjects` is not empty, say in `explanation` that those projects must be added to the source folder. --- ## 5. What NOT to Do - Do NOT create empty `artifactIds` arrays. -- Do NOT split orchestrations linked by call chains into separate groups. -- Do NOT skip decompilation/source reading when the connectionGraph has missing call-chain edges — incomplete grouping causes downstream analysis failures. +- Do NOT split orchestrations linked by call chains into separate groups, and do NOT split a proposed group. +- Do NOT merge flows only because they use the same schema, pipeline, helper library or binding file — mark those artifacts shared. +- Do NOT create a group per receive location or expect at least one group per receive location. diff --git a/resources/skills/detect-logical-groups/mulesoft/SKILL.md b/resources/skills/detect-logical-groups/mulesoft/SKILL.md index 3a70a63..2a271f5 100644 --- a/resources/skills/detect-logical-groups/mulesoft/SKILL.md +++ b/resources/skills/detect-logical-groups/mulesoft/SKILL.md @@ -13,7 +13,8 @@ description: Rules for detecting and grouping MuleSoft integration artifacts int - **HIGHEST PRIORITY**: If multiple flows reference the SAME sub-flow via `flow-ref` (directly or transitively), they MUST be in the SAME group — the shared sub-flow is the unifying element. - **Call-workflow edges**: The `connectionGraph` includes `call-workflow` edges when one flow calls another flow or sub-flow via `flow-ref`. Flows linked by these edges (directly or transitively) MUST be in the SAME group. Example: If Flow-A calls Sub-Flow-B and Sub-Flow-B calls Sub-Flow-C, all three belong in ONE group. -- **Shared-connection edges**: The `connectionGraph` includes `shared-connection` edges when multiple flows use the same global configuration (e.g., same `http:listener-config`, same `db:config`). Flows sharing configs SHOULD be in the same group unless they are clearly independent. +- **Shared configuration does not merge flows**: the `connectionGraph` includes `shared-connection` edges when multiple flows use the same global configuration (e.g., same `http:listener-config`, same `db:config`). Do NOT merge flows only because of these edges; list the configuration artifact in `sharedArtifactIds` and in the `artifactIds` of every group that uses it. +- **Start from `proposedGroups`** returned by `migration_detectFlowGroups` (computed deterministically from `flow-ref` chains). Keep the proposed `id` and `artifactIds`; improve only `name` and `description`. Do not split a proposed group. - Only create separate groups for flows that use DIFFERENT sub-flows with no transitive connection. - Transitively connected artifacts belong in the SAME group. - Name each group by business purpose (derived from flow names and HTTP listener paths). @@ -26,7 +27,7 @@ Do NOT return empty groups. Use this fallback order: 1. **Flow-root grouping** — one group per CONNECTED flow cluster. Follow `call-workflow` edges to find clusters. Do NOT create one group per individual flow when they reference each other. 2. **Trigger-capability grouping** — flows with sources (http:listener, scheduler, jms:listener, file:listener, vm:listener) as entry points. `receiveLocationCount` includes all triggers. -3. **Connected-component grouping** — from graph edges (`call-workflow`, `shared-connection`) and any remaining connections. +3. **Connected-component grouping** — from `call-workflow` edges and any remaining connections, ignoring `shared-connection` edges and edges into shared artifacts. Only leave artifacts in `ungroupedArtifactIds` if they are truly isolated with no meaningful edges or entry semantics. @@ -52,13 +53,13 @@ Each group MUST have: ## 4. Procedure -1. Call `migration_detectFlowGroups` to get the artifact connection graph and summaries. -2. **If the connectionGraph has few or no `call-workflow` or `shared-connection` edges**, the flow-ref data may be incomplete. In that case: +1. Call `migration_detectFlowGroups` to get `proposedGroups`, `proposedSharedArtifactIds`, `proposedUngroupedArtifactIds`, the artifact connection graph and summaries. +2. **Only if `proposedGroups` is empty or the connectionGraph has few or no `call-workflow` edges**, the flow-ref data may be incomplete. In that case: a. Call `migration_listArtifacts` with `category="custom-code"` to find JARs and custom Java classes. - b. Read flow source files (`migration_readSourceFile`) to find `flow-ref` targets and shared config references. - c. Use the discovered call chains and shared configs to merge groups that should be together. + b. Read flow source files (`migration_readSourceFile`) to find `flow-ref` targets. + c. Merge groups only with the call chains discovered this way. 3. Determine logical flow groups using the flow-reference chain strategy above, incorporating both graph edges AND any call chains discovered in step 2. -4. Call `migration_discovery_storeFlowGroups` with the groups array, `ungroupedArtifactIds`, and explanation. +4. Call `migration_discovery_storeFlowGroups` with the groups array, `sharedArtifactIds`, `ungroupedArtifactIds`, and explanation. --- @@ -66,4 +67,5 @@ Each group MUST have: - Do NOT create empty `artifactIds` arrays. - Do NOT split flows linked by flow-ref chains into separate groups. +- Do NOT merge flows only because they share a global configuration, schema or library — mark those artifacts shared. - Do NOT skip source reading when the connectionGraph has missing call-chain edges — incomplete grouping causes downstream analysis failures. diff --git a/resources/skills/detect-logical-groups/tibco/SKILL.md b/resources/skills/detect-logical-groups/tibco/SKILL.md index 71c2870..0083ab5 100644 --- a/resources/skills/detect-logical-groups/tibco/SKILL.md +++ b/resources/skills/detect-logical-groups/tibco/SKILL.md @@ -13,7 +13,8 @@ description: Rules for detecting and grouping TIBCO integration artifacts into l - **HIGHEST PRIORITY**: If multiple flows reference the SAME sub-process via `process-call` (directly or transitively), they MUST be in the SAME group — the shared sub-process is the unifying element. - **Call-workflow edges**: The `connectionGraph` includes `call-workflow` edges when one flow calls another flow or sub-process via `process-call`. Flows linked by these edges (directly or transitively) MUST be in the SAME group. Example: If Flow-A calls sub-process-B and sub-process-B calls sub-process-C, all three belong in ONE group. -- **Shared-connection edges**: The `connectionGraph` includes `shared-connection` edges when multiple flows use the same global configuration (e.g., same `http:listener-config`, same `db:config`). Flows sharing configs SHOULD be in the same group unless they are clearly independent. +- **Shared configuration does not merge flows**: the `connectionGraph` includes `shared-connection` edges when multiple flows use the same global configuration (e.g., same `http:listener-config`, same `db:config`). Do NOT merge flows only because of these edges; list the configuration artifact in `sharedArtifactIds` and in the `artifactIds` of every group that uses it. +- **Start from `proposedGroups`** returned by `migration_detectFlowGroups` (computed deterministically from `process-call` chains). Keep the proposed `id` and `artifactIds`; improve only `name` and `description`. Do not split a proposed group. - Only create separate groups for flows that use DIFFERENT sub-processes with no transitive connection. - Transitively connected artifacts belong in the SAME group. - Name each group by business purpose (derived from flow names and HTTP listener paths). @@ -26,7 +27,7 @@ Do NOT return empty groups. Use this fallback order: 1. **Flow-root grouping** — one group per CONNECTED flow cluster. Follow `call-workflow` edges to find clusters. Do NOT create one group per individual flow when they reference each other. 2. **Trigger-capability grouping** — flows with sources (http:listener, scheduler, jms:listener, file:listener, JMS/EMS listener) as entry points. `receiveLocationCount` includes all triggers. -3. **Connected-component grouping** — from graph edges (`call-workflow`, `shared-connection`) and any remaining connections. +3. **Connected-component grouping** — from `call-workflow` edges and any remaining connections, ignoring `shared-connection` edges and edges into shared artifacts. Only leave artifacts in `ungroupedArtifactIds` if they are truly isolated with no meaningful edges or entry semantics. @@ -52,13 +53,13 @@ Each group MUST have: ## 4. Procedure -1. Call `migration_detectFlowGroups` to get the artifact connection graph and summaries. -2. **If the connectionGraph has few or no `call-workflow` or `shared-connection` edges**, the process-call data may be incomplete. In that case: +1. Call `migration_detectFlowGroups` to get `proposedGroups`, `proposedSharedArtifactIds`, `proposedUngroupedArtifactIds`, the artifact connection graph and summaries. +2. **Only if `proposedGroups` is empty or the connectionGraph has few or no `call-workflow` edges**, the process-call data may be incomplete. In that case: a. Call `migration_listArtifacts` with `category="custom-code"` to find JARs and custom Java classes. - b. Read flow source files (`migration_readSourceFile`) to find `process-call` targets and shared config references. - c. Use the discovered call chains and shared configs to merge groups that should be together. + b. Read flow source files (`migration_readSourceFile`) to find `process-call` targets. + c. Merge groups only with the call chains discovered this way. 3. Determine logical flow groups using the process-call chain strategy above, incorporating both graph edges AND any call chains discovered in step 2. -4. Call `migration_discovery_storeFlowGroups` with the groups array, `ungroupedArtifactIds`, and explanation. +4. Call `migration_discovery_storeFlowGroups` with the groups array, `sharedArtifactIds`, `ungroupedArtifactIds`, and explanation. --- @@ -66,6 +67,7 @@ Each group MUST have: - Do NOT create empty `artifactIds` arrays. - Do NOT split flows linked by process-call chains into separate groups. +- Do NOT merge flows only because they share a global configuration, schema or library — mark those artifacts shared. - Do NOT skip source reading when the connectionGraph has missing call-chain edges — incomplete grouping causes downstream analysis failures. diff --git a/src/commands/CommandRegistry.ts b/src/commands/CommandRegistry.ts index ad18bd7..e97c709 100644 --- a/src/commands/CommandRegistry.ts +++ b/src/commands/CommandRegistry.ts @@ -15,6 +15,13 @@ import { StateManager } from '../services/StateManager'; import { ErrorHandler } from '../errors/ErrorHandler'; import { MsiExtractorService } from '../services/MsiExtractorService'; import { DiscoveryService } from '../stages/discovery'; +import { InventoryService } from '../stages/discovery/InventoryService'; +import { + compareInventoryWithGroups, + detectFlowGroups, + FlowGroupingMode, + resolveGroupingMode, +} from '../stages/discovery/FlowGroupDetector'; import { PlanningService } from '../stages/planning'; import { ConversionService } from '../stages/conversion'; import { AgentFileProvisioner } from '../services/AgentFileProvisioner'; @@ -121,6 +128,11 @@ export class CommandRegistry implements vscode.Disposable { handler: this.handleViewDependencyGraph.bind(this), title: 'View Dependency Graph', }, + { + id: 'logicAppsMigrationAgent.redetectFlowGroups', + handler: this.handleRedetectFlowGroups.bind(this), + title: 'Re-detect Logical Groups', + }, // Planning Stage Commands { id: 'logicAppsMigrationAgent.openPlanningView', @@ -780,13 +792,32 @@ export class CommandRegistry implements vscode.Disposable { UserPrompts.rescanComplete(result.inventory?.statistics.totalCount || 0) ); - // Auto-start logical group detection if groups are not available yet + // Auto-start logical group detection if groups are not available yet; + // otherwise offer to re-detect them when the inventory changed. try { const { DiscoveryCacheService } = await import('../stages/discovery/DiscoveryCacheService'); - const hasGroups = DiscoveryCacheService.getInstance().hasFlowGroups(); - if (!hasGroups) { + const discoveryCache = DiscoveryCacheService.getInstance(); + const flowGroups = discoveryCache.getFlowGroups(); + if (!discoveryCache.hasFlowGroups() || !flowGroups) { await this.handleViewFlowVisualization(); + } else { + const inventoryIds = ( + await InventoryService.getInstance().getAllParsedArtifacts() + ).map((artifact) => artifact.id); + const change = compareInventoryWithGroups(inventoryIds, flowGroups); + if (change.added.length > 0 || change.removed.length > 0) { + const choice = await vscode.window.showInformationMessage( + UserPrompts.inventoryChangedSinceGrouping( + change.added.length, + change.removed.length + ), + UserPrompts.BUTTON_REDETECT_GROUPS + ); + if (choice === UserPrompts.BUTTON_REDETECT_GROUPS) { + await this.handleRedetectFlowGroups(); + } + } } } catch (autoDetectError) { LoggingService.getInstance().debug( @@ -875,8 +906,64 @@ export class CommandRegistry implements vscode.Disposable { return; } - // No cache at all — open webview with loading state, then start flow group detection + // No cache at all — detect the logical groups + if ( + this.getGroupingMode() === 'deterministic' && + (await this.detectFlowGroupsDeterministically(extensionUri)) + ) { + return; + } + await this.startCopilotFlowGroupDetection(extensionUri); + } + + private getGroupingMode(): FlowGroupingMode { + return resolveGroupingMode( + vscode.workspace + .getConfiguration('logicAppsMigrationAgent') + .get('discovery.groupingMode', 'auto'), + StateManager.getInstance().getState().sourcePlatform + ); + } + + /** + * Group the discovered artifacts from call chains, references and port bindings (no Copilot) + * and show Home. Returns false when no orchestration/flow exists, so Copilot can group instead. + */ + private async detectFlowGroupsDeterministically(extensionUri: vscode.Uri): Promise { + const artifacts = await InventoryService.getInstance().getAllParsedArtifacts(); + const result = detectFlowGroups(artifacts); + if (result.groups.length === 0) { + LoggingService.getInstance().info( + '[Discovery] No orchestrations or flows to group deterministically; using Copilot' + ); + return false; + } + await SourceFlowVisualizer.applyFlowGroups(result, extensionUri); + TelemetryService.getInstance().logStep('flowgroups.detection.completed', { + mode: 'deterministic', + flowGroupCount: result.groups.length, + sharedArtifactCount: result.sharedArtifactIds?.length ?? 0, + ungroupedArtifactCount: result.ungroupedArtifactIds.length, + missingProjectCount: result.missingProjects?.length ?? 0, + }); + void vscode.window.showInformationMessage( + UserPrompts.flowGroupsDetected( + result.groups.length, + result.sharedArtifactIds?.length ?? 0 + ) + ); + if (result.missingProjects && result.missingProjects.length > 0) { + void vscode.window.showWarningMessage( + UserPrompts.missingReferencedProjects( + result.missingProjects.map((missing) => missing.project) + ) + ); + } + return true; + } + + private async startCopilotFlowGroupDetection(extensionUri: vscode.Uri): Promise { // Open webview immediately with a loading spinner SourceFlowVisualizer.showLoading(extensionUri, 'Detecting logical groups...'); SourceFlowVisualizer.isInitialGenerating = true; @@ -896,6 +983,32 @@ export class CommandRegistry implements vscode.Disposable { } } + /** + * Re-detect logical groups for the current inventory (e.g. after adding projects). + * Flow IDs are stable, so analysis, plans and conversions of unchanged flows are kept. + */ + private async handleRedetectFlowGroups(): Promise { + if (SourceFlowVisualizer.isAnyFlowBusy || SourceFlowVisualizer.isInitialGenerating) { + vscode.window.showWarningMessage(UserPrompts.FLOW_WORK_IN_PROGRESS); + return; + } + const inventory = DiscoveryService.getInstance().getCurrentInventory(); + if (!inventory || inventory.statistics.totalCount === 0) { + vscode.window.showWarningMessage(UserPrompts.NO_ARTIFACTS_RUN_DISCOVERY); + return; + } + const extensionUri = + vscode.extensions.getExtension('logicapps-migration-agent')?.extensionUri ?? + vscode.Uri.file(__dirname); + if ( + this.getGroupingMode() === 'deterministic' && + (await this.detectFlowGroupsDeterministically(extensionUri)) + ) { + return; + } + await this.startCopilotFlowGroupDetection(extensionUri); + } + /** * Handle viewing dependency graph */ diff --git a/src/constants/ChatPrompts.ts b/src/constants/ChatPrompts.ts index 7f6153a..474bdb0 100644 --- a/src/constants/ChatPrompts.ts +++ b/src/constants/ChatPrompts.ts @@ -127,6 +127,7 @@ export class ChatPrompts { SKILL_AUTHORITY + '\nREQUIRED SKILLS: Read `detect-logical-groups` first and follow it exactly.\n' + 'The skill contains all grouping rules, fallback logic, and required output fields.\n' + + 'Start from the deterministic proposedGroups returned by migration_detectFlowGroups: keep their ids, artifactIds, endpointNames and shared artifacts, and only improve names and descriptions.\n' + 'Do NOT read source files or generate architecture diagrams — only detect and store groups.' ); } @@ -278,9 +279,9 @@ export class ChatPrompts { '- `dependency-and-decompilation-analysis` — DLL decompilation, missing dependency classification\n' + '- `source-to-logic-apps-mapping` — component equivalents, service provider IDs, operation names\n' + `\nPROCEDURE:\n` + - `1. Call migration_detectFlowGroups with groupId="${params.flowId}" to retrieve the cached group artifact list.\n` + + `1. Call migration_detectFlowGroups with groupId="${params.flowId}" to retrieve the cached group artifact list. If it lists endpointNames, only those ports belong to this flow; ports of other flows in shared binding files are out of scope.\n` + '2. Call migration_getArtifactDetails and migration_readSourceFile for EVERY artifact per skill `analyse-source-design`.\n' + - '3. If any required dependency/detail is unresolved, expand to full-project lookup (all artifacts), then continue analysis.\n' + + '3. If any required dependency/detail is unresolved, expand to full-project lookup (all artifacts), then continue analysis. Record what you find outside the group as external dependencies, not as components of this flow.\n' + '4. Perform dependency analysis per skill `dependency-and-decompilation-analysis` (decompile DLLs/JARs, classify missing deps).\n' + '5. Look up every component in skill `source-to-logic-apps-mapping`, then search reference docs with those names.\n' + '6. Generate Mermaid architecture diagram per skill `analyse-source-design` rules.\n' + diff --git a/src/constants/UserMessages.ts b/src/constants/UserMessages.ts index 9858475..82d1f79 100644 --- a/src/constants/UserMessages.ts +++ b/src/constants/UserMessages.ts @@ -183,6 +183,33 @@ export class UserPrompts { return format('Failed to start flow group detection: {0}', errorMsg); } + static readonly BUTTON_REDETECT_GROUPS = 'Re-detect Groups'; + static readonly FLOW_WORK_IN_PROGRESS = + 'A flow is still being analysed, planned or converted. Stop it or wait before re-detecting logical groups.'; + + static missingReferencedProjects(projects: string[]): string { + return format( + 'Referenced projects are missing from the source folder: {0}. Add them and run Rescan Artifacts so flows include their schemas and code.', + projects.join(', ') + ); + } + + static inventoryChangedSinceGrouping(added: number, removed: number): string { + return format( + 'The rescan found {0} new and {1} removed artifact(s) that the logical groups do not reflect yet. Re-detect groups now? Progress on unchanged flows is kept.', + added, + removed + ); + } + + static flowGroupsDetected(count: number, shared: number): string { + return format( + 'Detected {0} logical group(s) from orchestration call chains and port bindings; {1} artifact(s) are shared between groups.', + count, + shared + ); + } + // ======================================================================== // Command Registry — Dependency Graph // ======================================================================== diff --git a/src/copilot/MigrationLMTools.ts b/src/copilot/MigrationLMTools.ts index 4a86034..504406f 100644 --- a/src/copilot/MigrationLMTools.ts +++ b/src/copilot/MigrationLMTools.ts @@ -21,6 +21,12 @@ import * as path from 'path'; import { randomUUID } from 'crypto'; import { InventoryService } from '../stages/discovery/InventoryService'; import { ParsedArtifact } from '../stages/discovery/types'; +import { + detectFlowGroups, + findCrossGroupDependencies, + findUndeclaredSharedArtifacts, + scopeEndpointsToFlow, +} from '../stages/discovery/FlowGroupDetector'; import { LoggingService } from '../services/LoggingService'; import { TelemetryService } from '../services/TelemetryService'; import { ContextBuilder, ContextScope } from './ContextBuilder'; @@ -112,9 +118,12 @@ interface StoreFlowGroupsInput { artifactIds: string[]; entryPoint?: { type: string; name: string; messageType?: string }; exitPoints?: { type: string; name: string; messageType?: string }[]; + endpointNames?: string[]; }[]; /** IDs of artifacts not belonging to any group */ ungroupedArtifactIds?: string[]; + /** Artifacts used by several groups; listed in each group that uses them */ + sharedArtifactIds?: string[]; /** Explanation of how groups were determined */ explanation?: string; } @@ -1137,15 +1146,28 @@ class DetectFlowGroupsTool implements vscode.LanguageModelTool { const summary: Record = { id: a.id, name: a.name, type: a.type, }; - if (a.ir.endpoints?.receive && a.ir.endpoints.receive.length > 0) { - summary.receiveEndpoints = a.ir.endpoints.receive.map((ep) => { + if (sharedIds.has(a.id)) { + summary.sharedWithOtherFlows = true; + } + const scoped = scopeEndpointsToFlow( + a.ir.endpoints?.receive ?? [], + a.ir.endpoints?.send ?? [], + group.endpointNames + ); + if (scoped.omitted > 0) { + summary.endpointsOfOtherFlowsOmitted = scoped.omitted; + } + if (scoped.receive.length > 0) { + summary.receiveEndpoints = scoped.receive.map((ep) => { const sourceMapping = ep.sourceMapping as | { biztalk?: { receivePortName?: string } } | undefined; @@ -1157,8 +1179,8 @@ class DetectFlowGroupsTool implements vscode.LanguageModelTool 0) { - summary.sendEndpoints = a.ir.endpoints.send.map((ep) => { + if (scoped.send.length > 0) { + summary.sendEndpoints = scoped.send.map((ep) => { const result: Record = { name: ep.name }; if ('transport' in ep) { result.transport = ep.transport; @@ -1199,6 +1221,11 @@ class DetectFlowGroupsTool implements vscode.LanguageModelTool(); - for (const group of input.groups) { - for (const artifactId of group.artifactIds || []) { - groupByArtifactId.set(artifactId, { id: group.id, name: group.name }); - } + // Enforce group independence for testing: reject group sets that introduce + // cross-group runtime/design dependencies. Shared artifacts (canonical schemas, + // binding files, common code) may be used by several groups. + const sharedArtifactIds = new Set( + (input.sharedArtifactIds ?? []).filter((id) => inventoryArtifactIds.has(id)) + ); + const undeclaredShared = findUndeclaredSharedArtifacts(input.groups, sharedArtifactIds); + if (undeclaredShared.length > 0) { + return new vscode.LanguageModelToolResult([ + new vscode.LanguageModelTextPart( + JSON.stringify({ + error: 'Some artifacts are listed in more than one group but not in sharedArtifactIds. Add them to sharedArtifactIds (they stay in every group that uses them) or keep each in one group.', + artifacts: undeclaredShared.slice(0, 12), + }) + ), + ]); } const connectionGraph = LLMFlowGenerator.getInstance().buildArtifactConnectionGraph(parsedArtifacts); - const blockingConnectionTypes = new Set([ - 'subscription-filter', - 'message-type-subscription', - 'map-source-schema', - 'map-target-schema', - 'orchestration-uses-map', - 'orchestration-calls', - 'binding-references', - ]); - - const crossGroupDependencies = connectionGraph.connections.filter((c) => { - if (!blockingConnectionTypes.has(c.type)) { - return false; - } - const fromGroup = groupByArtifactId.get(c.fromId); - const toGroup = groupByArtifactId.get(c.toId); - if (!fromGroup || !toGroup) { - return false; - } - return fromGroup.id !== toGroup.id; - }); + const crossGroupDependencies = findCrossGroupDependencies( + input.groups, + connectionGraph.connections, + sharedArtifactIds + ); if (crossGroupDependencies.length > 0) { - const dependencySample = crossGroupDependencies.slice(0, 12).map((c) => { - const fromGroup = groupByArtifactId.get(c.fromId); - const toGroup = groupByArtifactId.get(c.toId); - return { - fromGroup: fromGroup?.name || fromGroup?.id || 'unknown', - toGroup: toGroup?.name || toGroup?.id || 'unknown', - fromArtifactId: c.fromId, - toArtifactId: c.toId, - dependencyType: c.type, - evidence: c.evidence, - }; - }); - return new vscode.LanguageModelToolResult([ new vscode.LanguageModelTextPart( JSON.stringify({ - error: 'Group independence validation failed: one or more groups depend on artifacts in another group. Groups must be independently testable. Merge dependent artifacts into the same group or move shared dependencies to external mocks/stubs.', + error: 'Group independence validation failed: one or more groups depend on artifacts in another group. Groups must be independently testable. Merge groups only when their orchestrations call each other; otherwise list the depended-on artifacts (e.g. canonical schemas, binding files, common code) in sharedArtifactIds and in the artifactIds of every group that uses them.', dependencyCount: crossGroupDependencies.length, - dependencies: dependencySample, + dependencies: crossGroupDependencies.slice(0, 12), }) ), ]); @@ -1534,54 +1556,43 @@ class StoreFlowGroupsTool implements vscode.LanguageModelTool ({ - id: g.id, - name: g.name, - description: g.description, - category: (g.category || 'message-flow') as FlowGroup['category'], - artifactIds: g.artifactIds, - entryPoint: g.entryPoint as FlowGroup['entryPoint'], - exitPoints: g.exitPoints as FlowGroup['exitPoints'], - })), - ungroupedArtifactIds: input.ungroupedArtifactIds ?? [], - explanation: input.explanation ?? '', - }); - - // Also store in SourceFlowVisualizer static cache for backward compat - SourceFlowVisualizer.setStaticCachedFlowGroups({ - groups: input.groups.map((g) => ({ - id: g.id, - name: g.name, - description: g.description, - category: (g.category || 'message-flow') as FlowGroup['category'], - artifactIds: g.artifactIds, - })), - ungroupedArtifactIds: input.ungroupedArtifactIds ?? [], - explanation: input.explanation ?? '', - }); - - // Show flow group selector in the webview const extensionUri = vscode.extensions.getExtension('logicapps-migration-agent')?.extensionUri ?? vscode.Uri.file(__dirname); + const missingProjects = detectFlowGroups(parsedArtifacts).missingProjects ?? []; - SourceFlowVisualizer.showFlowGroupSelector(extensionUri); - - // Clear generation flags - SourceFlowVisualizer.isInitialGenerating = false; + // Store flow groups (replacing earlier ones) and show the flow group selector + await SourceFlowVisualizer.applyFlowGroups( + { + groups: input.groups.map((g) => ({ + id: g.id, + name: g.name, + description: g.description, + category: (g.category || 'message-flow') as FlowGroup['category'], + artifactIds: g.artifactIds, + entryPoint: g.entryPoint as FlowGroup['entryPoint'], + exitPoints: g.exitPoints as FlowGroup['exitPoints'], + ...(g.endpointNames && g.endpointNames.length > 0 + ? { endpointNames: g.endpointNames } + : {}), + })), + ungroupedArtifactIds: input.ungroupedArtifactIds ?? [], + sharedArtifactIds: [...sharedArtifactIds], + missingProjects, + explanation: input.explanation ?? '', + detectionMode: 'copilot', + }, + extensionUri + ); logger.debug( `[LMTool] migration_discovery_storeFlowGroups: stored ${input.groups.length} groups` ); TelemetryService.getInstance().logStep('flowgroups.detection.completed', { + mode: 'copilot', flowGroupCount: input.groups.length, + sharedArtifactCount: sharedArtifactIds.size, flows: input.groups .map((g) => `${g.id}|${g.name}|${g.category ?? 'message-flow'}`) .join('; ') diff --git a/src/parsers/biztalk/BizTalkBindingsParser.ts b/src/parsers/biztalk/BizTalkBindingsParser.ts index 820be82..73dc7cb 100644 --- a/src/parsers/biztalk/BizTalkBindingsParser.ts +++ b/src/parsers/biztalk/BizTalkBindingsParser.ts @@ -1009,6 +1009,8 @@ export class BizTalkBindingsParser extends AbstractParser implements IArtifactPa receivePipeline: sp.receivePipeline, isTwoWay: sp.isTwoWay, filter: sp.filter, + inboundMaps: sp.inboundMaps, + outboundMaps: sp.outboundMaps, }, }, } as unknown as IRSendEndpoint); diff --git a/src/parsers/biztalk/BizTalkMapParser.ts b/src/parsers/biztalk/BizTalkMapParser.ts index 476e266..c2de2bc 100644 --- a/src/parsers/biztalk/BizTalkMapParser.ts +++ b/src/parsers/biztalk/BizTalkMapParser.ts @@ -266,19 +266,24 @@ export class BizTalkMapParser extends AbstractParser implements IArtifactParser // Look for SchemaReference elements or SrcTree/TrgTree const srcTreeElements = getAllElements(rootElement, 'SrcTree'); const trgTreeElements = getAllElements(rootElement, 'TrgTree'); + // Mapper output records the schema as + const treeReference = (tree: Element): string => + getAllElements(tree, 'Reference') + .map((reference) => getAttr(reference, 'Location') || '') + .find((location) => location.length > 0) || ''; if (srcTreeElements.length > 0) { sourceSchema = getAttr(srcTreeElements[0], 'RootType_Name') || getAttr(srcTreeElements[0], 'SchemaRef') || - ''; + treeReference(srcTreeElements[0]); } if (trgTreeElements.length > 0) { targetSchema = getAttr(trgTreeElements[0], 'RootType_Name') || getAttr(trgTreeElements[0], 'SchemaRef') || - ''; + treeReference(trgTreeElements[0]); } // Parse functoids diff --git a/src/parsers/biztalk/BizTalkProjectParser.ts b/src/parsers/biztalk/BizTalkProjectParser.ts index ce7a1aa..64a2fd5 100644 --- a/src/parsers/biztalk/BizTalkProjectParser.ts +++ b/src/parsers/biztalk/BizTalkProjectParser.ts @@ -570,6 +570,7 @@ export class BizTalkProjectParser extends AbstractParser implements IProjectPars projectName: projectInfo.name, projectNamespace: projectInfo.namespace, assemblyVersion: projectInfo.version, + projectReferences: [...projectInfo.projectReferences], }, }, }; diff --git a/src/services/LLMFlowGenerator.ts b/src/services/LLMFlowGenerator.ts index 763bcef..65e721f 100644 --- a/src/services/LLMFlowGenerator.ts +++ b/src/services/LLMFlowGenerator.ts @@ -122,7 +122,7 @@ export interface FlowGroup { }; /** Entry point for this flow (if message-flow category) */ entryPoint?: { - type: 'receive-location' | 'receive-port' | 'orchestration'; + type: 'receive-location' | 'receive-port' | 'orchestration' | 'flow'; name: string; messageType?: string; }; @@ -132,6 +132,23 @@ export interface FlowGroup { name: string; messageType?: string; }[]; + /** + * Receive locations/ports, send ports and send port groups that belong to this flow. + * Binding files hold the ports of a whole application, so this scopes them per flow. + */ + endpointNames?: string[]; +} + +/** + * A source project referenced by a scanned project but missing from the scanned folder. + */ +export interface MissingProjectReference { + /** Referenced project name (file name without extension) */ + project: string; + /** Path recorded in the referencing project */ + path: string; + /** Projects that reference it */ + referencedBy: string[]; } /** @@ -144,12 +161,21 @@ export interface FlowGroupsResult { ungroupedArtifactIds: string[]; /** Overall explanation of the grouping */ explanation: string; + /** + * Artifacts used by more than one flow (e.g. canonical schemas, binding files). + * They are listed in every group that uses them instead of forcing those flows to merge. + */ + sharedArtifactIds?: string[]; + /** Referenced source projects that were not found in the scanned folder */ + missingProjects?: MissingProjectReference[]; + /** How the groups were produced */ + detectionMode?: 'deterministic' | 'copilot'; } /** * A deterministic connection between two artifacts discovered from IR data */ -interface ArtifactConnection { +export interface ArtifactConnection { fromId: string; toId: string; type: @@ -512,8 +538,10 @@ export class LLMFlowGenerator { for (const a of artifacts) { if (a.ir.maps) { for (const map of a.ir.maps) { - const sourceRef = map.source?.schemaRef; - const targetRef = map.target?.schemaRef; + // BizTalk maps record their trees as sourceSchema/targetSchema + const btmMap = map as { sourceSchema?: string; targetSchema?: string }; + const sourceRef = map.source?.schemaRef || btmMap.sourceSchema; + const targetRef = map.target?.schemaRef || btmMap.targetSchema; if (sourceRef) { // Find artifacts that define this source schema @@ -682,15 +710,14 @@ export class LLMFlowGenerator { if (other.id === a.id || other.type !== 'orchestration') { continue; } - // Match: exact name, or target ends with the artifact name, or artifact name ends with the target + // Match exact or namespace-qualified names only; substring matches + // ("Order" vs "OrderStatus") create false call chains. const otherName = other.name; if ( targetOrchName === otherName || targetOrchName.endsWith('.' + otherName) || targetOrchName.endsWith('/' + otherName) || - otherName.endsWith('.' + targetOrchName) || - targetOrchName.includes(otherName) || - otherName.includes(targetOrchName) + otherName.endsWith('.' + targetOrchName) ) { connections.push({ fromId: a.id, @@ -735,9 +762,7 @@ export class LLMFlowGenerator { targetName === other.name || targetName.endsWith('.' + other.name) || targetName.endsWith('/' + other.name) || - other.name.endsWith('.' + targetName) || - other.name.includes(targetName) || - targetName.includes(other.name) + other.name.endsWith('.' + targetName) ) { connections.push({ fromId: a.id, diff --git a/src/stages/discovery/DiscoveryCacheService.ts b/src/stages/discovery/DiscoveryCacheService.ts index 6b20a03..3f92e89 100644 --- a/src/stages/discovery/DiscoveryCacheService.ts +++ b/src/stages/discovery/DiscoveryCacheService.ts @@ -39,10 +39,8 @@ export interface DiscoveryFlowGroup extends FlowGroup { /** * Flow groups result with per-flow discovery status. */ -export interface DiscoveryFlowGroupsResult { +export interface DiscoveryFlowGroupsResult extends Omit { groups: DiscoveryFlowGroup[]; - ungroupedArtifactIds: string[]; - explanation: string; } /** @@ -97,20 +95,25 @@ export class DiscoveryCacheService { // ========================================================================= /** - * Store flow groups (from initial detection). - * Sets all flows to `discovered: false` unless they already have analysis on disk. + * Store flow groups (from initial detection or re-detection). + * Groups keep the analysis, planning and conversion progress saved under the same flow ID. */ public async storeFlowGroups(flowGroupsResult: FlowGroupsResult): Promise { - const discoveryGroups: DiscoveryFlowGroup[] = flowGroupsResult.groups.map((g) => ({ - ...g, - discovered: this.hasAnalysis(g.id), - })); - - this.flowGroupsCache = { - groups: discoveryGroups, - ungroupedArtifactIds: flowGroupsResult.ungroupedArtifactIds, - explanation: flowGroupsResult.explanation, - }; + this.ensureLoaded(); + const previous = new Map((this.flowGroupsCache?.groups ?? []).map((g) => [g.id, g])); + const discoveryGroups: DiscoveryFlowGroup[] = flowGroupsResult.groups.map((g) => { + const earlier = previous.get(g.id); + return { + ...g, + discovered: this.hasAnalysis(g.id), + ...(earlier?.planned ? { planned: true } : {}), + ...(earlier?.tasksCreated ? { tasksCreated: true } : {}), + ...(earlier?.converted ? { converted: true } : {}), + }; + }); + + this.flowGroupsCache = { ...flowGroupsResult, groups: discoveryGroups }; + this.reconcileFlowStates(); await this.saveFlowGroupsToDisk(); this.logger.debug(`[DiscoveryCache] Stored ${discoveryGroups.length} flow groups`); diff --git a/src/stages/discovery/FlowGroupDetector.ts b/src/stages/discovery/FlowGroupDetector.ts new file mode 100644 index 0000000..38e55d1 --- /dev/null +++ b/src/stages/discovery/FlowGroupDetector.ts @@ -0,0 +1,1034 @@ +/** + * Flow Group Detector + * + * Groups discovered artifacts into logical flows without Copilot: + * - orchestrations / flows / processes linked by call chains form one flow; + * - maps, schemas, pipelines, ports, projects and code attach to the flows that use them; + * - artifacts used by several flows are marked shared instead of forcing those flows to merge. + * + * The same inventory always produces the same groups, IDs and names. + * + * @module stages/discovery/FlowGroupDetector + */ + +import * as path from 'path'; +import { createHash } from 'crypto'; +import type { ParsedArtifact } from './types'; +import type { + ArtifactConnection, + FlowGroup, + FlowGroupsResult, + MissingProjectReference, +} from '../../services/LLMFlowGenerator'; + +type JsonObject = Record; + +const ROOT_TYPES: ReadonlySet = new Set(['orchestration', 'flow', 'process', 'workflow']); +const MAP_TYPES: ReadonlySet = new Set(['map']); +const SCHEMA_TYPES: ReadonlySet = new Set(['schema']); +const PIPELINE_TYPES: ReadonlySet = new Set(['pipeline']); +const PROJECT_EXTENSIONS: ReadonlySet = new Set(['.btproj', '.csproj', '.vbproj']); +const MAX_LISTED = 5; + +/** Connection types that make two groups depend on each other. */ +export const BLOCKING_CONNECTION_TYPES: ReadonlySet = new Set([ + 'subscription-filter', + 'message-type-subscription', + 'map-source-schema', + 'map-target-schema', + 'orchestration-uses-map', + 'orchestration-calls', + 'binding-references', +]); + +export type FlowGroupingMode = 'deterministic' | 'copilot'; + +/** Resolve the `discovery.groupingMode` setting; `auto` groups BizTalk deterministically. */ +export function resolveGroupingMode( + setting: unknown, + platform: string | undefined +): FlowGroupingMode { + if (setting === 'deterministic' || setting === 'copilot') { + return setting; + } + return (platform || 'biztalk').toLowerCase() === 'biztalk' ? 'deterministic' : 'copilot'; +} + +// ============================================================================= +// Small helpers +// ============================================================================= + +function asObject(value: unknown): JsonObject | undefined { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? (value as JsonObject) + : undefined; +} + +function asString(value: unknown): string | undefined { + return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined; +} + +function asStringArray(value: unknown): string[] { + return Array.isArray(value) + ? value.map(asString).filter((item): item is string => item !== undefined) + : []; +} + +function objectsOf(value: unknown): JsonObject[] { + return Array.isArray(value) + ? value.map(asObject).filter((item): item is JsonObject => item !== undefined) + : []; +} + +function biztalkExtension(artifact: ParsedArtifact): JsonObject { + return asObject(asObject(artifact.ir?.extensions)?.biztalk) ?? {}; +} + +function byName(a: string, b: string): number { + return a.localeCompare(b, 'en', { sensitivity: 'base' }) || a.localeCompare(b); +} + +/** Reduce a type name, assembly-qualified name or file path to its lower-case simple name. */ +export function simpleName(reference: string): string { + const typeName = reference.split(',')[0].split('+')[0].trim(); + const fileName = typeName.split(/[\\/]/).pop() ?? typeName; + const withoutExtension = fileName.replace( + /\.(xsd|btm|odx|btp|xslt?|dwl|bwp|process|xml|cs|btproj|csproj)$/i, + '' + ); + const segments = withoutExtension.split('.'); + return (segments[segments.length - 1] ?? '').trim().toLowerCase(); +} + +function normalizePath(filePath: string): string { + return path + .resolve(filePath) + .replace(/[\\/]+$/, '') + .toLowerCase(); +} + +function isWithin(filePath: string, directory: string): boolean { + return normalizePath(filePath).startsWith(normalizePath(directory) + path.sep); +} + +function artifactPath(artifact: ParsedArtifact): string { + return artifact.absolutePath || artifact.sourcePath; +} + +function isProject(artifact: ParsedArtifact): boolean { + return PROJECT_EXTENSIONS.has(path.extname(artifactPath(artifact)).toLowerCase()); +} + +function slug(value: string): string { + const result = value + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 60) + .replace(/-+$/g, ''); + return result || 'flow'; +} + +function shortHash(value: string): string { + return createHash('sha256').update(value).digest('hex').slice(0, 6); +} + +/** Turn `Orch_OrderNotification` or `Company.Sales.OrderNotification` into `Order Notification`. */ +export function humanizeName(name: string): string { + const base = name.split(/[.\\/]/).pop() || name; + const words = base + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') + .split(/[\s_-]+/) + .filter(Boolean); + const meaningful = words.filter((word) => !/^(orch|orchestration|odx)$/i.test(word)); + return (meaningful.length > 0 ? meaningful : words) + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(' '); +} + +function listNames(names: readonly string[]): string { + const shown = names.slice(0, MAX_LISTED).join(', '); + return names.length > MAX_LISTED ? `${shown} (+${names.length - MAX_LISTED} more)` : shown; +} + +/** Visit every nested object of an IR fragment (actions, branches, scopes, source mappings). */ +function visitObjects(value: unknown, visit: (node: JsonObject) => void, depth = 0): void { + if (depth > 60 || value === null || typeof value !== 'object') { + return; + } + if (Array.isArray(value)) { + for (const item of value) { + visitObjects(item, visit, depth + 1); + } + return; + } + const node = value as JsonObject; + visit(node); + for (const child of Object.values(node)) { + if (child !== null && typeof child === 'object') { + visitObjects(child, visit, depth + 1); + } + } +} + +// ============================================================================= +// Artifact lookup by referenced type/file name +// ============================================================================= + +class ArtifactIndex { + private readonly entries = new Map(); + + constructor(artifacts: readonly ParsedArtifact[]) { + for (const artifact of artifacts) { + const names = new Set([simpleName(artifact.name)]); + for (const schema of artifact.ir?.schemas ?? []) { + if (schema.name) { + names.add(simpleName(schema.name)); + } + } + for (const map of artifact.ir?.maps ?? []) { + if (map.name) { + names.add(simpleName(map.name)); + } + } + const orchestrationName = asString(biztalkExtension(artifact).orchestrationName); + if (orchestrationName) { + names.add(simpleName(orchestrationName)); + } + for (const name of names) { + if (name) { + const list = this.entries.get(name) ?? []; + list.push(artifact); + this.entries.set(name, list); + } + } + } + } + + find(reference: string, types: ReadonlySet): ParsedArtifact[] { + const candidates = (this.entries.get(simpleName(reference)) ?? []).filter((artifact) => + types.has(artifact.type) + ); + return this.disambiguate(reference, candidates); + } + + /** Prefer candidates whose folders match the namespace of a qualified reference. */ + private disambiguate(reference: string, candidates: ParsedArtifact[]): ParsedArtifact[] { + if (candidates.length <= 1) { + return candidates; + } + const qualifiers = reference + .split(',')[0] + .split('+')[0] + .trim() + .toLowerCase() + .split('.') + .slice(0, -1); + if (qualifiers.length === 0) { + return candidates; + } + const scored = candidates.map((candidate) => { + const location = artifactPath(candidate) + .toLowerCase() + .split(/[\\/.]/); + return { + candidate, + score: qualifiers.filter((qualifier) => location.includes(qualifier)).length, + }; + }); + const best = Math.max(...scored.map((entry) => entry.score)); + return best === 0 + ? candidates + : scored.filter((entry) => entry.score === best).map((entry) => entry.candidate); + } +} + +// ============================================================================= +// BizTalk binding model +// ============================================================================= + +interface ReceivePortModel { + port: string; + locations: { name: string; adapter?: string }[]; + pipelines: string[]; + maps: string[]; +} + +interface SendPortModel { + port: string; + adapter?: string; + filter: string; + pipelines: string[]; + maps: string[]; +} + +interface BindingModel { + artifact: ParsedArtifact; + receivePorts: Map; + sendPorts: Map; + sendGroups: Map; + orchestrationBindings: { orchestrationName: string; boundTo: string[] }[]; +} + +function readBinding(artifact: ParsedArtifact): BindingModel { + const endpoints = asObject((artifact.ir as unknown as JsonObject)?.endpoints) ?? {}; + const extension = biztalkExtension(artifact); + + const receivePorts = new Map(); + const receivePort = (name: string): ReceivePortModel => { + const existing = receivePorts.get(name); + if (existing) { + return existing; + } + const created: ReceivePortModel = { port: name, locations: [], pipelines: [], maps: [] }; + receivePorts.set(name, created); + return created; + }; + for (const endpoint of objectsOf(endpoints.receive)) { + const biztalk = asObject(asObject(endpoint.sourceMapping)?.biztalk) ?? {}; + const location = asString(endpoint.name) ?? asString(biztalk.receiveLocationName); + const portName = asString(biztalk.receivePortName) ?? location; + if (!portName) { + continue; + } + const port = receivePort(portName); + if (location) { + port.locations.push({ + name: location, + adapter: asString(biztalk.adapterType) ?? asString(endpoint.transport), + }); + } + port.pipelines.push(...asStringArray([biztalk.pipeline, biztalk.sendPipeline])); + } + for (const detail of objectsOf(extension.receivePortDetails)) { + const name = asString(detail.name); + if (name) { + receivePort(name).maps.push( + ...asStringArray(detail.inboundMaps), + ...asStringArray(detail.outboundMaps) + ); + } + } + + const sendPorts = new Map(); + for (const endpoint of objectsOf(endpoints.send)) { + const biztalk = asObject(asObject(endpoint.sourceMapping)?.biztalk) ?? {}; + const name = asString(endpoint.name) ?? asString(biztalk.sendPortName); + if (!name) { + continue; + } + sendPorts.set(name, { + port: name, + adapter: asString(biztalk.adapterType) ?? asString(endpoint.transport), + filter: asString(biztalk.filter) ?? '', + pipelines: asStringArray([biztalk.pipeline, biztalk.receivePipeline]), + maps: [...asStringArray(biztalk.inboundMaps), ...asStringArray(biztalk.outboundMaps)], + }); + } + + const sendGroups = new Map(); + for (const group of objectsOf(endpoints.sendGroups)) { + const name = asString(group.name); + if (name) { + const filter = objectsOf(group.filters) + .map((item) => asString(item.value) ?? '') + .join(' '); + sendGroups.set(name, { members: asStringArray(group.sendEndpoints), filter }); + } + } + + const orchestrationBindings = objectsOf(extension.orchestrationBindings).map((binding) => ({ + orchestrationName: asString(binding.orchestrationName) ?? '', + boundTo: objectsOf(binding.portBindings) + .map((portBinding) => asString(portBinding.boundTo)) + .filter((name): name is string => name !== undefined), + })); + + return { artifact, receivePorts, sendPorts, sendGroups, orchestrationBindings }; +} + +/** Receive ports a BizTalk subscription filter routes from (`BTS.ReceivePortName == X`). */ +export function subscribedReceivePorts(filter: string): string[] { + const ports = new Set(); + for (const statement of filter.match(/]*>/gi) ?? []) { + const attribute = (name: string) => + new RegExp(`\\b${name}\\s*=\\s*"([^"]*)"`, 'i').exec(statement)?.[1]; + const operator = attribute('Operator') ?? '0'; + const value = attribute('Value'); + if ( + attribute('Property')?.toLowerCase() === 'bts.receiveportname' && + operator === '0' && + value + ) { + ports.add(value); + } + } + for (const match of filter.matchAll(/BTS\.ReceivePortName\s*==\s*["']?([^"'\s)]+)["']?/gi)) { + ports.add(match[1]); + } + return [...ports]; +} + +// ============================================================================= +// Detection +// ============================================================================= + +interface Cluster { + key: string; + roots: ParsedArtifact[]; + routePort?: string; + seeds: Set; + members: Set; + bindings: Set; + receiveLocations: Map; + receivePorts: Set; + sendPorts: Map; + sendGroups: Set; +} + +function newCluster(key: string, roots: ParsedArtifact[], routePort?: string): Cluster { + return { + key, + roots, + routePort, + seeds: new Set(roots.map((root) => root.id)), + members: new Set(), + bindings: new Set(), + receiveLocations: new Map(), + receivePorts: new Set(), + sendPorts: new Map(), + sendGroups: new Set(), + }; +} + +/** + * Find project references (recorded by `.btproj` files) whose projects were not scanned. + */ +export function findMissingProjectReferences( + artifacts: readonly ParsedArtifact[] +): MissingProjectReference[] { + const scanned = new Set(artifacts.map((artifact) => normalizePath(artifactPath(artifact)))); + const missing = new Map(); + for (const artifact of artifacts) { + for (const reference of asStringArray(biztalkExtension(artifact).projectReferences)) { + const key = normalizePath(reference); + if (scanned.has(key)) { + continue; + } + const entry = missing.get(key) ?? { + project: path.basename(reference).replace(/\.[^.]+$/, ''), + path: reference, + referencedBy: [], + }; + if (!entry.referencedBy.includes(artifact.name)) { + entry.referencedBy.push(artifact.name); + entry.referencedBy.sort(byName); + } + missing.set(key, entry); + } + } + return [...missing.values()].sort((a, b) => byName(a.project, b.project)); +} + +/** + * Deterministically group artifacts into logical flows. + */ +export function detectFlowGroups(artifacts: readonly ParsedArtifact[]): FlowGroupsResult { + const sorted = [...artifacts].sort((a, b) => byName(a.id, b.id)); + const byId = new Map(sorted.map((artifact) => [artifact.id, artifact])); + const index = new ArtifactIndex(sorted); + const roots = sorted.filter((artifact) => ROOT_TYPES.has(artifact.type)); + + // ── Call chains: union roots that call or start each other (exact names only) ── + const parent = new Map(roots.map((root) => [root.id, root.id])); + const find = (id: string): string => { + let current = id; + while (parent.get(current) !== current) { + current = parent.get(current) as string; + } + parent.set(id, current); + return current; + }; + const union = (a: string, b: string) => { + const rootA = find(a); + const rootB = find(b); + if (rootA !== rootB) { + if (rootA < rootB) { + parent.set(rootB, rootA); + } else { + parent.set(rootA, rootB); + } + } + }; + + const uses = new Map>(); + const addUse = (from: string, to: string) => { + if (from !== to) { + const set = uses.get(from) ?? new Set(); + set.add(to); + uses.set(from, set); + } + }; + const calledRoots = new Set(); + + for (const root of roots) { + const callTargets = new Set(); + const mapReferences = new Set(); + visitObjects(root.ir?.actions, (node) => { + const shapeType = asString(node.shapeType); + if (shapeType === 'CallOrchestration' && asString(node.calledOrchestration)) { + callTargets.add(asString(node.calledOrchestration) as string); + } + if (shapeType === 'StartOrchestration' && asString(node.startedOrchestration)) { + callTargets.add(asString(node.startedOrchestration) as string); + } + if (node.type === 'call-workflow') { + const workflowName = asString(asObject(node.config)?.workflowName); + if (workflowName) { + callTargets.add(workflowName); + } + } + for (const reference of [asString(node.mapReference), asString(node.mapTypeName)]) { + if (reference) { + mapReferences.add(reference); + } + } + }); + for (const target of callTargets) { + for (const callee of index.find(target, ROOT_TYPES)) { + if (callee.id !== root.id) { + union(root.id, callee.id); + calledRoots.add(callee.id); + } + } + } + for (const reference of mapReferences) { + for (const map of index.find(reference, MAP_TYPES)) { + addUse(root.id, map.id); + } + } + for (const messageType of asStringArray(biztalkExtension(root).messageTypes)) { + for (const schema of index.find(messageType, SCHEMA_TYPES)) { + addUse(root.id, schema.id); + } + } + } + + // ── Maps use their source and target schemas ── + for (const artifact of sorted) { + for (const map of artifact.ir?.maps ?? []) { + const btm = map as unknown as JsonObject; + const references = [ + asString(btm.sourceSchema), + asString(btm.targetSchema), + asString(map.source?.schemaRef), + asString(map.target?.schemaRef), + ].filter((reference): reference is string => reference !== undefined); + for (const reference of references) { + for (const schema of index.find(reference, SCHEMA_TYPES)) { + addUse(artifact.id, schema.id); + } + } + } + } + + // ── Build clusters from call chains ── + const clustersByRoot = new Map(); + const clusters: Cluster[] = []; + for (const root of roots) { + const key = find(root.id); + let cluster = clustersByRoot.get(key); + if (!cluster) { + cluster = newCluster(key, []); + clustersByRoot.set(key, cluster); + clusters.push(cluster); + } + cluster.roots.push(root); + cluster.seeds.add(root.id); + } + const clusterOfRoot = (rootId: string) => clustersByRoot.get(find(rootId)); + + // ── Attribute binding ports to flows ── + const bindings = sorted + .filter((artifact) => artifact.type === 'binding') + .map((artifact) => readBinding(artifact)); + const attributedReceivePorts = new Set(); + const attributedSendPorts = new Set(); + const findRootForBinding = (orchestrationName: string): ParsedArtifact | undefined => { + const qualified = orchestrationName.toLowerCase(); + const exact = roots.find((root) => { + const extension = biztalkExtension(root); + const namespace = asString(extension.namespace); + const name = asString(extension.orchestrationName) ?? root.name; + return namespace ? `${namespace}.${name}`.toLowerCase() === qualified : false; + }); + return exact ?? index.find(orchestrationName, ROOT_TYPES)[0]; + }; + + const attributePort = (cluster: Cluster, binding: BindingModel, portName: string) => { + cluster.bindings.add(binding.artifact.id); + const receive = binding.receivePorts.get(portName); + if (receive) { + cluster.receivePorts.add(receive.port); + attributedReceivePorts.add(`${binding.artifact.id}:${receive.port}`); + for (const location of receive.locations) { + cluster.receiveLocations.set(location.name, location.adapter); + } + for (const pipeline of receive.pipelines) { + index.find(pipeline, PIPELINE_TYPES).forEach((a) => cluster.seeds.add(a.id)); + } + for (const map of receive.maps) { + index.find(map, MAP_TYPES).forEach((a) => cluster.seeds.add(a.id)); + } + return; + } + const send = binding.sendPorts.get(portName); + if (send) { + cluster.sendPorts.set(send.port, send.adapter); + attributedSendPorts.add(`${binding.artifact.id}:${send.port}`); + for (const pipeline of send.pipelines) { + index.find(pipeline, PIPELINE_TYPES).forEach((a) => cluster.seeds.add(a.id)); + } + for (const map of send.maps) { + index.find(map, MAP_TYPES).forEach((a) => cluster.seeds.add(a.id)); + } + return; + } + const group = binding.sendGroups.get(portName); + if (group) { + cluster.sendGroups.add(portName); + for (const member of group.members) { + if (binding.sendPorts.has(member)) { + attributePort(cluster, binding, member); + } + } + } + }; + + const attributeSubscribers = (cluster: Cluster, binding: BindingModel) => { + for (const send of binding.sendPorts.values()) { + if (subscribedReceivePorts(send.filter).some((p) => cluster.receivePorts.has(p))) { + attributePort(cluster, binding, send.port); + } + } + for (const [name, group] of binding.sendGroups) { + if (subscribedReceivePorts(group.filter).some((p) => cluster.receivePorts.has(p))) { + attributePort(cluster, binding, name); + } + } + }; + + for (const binding of bindings) { + for (const orchestrationBinding of binding.orchestrationBindings) { + const root = findRootForBinding(orchestrationBinding.orchestrationName); + const cluster = root ? clusterOfRoot(root.id) : undefined; + if (!cluster) { + continue; + } + for (const portName of orchestrationBinding.boundTo) { + attributePort(cluster, binding, portName); + } + } + for (const cluster of clusters) { + if (cluster.bindings.has(binding.artifact.id)) { + attributeSubscribers(cluster, binding); + } + } + } + + // ── Messaging-only routes: receive ports subscribed by send ports, no orchestration ── + for (const binding of bindings) { + const subscribed = new Set(); + for (const send of binding.sendPorts.values()) { + subscribedReceivePorts(send.filter).forEach((port) => subscribed.add(port)); + } + for (const group of binding.sendGroups.values()) { + subscribedReceivePorts(group.filter).forEach((port) => subscribed.add(port)); + } + for (const portName of [...binding.receivePorts.keys()].sort(byName)) { + if ( + !subscribed.has(portName) || + attributedReceivePorts.has(`${binding.artifact.id}:${portName}`) + ) { + continue; + } + const route = newCluster(`route:${binding.artifact.id}:${portName}`, [], portName); + clusters.push(route); + attributePort(route, binding, portName); + attributeSubscribers(route, binding); + } + } + + // ── Attach what each flow uses (transitively), then bindings ── + for (const cluster of clusters) { + const queue = [...cluster.seeds]; + while (queue.length > 0) { + const id = queue.shift() as string; + if (cluster.members.has(id) || !byId.has(id)) { + continue; + } + cluster.members.add(id); + for (const used of uses.get(id) ?? []) { + if (!ROOT_TYPES.has(byId.get(used)?.type ?? '')) { + queue.push(used); + } + } + } + cluster.bindings.forEach((id) => cluster.members.add(id)); + } + + // ── Attach projects containing members, the projects they reference, and their code ── + const projects = sorted.filter(isProject); + const projectByPath = new Map(projects.map((p) => [normalizePath(artifactPath(p)), p])); + const codeFiles = sorted.filter( + (artifact) => artifact.type === 'custom-code' && !isProject(artifact) + ); + for (const cluster of clusters) { + const memberPaths = [...cluster.members] + .map((id) => byId.get(id)) + .filter((artifact): artifact is ParsedArtifact => artifact !== undefined) + .map(artifactPath); + const attached = new Set( + projects.filter((project) => { + const directory = path.dirname(artifactPath(project)); + return memberPaths.some((memberPath) => isWithin(memberPath, directory)); + }) + ); + const pending = [...attached]; + while (pending.length > 0) { + const project = pending.shift() as ParsedArtifact; + for (const reference of asStringArray(biztalkExtension(project).projectReferences)) { + const referenced = projectByPath.get(normalizePath(reference)); + if (referenced && !attached.has(referenced)) { + attached.add(referenced); + pending.push(referenced); + } + } + } + for (const project of attached) { + cluster.members.add(project.id); + const directory = path.dirname(artifactPath(project)); + for (const code of codeFiles) { + if (isWithin(artifactPath(code), directory)) { + cluster.members.add(code.id); + } + } + } + } + + const populated = clusters.filter((cluster) => cluster.members.size > 0); + + // ── Shared artifacts: used by more than one flow ── + const usage = new Map(); + for (const cluster of populated) { + for (const id of cluster.members) { + usage.set(id, (usage.get(id) ?? 0) + 1); + } + } + const sharedArtifactIds = [...usage] + .filter(([, count]) => count > 1) + .map(([id]) => id) + .sort(byName); + + // ── Name and describe each flow ── + const groups = buildGroups(populated, byId, calledRoots); + const grouped = new Set(groups.flatMap((group) => group.artifactIds)); + const ungroupedArtifactIds = sorted + .filter((artifact) => !grouped.has(artifact.id)) + .map((artifact) => artifact.id); + + const unattributedPorts = bindings.flatMap((binding) => [ + ...[...binding.receivePorts.keys()].filter( + (port) => !attributedReceivePorts.has(`${binding.artifact.id}:${port}`) + ), + ...[...binding.sendPorts.keys()].filter( + (port) => !attributedSendPorts.has(`${binding.artifact.id}:${port}`) + ), + ]); + const missingProjects = findMissingProjectReferences(sorted); + + return { + groups, + ungroupedArtifactIds, + sharedArtifactIds, + missingProjects, + detectionMode: 'deterministic', + explanation: explain({ + artifactCount: sorted.length, + groups, + routes: populated.filter((cluster) => cluster.roots.length === 0).length, + rootCount: roots.length, + sharedCount: sharedArtifactIds.length, + ungroupedCount: ungroupedArtifactIds.length, + unattributedPorts: [...new Set(unattributedPorts)].sort(byName), + missingProjects, + }), + }; +} + +function buildGroups( + clusters: Cluster[], + byId: Map, + calledRoots: Set +): FlowGroup[] { + const candidates = clusters.map((cluster) => { + const roots = [...cluster.roots].sort((a, b) => byName(a.name, b.name)); + const entryRoots = roots.filter((root) => !calledRoots.has(root.id)); + const primary = entryRoots[0] ?? roots[0]; + const baseName = primary ? primary.name : (cluster.routePort ?? 'flow'); + return { cluster, roots, primary, baseName }; + }); + candidates.sort( + (a, b) => byName(slug(a.baseName), slug(b.baseName)) || byName(a.cluster.key, b.cluster.key) + ); + + const usedIds = new Set(); + const groups = candidates.map(({ cluster, roots, primary, baseName }) => { + let id = `flow-${slug(baseName)}`; + if (usedIds.has(id)) { + id = `flow-${slug(baseName)}-${shortHash(cluster.key)}`; + } + usedIds.add(id); + + const artifactIds = [...cluster.members].sort(byName); + const maps = artifactIds + .map((artifactId) => byId.get(artifactId)) + .filter((artifact): artifact is ParsedArtifact => artifact?.type === 'map') + .map((artifact) => artifact.name) + .sort(byName); + const receiveLocations = [...cluster.receiveLocations.keys()].sort(byName); + const sendPorts = [...cluster.sendPorts.keys()].sort(byName); + const endpointNames = [ + ...new Set([ + ...receiveLocations, + ...cluster.receivePorts, + ...sendPorts, + ...cluster.sendGroups, + ]), + ].sort(byName); + + const withAdapter = (name: string, adapter: string | undefined) => + adapter ? `${name} (${adapter})` : name; + const parts: string[] = []; + if (roots.length > 0) { + const label = + primary?.type === 'orchestration' + ? 'Orchestrations' + : primary?.type === 'process' + ? 'Processes' + : primary?.type === 'workflow' + ? 'Workflows' + : 'Flows'; + parts.push(`${label}: ${listNames(roots.map((root) => root.name))}.`); + } else { + parts.push( + `Messaging route without an orchestration (receive port ${cluster.routePort}).` + ); + } + if (receiveLocations.length > 0) { + parts.push( + `Receives: ${listNames(receiveLocations.map((name) => withAdapter(name, cluster.receiveLocations.get(name))))}.` + ); + } + if (sendPorts.length > 0) { + parts.push( + `Sends: ${listNames(sendPorts.map((name) => withAdapter(name, cluster.sendPorts.get(name))))}.` + ); + } + if (maps.length > 0) { + parts.push(`Maps: ${listNames(maps)}.`); + } + + let entryPoint: FlowGroup['entryPoint']; + if (receiveLocations.length > 0) { + entryPoint = { type: 'receive-location', name: receiveLocations[0] }; + } else if (cluster.routePort) { + entryPoint = { type: 'receive-port', name: cluster.routePort }; + } else if (primary) { + entryPoint = { + type: primary.type === 'orchestration' ? 'orchestration' : 'flow', + name: primary.name, + }; + } + + const group: FlowGroup = { + id, + name: roots.length > 0 ? humanizeName(baseName) : `${humanizeName(baseName)} Route`, + description: parts.join(' '), + category: + receiveLocations.length > 0 || cluster.routePort + ? 'message-flow' + : 'business-process', + artifactIds, + summary: { + receivePorts: receiveLocations.length || cluster.receivePorts.size, + orchestrations: roots.length, + maps: maps.length, + sendPorts: sendPorts.length, + }, + ...(entryPoint ? { entryPoint } : {}), + ...(sendPorts.length > 0 + ? { + exitPoints: sendPorts.map((name) => ({ + type: 'send-port' as const, + name, + })), + } + : {}), + ...(endpointNames.length > 0 ? { endpointNames } : {}), + }; + return group; + }); + return groups.sort((a, b) => byName(a.name, b.name) || byName(a.id, b.id)); +} + +function explain(details: { + artifactCount: number; + groups: FlowGroup[]; + routes: number; + rootCount: number; + sharedCount: number; + ungroupedCount: number; + unattributedPorts: string[]; + missingProjects: MissingProjectReference[]; +}): string { + const sentences = [ + `Grouped ${details.artifactCount} artifacts deterministically into ${details.groups.length} flow(s): ` + + `${details.groups.length - details.routes} built from ${details.rootCount} orchestration(s)/flow(s) ` + + `joined only by Call/Start Orchestration chains, and ${details.routes} messaging-only route(s).`, + `Maps, schemas, pipelines, ports and projects belong to the flows that reference them; ` + + `${details.sharedCount} artifact(s) used by several flows are shared and listed in each of them.`, + ]; + if (details.ungroupedCount > 0) { + sentences.push(`${details.ungroupedCount} artifact(s) are not referenced by any flow.`); + } + if (details.unattributedPorts.length > 0) { + sentences.push( + `Ports not linked to a flow by orchestration bindings or subscription filters: ${listNames(details.unattributedPorts)}.` + ); + } + if (details.missingProjects.length > 0) { + sentences.push( + `Referenced projects missing from the source folder: ${listNames(details.missingProjects.map((p) => p.project))}. Add them and rescan.` + ); + } + return sentences.join(' '); +} + +// ============================================================================= +// Validation and scoping helpers +// ============================================================================= + +export interface CrossGroupDependency { + fromGroup: string; + toGroup: string; + fromArtifactId: string; + toArtifactId: string; + dependencyType: string; + evidence: string; +} + +interface GroupMembership { + id: string; + name: string; + artifactIds?: readonly string[]; +} + +/** Artifacts placed in more than one group without being declared shared. */ +export function findUndeclaredSharedArtifacts( + groups: readonly GroupMembership[], + sharedArtifactIds: ReadonlySet +): { artifactId: string; groups: string[] }[] { + const memberships = new Map(); + for (const group of groups) { + for (const artifactId of new Set(group.artifactIds ?? [])) { + if (!sharedArtifactIds.has(artifactId)) { + memberships.set(artifactId, [...(memberships.get(artifactId) ?? []), group.name]); + } + } + } + return [...memberships] + .filter(([, names]) => names.length > 1) + .map(([artifactId, names]) => ({ artifactId, groups: names })); +} + +/** Dependencies between groups; edges touching shared artifacts are allowed. */ +export function findCrossGroupDependencies( + groups: readonly GroupMembership[], + connections: readonly ArtifactConnection[], + sharedArtifactIds: ReadonlySet +): CrossGroupDependency[] { + const groupOf = new Map(); + for (const group of groups) { + for (const artifactId of group.artifactIds ?? []) { + if (!sharedArtifactIds.has(artifactId)) { + groupOf.set(artifactId, group); + } + } + } + return connections + .filter((connection) => BLOCKING_CONNECTION_TYPES.has(connection.type)) + .map((connection) => ({ + connection, + from: groupOf.get(connection.fromId), + to: groupOf.get(connection.toId), + })) + .filter(({ from, to }) => from !== undefined && to !== undefined && from.id !== to.id) + .map(({ connection, from, to }) => ({ + fromGroup: from?.name || from?.id || 'unknown', + toGroup: to?.name || to?.id || 'unknown', + fromArtifactId: connection.fromId, + toArtifactId: connection.toId, + dependencyType: connection.type, + evidence: connection.evidence, + })); +} + +/** + * Artifacts added to or removed from the inventory since the groups were detected. + */ +export function compareInventoryWithGroups( + inventoryIds: readonly string[], + result: Pick +): { added: string[]; removed: string[] } { + const known = new Set([ + ...result.groups.flatMap((group) => group.artifactIds ?? []), + ...(result.ungroupedArtifactIds ?? []), + ...(result.sharedArtifactIds ?? []), + ]); + const current = new Set(inventoryIds); + return { + added: [...current].filter((id) => !known.has(id)).sort(byName), + removed: [...known].filter((id) => !current.has(id)).sort(byName), + }; +} + +/** + * Keep only the endpoints of an artifact that belong to a flow. Without endpoint names + * (non-BizTalk platforms or legacy groups) every endpoint is kept. + */ +export function scopeEndpointsToFlow( + receive: readonly R[], + send: readonly S[], + endpointNames: readonly string[] | undefined +): { receive: R[]; send: S[]; omitted: number } { + if (!endpointNames || endpointNames.length === 0) { + return { receive: [...receive], send: [...send], omitted: 0 }; + } + const names = new Set(endpointNames.map((name) => name.toLowerCase())); + const belongs = (endpoint: unknown, extraName: string) => { + const node = asObject(endpoint) ?? {}; + const biztalk = asObject(asObject(node.sourceMapping)?.biztalk) ?? {}; + return [asString(node.name), asString(biztalk[extraName])].some( + (name) => typeof name === 'string' && names.has(name.toLowerCase()) + ); + }; + const scopedReceive = receive.filter((endpoint) => belongs(endpoint, 'receivePortName')); + const scopedSend = send.filter((endpoint) => belongs(endpoint, 'sendPortName')); + return { + receive: scopedReceive, + send: scopedSend, + omitted: receive.length - scopedReceive.length + (send.length - scopedSend.length), + }; +} diff --git a/src/test/unit/flow-group-detector.test.ts b/src/test/unit/flow-group-detector.test.ts new file mode 100644 index 0000000..7394627 --- /dev/null +++ b/src/test/unit/flow-group-detector.test.ts @@ -0,0 +1,496 @@ +import * as assert from 'assert/strict'; +import * as path from 'path'; +import { createWorkspace, disposeWorkspace, discoverSample } from '../helpers/biztalk'; +import { InventoryService } from '../../stages/discovery/InventoryService'; +import { + compareInventoryWithGroups, + detectFlowGroups, + findCrossGroupDependencies, + findMissingProjectReferences, + findUndeclaredSharedArtifacts, + humanizeName, + resolveGroupingMode, + scopeEndpointsToFlow, + simpleName, + subscribedReceivePorts, +} from '../../stages/discovery/FlowGroupDetector'; +import { ArtifactCategory, ParsedArtifact } from '../../stages/discovery/types'; +import { createEmptyIRDocument, IRDocument } from '../../ir/types'; + +const appRoot = path.resolve('/contoso-app'); + +function artifact( + id: string, + name: string, + type: ArtifactCategory, + relativePath: string, + ir: Record = {} +): ParsedArtifact { + return { + id, + name, + type, + sourcePath: relativePath, + absolutePath: path.join(appRoot, relativePath), + ir: { ...createEmptyIRDocument(id, name, 'biztalk'), ...ir } as unknown as IRDocument, + fileSize: 1, + lastModified: '2026-01-01T00:00:00.000Z', + parserId: 'test', + }; +} + +const transform = (mapTypeName: string) => ({ + type: 'compose', + actions: [ + { + type: 'transform', + config: { mapReference: mapTypeName }, + sourceMapping: { biztalk: { shapeType: 'Transform', mapTypeName } }, + }, + ], +}); + +const receive = (name: string, port: string, extra: Record = {}) => ({ + name, + sourceMapping: { biztalk: { receivePortName: port, adapterType: 'FILE', ...extra } }, +}); + +const send = (name: string, adapterType: string, filter?: string) => ({ + name, + sourceMapping: { biztalk: { adapterType, ...(filter ? { filter } : {}) } }, +}); + +/** A BizTalk application with shared canonical schemas and one binding file for several flows. */ +function sampleApplication(): ParsedArtifact[] { + return [ + artifact( + 'orch-invoice', + 'InvoiceNotification', + 'orchestration', + 'Orchestrations/InvoiceNotification.odx', + { + actions: [ + transform('Contoso.Maps.InvoiceToNotification'), + { + type: 'call-workflow', + sourceMapping: { + biztalk: { + shapeType: 'CallOrchestration', + calledOrchestration: 'Contoso.Orchestrations.SendNotification', + }, + }, + }, + ], + extensions: { + biztalk: { + orchestrationName: 'InvoiceNotification', + namespace: 'Contoso.Orchestrations', + messageTypes: [ + 'Contoso.Cdm.Invoice', + 'Contoso.Schemas.Notification', + 'System.Xml.XmlDocument', + ], + }, + }, + } + ), + artifact( + 'orch-send', + 'SendNotification', + 'orchestration', + 'Orchestrations/SendNotification.odx' + ), + artifact( + 'orch-customer', + 'CustomerSync', + 'orchestration', + 'Orchestrations/CustomerSync.odx', + { + actions: [transform('Contoso.Maps.InvoiceToCustomer')], + extensions: { + biztalk: { messageTypes: ['Contoso.Cdm.Invoice', 'Contoso.Schemas.Customer'] }, + }, + } + ), + artifact( + 'map-notification', + 'InvoiceToNotification', + 'map', + 'Maps/InvoiceToNotification.btm', + { + maps: [ + { + id: 'm1', + name: 'InvoiceToNotification', + sourceSchema: 'Contoso.Cdm.Invoice', + targetSchema: 'Contoso.Schemas.Notification', + }, + ], + } + ), + artifact('map-customer', 'InvoiceToCustomer', 'map', 'Maps/InvoiceToCustomer.btm', { + maps: [ + { + id: 'm2', + name: 'InvoiceToCustomer', + sourceSchema: '..\\Cdm\\Invoice.xsd', + targetSchema: 'Contoso.Schemas.Customer', + }, + ], + }), + artifact('schema-invoice', 'Invoice', 'schema', 'Cdm/Invoice.xsd'), + artifact('schema-notification', 'Notification', 'schema', 'Schemas/Notification.xsd'), + artifact('schema-customer', 'Customer', 'schema', 'Schemas/Customer.xsd'), + artifact('schema-unused', 'Unused', 'schema', 'Schemas/Unused.xsd'), + artifact('pipeline-receive', 'RcvInvoice', 'pipeline', 'Pipelines/RcvInvoice.btp'), + artifact( + 'project-orchestrations', + 'Orchestrations', + 'custom-code', + 'Orchestrations/Orchestrations.btproj', + { + extensions: { + biztalk: { + projectReferences: [ + path.join(appRoot, 'Cdm', 'Cdm.btproj'), + path.join(appRoot, 'Common', 'Common.btproj'), + ], + }, + }, + } + ), + artifact('project-cdm', 'Cdm', 'custom-code', 'Cdm/Cdm.btproj'), + artifact('binding-app', 'Contoso.Application', 'binding', 'Deployment/Bindings.xml', { + endpoints: { + receive: [ + receive('RL_Invoice_File', 'RP_Invoice', { + pipeline: + 'Contoso.Pipelines.RcvInvoice, Contoso.Pipelines, Version=1.0.0.0, Culture=neutral', + }), + receive('RL_Customer_File', 'RP_Customer'), + receive('RL_Archive', 'RP_Archive'), + receive('RL_Orphan', 'RP_Orphan'), + ], + send: [ + send('SP_Notification_SB', 'SB-Messaging'), + send( + 'SP_Customer_Out', + 'FILE', + '' + ), + send('SP_Archive', 'FILE', 'BTS.ReceivePortName == RP_Archive'), + ], + }, + extensions: { + biztalk: { + orchestrationBindings: [ + { + orchestrationName: 'Contoso.Orchestrations.InvoiceNotification', + portBindings: [ + { portName: 'ReceiveInvoice', boundTo: 'RP_Invoice' }, + { portName: 'SendNotification', boundTo: 'SP_Notification_SB' }, + ], + }, + ], + }, + }, + }), + ]; +} + +describe('Deterministic flow group detection', () => { + it('groups call chains and messaging routes, sharing canonical schemas and bindings', () => { + const result = detectFlowGroups(sampleApplication()); + + assert.equal(result.detectionMode, 'deterministic'); + assert.deepEqual( + result.groups.map((group) => [group.id, group.name]), + [ + ['flow-customersync', 'Customer Sync'], + ['flow-invoicenotification', 'Invoice Notification'], + ['flow-rp-archive', 'RP Archive Route'], + ['flow-rp-customer', 'RP Customer Route'], + ] + ); + + const invoice = result.groups.find((group) => group.id === 'flow-invoicenotification'); + assert.ok(invoice); + assert.deepEqual(invoice.artifactIds, [ + 'binding-app', + 'map-notification', + 'orch-invoice', + 'orch-send', + 'pipeline-receive', + 'project-cdm', + 'project-orchestrations', + 'schema-invoice', + 'schema-notification', + ]); + assert.deepEqual(invoice.endpointNames, [ + 'RL_Invoice_File', + 'RP_Invoice', + 'SP_Notification_SB', + ]); + assert.deepEqual(invoice.entryPoint, { + type: 'receive-location', + name: 'RL_Invoice_File', + }); + assert.deepEqual(invoice.exitPoints, [{ type: 'send-port', name: 'SP_Notification_SB' }]); + assert.equal(invoice.category, 'message-flow'); + assert.match( + invoice.description, + /Orchestrations: InvoiceNotification, SendNotification\./ + ); + assert.match(invoice.description, /Receives: RL_Invoice_File \(FILE\)\./); + assert.match(invoice.description, /Sends: SP_Notification_SB \(SB-Messaging\)\./); + + const customer = result.groups.find((group) => group.id === 'flow-customersync'); + assert.ok(customer); + assert.deepEqual(customer.artifactIds, [ + 'map-customer', + 'orch-customer', + 'project-cdm', + 'project-orchestrations', + 'schema-customer', + 'schema-invoice', + ]); + assert.equal(customer.endpointNames, undefined); + assert.equal(customer.category, 'business-process'); + + const route = result.groups.find((group) => group.id === 'flow-rp-customer'); + assert.ok(route); + assert.deepEqual(route.artifactIds, ['binding-app']); + assert.deepEqual(route.endpointNames, [ + 'RL_Customer_File', + 'RP_Customer', + 'SP_Customer_Out', + ]); + + assert.deepEqual(result.sharedArtifactIds, [ + 'binding-app', + 'project-cdm', + 'project-orchestrations', + 'schema-invoice', + ]); + assert.deepEqual(result.ungroupedArtifactIds, ['schema-unused']); + assert.deepEqual(result.missingProjects, [ + { + project: 'Common', + path: path.join(appRoot, 'Common', 'Common.btproj'), + referencedBy: ['Orchestrations'], + }, + ]); + assert.match(result.explanation, /Ports not linked to a flow [^:]*: RP_Orphan\./); + assert.match( + result.explanation, + /Referenced projects missing from the source folder: Common/ + ); + }); + + it('returns identical groups regardless of inventory order', () => { + const artifacts = sampleApplication(); + const expected = detectFlowGroups(artifacts); + for (const order of [ + [...artifacts].reverse(), + [...artifacts.slice(5), ...artifacts.slice(0, 5)], + ]) { + assert.deepEqual(detectFlowGroups(order), expected); + } + }); + + it('does not merge orchestrations whose names only overlap', () => { + const result = detectFlowGroups([ + artifact('orch-order', 'Order', 'orchestration', 'Orch/Order.odx', { + actions: [ + { + type: 'call-workflow', + sourceMapping: { + biztalk: { + shapeType: 'StartOrchestration', + startedOrchestration: 'OrderStatus', + }, + }, + }, + ], + }), + artifact('orch-order-status', 'OrderStatus', 'orchestration', 'Orch/OrderStatus.odx'), + artifact('orch-order-audit', 'OrderAudit', 'orchestration', 'Orch/OrderAudit.odx'), + ]); + assert.deepEqual( + result.groups.map((group) => group.artifactIds), + [['orch-order', 'orch-order-status'], ['orch-order-audit']] + ); + }); +}); + +describe('Deterministic flow grouping of the BizTalk sample', () => { + let workspace: string; + + beforeEach(() => { + workspace = createWorkspace(); + }); + afterEach(() => disposeWorkspace(workspace)); + + it('links the orchestration to its map, message schemas and projects', async () => { + await discoverSample(); + const artifacts = await InventoryService.getInstance().getAllParsedArtifacts(); + const result = detectFlowGroups(artifacts); + const nameOf = (id: string) => artifacts.find((a) => a.id === id)?.name; + + assert.equal(result.groups.length, 1); + assert.equal(result.groups[0].id, 'flow-helloschedule'); + assert.equal(result.groups[0].name, 'Hello Schedule'); + assert.deepEqual(result.groups[0].artifactIds.map(nameOf).sort(), [ + 'HelloSchedule', + 'InvoiceSchema', + 'Maps', + 'Orchestrations', + 'POSchema', + 'POToInvoice', + 'Schemas', + ]); + assert.deepEqual(result.ungroupedArtifactIds.map(nameOf), ['HelloApplicationDeployment']); + assert.deepEqual(result.sharedArtifactIds, []); + assert.deepEqual(result.missingProjects, []); + assert.deepEqual(findMissingProjectReferences(artifacts), []); + }); + + it('reports referenced projects that were not scanned', async () => { + await discoverSample(); + const artifacts = (await InventoryService.getInstance().getAllParsedArtifacts()).filter( + (a) => a.name !== 'Schemas' && a.name !== 'POSchema' && a.name !== 'InvoiceSchema' + ); + assert.deepEqual( + findMissingProjectReferences(artifacts).map((missing) => [ + missing.project, + missing.referencedBy, + ]), + [['Schemas', ['Maps', 'Orchestrations']]] + ); + }); +}); + +describe('Flow group validation and scoping helpers', () => { + const groups = [ + { id: 'a', name: 'A', artifactIds: ['orch-a', 'schema-cdm', 'binding'] }, + { id: 'b', name: 'B', artifactIds: ['orch-b', 'schema-cdm', 'binding', 'map-b'] }, + ]; + const connections = [ + { + fromId: 'schema-cdm', + toId: 'map-b', + type: 'map-source-schema' as const, + evidence: 'cdm', + }, + { + fromId: 'binding', + toId: 'orch-a', + type: 'binding-references' as const, + evidence: 'bind', + }, + { + fromId: 'orch-a', + toId: 'map-b', + type: 'orchestration-uses-map' as const, + evidence: 'uses', + }, + { fromId: 'orch-a', toId: 'orch-b', type: 'shared-namespace' as const, evidence: 'ns' }, + ]; + + it('allows dependencies on shared artifacts but rejects other cross-group links', () => { + const shared = new Set(['schema-cdm', 'binding']); + assert.deepEqual(findUndeclaredSharedArtifacts(groups, shared), []); + assert.deepEqual( + findCrossGroupDependencies(groups, connections, shared).map((d) => [ + d.fromGroup, + d.toGroup, + d.dependencyType, + ]), + [['A', 'B', 'orchestration-uses-map']] + ); + assert.deepEqual(findUndeclaredSharedArtifacts(groups, new Set(['binding'])), [ + { artifactId: 'schema-cdm', groups: ['A', 'B'] }, + ]); + }); + + it('scopes binding endpoints to the ports of one flow', () => { + const receiveEndpoints = [ + { + name: 'RL_Invoice_File', + sourceMapping: { biztalk: { receivePortName: 'RP_Invoice' } }, + }, + { + name: 'RL_Customer_File', + sourceMapping: { biztalk: { receivePortName: 'RP_Customer' } }, + }, + ]; + const sendEndpoints = [{ name: 'SP_Notification_SB' }, { name: 'SP_Customer_Out' }]; + + const scoped = scopeEndpointsToFlow(receiveEndpoints, sendEndpoints, [ + 'RP_Invoice', + 'sp_notification_sb', + ]); + assert.deepEqual( + scoped.receive.map((e) => e.name), + ['RL_Invoice_File'] + ); + assert.deepEqual( + scoped.send.map((e) => e.name), + ['SP_Notification_SB'] + ); + assert.equal(scoped.omitted, 2); + assert.equal(scopeEndpointsToFlow(receiveEndpoints, sendEndpoints, undefined).omitted, 0); + }); + + it('reads receive-port subscriptions from XML and text filters', () => { + assert.deepEqual( + subscribedReceivePorts( + '' + + '' + + '' + + '' + ), + ['RP_A', 'RP_B'] + ); + assert.deepEqual(subscribedReceivePorts('BTS.ReceivePortName == "RP_D"'), ['RP_D']); + }); + + it('reports artifacts added or removed since grouping', () => { + const grouped = { + groups: [ + { + id: 'a', + name: 'A', + description: '', + category: 'other' as const, + artifactIds: ['x', 'y'], + }, + ], + ungroupedArtifactIds: ['z'], + sharedArtifactIds: ['y'], + }; + assert.deepEqual(compareInventoryWithGroups(['x', 'y', 'z'], grouped), { + added: [], + removed: [], + }); + assert.deepEqual(compareInventoryWithGroups(['x', 'z', 'cdm-schema'], grouped), { + added: ['cdm-schema'], + removed: ['y'], + }); + }); + + it('names and resolves references deterministically', () => { + assert.equal(humanizeName('Orch_InvoiceNotification'), 'Invoice Notification'); + assert.equal(humanizeName('Contoso.HR.ProcessXMLInvoice'), 'Process XML Invoice'); + assert.equal( + simpleName('Contoso.Pipelines.Rcv, Contoso.Pipelines, Version=1.0.0.0'), + 'rcv' + ); + assert.equal(simpleName('..\\Cdm\\Invoice.xsd'), 'invoice'); + assert.equal(simpleName('Contoso.Schemas.Order+OrderLine'), 'order'); + assert.equal(resolveGroupingMode('auto', 'biztalk'), 'deterministic'); + assert.equal(resolveGroupingMode(undefined, 'mulesoft'), 'copilot'); + assert.equal(resolveGroupingMode('copilot', 'biztalk'), 'copilot'); + assert.equal(resolveGroupingMode('deterministic', 'tibco'), 'deterministic'); + }); +}); diff --git a/src/views/discovery/SourceFlowVisualizer.ts b/src/views/discovery/SourceFlowVisualizer.ts index 2dcad80..59ab034 100644 --- a/src/views/discovery/SourceFlowVisualizer.ts +++ b/src/views/discovery/SourceFlowVisualizer.ts @@ -204,6 +204,26 @@ export class SourceFlowVisualizer implements vscode.Disposable { `; } + /** + * Store a complete set of detected flow groups (replacing earlier groups) and show Home. + * Progress saved under unchanged flow IDs is kept. + */ + public static async applyFlowGroups( + result: FlowGroupsResult, + extensionUri: vscode.Uri + ): Promise { + const { DiscoveryCacheService } = + await import('../../stages/discovery/DiscoveryCacheService'); + const discoveryCacheService = DiscoveryCacheService.getInstance(); + await discoveryCacheService.storeFlowGroups(result); + SourceFlowVisualizer.setStaticCachedFlowGroups( + discoveryCacheService.getFlowGroups() ?? result, + true + ); + SourceFlowVisualizer.isInitialGenerating = false; + SourceFlowVisualizer.showFlowGroupSelector(extensionUri); + } + /** * Show a flow group selector page listing all detected flow groups. * The user picks a flow to analyse. If the flow is already discovered @@ -906,8 +926,18 @@ export class SourceFlowVisualizer implements vscode.Disposable { /** * Store flow groups in the static cache and persist via DiscoveryCacheService. + * With `replace`, groups missing from the new result are dropped instead of merged back. */ - public static setStaticCachedFlowGroups(flowGroups: FlowGroupsResult): void { + public static setStaticCachedFlowGroups(flowGroups: FlowGroupsResult, replace = false): void { + if (replace) { + this.cachedFlowGroupsResult = flowGroups; + LoggingService.getInstance().debug( + `[FlowViz] Replaced cached flow groups (${flowGroups.groups.length} groups)` + ); + void vscode.commands.executeCommand('logicAppsMigrationAgent.refreshViews'); + return; + } + const existingMap = new Map( (this.cachedFlowGroupsResult?.groups ?? []).map((g) => [g.id, g]) ); From 3f2b5beffc502ab2f651264e9df3c5f238ccda3e Mon Sep 17 00:00:00 2001 From: Shreyansh Gupta Date: Fri, 27 Nov 2026 12:24:54 +0530 Subject: [PATCH 02/10] Show what each logical group contains on Home Users could not tell which functionality sat in which of dozens of groups. - Flow cards show the entry receive location, orchestrations and send ports, the flow ID, and an expandable artifact list with shared artifacts marked. - Add a filter box (flow, orchestration, port, schema or map name), a shared-artifact count, a missing-projects banner, and how the groups were formed. - Add Re-detect Groups and Export Inventory actions; the inventory is a Markdown map of every group with its ports, artifacts, shared and ungrouped artifacts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 3 + package.json | 5 + src/commands/CommandRegistry.ts | 49 +++++ src/constants/UserMessages.ts | 3 + src/stages/discovery/FlowGroupInventory.ts | 190 ++++++++++++++++++++ src/test/unit/flow-group-inventory.test.ts | 110 ++++++++++++ src/views/discovery/SourceFlowVisualizer.ts | 180 ++++++++++++++++++- 7 files changed, 536 insertions(+), 4 deletions(-) create mode 100644 src/stages/discovery/FlowGroupInventory.ts create mode 100644 src/test/unit/flow-group-inventory.test.ts diff --git a/README.md b/README.md index 2baa2d7..f9ab6f5 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,8 @@ After discovery, the extension groups BizTalk artifacts into logical flows witho - Maps, message schemas, pipelines and projects belong to the flows that reference them. Artifacts used by several flows — for example canonical schemas from a shared canonical data model project or one application binding file — are **shared**: they appear in each flow that uses them instead of merging flows, and analysis of a flow only covers its own ports. - Referenced projects missing from the source folder are reported right away. After adding them, **Rescan Artifacts** offers to re-detect groups; flows that keep their ID keep their analysis, plan and conversion progress. You can also run **Re-detect Logical Groups** at any time. +Each Home card shows the flow's entry (receive location), orchestrations and exits (send ports), its ID, and an expandable artifact list with shared artifacts marked. Filter the cards by flow, orchestration, port, schema or map name, and use **Export Inventory** to save a Markdown map of every group with its ports, artifacts, shared and ungrouped artifacts. + Set `logicAppsMigrationAgent.discovery.groupingMode` to `copilot` to let Copilot group the artifacts instead, starting from the same proposal. MuleSoft and TIBCO use Copilot grouping by default. ### Decision-first planning @@ -139,6 +141,7 @@ Configure via `Settings > Extensions > Logic Apps Migration Agent`: | `Logic Apps Migration Agent: Reset Migration` | Reset all migration state and start over | | `Logic Apps Migration Agent: Show Extension Logs` | Open the extension output channel for debugging | | `Logic Apps Migration Agent: Re-detect Logical Groups` | Re-group the current inventory, keeping progress of flows whose ID is unchanged | +| `Logic Apps Migration Agent: Export Logical Group Inventory` | Save a Markdown map of every logical group with its ports and artifacts | ## Architecture diff --git a/package.json b/package.json index 5ead207..bd69ee1 100644 --- a/package.json +++ b/package.json @@ -1796,6 +1796,11 @@ "category": "Logic Apps Migration Agent", "icon": "$(refresh)" }, + { + "command": "logicAppsMigrationAgent.exportFlowGroupInventory", + "title": "Export Logical Group Inventory", + "category": "Logic Apps Migration Agent" + }, { "command": "logicAppsMigrationAgent.openPlanningView", "title": "Open Planning View", diff --git a/src/commands/CommandRegistry.ts b/src/commands/CommandRegistry.ts index e97c709..6e181f1 100644 --- a/src/commands/CommandRegistry.ts +++ b/src/commands/CommandRegistry.ts @@ -22,6 +22,7 @@ import { FlowGroupingMode, resolveGroupingMode, } from '../stages/discovery/FlowGroupDetector'; +import { renderFlowGroupInventoryMarkdown } from '../stages/discovery/FlowGroupInventory'; import { PlanningService } from '../stages/planning'; import { ConversionService } from '../stages/conversion'; import { AgentFileProvisioner } from '../services/AgentFileProvisioner'; @@ -133,6 +134,11 @@ export class CommandRegistry implements vscode.Disposable { handler: this.handleRedetectFlowGroups.bind(this), title: 'Re-detect Logical Groups', }, + { + id: 'logicAppsMigrationAgent.exportFlowGroupInventory', + handler: this.handleExportFlowGroupInventory.bind(this), + title: 'Export Logical Group Inventory', + }, // Planning Stage Commands { id: 'logicAppsMigrationAgent.openPlanningView', @@ -1009,6 +1015,49 @@ export class CommandRegistry implements vscode.Disposable { await this.startCopilotFlowGroupDetection(extensionUri); } + /** + * Save a Markdown inventory mapping every logical group to its ports and artifacts. + */ + private async handleExportFlowGroupInventory(): Promise { + const { DiscoveryCacheService } = await import('../stages/discovery/DiscoveryCacheService'); + const flowGroups = DiscoveryCacheService.getInstance().getFlowGroups(); + if (!flowGroups || flowGroups.groups.length === 0) { + vscode.window.showWarningMessage(UserPrompts.NO_FLOW_GROUPS_TO_EXPORT); + return; + } + + const inventory = InventoryService.getInstance(); + const markdown = renderFlowGroupInventoryMarkdown(flowGroups, (id) => { + const item = inventory.getItem(id); + return item + ? { name: item.name, type: item.category, sourcePath: item.sourcePath } + : undefined; + }); + const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; + const target = await vscode.window.showSaveDialog({ + defaultUri: workspaceFolder + ? vscode.Uri.joinPath(workspaceFolder.uri, 'logical-groups.md') + : undefined, + filters: { Markdown: ['md'] }, + title: 'Export Logical Group Inventory', + }); + if (!target) { + return; + } + + await fs.promises.writeFile(target.fsPath, markdown, 'utf-8'); + TelemetryService.getInstance().logStep('flowgroups.inventory.exported', { + flowGroupCount: flowGroups.groups.length, + }); + const open = await vscode.window.showInformationMessage( + UserPrompts.FLOW_GROUP_INVENTORY_SAVED, + UserPrompts.BUTTON_OPEN_FILE + ); + if (open === UserPrompts.BUTTON_OPEN_FILE) { + await vscode.commands.executeCommand('vscode.open', target); + } + } + /** * Handle viewing dependency graph */ diff --git a/src/constants/UserMessages.ts b/src/constants/UserMessages.ts index 82d1f79..53077bc 100644 --- a/src/constants/UserMessages.ts +++ b/src/constants/UserMessages.ts @@ -184,6 +184,9 @@ export class UserPrompts { } static readonly BUTTON_REDETECT_GROUPS = 'Re-detect Groups'; + static readonly NO_FLOW_GROUPS_TO_EXPORT = + 'No logical groups detected yet. Run discovery and open Home first.'; + static readonly FLOW_GROUP_INVENTORY_SAVED = 'Logical group inventory saved.'; static readonly FLOW_WORK_IN_PROGRESS = 'A flow is still being analysed, planned or converted. Stop it or wait before re-detecting logical groups.'; diff --git a/src/stages/discovery/FlowGroupInventory.ts b/src/stages/discovery/FlowGroupInventory.ts new file mode 100644 index 0000000..2843669 --- /dev/null +++ b/src/stages/discovery/FlowGroupInventory.ts @@ -0,0 +1,190 @@ +/** + * Flow Group Inventory + * + * Text shown on Home flow cards and the exportable Markdown inventory that maps every + * logical group to its entry points, orchestrations, exit points and artifacts. + * + * @module stages/discovery/FlowGroupInventory + */ + +import type { FlowGroup, FlowGroupsResult } from '../../services/LLMFlowGenerator'; + +/** Name, type and location of an inventory artifact. */ +export interface InventoryArtifactInfo { + readonly name: string; + readonly type: string; + readonly sourcePath?: string; +} + +export type ArtifactLookup = (artifactId: string) => InventoryArtifactInfo | undefined; + +const PROCESS_TYPES: ReadonlySet = new Set([ + 'orchestration', + 'flow', + 'process', + 'workflow', +]); + +/** Receive → process → send summary of one flow, for display. */ +export interface FlowRoute { + readonly entry?: string; + readonly additionalEntries: number; + readonly processes: string[]; + readonly exits: string[]; +} + +function byName(a: string, b: string): number { + return a.localeCompare(b, 'en', { sensitivity: 'base' }) || a.localeCompare(b); +} + +export function describeFlowRoute(group: FlowGroup, lookup: ArtifactLookup): FlowRoute { + const processes = group.artifactIds + .map((id) => lookup(id)) + .filter((info): info is InventoryArtifactInfo => !!info && PROCESS_TYPES.has(info.type)) + .map((info) => info.name) + .sort(byName); + const entry = + group.entryPoint && !PROCESS_TYPES.has(group.entryPoint.type) + ? group.entryPoint.name + : undefined; + return { + entry, + additionalEntries: entry ? Math.max(0, (group.summary?.receivePorts ?? 1) - 1) : 0, + processes, + exits: (group.exitPoints ?? []).map((exit) => exit.name), + }; +} + +/** "RL_A (+2 more)" style label for the entry of a flow. */ +export function entryLabel(route: FlowRoute): string { + if (!route.entry) { + return ''; + } + return route.additionalEntries > 0 + ? `${route.entry} (+${route.additionalEntries} more)` + : route.entry; +} + +/** Lower-case text a Home search box matches against. */ +export function flowSearchText(group: FlowGroup, lookup: ArtifactLookup): string { + const artifacts = group.artifactIds.map((id) => lookup(id)?.name ?? ''); + return [ + group.id, + group.name, + group.description, + group.category, + group.entryPoint?.name ?? '', + ...(group.exitPoints ?? []).map((exit) => exit.name), + ...(group.endpointNames ?? []), + ...artifacts, + ] + .join(' ') + .toLowerCase(); +} + +function cell(value: string | undefined): string { + return (value ?? '').replace(/\|/g, '\\|').replace(/\r?\n/g, '
') || '—'; +} + +/** Markdown inventory of all logical groups, shared and ungrouped artifacts. */ +export function renderFlowGroupInventoryMarkdown( + result: FlowGroupsResult, + lookup: ArtifactLookup +): string { + const shared = new Set(result.sharedArtifactIds ?? []); + const usedBy = new Map(); + for (const group of result.groups) { + for (const id of group.artifactIds) { + usedBy.set(id, [...(usedBy.get(id) ?? []), group.name]); + } + } + const artifactRow = (id: string, extra: string[] = []) => { + const info = lookup(id); + return `| ${[info?.name ?? id, info?.type, info?.sourcePath, ...extra].map(cell).join(' | ')} |`; + }; + + const lines: string[] = [ + '# Logical Group Inventory', + '', + `${result.groups.length} flow(s), ${shared.size} shared artifact(s), ${result.ungroupedArtifactIds.length} ungrouped artifact(s).` + + (result.detectionMode ? ` Detection: ${result.detectionMode}.` : ''), + ]; + if (result.explanation) { + lines.push('', `> ${result.explanation.replace(/\r?\n/g, ' ')}`); + } + + if (result.missingProjects && result.missingProjects.length > 0) { + lines.push( + '', + '## Missing Referenced Projects', + '', + 'Add these projects to the source folder and rescan so flows include their schemas and code.', + '', + '| Project | Referenced by | Path |', + '| --- | --- | --- |', + ...result.missingProjects.map( + (missing) => + `| ${cell(missing.project)} | ${cell(missing.referencedBy.join(', '))} | ${cell(missing.path)} |` + ) + ); + } + + lines.push( + '', + '## Flows', + '', + '| Flow | ID | Entry | Orchestrations / flows | Exits | Artifacts |', + '| --- | --- | --- | --- | --- | --- |' + ); + for (const group of result.groups) { + const route = describeFlowRoute(group, lookup); + lines.push( + `| ${cell(group.name)} | \`${group.id}\` | ${cell(entryLabel(route))} | ${cell(route.processes.join(', '))} | ${cell(route.exits.join(', '))} | ${group.artifactIds.length} |` + ); + } + + for (const group of result.groups) { + lines.push('', `### ${group.name} (\`${group.id}\`)`, ''); + if (group.description) { + lines.push(group.description, ''); + } + if (group.endpointNames && group.endpointNames.length > 0) { + lines.push(`Ports: ${group.endpointNames.join(', ')}`, ''); + } + lines.push('| Artifact | Type | Path | Shared |', '| --- | --- | --- | --- |'); + const ids = [...group.artifactIds].sort( + (a, b) => + byName(lookup(a)?.type ?? '', lookup(b)?.type ?? '') || + byName(lookup(a)?.name ?? a, lookup(b)?.name ?? b) + ); + for (const id of ids) { + lines.push(artifactRow(id, [shared.has(id) ? 'yes' : ''])); + } + } + + if (shared.size > 0) { + lines.push( + '', + '## Shared Artifacts', + '', + '| Artifact | Type | Path | Used by |', + '| --- | --- | --- | --- |', + ...[...shared].map((id) => artifactRow(id, [(usedBy.get(id) ?? []).join(', ')])) + ); + } + + if (result.ungroupedArtifactIds.length > 0) { + lines.push( + '', + '## Ungrouped Artifacts', + '', + 'Not referenced by any flow.', + '', + '| Artifact | Type | Path |', + '| --- | --- | --- |', + ...result.ungroupedArtifactIds.map((id) => artifactRow(id)) + ); + } + + return `${lines.join('\n')}\n`; +} diff --git a/src/test/unit/flow-group-inventory.test.ts b/src/test/unit/flow-group-inventory.test.ts new file mode 100644 index 0000000..0c61c64 --- /dev/null +++ b/src/test/unit/flow-group-inventory.test.ts @@ -0,0 +1,110 @@ +import * as assert from 'assert/strict'; +import { + describeFlowRoute, + entryLabel, + flowSearchText, + renderFlowGroupInventoryMarkdown, +} from '../../stages/discovery/FlowGroupInventory'; +import { FlowGroupsResult } from '../../services/LLMFlowGenerator'; + +const artifacts: Record = { + orch: { name: 'InvoiceNotification', type: 'orchestration', sourcePath: 'Orch/Inv.odx' }, + called: { name: 'SendNotification', type: 'orchestration', sourcePath: 'Orch/Send.odx' }, + map: { name: 'Invoice|ToNotification', type: 'map', sourcePath: 'Maps/E.btm' }, + cdm: { name: 'Invoice', type: 'schema', sourcePath: 'Cdm/Invoice.xsd' }, + binding: { name: 'Contoso.Application', type: 'binding', sourcePath: 'Deploy/Bindings.xml' }, + unused: { name: 'Unused', type: 'schema', sourcePath: 'Schemas/Unused.xsd' }, +}; +const lookup = (id: string) => artifacts[id]; + +const result: FlowGroupsResult = { + groups: [ + { + id: 'flow-invoicenotification', + name: 'Invoice Notification', + description: 'Orchestrations: InvoiceNotification, SendNotification.', + category: 'message-flow', + artifactIds: ['orch', 'called', 'map', 'cdm', 'binding'], + entryPoint: { type: 'receive-location', name: 'RL_Invoice_File' }, + exitPoints: [{ type: 'send-port', name: 'SP_Notification_SB' }], + endpointNames: [ + 'RL_Invoice_File', + 'RL_Invoice_Ftp', + 'RP_Invoice', + 'SP_Notification_SB', + ], + summary: { receivePorts: 2, orchestrations: 2, maps: 1, sendPorts: 1 }, + }, + { + id: 'flow-rp-archive', + name: 'RP Archive Route', + description: 'Messaging route without an orchestration (receive port RP_Archive).', + category: 'message-flow', + artifactIds: ['binding'], + entryPoint: { type: 'receive-port', name: 'RP_Archive' }, + }, + ], + ungroupedArtifactIds: ['unused'], + sharedArtifactIds: ['binding'], + missingProjects: [ + { + project: 'Common', + path: 'C:\\src\\Common\\Common.btproj', + referencedBy: ['Orchestrations'], + }, + ], + explanation: 'Grouped deterministically.', + detectionMode: 'deterministic', +}; + +describe('Logical group inventory', () => { + it('summarizes the receive, process and send route of a flow', () => { + const route = describeFlowRoute(result.groups[0], lookup); + assert.deepEqual(route, { + entry: 'RL_Invoice_File', + additionalEntries: 1, + processes: ['InvoiceNotification', 'SendNotification'], + exits: ['SP_Notification_SB'], + }); + assert.equal(entryLabel(route), 'RL_Invoice_File (+1 more)'); + assert.equal(entryLabel(describeFlowRoute(result.groups[1], lookup)), 'RP_Archive'); + }); + + it('searches flows by ports and artifact names', () => { + const text = flowSearchText(result.groups[0], lookup); + assert.ok(text.includes('rl_invoice_ftp')); + assert.ok(text.includes('invoice|tonotification')); + assert.ok(text.includes('flow-invoicenotification')); + }); + + it('exports flows, shared, ungrouped and missing artifacts as Markdown', () => { + const markdown = renderFlowGroupInventoryMarkdown(result, lookup); + assert.match(markdown, /^# Logical Group Inventory\n/); + assert.match( + markdown, + /2 flow\(s\), 1 shared artifact\(s\), 1 ungrouped artifact\(s\)\. Detection: deterministic\./ + ); + assert.match( + markdown, + /## Missing Referenced Projects[\s\S]*\| Common \| Orchestrations \| C:\\src\\Common\\Common\.btproj \|/ + ); + assert.match( + markdown, + /\| Invoice Notification \| `flow-invoicenotification` \| RL_Invoice_File \(\+1 more\) \| InvoiceNotification, SendNotification \| SP_Notification_SB \| 5 \|/ + ); + assert.match(markdown, /\| Invoice\\\|ToNotification \| map \| Maps\/E\.btm \| — \|/); + assert.match( + markdown, + /\| Contoso\.Application \| binding \| Deploy\/Bindings\.xml \| yes \|/ + ); + assert.match( + markdown, + /## Shared Artifacts[\s\S]*\| Contoso\.Application \| binding \| Deploy\/Bindings\.xml \| Invoice Notification, RP Archive Route \|/ + ); + assert.match( + markdown, + /## Ungrouped Artifacts[\s\S]*\| Unused \| schema \| Schemas\/Unused\.xsd \|/ + ); + assert.ok(!markdown.includes('undefined')); + }); +}); diff --git a/src/views/discovery/SourceFlowVisualizer.ts b/src/views/discovery/SourceFlowVisualizer.ts index 59ab034..c87c912 100644 --- a/src/views/discovery/SourceFlowVisualizer.ts +++ b/src/views/discovery/SourceFlowVisualizer.ts @@ -19,6 +19,11 @@ import { LoggingService } from '../../services/LoggingService'; import { TelemetryService } from '../../services/TelemetryService'; import { ParsedArtifact } from '../../stages/discovery/types'; import { InventoryService } from '../../stages/discovery/InventoryService'; +import { + describeFlowRoute, + entryLabel, + flowSearchText, +} from '../../stages/discovery/FlowGroupInventory'; import { GeneratedFlowResult, FlowGroupsResult } from '../../services/LLMFlowGenerator'; import { UserPrompts } from '../../constants/UserMessages'; import { ChatPrompts } from '../../constants/ChatPrompts'; @@ -264,6 +269,23 @@ export class SourceFlowVisualizer implements vscode.Disposable { const migrationBannerHtml = SourceFlowVisualizer.getMigrationBannerHtml(sourcePlatform); const isAnyFlowBusy = SourceFlowVisualizer.isAnyFlowBusy; + const inventory = InventoryService.getInstance(); + const lookup = (id: string) => { + const item = inventory.getItem(id); + return item + ? { name: item.name, type: item.category, sourcePath: item.sourcePath } + : undefined; + }; + const sharedIds = new Set(flowGroups.sharedArtifactIds ?? []); + const missingProjects = flowGroups.missingProjects ?? []; + const missingProjectsHtml = + missingProjects.length > 0 + ? `
⚠ Referenced projects are missing from the source folder: ${escapeHtml(missingProjects.map((p) => p.project).join(', '))}. Add them and run Rescan Artifacts so flows include their schemas and code.
` + : ''; + const explanationHtml = flowGroups.explanation + ? `
How these groups were formed

${escapeHtml(flowGroups.explanation)}

` + : ''; + const flowCards = flowGroups.groups .map((g) => { const isGenerating = SourceFlowVisualizer.generatingGroupIds.has(g.id); @@ -377,17 +399,52 @@ export class SourceFlowVisualizer implements vscode.Disposable { ? `` : ''; + const route = describeFlowRoute(g, lookup); + const routeParts = [ + route.entry + ? `In${escapeHtml(entryLabel(route))}` + : '', + route.processes.length > 0 + ? `Process${escapeHtml(route.processes.join(', '))}` + : '', + route.exits.length > 0 + ? `Out${escapeHtml(route.exits.join(', '))}` + : '', + ].filter(Boolean); + const routeHtml = + routeParts.length > 0 + ? `
${routeParts.join('→')}
` + : ''; + const sharedCount = (g.artifactIds ?? []).filter((id) => + sharedIds.has(id) + ).length; + const artifactItems = (g.artifactIds ?? []) + .map((id) => ({ id, info: lookup(id) })) + .sort( + (a, b) => + (a.info?.type ?? '').localeCompare(b.info?.type ?? '') || + (a.info?.name ?? a.id).localeCompare(b.info?.name ?? b.id) + ) + .map( + ({ id, info }) => + `
  • ${escapeHtml(info?.type ?? 'artifact')}${escapeHtml(info?.name ?? id)}${sharedIds.has(id) ? 'shared' : ''}
  • ` + ) + .join(''); + return ` -
    +
    ${escapeHtml(g.name)} ${resetBtn}${stopBtn}
    ${escapeHtml(g.description)}
    + ${routeHtml}
    - ${artifactCount} artifacts + ${artifactCount} artifacts${sharedCount > 0 ? ` (${sharedCount} shared)` : ''} ${escapeHtml(g.category)} + ${escapeHtml(g.id)}
    +
    Artifacts
      ${artifactItems}
    ${analyseBtn}${stepArrow}${planBtn}${stepArrow}${createBtn}${stepArrow}${executeBtn}${stepArrow}${openBtn}
    @@ -648,24 +705,127 @@ export class SourceFlowVisualizer implements vscode.Disposable { display: flex; align-items: center; } + .page-header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + flex-wrap: wrap; + } + .page-actions { display: flex; gap: 8px; flex-wrap: wrap; } + .page-actions .btn[disabled] { opacity: 0.5; cursor: not-allowed; } + .warning-banner { + padding: 10px 14px; + margin-bottom: 16px; + border-radius: 6px; + border: 1px solid var(--vscode-inputValidation-warningBorder, #cca700); + background: var(--vscode-inputValidation-warningBackground, rgba(204, 167, 0, 0.12)); + font-size: 13px; + } + .grouping-explanation { margin: -12px 0 16px; font-size: 12px; color: var(--vscode-descriptionForeground); } + .grouping-explanation summary { cursor: pointer; } + .flow-filter { display: flex; align-items: center; gap: 10px; margin-bottom: 16px; } + .flow-filter input { + flex: 1; + padding: 6px 10px; + border-radius: 4px; + border: 1px solid var(--vscode-input-border, var(--vscode-panel-border)); + background: var(--vscode-input-background); + color: var(--vscode-input-foreground); + } + #flow-filter-count { font-size: 12px; color: var(--vscode-descriptionForeground); white-space: nowrap; } + .flow-route { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + font-size: 12px; + margin-bottom: 8px; + } + .route-label { + font-size: 10px; + font-weight: 600; + text-transform: uppercase; + padding: 1px 6px; + margin-right: 4px; + border-radius: 8px; + background: var(--vscode-badge-background); + color: var(--vscode-badge-foreground); + } + .route-arrow { opacity: 0.6; } + .flow-id { font-family: var(--vscode-editor-font-family); } + .flow-artifacts { margin-top: 8px; font-size: 12px; } + .flow-artifacts summary { cursor: pointer; color: var(--vscode-textLink-foreground); } + .flow-artifacts ul { margin: 6px 0 0; padding-left: 18px; columns: 2; } + .artifact-type { + display: inline-block; + min-width: 84px; + margin-right: 6px; + color: var(--vscode-descriptionForeground); + } + .badge-shared { + margin-left: 6px; + background: rgba(0, 123, 255, 0.15); + color: var(--vscode-textLink-foreground); + } -
    + ${migrationBannerHtml} + ${missingProjectsHtml}

    Select a flow to analyse its architecture, components, and migration gaps.

    + ${explanationHtml}
    ${flowGroups.groups.length} Total Flows
    ${flowGroups.groups.filter((g) => g.discovered).length} Analysed
    ${flowGroups.groups.filter((g) => g.planned).length} Planned
    ${flowGroups.groups.filter((g) => g.converted).length} Converted
    + ${sharedIds.size > 0 ? `
    ${sharedIds.size} Shared Artifacts
    ` : ''} +
    +
    + +
    ${flowCards}